conversation-session-plan-approval-primary-submit.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import { readFile, rm } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { DEFAULT_WORKSPACE, clearAppData } from "#e2e/helpers/desktop-app";
  4. import { waitForUpstreamRequest } from "#e2e/helpers/conversation-session-network";
  5. import { waitForToolCallBlockByToolName } from "#e2e/helpers/conversation-session-tool";
  6. import {
  7. E2E_REPLY_TOKEN,
  8. getV4ConfigProjection,
  9. getV4ComposerText,
  10. prepareV4ConversationE2E,
  11. sendV4Prompt,
  12. switchV4Mode,
  13. waitForV4AssistantMessageContaining,
  14. waitForV4Pane,
  15. waitForV4TimelineContaining,
  16. } from "#e2e/helpers/v4-conversation";
  17. const PROMPT_MARKER = "E2E_PLAN_APPROVAL_PRIMARY_SUBMIT";
  18. const ENTER_MARKER = "E2E_PLAN_APPROVAL_PRIMARY_SUBMIT_ENTER_PLAN";
  19. const EXIT_MARKER = "E2E_PLAN_APPROVAL_PRIMARY_SUBMIT_EXIT_PLAN";
  20. const PLAN_MARKER = "E2E_PLAN_APPROVAL_PRIMARY_SUBMIT_PLAN_BODY";
  21. const APPROVED_PLAN_TEXT = `${PLAN_MARKER}: verify footer submit approves an unchanged plan.`;
  22. const EXIT_TOOL_CALL_ID = "toolu_e2e_plan_approval_primary_submit_exit";
  23. const APPROVED_MESSAGE = "User has approved your plan";
  24. const DENIED_MESSAGE = "The plan was not approved by the user.";
  25. let createdPlanFilePath: string | null = null;
  26. describe("conversation session plan approval primary submit", () => {
  27. after(async () => {
  28. if (createdPlanFilePath) {
  29. await rm(createdPlanFilePath, { force: true });
  30. }
  31. await browser.electron.restoreAllMocks();
  32. await clearAppData();
  33. });
  34. it("空反馈时只点击 footer 主提交应批准 ExitPlanMode", async function () {
  35. this.timeout(120_000);
  36. // Bug 根因:formal case 仍从 legacy store 读 session/运行态,
  37. // V4 pane 转正后这些证据不再是权威投影。
  38. await prepareV4ConversationE2E();
  39. await switchV4Mode("yolo");
  40. const runId = Date.now();
  41. const prompt = [
  42. `${PROMPT_MARKER}_${runId}: enter plan mode and request approval.`,
  43. `${ENTER_MARKER}: call EnterPlanMode before drafting.`,
  44. `${EXIT_MARKER}: call ExitPlanMode with the proposed plan.`,
  45. ].join(" ");
  46. await sendV4Prompt(prompt);
  47. await waitForEmptyV4Composer();
  48. await waitForV4TimelineContaining(PROMPT_MARKER);
  49. const activeTask = await waitForV4Pane(
  50. (snapshot) => snapshot.sessionId !== null && snapshot.sessionId !== "draft",
  51. "plan approval primary submit 没有创建 session",
  52. 30_000,
  53. );
  54. const sessionId = activeTask.sessionId;
  55. if (!sessionId || sessionId === "draft") {
  56. throw new Error("plan approval primary submit sessionId 为空");
  57. }
  58. createdPlanFilePath = join(DEFAULT_WORKSPACE, ".zcode", "plans", `plan-${sessionId}.md`);
  59. await waitForUpstreamRequest(
  60. {
  61. includes: [PROMPT_MARKER, ENTER_MARKER, EXIT_MARKER],
  62. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  63. },
  64. "plan approval primary submit initial request",
  65. 60_000,
  66. );
  67. // EnterPlanMode 是瞬时状态,fast replay 下 UI 行可能在查询前已被 ExitPlanMode 替换;
  68. // 第二次 provider 请求携带 EnterPlanMode tool id,才是进入 plan mode 的稳定协议证据。
  69. await waitForUpstreamRequest(
  70. {
  71. includes: [EXIT_MARKER, "toolu_e2e_plan_approval_primary_submit_enter"],
  72. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  73. },
  74. "plan approval primary submit ExitPlanMode request",
  75. 60_000,
  76. );
  77. await waitForToolCallBlockByToolName("ExitPlanMode", 60_000);
  78. await waitForPlanApprovalDialog(60_000);
  79. // Todo151:工具进入直接开启草稿标记,不能把原有完全访问权限改成 plan/build。
  80. await browser.waitUntil(async () => (await getV4ConfigProjection()).planEnabled === true, {
  81. timeout: 10000,
  82. timeoutMsg: "EnterPlanMode 结果未开启输入框 Plan 标记",
  83. });
  84. expect((await getV4ConfigProjection()).mode).toBe("yolo");
  85. expect(await readPlanApprovalCustomInputSemantics()).toEqual({
  86. tagName: "TEXTAREA",
  87. rows: "1",
  88. autoSizing: true,
  89. maxVisibleLines: 5,
  90. index: "2.",
  91. indexVisible: true,
  92. indexCenteredOnFirstLine: true,
  93. });
  94. // Q21 回归点:ExitPlanMode 与普通 AskUserQuestion 隔离,批准项会获得真实
  95. // 键盘焦点,但焦点本身不会提前写成已选答案。
  96. await expectApproveOptionInitiallyFocused();
  97. // 这里只点击 footer 的“提交”,
  98. // 避免把直接点击批准选项的既有正常路径误当成主提交按钮覆盖。
  99. await clickPrimarySubmitWithoutSelectingApprove();
  100. await waitForPlanApprovalDialogClosed(30_000);
  101. await browser.waitUntil(async () => (await getV4ConfigProjection()).planEnabled === false, {
  102. timeout: 10000,
  103. timeoutMsg: "批准结果未清除输入框 Plan 标记",
  104. });
  105. expect((await getV4ConfigProjection()).mode).toBe("yolo");
  106. const planFileContent = await waitForPlanFileContent(createdPlanFilePath, 30_000);
  107. expect(planFileContent).toBe(APPROVED_PLAN_TEXT);
  108. await waitForUpstreamRequest(
  109. {
  110. includes: [EXIT_TOOL_CALL_ID, APPROVED_PLAN_TEXT, APPROVED_MESSAGE],
  111. excludes: [DENIED_MESSAGE, "Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  112. },
  113. "plan approval primary submit continuation request",
  114. 60_000,
  115. );
  116. await waitForV4AssistantMessageContaining(E2E_REPLY_TOKEN);
  117. await waitForV4Pane(
  118. (snapshot) => snapshot.sessionId === sessionId && !snapshot.canStop,
  119. "plan approval primary submit continuation 没有结束",
  120. 60_000,
  121. );
  122. });
  123. });
  124. async function waitForEmptyV4Composer() {
  125. let latest: string | null = null;
  126. await browser.waitUntil(
  127. async () => {
  128. latest = await getV4ComposerText();
  129. return latest === "";
  130. },
  131. {
  132. timeout: 30_000,
  133. timeoutMsg: `plan approval primary submit 首发后输入框没有清空; latest=${JSON.stringify(latest)}`,
  134. },
  135. );
  136. }
  137. async function waitForPlanApprovalDialog(timeoutMs: number) {
  138. let latestDialogText = "";
  139. await browser.waitUntil(
  140. async () => {
  141. latestDialogText = await browser.execute(() => {
  142. const body = document.querySelector<HTMLElement>('[data-elicitation-dialog-body="true"]');
  143. const footer = document.querySelector<HTMLElement>(
  144. '[data-elicitation-dialog-footer="true"]',
  145. );
  146. return [body?.innerText, footer?.innerText].filter(Boolean).join("\n");
  147. });
  148. return ["Approve", "批准"].some((text) => latestDialogText.includes(text));
  149. },
  150. {
  151. timeout: timeoutMs,
  152. timeoutMsg: `ExitPlanMode 计划审批弹窗没有出现; latest=${latestDialogText}`,
  153. },
  154. );
  155. }
  156. function readPlanApprovalCustomInputSemantics() {
  157. return browser.execute(() => {
  158. const textarea = document.querySelector<HTMLTextAreaElement>(
  159. '[data-elicitation-dialog-body="true"] textarea',
  160. );
  161. const index = textarea?.previousElementSibling;
  162. const style = textarea ? getComputedStyle(textarea) : null;
  163. const indexRect = index?.getBoundingClientRect();
  164. return {
  165. tagName: textarea?.tagName ?? null,
  166. rows: textarea?.getAttribute("rows") ?? null,
  167. autoSizing: textarea?.classList.contains("field-sizing-content") ?? false,
  168. maxVisibleLines: textarea
  169. ? parseFloat(getComputedStyle(textarea).maxHeight) /
  170. parseFloat(getComputedStyle(textarea).lineHeight)
  171. : null,
  172. index: index?.textContent ?? null,
  173. indexCenteredOnFirstLine: Boolean(
  174. textarea &&
  175. style &&
  176. indexRect &&
  177. Math.abs(
  178. indexRect.top +
  179. indexRect.height / 2 -
  180. (textarea.getBoundingClientRect().top +
  181. parseFloat(style.borderTopWidth) +
  182. parseFloat(style.paddingTop) +
  183. parseFloat(style.lineHeight) / 2),
  184. ) <= 0.5,
  185. ),
  186. indexVisible: Boolean(
  187. index &&
  188. index.getBoundingClientRect().width > 0 &&
  189. getComputedStyle(index).visibility !== "hidden" &&
  190. index.getAttribute("aria-hidden") !== "true",
  191. ),
  192. };
  193. });
  194. }
  195. async function expectApproveOptionInitiallyFocused() {
  196. let latest: {
  197. activeText: string;
  198. approveFound: boolean;
  199. approveSelected: boolean;
  200. focusedIsApprove: boolean;
  201. } | null = null;
  202. await browser.waitUntil(
  203. async () => {
  204. latest = await browser.execute(() => {
  205. const normalizeText = (value: string | null | undefined) =>
  206. (value ?? "").replace(/\u00a0/g, " ").trim();
  207. const body = document.querySelector<HTMLElement>('[data-elicitation-dialog-body="true"]');
  208. const approve = Array.from(
  209. body?.querySelectorAll<HTMLButtonElement>('button[role="option"]') ?? [],
  210. ).find((button) =>
  211. ["Approve", "批准"].some((label) => normalizeText(button.textContent).includes(label)),
  212. );
  213. return {
  214. activeText: normalizeText((document.activeElement as HTMLElement | null)?.textContent),
  215. approveFound: Boolean(approve),
  216. approveSelected: approve?.getAttribute("aria-selected") === "true",
  217. focusedIsApprove: document.activeElement === approve,
  218. };
  219. });
  220. return latest.approveFound && latest.focusedIsApprove && !latest.approveSelected;
  221. },
  222. {
  223. timeout: 10_000,
  224. timeoutMsg: `ExitPlanMode 批准项没有获得初始真实焦点,或被提前选中; latest=${JSON.stringify(latest)}`,
  225. },
  226. );
  227. }
  228. async function clickPrimarySubmitWithoutSelectingApprove() {
  229. const result = await browser.execute(() => {
  230. const normalizeText = (value: string | null | undefined) =>
  231. (value ?? "").replace(/\u00a0/g, " ").trim();
  232. const body = document.querySelector<HTMLElement>('[data-elicitation-dialog-body="true"]');
  233. const footer = document.querySelector<HTMLElement>('[data-elicitation-dialog-footer="true"]');
  234. const approveOption = Array.from(
  235. body?.querySelectorAll<HTMLButtonElement>('button[role="option"]') ?? [],
  236. ).find((button) =>
  237. ["Approve", "批准"].some((label) => normalizeText(button.textContent).includes(label)),
  238. );
  239. const buttons = Array.from(footer?.querySelectorAll<HTMLButtonElement>("button") ?? []);
  240. const submitButton = buttons.find((button) =>
  241. ["Submit", "提交"].includes(normalizeText(button.textContent)),
  242. );
  243. const customAnswer = body?.querySelector<HTMLTextAreaElement>("textarea")?.value ?? null;
  244. if (submitButton && !submitButton.disabled && customAnswer === "") {
  245. submitButton.click();
  246. }
  247. return {
  248. approveOptionFound: Boolean(approveOption),
  249. approveOptionSelected: approveOption?.getAttribute("aria-selected") === "true",
  250. customAnswer,
  251. submitButtonClicked: Boolean(submitButton && !submitButton.disabled && customAnswer === ""),
  252. };
  253. });
  254. expect(result).toEqual({
  255. approveOptionFound: true,
  256. approveOptionSelected: false,
  257. customAnswer: "",
  258. submitButtonClicked: true,
  259. });
  260. }
  261. async function waitForPlanApprovalDialogClosed(timeoutMs: number) {
  262. await browser.waitUntil(
  263. async () =>
  264. !(await browser.execute(() =>
  265. Boolean(document.querySelector('[data-elicitation-dialog-footer="true"]')),
  266. )),
  267. {
  268. timeout: timeoutMs,
  269. timeoutMsg: "点击 footer 主提交后 ExitPlanMode 计划审批弹窗没有关闭",
  270. },
  271. );
  272. }
  273. async function waitForPlanFileContent(planFilePath: string, timeoutMs: number) {
  274. let latestError = "";
  275. await browser.waitUntil(
  276. async () => {
  277. try {
  278. return (await readFile(planFilePath, "utf8")) === APPROVED_PLAN_TEXT;
  279. } catch (error) {
  280. latestError = error instanceof Error ? error.message : String(error);
  281. return false;
  282. }
  283. },
  284. {
  285. timeout: timeoutMs,
  286. timeoutMsg: `主提交批准后的 plan 没有写入 ${planFilePath}: ${latestError}`,
  287. },
  288. );
  289. return readFile(planFilePath, "utf8");
  290. }