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

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