conversation-session-subagent-legacy-part-cold-load.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. import { DatabaseSync } from "node:sqlite";
  2. import { join } from "node:path";
  3. import {
  4. TID_CHAT_TOOL_CALL_BLOCK,
  5. TID_TASK_ITEM,
  6. TID_V4_SUBAGENT_OPEN_SIDE_PANE,
  7. testId,
  8. } from "@zcode/shared/test-ids";
  9. import { releaseControlledReplay, waitForControlledReplay } from "#e2e/helpers/controlled-replay";
  10. import { clearAppData, getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  11. import { waitForUpstreamRequest } from "#e2e/helpers/conversation-session-network";
  12. import { expandAssistantHistoriesWithContent } from "#e2e/helpers/conversation-session-tool";
  13. import { ensureToolCrossProductFullAccessMode } from "#e2e/helpers/conversation-session-tool-cross-product";
  14. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  15. import {
  16. getV4PaneSnapshot,
  17. prepareV4ConversationE2E,
  18. sendV4PromptAndWaitAccepted,
  19. waitForV4AssistantMessageContaining,
  20. waitForV4Pane,
  21. } from "#e2e/helpers/v4-conversation";
  22. const PARENT = "E2E_SAT31_PARENT";
  23. const PARENT_LAUNCHED = "E2E_SAT31_PARENT_LAUNCHED";
  24. const NOTIFICATION_DONE = "E2E_SAT31_NOTIFICATION_DONE";
  25. const SYNC_DONE = "E2E_SAT31_SYNC_DONE";
  26. const BG_DONE = "E2E_SAT31_BG_DONE";
  27. const SYNC_CALL = "toolu_e2e_sat31_sync";
  28. const BG_CALL = "toolu_e2e_sat31_bg";
  29. const BG_CHILD_FIXTURE = "conversation-session-subagent-legacy-part-cold-load-background-child";
  30. // Agent 工具结算时新写进 part.metadata 的结构化字段;升级前写下的 part 没有它们。
  31. const STRUCTURED_FACT_KEYS = ["agentId", "childSessionId", "outputFile", "background"] as const;
  32. const paths = getE2EAppDataPaths();
  33. interface ChildEntry {
  34. childSessionId: string;
  35. toolCallId: string | null;
  36. }
  37. // 回归 2026-11-11(!3624 评审 CR-01):冷加载只读结构化字段时,升级前写下的 Agent part(只有回执文本)
  38. // 都没有子会话入口。当前版本先跑出真实的 Agent part,重启时在进程退出后删掉结构化字段,得到与升级前
  39. // 一样的数据:回执文本不变,part.metadata 里没有这些字段。
  40. describe("SAT31 升级前的 Agent part 冷加载", () => {
  41. after(async () => {
  42. await browser.electron.restoreAllMocks();
  43. await clearAppData();
  44. });
  45. it("SAT31: 没有结构化字段的旧 Agent part 冷加载后仍带各自的子会话入口", async function () {
  46. this.timeout(300000);
  47. await prepareV4ConversationE2E();
  48. await ensureToolCrossProductFullAccessMode();
  49. await sendV4PromptAndWaitAccepted(
  50. `${PARENT}: call Agent once in the foreground, then once in the background, then finish.`,
  51. PARENT,
  52. "SAT31 首轮用户消息没有进入 timeline",
  53. 90000,
  54. );
  55. await waitForV4AssistantMessageContaining(PARENT_LAUNCHED, 90000);
  56. await waitForV4Pane((state) => !state.canStop, "SAT31 首轮没有收口", 30000);
  57. // 后台 child 停在半途,父 turn 先收口;释放后完成通知单独唤醒父会话。
  58. await waitForControlledReplay(BG_CHILD_FIXTURE);
  59. await releaseControlledReplay(BG_CHILD_FIXTURE);
  60. await waitForV4AssistantMessageContaining(NOTIFICATION_DONE, 120000);
  61. await waitForV4Pane((state) => !state.canStop, "SAT31 完成通知轮没有收口", 30000);
  62. await waitForUpstreamRequest(
  63. { includes: [PARENT, BG_DONE, "<task-notification>", "<status>completed</status>"] },
  64. "后台 Agent 的完成通知没有回到父模型",
  65. 30000,
  66. );
  67. const parentId = (await getV4PaneSnapshot()).sessionId;
  68. if (!parentId) throw new Error("missing parent session");
  69. const children = readAgentChildren(parentId);
  70. expect(Object.keys(children).sort()).toEqual([BG_CALL, SYNC_CALL]);
  71. const expected = [
  72. { childSessionId: children[SYNC_CALL]!, toolCallId: SYNC_CALL },
  73. { childSessionId: children[BG_CALL]!, toolCallId: BG_CALL },
  74. ];
  75. expect(await waitForChildEntries(expected, "实时 Agent 卡片没有子会话入口")).toEqual(expected);
  76. // 真正重启 CLI;进程树退出后、新进程启动前没有别的写入方,在这里把 part 改成升级前的样子。
  77. let stripped: string[] = [];
  78. await restartIntoWorkspacePreservingProfile(paths.workspace, {
  79. afterElectronProcessExit: () => {
  80. stripped = stripStructuredAgentFacts(parentId);
  81. },
  82. });
  83. expect(stripped.sort()).toEqual([BG_CALL, SYNC_CALL]);
  84. const parent = $(`[data-testid="${testId(TID_TASK_ITEM, parentId)}"]`);
  85. await parent.waitForDisplayed({ timeout: 30000 });
  86. await parent.click();
  87. await waitForV4AssistantMessageContaining(NOTIFICATION_DONE, 30000);
  88. // 修复点:没有结构化字段的旧 part 按原来的逻辑读回执文本里的 agentId 行,两张卡片都带各自的入口。
  89. expect(await waitForChildEntries(expected, "旧 Agent part 冷加载后没有子会话入口")).toEqual(
  90. expected,
  91. );
  92. // 入口能打开对应 child 的历史。
  93. expect(await openChildAndReadAssistantText(children[SYNC_CALL]!)).toContain(SYNC_DONE);
  94. expect(await openChildAndReadAssistantText(children[BG_CALL]!)).toContain(BG_DONE);
  95. });
  96. });
  97. /** 父会话里每个 Agent 调用的 child session(当前版本写在 part.metadata 上)。 */
  98. function readAgentChildren(parentId: string): Record<string, string> {
  99. const db = new DatabaseSync(join(paths.storageRoot, "cli", "db", "db.sqlite"), {
  100. readOnly: true,
  101. });
  102. try {
  103. const rows = db.prepare("SELECT data FROM part WHERE session_id = ?").all(parentId) as {
  104. data: string;
  105. }[];
  106. const children: Record<string, string> = {};
  107. for (const row of rows) {
  108. const part = JSON.parse(row.data) as {
  109. callID?: string;
  110. metadata?: Record<string, unknown>;
  111. tool?: string;
  112. type?: string;
  113. };
  114. const childSessionId = part.metadata?.childSessionId;
  115. if (part.type === "tool" && part.tool === "Agent" && part.callID) {
  116. if (typeof childSessionId !== "string") {
  117. throw new Error(`当前版本的 Agent part 没有结构化 childSessionId: ${part.callID}`);
  118. }
  119. children[part.callID] = childSessionId;
  120. }
  121. }
  122. return children;
  123. } finally {
  124. db.close();
  125. }
  126. }
  127. /**
  128. * 删掉父会话 Agent part 上本次新增的结构化字段,返回改过的 tool call id。
  129. * 先确认字段齐全、回执文本里有 agentId 行:删掉之后的 part 与升级前写下的一样。
  130. */
  131. function stripStructuredAgentFacts(parentId: string): string[] {
  132. // node:sqlite 只有同步 API;只在 Electron 进程树退出后、新进程启动前的离线窗口里改写。
  133. const db = new DatabaseSync(join(paths.storageRoot, "cli", "db", "db.sqlite"));
  134. const stripped: string[] = [];
  135. try {
  136. db.exec("BEGIN IMMEDIATE");
  137. const rows = db.prepare("SELECT id, data FROM part WHERE session_id = ?").all(parentId) as {
  138. data: string;
  139. id: string;
  140. }[];
  141. const update = db.prepare("UPDATE part SET data = ? WHERE id = ?");
  142. for (const row of rows) {
  143. const part = JSON.parse(row.data) as {
  144. callID: string;
  145. metadata?: Record<string, unknown>;
  146. state?: { output?: unknown; status?: string };
  147. tool?: string;
  148. type?: string;
  149. };
  150. if (part.type !== "tool" || part.tool !== "Agent") continue;
  151. const metadata = part.metadata ?? {};
  152. for (const key of ["agentId", "childSessionId", "outputFile"] as const) {
  153. if (typeof metadata[key] !== "string") {
  154. throw new Error(`Agent part ${part.callID} 缺少结构化字段 ${key}`);
  155. }
  156. }
  157. if (part.callID === BG_CALL && metadata.background !== true) {
  158. throw new Error("后台 Agent part 缺少 background");
  159. }
  160. const output = part.state?.status === "completed" ? part.state.output : undefined;
  161. if (typeof output !== "string" || !/(?:^|\n)agentId: agent_/u.test(output)) {
  162. throw new Error(`Agent part ${part.callID} 的回执文本没有 agentId 行`);
  163. }
  164. for (const key of STRUCTURED_FACT_KEYS) delete metadata[key];
  165. part.metadata = metadata;
  166. update.run(JSON.stringify(part), row.id);
  167. stripped.push(part.callID);
  168. }
  169. db.exec("COMMIT");
  170. } catch (error) {
  171. db.exec("ROLLBACK");
  172. throw error;
  173. } finally {
  174. db.close();
  175. }
  176. return stripped;
  177. }
  178. /** 页面上全部子会话入口,以及它们所在的 Agent 卡片。 */
  179. async function readChildEntries(): Promise<ChildEntry[]> {
  180. await expandAssistantHistoriesWithContent();
  181. return browser.execute(
  182. (prefix, cardPrefix) =>
  183. Array.from(document.querySelectorAll<HTMLElement>(`[data-testid^="${prefix}-"]`)).map(
  184. (element) => {
  185. const card = element.closest<HTMLElement>(`[data-testid^="${cardPrefix}-"]`);
  186. return {
  187. childSessionId: (element.getAttribute("data-testid") ?? "").slice(prefix.length + 1),
  188. toolCallId: card
  189. ? (card.getAttribute("data-testid") ?? "").slice(cardPrefix.length + 1)
  190. : null,
  191. };
  192. },
  193. ),
  194. TID_V4_SUBAGENT_OPEN_SIDE_PANE,
  195. TID_CHAT_TOOL_CALL_BLOCK,
  196. );
  197. }
  198. async function waitForChildEntries(
  199. expected: readonly ChildEntry[],
  200. timeoutMsg: string,
  201. ): Promise<ChildEntry[]> {
  202. let entries: ChildEntry[] = [];
  203. await browser
  204. .waitUntil(
  205. async () => {
  206. entries = await readChildEntries();
  207. return JSON.stringify(entries) === JSON.stringify(expected);
  208. },
  209. { timeout: 30000, timeoutMsg },
  210. )
  211. .catch(() => undefined);
  212. return entries;
  213. }
  214. /** 点开子会话入口,等右侧 child pane 加载出历史,返回其中 assistant 行的文本。 */
  215. async function openChildAndReadAssistantText(childSessionId: string): Promise<string> {
  216. await browser.execute(
  217. (id) => {
  218. document.querySelector<HTMLElement>(`[data-testid=${JSON.stringify(id)}]`)?.click();
  219. },
  220. testId(TID_V4_SUBAGENT_OPEN_SIDE_PANE, childSessionId),
  221. );
  222. let text = "";
  223. await browser
  224. .waitUntil(
  225. async () => {
  226. text = await browser.execute((id) => {
  227. const pane = Array.from(
  228. document.querySelectorAll<HTMLElement>('[data-testid^="v4-session-pane-"]'),
  229. ).find((candidate) => candidate.dataset.sessionId === id);
  230. const timeline = pane?.querySelector<HTMLElement>('[data-testid="v4-timeline"]');
  231. // 不读 user prompt:child 的任务里已经写了 DONE marker。
  232. return Array.from(timeline?.querySelectorAll<HTMLElement>("[data-row-id]") ?? [])
  233. .filter((row) => row.classList.contains("group/assistant-row"))
  234. .map((row) => row.textContent ?? "")
  235. .join("\n");
  236. }, childSessionId);
  237. return text.length > 0;
  238. },
  239. { timeout: 30000, timeoutMsg: `child ${childSessionId} 的历史没有在右侧打开` },
  240. )
  241. .catch(() => undefined);
  242. return text;
  243. }