conversation-session-plan-file-compact-continuity.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. import { readFile, rm } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { DEFAULT_WORKSPACE, clearAppData } from "../../../helpers/desktop-app.js";
  4. import type { E2ENetworkCaptureArtifact } from "../../../helpers/network-capture-proxy.js";
  5. import {
  6. E2E_REPLY_TOKEN,
  7. getUpstreamRequestRecordCount,
  8. prepareConversationE2E,
  9. sendPrompt,
  10. waitForAssistantMessageContaining,
  11. waitForChatState,
  12. waitForCompactMarkerStatus,
  13. waitForComposerText,
  14. waitForUpstreamRequest,
  15. waitForToolCallBlockByToolName,
  16. waitForUserMessageContaining,
  17. } from "../../../helpers/conversation-session.js";
  18. const PROMPT_MARKER = "E2E_PLAN_FILE_COMPACT_CONTINUITY";
  19. const ENTER_MARKER = "E2E_PLAN_FILE_COMPACT_ENTER_PLAN";
  20. const EXIT_MARKER = "E2E_PLAN_FILE_COMPACT_EXIT_PLAN";
  21. const PLAN_MARKER = "E2E_PLAN_FILE_COMPACT_PLAN_BODY";
  22. const APPROVED_PLAN_TEXT =
  23. `${PLAN_MARKER}: 1. Persist the approved plan under .zcode/plans. 2. Preserve the plan through manual compact via plan_file_reference.`;
  24. const CHECKPOINT_MARKER = "E2E_PLAN_FILE_COMPACT_CHECKPOINT";
  25. const AFTER_COMPACT_MARKER = "E2E_PLAN_FILE_COMPACT_AFTER";
  26. const EXIT_TOOL_CALL_ID = "toolu_e2e_plan_file_compact_exit_plan_mode";
  27. const COMPACT_REQUEST_SENTINEL = "CRITICAL: Respond with TEXT ONLY";
  28. const PLAN_FILE_REFERENCE_SENTINEL = "A plan file exists from plan mode at:";
  29. const PLAN_CONTENTS_SENTINEL = "Plan contents:";
  30. const PLAN_RELEVANCE_SENTINEL =
  31. "If this plan is relevant to the current work and not already complete, continue working on it.";
  32. describe("conversation session plan file compact continuity", () => {
  33. after(async () => {
  34. await browser.electron.restoreAllMocks();
  35. await clearAppData();
  36. });
  37. it("keeps the approved ExitPlanMode plan visible after manual compact", async function () {
  38. this.timeout(180000);
  39. await rm(join(DEFAULT_WORKSPACE, ".zcode", "plans"), {
  40. force: true,
  41. recursive: true,
  42. });
  43. await prepareConversationE2E();
  44. const runId = Date.now();
  45. const prompt = [
  46. `${PROMPT_MARKER}_${runId}: enter plan mode and request approval.`,
  47. `${ENTER_MARKER}: call EnterPlanMode before drafting.`,
  48. `${EXIT_MARKER}: call ExitPlanMode with the proposed plan.`,
  49. ].join(" ");
  50. await sendPrompt(prompt);
  51. await waitForComposerText("", "plan file compact prompt 发送后输入框没有清空");
  52. await waitForUserMessageContaining(PROMPT_MARKER);
  53. const activeTask = await waitForChatState(
  54. (snapshot) => Boolean(snapshot.sessionId),
  55. "plan file compact case 没有创建 session",
  56. 30000,
  57. );
  58. const sessionId = activeTask.sessionId;
  59. if (!sessionId) {
  60. throw new Error("plan file compact case sessionId 为空");
  61. }
  62. const planFilePath = join(
  63. DEFAULT_WORKSPACE,
  64. ".zcode",
  65. "plans",
  66. `plan-${sessionId}.md`,
  67. );
  68. await waitForUpstreamRequest(
  69. {
  70. includes: [PROMPT_MARKER, ENTER_MARKER, EXIT_MARKER],
  71. excludes: ["Generate a concise title", COMPACT_REQUEST_SENTINEL],
  72. },
  73. "plan file compact initial plan-mode request",
  74. 60000,
  75. );
  76. await waitForToolCallBlockByToolName("EnterPlanMode", 60000);
  77. await waitForUpstreamRequest(
  78. {
  79. includes: [EXIT_MARKER, "toolu_e2e_plan_file_compact_enter_plan_mode"],
  80. excludes: ["Generate a concise title", COMPACT_REQUEST_SENTINEL],
  81. },
  82. "plan file compact exit plan-mode request",
  83. 60000,
  84. );
  85. await waitForToolCallBlockByToolName("ExitPlanMode", 60000);
  86. await waitForElicitationDialogContaining("Approve", 60000);
  87. await approvePlanWithoutFeedback();
  88. const planFileContent = await waitForPlanFileContent(planFilePath);
  89. expect(planFileContent).toBe(APPROVED_PLAN_TEXT);
  90. await waitForUpstreamRequest(
  91. {
  92. includes: [
  93. EXIT_TOOL_CALL_ID,
  94. APPROVED_PLAN_TEXT,
  95. "User has approved your plan",
  96. ],
  97. excludes: ["Generate a concise title", COMPACT_REQUEST_SENTINEL],
  98. },
  99. "plan file compact approval continuation request",
  100. 60000,
  101. );
  102. await waitForAssistantMessageContaining(E2E_REPLY_TOKEN);
  103. await waitForIdle("plan approval continuation 没有结束");
  104. const checkpointPrompt = `${CHECKPOINT_MARKER}_${runId}: reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  105. await sendPrompt(checkpointPrompt);
  106. await waitForComposerText("", "plan file compact checkpoint 发送后输入框没有清空");
  107. await waitForUpstreamRequest(
  108. {
  109. includes: [CHECKPOINT_MARKER, APPROVED_PLAN_TEXT],
  110. excludes: ["Generate a concise title", COMPACT_REQUEST_SENTINEL],
  111. },
  112. "plan file compact checkpoint request",
  113. 60000,
  114. );
  115. await waitForAssistantMessageContaining(E2E_REPLY_TOKEN);
  116. await waitForIdle("plan file compact checkpoint 没有结束");
  117. const compactRequestStartIndex = await getUpstreamRequestRecordCount();
  118. await sendPrompt("/compact");
  119. await waitForComposerText("", "plan file compact /compact 发送后输入框没有清空");
  120. const startedMarker = await waitForCompactMarkerStatus("started", "manual");
  121. await waitForUpstreamRequest(
  122. {
  123. includes: [COMPACT_REQUEST_SENTINEL, APPROVED_PLAN_TEXT, CHECKPOINT_MARKER],
  124. excludes: ["Generate a concise title"],
  125. },
  126. "plan file compact manual compact request",
  127. 60000,
  128. afterRecordCount(compactRequestStartIndex),
  129. );
  130. const completedMarker = await waitForCompactMarkerStatus(
  131. "completed",
  132. "manual",
  133. startedMarker.inputId,
  134. );
  135. expect(completedMarker.operationId).toBeTruthy();
  136. const afterCompactRequestStartIndex = await getUpstreamRequestRecordCount();
  137. const afterCompactPrompt = `${AFTER_COMPACT_MARKER}_${runId}: reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  138. await sendPrompt(afterCompactPrompt);
  139. await waitForComposerText("", "plan file compact 后续输入发送后输入框没有清空");
  140. await waitForUpstreamRequest(
  141. {
  142. // 修复原因:plan file 路径在 Windows 捕获里使用反斜杠,等待条件只校验语义;
  143. // 下面会用平台原生 planFilePath 精确断言完整路径。
  144. includes: [
  145. AFTER_COMPACT_MARKER,
  146. PLAN_FILE_REFERENCE_SENTINEL,
  147. PLAN_CONTENTS_SENTINEL,
  148. APPROVED_PLAN_TEXT,
  149. PLAN_RELEVANCE_SENTINEL,
  150. ],
  151. excludes: ["Generate a concise title", COMPACT_REQUEST_SENTINEL],
  152. },
  153. "plan file compact post-compact provider request",
  154. 60000,
  155. afterRecordCount(afterCompactRequestStartIndex),
  156. );
  157. await waitForAssistantMessageContaining(E2E_REPLY_TOKEN);
  158. await waitForIdle("plan file compact 后续请求没有结束");
  159. await expectNoVisibleChatErrorBanner();
  160. const postCompactRequest = await readLatestUpstreamRequestContaining([
  161. AFTER_COMPACT_MARKER,
  162. PLAN_FILE_REFERENCE_SENTINEL,
  163. PLAN_CONTENTS_SENTINEL,
  164. APPROVED_PLAN_TEXT,
  165. PLAN_RELEVANCE_SENTINEL,
  166. ]);
  167. expect(captureContainsText(postCompactRequest?.requestJson, planFilePath)).toBe(
  168. true,
  169. );
  170. expect(captureContainsText(postCompactRequest?.requestJson, APPROVED_PLAN_TEXT)).toBe(
  171. true,
  172. );
  173. });
  174. });
  175. async function waitForElicitationDialogContaining(
  176. text: string,
  177. timeoutMs: number,
  178. ) {
  179. const expectedTexts = expandElicitationDialogTextAlternatives(text);
  180. let latestDialogText = "";
  181. await browser.waitUntil(
  182. async () => {
  183. // 修复原因:ExitPlanMode 的批准/忽略选项渲染在 footer,body 只包含计划正文。
  184. // 旧等待只查 body,会在真实弹窗已出现时继续等到超时。
  185. latestDialogText = await browser.execute(() => {
  186. const body = document.querySelector<HTMLElement>(
  187. "[data-elicitation-dialog-body='true']",
  188. );
  189. const footer = document.querySelector<HTMLElement>(
  190. "[data-elicitation-dialog-footer='true']",
  191. );
  192. return [body?.innerText, footer?.innerText].filter(Boolean).join("\n");
  193. });
  194. return expectedTexts.some((expectedText) =>
  195. latestDialogText.includes(expectedText),
  196. );
  197. },
  198. {
  199. timeout: timeoutMs,
  200. timeoutMsg: `Timed out waiting for elicitation dialog containing ${expectedTexts.join(
  201. " / ",
  202. )}; latest=${latestDialogText}`,
  203. },
  204. );
  205. }
  206. function expandElicitationDialogTextAlternatives(text: string) {
  207. if (text === "Approve") {
  208. return ["Approve", "批准"];
  209. }
  210. if (text === "Dismiss") {
  211. return ["Dismiss", "忽略"];
  212. }
  213. return [text];
  214. }
  215. async function approvePlanWithoutFeedback() {
  216. const approveButton = await $(
  217. "//button[contains(., 'Approve') or contains(., '批准')]",
  218. );
  219. await approveButton.waitForEnabled({ timeout: 30000 });
  220. await approveButton.click();
  221. }
  222. async function waitForPlanFileContent(planFilePath: string) {
  223. let latestError = "";
  224. await browser.waitUntil(
  225. async () => {
  226. try {
  227. const content = await readFile(planFilePath, "utf8");
  228. return content === APPROVED_PLAN_TEXT;
  229. } catch (error) {
  230. latestError = error instanceof Error ? error.message : String(error);
  231. return false;
  232. }
  233. },
  234. {
  235. timeout: 30000,
  236. timeoutMsg: `批准后的 plan file 没有写入 ${planFilePath}: ${latestError}`,
  237. },
  238. );
  239. return readFile(planFilePath, "utf8");
  240. }
  241. async function waitForIdle(timeoutMsg: string) {
  242. await waitForChatState(
  243. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  244. timeoutMsg,
  245. 60000,
  246. );
  247. }
  248. function afterRecordCount(recordCount: number) {
  249. return recordCount > 0 ? { afterIndex: recordCount - 1 } : {};
  250. }
  251. async function expectNoVisibleChatErrorBanner() {
  252. const bannerText = await browser.execute(() => {
  253. const composerRegion = document.querySelector<HTMLElement>(
  254. "[data-chat-composer-region='true']",
  255. );
  256. if (!composerRegion) {
  257. return "";
  258. }
  259. const errorActionLabels = ["复制完整错误", "Copy full error", "提交反馈", "Feedback"];
  260. const hasErrorActions = Array.from(
  261. composerRegion.querySelectorAll<HTMLButtonElement>("button"),
  262. ).some((button) =>
  263. errorActionLabels.some((label) => button.innerText.includes(label)),
  264. );
  265. return hasErrorActions ? composerRegion.innerText : "";
  266. });
  267. expect(bannerText).toBe("");
  268. }
  269. async function readLatestUpstreamRequestContaining(includes: string[]) {
  270. const artifact = await readCaptureArtifact();
  271. return [...artifact.records].reverse().find(
  272. (record) =>
  273. record.method === "POST" &&
  274. (record.path.includes("/messages") ||
  275. record.path.includes("/chat/completions")) &&
  276. includes.every((text) => captureContainsText(record.requestJson, text)),
  277. );
  278. }
  279. async function readCaptureArtifact(): Promise<E2ENetworkCaptureArtifact> {
  280. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH;
  281. if (!capturePath) {
  282. throw new Error("E2E_PROVIDER_CAPTURE_PATH is not set");
  283. }
  284. return JSON.parse(await readFile(capturePath, "utf8")) as E2ENetworkCaptureArtifact;
  285. }
  286. function captureContainsText(value: unknown, needle: string): boolean {
  287. if (typeof value === "string") {
  288. return value.includes(needle);
  289. }
  290. if (Array.isArray(value)) {
  291. return value.some((item) => captureContainsText(item, needle));
  292. }
  293. if (value && typeof value === "object") {
  294. return Object.values(value).some((item) => captureContainsText(item, needle));
  295. }
  296. return false;
  297. }