conversation-session-background-file-diff.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. // BG41:background Agent 在父 launch turn 已 idle 后完成,独立 model-only turn
  2. // 修改文件时仍必须能用隐藏 messageId 查询 checkpoint 并打开真实 Diff。
  3. // 本 case 只覆盖 local desktop-continuous + 单 Agent + 单文件 Read/Edit;
  4. // active-loop、batch、rewind、cold start、remote/replayable 由 catalog 剪枝。
  5. import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
  6. import { join } from "node:path";
  7. import { TID_PREVIEW_PANE } from "@zcode/shared/test-ids";
  8. import { clearAppData, DEFAULT_WORKSPACE } from "#e2e/helpers/desktop-app";
  9. import {
  10. findFirstUpstreamRequestIndex,
  11. getUpstreamRequestRecordCount,
  12. waitForUpstreamRequest,
  13. } from "#e2e/helpers/conversation-session-network";
  14. import { waitForToolCallBlockByToolCallId } from "#e2e/helpers/conversation-session-tool";
  15. import {
  16. assertVisibleV4UserMessagesNotContaining,
  17. clickV4Stop,
  18. getV4PaneSnapshot,
  19. prepareV4ConversationE2E,
  20. sendV4Prompt,
  21. switchV4Mode,
  22. waitForV4Pane,
  23. waitForV4TimelineContaining,
  24. } from "#e2e/helpers/v4-conversation";
  25. const CASE_ROOT = join(DEFAULT_WORKSPACE, "background-file-diff-e2e");
  26. const RELATIVE_PATH = "background-file-diff-e2e/result.md";
  27. const FILE_PATH = join(DEFAULT_WORKSPACE, RELATIVE_PATH);
  28. const REQUEST_MARKER = "E2E_BACKGROUND_FILE_DIFF";
  29. const CHILD_MARKER = "E2E_BACKGROUND_FILE_DIFF_CHILD_DONE";
  30. const LAUNCH_MARKER = "background-file-diff-agent-launched-ok";
  31. const FINAL_MARKER = "background-file-diff-ok";
  32. const INITIAL_CONTENT = "before-background-diff\n";
  33. const EXPECTED_CONTENT = "after-background-diff\n";
  34. interface FileSummarySnapshot {
  35. diffUnavailable: boolean;
  36. expanded: boolean;
  37. headerText: string;
  38. pathVisible: boolean;
  39. reviewEnabled: boolean;
  40. turnText: string;
  41. }
  42. describe("BG41 background model-only turn 文件 Diff", () => {
  43. afterEach(async () => {
  44. await stopIfBusy();
  45. await rm(CASE_ROOT, { force: true, recursive: true });
  46. });
  47. after(async () => {
  48. await browser.electron.restoreAllMocks();
  49. await clearAppData();
  50. });
  51. it("父 turn idle 后的 notification Read/Edit 摘要可展开并打开真实 before/after Diff", async function () {
  52. this.timeout(240000);
  53. await prepareV4ConversationE2E();
  54. await switchV4Mode("yolo");
  55. await rm(CASE_ROOT, { force: true, recursive: true });
  56. await mkdir(CASE_ROOT, { recursive: true });
  57. await writeFile(FILE_PATH, INITIAL_CONTENT, "utf8");
  58. const firstExistingRecordIndex = (await getUpstreamRequestRecordCount()) - 1;
  59. await sendV4Prompt(
  60. `${REQUEST_MARKER}: launch one background Agent, then update ${RELATIVE_PATH} only after its completion notification.`,
  61. );
  62. await waitForToolCallBlockByToolCallId("toolu_e2e_background_file_diff_agent", 60000);
  63. await waitForUpstreamRequest(
  64. {
  65. lastUserMessageIncludes: ["E2E_BACKGROUND_FILE_DIFF_CHILD"],
  66. },
  67. "BG41 background child provider request 没有开始",
  68. 60000,
  69. { afterIndex: firstExistingRecordIndex },
  70. );
  71. await waitForV4TimelineContaining(LAUNCH_MARKER, 60000);
  72. await waitForV4Pane(
  73. (snapshot) =>
  74. snapshot.sessionId !== null && snapshot.sessionId !== "draft" && !snapshot.canStop,
  75. "BG41 父 launch turn 没有在 child completion 前回到 idle",
  76. 45000,
  77. );
  78. // Bug 复现前提:必须先观察到父轮稳定 idle,再允许 child 的延迟响应完成;
  79. // 否则 notification 可能合流 active loop,无法覆盖 model-only 隐藏 messageId。
  80. await browser.pause(500);
  81. expect((await getV4PaneSnapshot()).canStop).toBe(false);
  82. expect(
  83. await findFirstUpstreamRequestIndex(
  84. {
  85. includes: [REQUEST_MARKER, "<task-notification>", CHILD_MARKER],
  86. lastUserMessageIncludes: ["<task-notification>", CHILD_MARKER],
  87. },
  88. { afterIndex: firstExistingRecordIndex },
  89. ),
  90. ).toBeNull();
  91. await waitForUpstreamRequest(
  92. {
  93. includes: [REQUEST_MARKER, "<task-notification>", CHILD_MARKER],
  94. lastUserMessageIncludes: ["<task-notification>", CHILD_MARKER],
  95. },
  96. "BG41 child completion 没有触发独立 model-only notification request",
  97. 60000,
  98. { afterIndex: firstExistingRecordIndex },
  99. );
  100. await waitForUpstreamRequest(
  101. {
  102. includes: ["toolu_e2e_background_file_diff_read", "before-background-diff"],
  103. },
  104. "BG41 Read 结果没有进入 notification product turn",
  105. 60000,
  106. { afterIndex: firstExistingRecordIndex },
  107. );
  108. await waitForToolCallBlockByToolCallId("toolu_e2e_background_file_diff_edit", 60000);
  109. await waitForV4TimelineContaining(FINAL_MARKER, 90000);
  110. await waitForFileContent(EXPECTED_CONTENT);
  111. await waitForV4Pane(
  112. (snapshot) => !snapshot.canStop,
  113. "BG41 notification Read/Edit 完成后没有回到 idle",
  114. 60000,
  115. );
  116. await assertVisibleV4UserMessagesNotContaining("<task-notification>");
  117. await assertVisibleV4UserMessagesNotContaining(CHILD_MARKER);
  118. const collapsed = await waitForFileSummary(false);
  119. expect(collapsed.headerText).toMatch(/1 (file changed|个文件已更改)/);
  120. expect(collapsed.headerText).toContain("+1");
  121. expect(collapsed.headerText).toContain("-1");
  122. expect(collapsed.turnText).toContain(FINAL_MARKER);
  123. await expandFileSummary();
  124. const expanded = await waitForFileSummary(true);
  125. expect(expanded.pathVisible).toBe(true);
  126. expect(expanded.reviewEnabled).toBe(true);
  127. expect(expanded.diffUnavailable).toBe(false);
  128. expect(expanded.turnText).toContain(FINAL_MARKER);
  129. await clickFileSummaryReview();
  130. await waitForPreviewDiff();
  131. });
  132. });
  133. async function stopIfBusy() {
  134. const snapshot = await getV4PaneSnapshot().catch(() => null);
  135. if (!snapshot?.canStop) return;
  136. await clickV4Stop().catch(() => undefined);
  137. await waitForV4Pane(
  138. (candidate) => !candidate.canStop,
  139. "BG41 清理阶段主会话没有退出 running",
  140. 30000,
  141. ).catch(() => undefined);
  142. }
  143. async function waitForFileContent(expected: string) {
  144. await browser.waitUntil(
  145. async () => (await readFile(FILE_PATH, "utf8").catch(() => "")) === expected,
  146. {
  147. timeout: 60000,
  148. timeoutMsg: `${FILE_PATH} 没有收敛到期望内容`,
  149. },
  150. );
  151. }
  152. async function waitForFileSummary(expectExpanded: boolean): Promise<FileSummarySnapshot> {
  153. let latest: FileSummarySnapshot | null = null;
  154. await browser.waitUntil(
  155. async () => {
  156. latest = await readFileSummary();
  157. return Boolean(
  158. latest &&
  159. latest.expanded === expectExpanded &&
  160. (!expectExpanded ||
  161. (latest.pathVisible && latest.reviewEnabled && !latest.diffUnavailable)),
  162. );
  163. },
  164. {
  165. timeout: 30000,
  166. timeoutMsg: expectExpanded
  167. ? `BG41 文件摘要展开后没有返回 ${RELATIVE_PATH} 的可审查 Diff`
  168. : "BG41 notification 产品轮次没有显示文件变更摘要",
  169. },
  170. );
  171. if (!latest) throw new Error("BG41 文件变更摘要快照为空");
  172. return latest;
  173. }
  174. function readFileSummary(): Promise<FileSummarySnapshot | null> {
  175. return browser.execute((relativePath) => {
  176. const expandLabels = new Set(["Expand changed files", "展开已更改文件"]);
  177. const collapseLabels = new Set(["Collapse changed files", "收起已更改文件"]);
  178. const reviewLabels = new Set(["Review", "审查"]);
  179. const header = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find(
  180. (button) => {
  181. const label = button.getAttribute("aria-label") ?? "";
  182. return expandLabels.has(label) || collapseLabels.has(label);
  183. },
  184. );
  185. if (!header) return null;
  186. const card = header.parentElement?.parentElement;
  187. const turn = header.closest<HTMLElement>("[data-turn-key]");
  188. const label = header.getAttribute("aria-label") ?? "";
  189. const review = Array.from(card?.querySelectorAll<HTMLButtonElement>("button") ?? []).find(
  190. (button) => reviewLabels.has(button.getAttribute("aria-label") ?? ""),
  191. );
  192. const cardText = (card?.innerText ?? "").replace(/\u00a0/g, " ");
  193. return {
  194. diffUnavailable:
  195. cardText.includes("暂时无法预览这份 Diff") ||
  196. cardText.includes("Diff preview is temporarily unavailable"),
  197. expanded: collapseLabels.has(label),
  198. headerText: (header.innerText ?? "").replace(/\u00a0/g, " ").trim(),
  199. pathVisible: Boolean(
  200. card &&
  201. Array.from(card.querySelectorAll<HTMLElement>("[title]")).some((element) =>
  202. (element.getAttribute("title") ?? "").endsWith(relativePath),
  203. ),
  204. ),
  205. reviewEnabled: Boolean(review && !review.disabled),
  206. turnText: (turn?.innerText ?? "").replace(/\u00a0/g, " ").trim(),
  207. };
  208. }, RELATIVE_PATH);
  209. }
  210. async function expandFileSummary() {
  211. const clicked = await browser.execute(() => {
  212. const labels = new Set(["Expand changed files", "展开已更改文件"]);
  213. const header = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find(
  214. (button) => labels.has(button.getAttribute("aria-label") ?? ""),
  215. );
  216. header?.click();
  217. return Boolean(header);
  218. });
  219. expect(clicked).toBe(true);
  220. }
  221. async function clickFileSummaryReview() {
  222. const clicked = await browser.execute(() => {
  223. const collapseLabels = new Set(["Collapse changed files", "收起已更改文件"]);
  224. const reviewLabels = new Set(["Review", "审查"]);
  225. const header = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find(
  226. (button) => collapseLabels.has(button.getAttribute("aria-label") ?? ""),
  227. );
  228. const card = header?.parentElement?.parentElement;
  229. const review = Array.from(card?.querySelectorAll<HTMLButtonElement>("button") ?? []).find(
  230. (button) => reviewLabels.has(button.getAttribute("aria-label") ?? ""),
  231. );
  232. if (!review || review.disabled) return false;
  233. review.click();
  234. return true;
  235. });
  236. expect(clicked).toBe(true);
  237. }
  238. async function waitForPreviewDiff() {
  239. let latest = "";
  240. await browser.waitUntil(
  241. async () => {
  242. latest = await browser.execute((previewPaneTestId) => {
  243. const preview = document.querySelector<HTMLElement>(`[data-testid="${previewPaneTestId}"]`);
  244. if (!preview) return "";
  245. // 原因:文件标题已通过 portal 放到 FileManager 共享头部,不能只在 PreviewPane body 内找文件名。
  246. const fileManager = preview.closest<HTMLElement>("[data-file-manager-pane]");
  247. const fragments: string[] = [fileManager?.innerText ?? preview.innerText ?? ""];
  248. const visit = (root: ParentNode) => {
  249. for (const element of Array.from(root.querySelectorAll<HTMLElement>("*"))) {
  250. if (!element.shadowRoot) continue;
  251. fragments.push(element.shadowRoot.textContent ?? "");
  252. visit(element.shadowRoot);
  253. }
  254. };
  255. visit(preview);
  256. return fragments.join("\n").replace(/\u00a0/g, " ");
  257. }, TID_PREVIEW_PANE);
  258. return (
  259. latest.includes("result.md") &&
  260. latest.includes("before-background-diff") &&
  261. latest.includes("after-background-diff")
  262. );
  263. },
  264. {
  265. timeout: 30000,
  266. timeoutMsg: `BG41 Review 没有打开真实 before/after Diff: ${latest}`,
  267. },
  268. );
  269. }