conversation-session-plan-mode-capabilities.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. import { readFile, rm } from "node:fs/promises";
  2. import { clearAppData } from "#e2e/helpers/desktop-app";
  3. import { resolveE2EToolPath } from "#e2e/helpers/e2e-runtime-paths";
  4. import {
  5. E2E_READONLY_TOOL_FILE_CONTENT,
  6. ensureReadonlyToolFixtureFile,
  7. } from "#e2e/helpers/conversation-session-readonly-tool";
  8. import {
  9. E2E_REPLY_TOKEN,
  10. getV4Messages,
  11. prepareV4ConversationE2E,
  12. sendV4Prompt,
  13. waitForV4AssistantMessageContaining,
  14. waitForV4ConversationState,
  15. waitForV4ComposerText,
  16. waitForV4UserMessageContaining,
  17. } from "#e2e/helpers/v4-conversation";
  18. import {
  19. getLatestUpstreamToolResultByToolCallId,
  20. countUpstreamRequests,
  21. getUpstreamRequestRecordCount,
  22. waitForUpstreamRequest,
  23. } from "#e2e/helpers/conversation-session-network";
  24. import {
  25. waitForToolCallBlockByToolCallId,
  26. waitForToolCallBlockByToolName,
  27. } from "#e2e/helpers/conversation-session-tool";
  28. const DENY_PROMPT_MARKER = "E2E_PLAN_MODE_DENY_STOPS_TURN";
  29. const DENY_ENTER_MARKER = "E2E_PLAN_MODE_DENY_ENTER_PLAN";
  30. const DENY_EXIT_MARKER = "E2E_PLAN_MODE_DENY_EXIT_PLAN";
  31. const DENY_NEXT_MARKER = "E2E_PLAN_MODE_DENY_NEXT_INPUT";
  32. const DENY_EXIT_TOOL_CALL_ID = "toolu_e2e_plan_mode_deny_exit_plan_mode";
  33. const TOOL_PROMPT_MARKER = "E2E_PLAN_MODE_TOOL_BOUNDARY";
  34. const TOOL_ENTER_MARKER = "E2E_PLAN_MODE_TOOL_BOUNDARY_ENTER";
  35. const TOOL_MIXED_MARKER = "E2E_PLAN_MODE_TOOL_BOUNDARY_MIXED";
  36. const TOOL_WRITE_CALL_ID = "toolu_e2e_plan_mode_boundary_write";
  37. const TOOL_READ_CALL_ID = "toolu_e2e_plan_mode_boundary_read";
  38. const DENIED_WRITE_FILE_NAME = "zcode-e2e-plan-mode-denied-write.txt";
  39. const DENIED_WRITE_FILE_PATH = resolveE2EToolPath(
  40. "conversation-session-plan-mode-capabilities",
  41. DENIED_WRITE_FILE_NAME,
  42. );
  43. const TITLE_REQUEST_SENTINEL = "Generate a concise title";
  44. const COMPACT_REQUEST_SENTINEL = "CRITICAL: Respond with TEXT ONLY";
  45. const PLAN_MODE_REMINDER = "Plan mode is active";
  46. const PLAN_MODE_NO_EDIT_REMINDER = "MUST NOT make any edits";
  47. const PLAN_MODE_DENIAL_REASON = "Plan mode only allows read-only, non-destructive tools";
  48. describe("conversation session plan mode capabilities", () => {
  49. after(async () => {
  50. await browser.electron.restoreAllMocks();
  51. await clearAppData();
  52. });
  53. afterEach(async () => {
  54. await rm(DENIED_WRITE_FILE_PATH, { force: true });
  55. });
  56. it("stops the current turn after ExitPlanMode is declined without feedback", async () => {
  57. await prepareV4ConversationE2E();
  58. // 原因:旧聚合 helper 隐式创建只读文件;V4 用例显式保留工具执行前置。
  59. await ensureReadonlyToolFixtureFile();
  60. const runId = Date.now();
  61. const prompt = [
  62. `${DENY_PROMPT_MARKER}_${runId}: enter plan mode and request approval.`,
  63. `${DENY_ENTER_MARKER}: call EnterPlanMode before drafting.`,
  64. `${DENY_EXIT_MARKER}: call ExitPlanMode with the proposed plan.`,
  65. ].join(" ");
  66. await sendV4Prompt(prompt);
  67. await waitForV4ComposerText("", "plan mode deny prompt 发送后输入框没有清空");
  68. await waitForV4UserMessageContaining(DENY_PROMPT_MARKER);
  69. await waitForUpstreamRequest(
  70. {
  71. includes: [DENY_PROMPT_MARKER, DENY_ENTER_MARKER, DENY_EXIT_MARKER],
  72. excludes: [TITLE_REQUEST_SENTINEL, COMPACT_REQUEST_SENTINEL],
  73. },
  74. "plan mode deny initial request",
  75. 60000,
  76. );
  77. // 原因:V4 隐藏内部 EnterPlanMode;以真实工具成功结果确认进入 Plan。
  78. await browser.waitUntil(
  79. async () =>
  80. (await getLatestUpstreamToolResultByToolCallId("toolu_e2e_plan_mode_deny_enter_plan_mode"))
  81. ?.isError === false,
  82. { timeout: 60_000, timeoutMsg: "EnterPlanMode 没有真实执行成功" },
  83. );
  84. await waitForUpstreamRequest(
  85. {
  86. includes: [DENY_EXIT_MARKER, "toolu_e2e_plan_mode_deny_enter_plan_mode"],
  87. excludes: [TITLE_REQUEST_SENTINEL, COMPACT_REQUEST_SENTINEL],
  88. },
  89. "plan mode deny exit request",
  90. 60000,
  91. );
  92. await waitForToolCallBlockByToolName("ExitPlanMode", 60000);
  93. await waitForElicitationDialogContaining("Approve", 60000);
  94. const requestCountBeforeDecline = await getUpstreamRequestRecordCount();
  95. await dismissPlanApprovalWithoutFeedback();
  96. await waitForIdle("plan mode deny without feedback 没有回到 idle");
  97. await expectNoNewUpstreamRequestContaining(
  98. [DENY_EXIT_TOOL_CALL_ID],
  99. requestCountBeforeDecline,
  100. 2500,
  101. );
  102. const nextPrompt = `${DENY_NEXT_MARKER}_${runId}: reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  103. const nextRequestStart = await getUpstreamRequestRecordCount();
  104. await sendV4Prompt(nextPrompt);
  105. await waitForV4ComposerText("", "plan mode deny 后续输入发送后输入框没有清空");
  106. await waitForUpstreamRequest(
  107. {
  108. includes: [DENY_NEXT_MARKER, PLAN_MODE_REMINDER, PLAN_MODE_NO_EDIT_REMINDER],
  109. excludes: [TITLE_REQUEST_SENTINEL, COMPACT_REQUEST_SENTINEL],
  110. },
  111. "plan mode deny follow-up request should remain in plan mode",
  112. 60000,
  113. afterRecordCount(nextRequestStart),
  114. );
  115. await waitForV4AssistantMessageContaining(E2E_REPLY_TOKEN);
  116. await waitForIdle("plan mode deny 后续请求没有结束");
  117. });
  118. it("blocks mutating tools but still runs later read-only tools in plan mode", async () => {
  119. await rm(DENIED_WRITE_FILE_PATH, { force: true });
  120. await prepareV4ConversationE2E();
  121. await ensureReadonlyToolFixtureFile();
  122. const runId = Date.now();
  123. const prompt = [
  124. `${TOOL_PROMPT_MARKER}_${runId}: enter plan mode and inspect without edits.`,
  125. `${TOOL_ENTER_MARKER}: call EnterPlanMode first.`,
  126. `${TOOL_MIXED_MARKER}: then call Write and Read in the same assistant message.`,
  127. ].join(" ");
  128. await sendV4Prompt(prompt);
  129. await waitForV4ComposerText("", "plan mode tool boundary prompt 发送后输入框没有清空");
  130. await waitForV4UserMessageContaining(TOOL_PROMPT_MARKER);
  131. await waitForUpstreamRequest(
  132. {
  133. includes: [TOOL_PROMPT_MARKER, TOOL_ENTER_MARKER, TOOL_MIXED_MARKER],
  134. excludes: [TITLE_REQUEST_SENTINEL, COMPACT_REQUEST_SENTINEL],
  135. },
  136. "plan mode tool boundary initial request",
  137. 60000,
  138. );
  139. // 原因:V4 隐藏内部 EnterPlanMode;以真实工具成功结果确认进入 Plan。
  140. await browser.waitUntil(
  141. async () =>
  142. (
  143. await getLatestUpstreamToolResultByToolCallId(
  144. "toolu_e2e_plan_mode_boundary_enter_plan_mode",
  145. )
  146. )?.isError === false,
  147. { timeout: 60_000, timeoutMsg: "EnterPlanMode 没有真实执行成功" },
  148. );
  149. await waitForUpstreamRequest(
  150. {
  151. includes: [
  152. TOOL_MIXED_MARKER,
  153. "toolu_e2e_plan_mode_boundary_enter_plan_mode",
  154. PLAN_MODE_REMINDER,
  155. PLAN_MODE_NO_EDIT_REMINDER,
  156. ],
  157. excludes: [TITLE_REQUEST_SENTINEL, COMPACT_REQUEST_SENTINEL],
  158. },
  159. "plan mode tool boundary mixed tool request",
  160. 60000,
  161. );
  162. await waitForToolCallBlockByToolCallId(TOOL_WRITE_CALL_ID, 60000);
  163. await waitForToolCallBlockByToolCallId(TOOL_READ_CALL_ID, 60000);
  164. await waitForUpstreamRequest(
  165. {
  166. includes: [
  167. TOOL_MIXED_MARKER,
  168. TOOL_WRITE_CALL_ID,
  169. TOOL_READ_CALL_ID,
  170. PLAN_MODE_DENIAL_REASON,
  171. E2E_READONLY_TOOL_FILE_CONTENT,
  172. ],
  173. excludes: [TITLE_REQUEST_SENTINEL, COMPACT_REQUEST_SENTINEL],
  174. },
  175. "plan mode tool boundary continuation request",
  176. 60000,
  177. );
  178. expect(await readFileIfExists(DENIED_WRITE_FILE_PATH)).toBe(null);
  179. await waitForV4AssistantMessageContaining(E2E_REPLY_TOKEN);
  180. await expectAssistantReplyWithoutDeniedChangeSummary();
  181. await waitForIdle("plan mode tool boundary 没有结束");
  182. });
  183. });
  184. async function waitForElicitationDialogContaining(text: string, timeoutMs: number) {
  185. const expectedTexts = expandElicitationDialogTextAlternatives(text);
  186. let latestDialogText = "";
  187. await browser.waitUntil(
  188. async () => {
  189. // 修复原因:ExitPlanMode 的批准/忽略选项渲染在 footer,body 只包含计划正文。
  190. // 旧等待只查 body,会在真实弹窗已出现时继续等到超时。
  191. latestDialogText = await browser.execute(() => {
  192. const body = document.querySelector<HTMLElement>("[data-elicitation-dialog-body='true']");
  193. const footer = document.querySelector<HTMLElement>(
  194. "[data-elicitation-dialog-footer='true']",
  195. );
  196. return [body?.innerText, footer?.innerText].filter(Boolean).join("\n");
  197. });
  198. return expectedTexts.some((expectedText) => latestDialogText.includes(expectedText));
  199. },
  200. {
  201. timeout: timeoutMs,
  202. timeoutMsg: `Timed out waiting for elicitation dialog containing ${expectedTexts.join(
  203. " / ",
  204. )}; latest=${latestDialogText}`,
  205. },
  206. );
  207. }
  208. function expandElicitationDialogTextAlternatives(text: string) {
  209. if (text === "Approve") {
  210. return ["Approve", "批准"];
  211. }
  212. if (text === "Dismiss") {
  213. return ["Dismiss", "忽略"];
  214. }
  215. return [text];
  216. }
  217. async function dismissPlanApprovalWithoutFeedback() {
  218. const dismissButton = await $(
  219. "//*[@data-elicitation-dialog-footer='true']//button[normalize-space(.)='Dismiss' or normalize-space(.)='忽略']",
  220. );
  221. // 仅操作审批 footer 的拒绝按钮;等待实际可点击,避免命中其他页面的同名按钮。
  222. await dismissButton.waitForClickable({ timeout: 30000 });
  223. await dismissButton.click();
  224. }
  225. async function expectNoNewUpstreamRequestContaining(
  226. includes: string[],
  227. afterRecordCountValue: number,
  228. durationMs: number,
  229. ) {
  230. await browser.pause(durationMs);
  231. const count = await countUpstreamRequests(
  232. {
  233. includes,
  234. excludes: [TITLE_REQUEST_SENTINEL, COMPACT_REQUEST_SENTINEL],
  235. },
  236. afterRecordCount(afterRecordCountValue),
  237. );
  238. expect(count).toBe(0);
  239. }
  240. async function waitForIdle(timeoutMsg: string) {
  241. await waitForV4ConversationState(
  242. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  243. timeoutMsg,
  244. 60000,
  245. );
  246. }
  247. async function expectAssistantReplyWithoutDeniedChangeSummary() {
  248. const replies = (await getV4Messages("assistant")).filter((message) =>
  249. message.text.includes(E2E_REPLY_TOKEN),
  250. );
  251. expect(replies.length).toBeGreaterThan(0);
  252. for (const reply of replies) {
  253. expect(reply.text).not.toContain("file changed");
  254. expect(reply.text).not.toContain("文件已更改");
  255. }
  256. }
  257. async function readFileIfExists(path: string) {
  258. try {
  259. return await readFile(path, "utf8");
  260. } catch (error) {
  261. if (error instanceof Error && "code" in error && error.code === "ENOENT") {
  262. return null;
  263. }
  264. throw error;
  265. }
  266. }
  267. function afterRecordCount(recordCount: number) {
  268. return recordCount > 0 ? { afterIndex: recordCount - 1 } : {};
  269. }