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

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