conversation-session-subagent-cold-failed-resume.test.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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_ROW,
  7. TID_V4_SUBAGENT_OPEN_SIDE_PANE,
  8. testId,
  9. } from "@zcode/shared/test-ids";
  10. import { releaseControlledReplay, waitForControlledReplay } from "#e2e/helpers/controlled-replay";
  11. import { clearAppData, getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  12. import { waitForUpstreamRequest } from "#e2e/helpers/conversation-session-network";
  13. import {
  14. expandAssistantHistoriesWithContent,
  15. waitForFoldedToolCallBlockByToolCallId,
  16. waitForToolCallBlockByToolCallId,
  17. } from "#e2e/helpers/conversation-session-tool";
  18. import { ensureToolCrossProductFullAccessMode } from "#e2e/helpers/conversation-session-tool-cross-product";
  19. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart";
  20. import {
  21. getV4ComposerBackgroundWorkCounts,
  22. getV4PaneSnapshot,
  23. prepareV4ConversationE2E,
  24. sendV4PromptAndWaitAccepted,
  25. waitForV4AssistantMessageContaining,
  26. waitForV4Pane,
  27. } from "#e2e/helpers/v4-conversation";
  28. const PARENT = "E2E_SAT32_PARENT";
  29. const PARENT_AFTER_FAILURE = "E2E_SAT32_PARENT_AFTER_FAILURE";
  30. const RESUME = "E2E_SAT32_RESUME";
  31. const CHILD_DONE = "E2E_SAT32_CHILD_DONE";
  32. const RESUME_ACK = "E2E_SAT32_RESUME_ACK";
  33. const NOTIFICATION_DONE = "E2E_SAT32_NOTIFICATION_DONE";
  34. const AGENT_CALL = "toolu_e2e_sat32_agent";
  35. const SEND_MESSAGE_CALL = "toolu_e2e_sat32_send_message";
  36. const CHILD_RESUMED_FIXTURE = "subagent-cold-failed-resume-child-resumed";
  37. const paths = getE2EAppDataPaths();
  38. interface ChildEntry {
  39. childSessionId: string;
  40. inAgentCard: boolean;
  41. }
  42. // 回归 2026-11-10:前台 Agent 失败后 App 重启,registry 为空,SendMessage 原来找不到目标;
  43. // 找回后 App 冷加载读不到失败 Agent 的 agentId,续接的运行在 SendMessage 那一轮另起一行。
  44. describe("SAT32 失败的前台 Agent 冷恢复后续接", () => {
  45. after(async () => {
  46. await browser.electron.restoreAllMocks();
  47. await clearAppData();
  48. });
  49. it("SAT32: App 重启后 SendMessage 续接失败的 Agent,仍只有原 Agent 卡片", async function () {
  50. this.timeout(300000);
  51. await prepareV4ConversationE2E();
  52. await ensureToolCrossProductFullAccessMode();
  53. await sendV4PromptAndWaitAccepted(
  54. `${PARENT}: call Agent exactly once in the foreground, then finish.`,
  55. PARENT,
  56. "SAT32 首轮用户消息没有进入 timeline",
  57. 90000,
  58. );
  59. await waitForV4AssistantMessageContaining(PARENT_AFTER_FAILURE, 90000);
  60. await waitForV4Pane((state) => !state.canStop, "SAT32 首轮没有收口", 30000);
  61. await waitForUpstreamRequest(
  62. { includes: [PARENT, AGENT_CALL, "agentId: agent_"] },
  63. "同步失败结果没有把 agentId 交给父模型",
  64. 30000,
  65. );
  66. expect((await waitForToolCallBlockByToolCallId(AGENT_CALL, 30000)).status).toBe("failed");
  67. const parentId = (await getV4PaneSnapshot()).sessionId;
  68. if (!parentId) throw new Error("missing parent session");
  69. const [childId] = readChildIds(parentId);
  70. if (!childId) throw new Error("失败的 Agent 没有持久化 subagent_child");
  71. expect(await waitForChildEntries([childId], "实时失败卡片没有子会话入口")).toEqual([
  72. { childSessionId: childId, inAgentCard: true },
  73. ]);
  74. // 真正重启 CLI:registry 清空,父 timeline 只能从 transcript 冷加载。
  75. await restartIntoWorkspacePreservingProfile();
  76. const parent = $(`[data-testid="${testId(TID_TASK_ITEM, parentId)}"]`);
  77. await parent.waitForDisplayed({ timeout: 30000 });
  78. await parent.click();
  79. await waitForV4AssistantMessageContaining(PARENT_AFTER_FAILURE, 30000);
  80. // 修复点:冷加载从 part 上结构化的 agentId / childSessionId 恢复失败卡片的身份与子会话入口。
  81. expect(await waitForChildEntries([childId], "冷加载后失败卡片没有子会话入口")).toEqual([
  82. { childSessionId: childId, inAgentCard: true },
  83. ]);
  84. await sendV4PromptAndWaitAccepted(
  85. `${RESUME}: call SendMessage exactly once for the failed agent, then finish.`,
  86. RESUME,
  87. "SAT32 续接用户消息没有进入 timeline",
  88. 90000,
  89. );
  90. await waitForV4AssistantMessageContaining(RESUME_ACK, 90000);
  91. // 卡片一出现就会被读到,要等父 turn 用正文收口、卡片收进工作记录后再读终态。
  92. expect((await waitForFoldedToolCallBlockByToolCallId(SEND_MESSAGE_CALL, 30000)).status).toBe(
  93. "completed",
  94. );
  95. // 续接进行中:child 的输出停在半途(受控流)。续接的 SubagentSpawned 与后台任务在同一批投影里,
  96. // 等 Composer 出现这一个运行中的 Agent,再检查它挂在原卡片上、没有另起裸 subagent 行。
  97. await waitForControlledReplay(CHILD_RESUMED_FIXTURE);
  98. await browser.waitUntil(
  99. async () => (await getV4ComposerBackgroundWorkCounts())?.subagentCount === 1,
  100. { timeout: 30000, timeoutMsg: "续接的 Agent 没有作为运行中的后台任务出现" },
  101. );
  102. expect(await waitForChildEntries([childId], "续接进行中子会话入口不唯一")).toEqual([
  103. { childSessionId: childId, inAgentCard: true },
  104. ]);
  105. expect(await readBareSubagentRowTexts()).toEqual([]);
  106. await releaseControlledReplay(CHILD_RESUMED_FIXTURE);
  107. await waitForV4AssistantMessageContaining(NOTIFICATION_DONE, 120000);
  108. await waitForV4Pane((state) => !state.canStop, "SAT32 完成通知轮没有收口", 30000);
  109. await waitForUpstreamRequest(
  110. { includes: [RESUME, CHILD_DONE, "<task-notification>", "<status>completed</status>"] },
  111. "续接运行的完成通知没有回到父模型",
  112. 30000,
  113. );
  114. // 修复点:续接的运行回到原 Agent 卡片,不在 SendMessage 那一轮另起裸 subagent 行。
  115. expect(await waitForChildEntries([childId], "续接后子会话入口不唯一")).toEqual([
  116. { childSessionId: childId, inAgentCard: true },
  117. ]);
  118. expect(await readBareSubagentRowTexts()).toEqual([]);
  119. expect(readChildIds(parentId)).toEqual([childId]);
  120. });
  121. });
  122. function readChildIds(parentId: string): string[] {
  123. const db = new DatabaseSync(join(paths.storageRoot, "cli", "db", "db.sqlite"), {
  124. readOnly: true,
  125. });
  126. try {
  127. const rows = db
  128. .prepare("SELECT id FROM session WHERE parent_id = ? AND task_type = 'subagent_child'")
  129. .all(parentId) as { id: string }[];
  130. return rows.map((row) => row.id);
  131. } finally {
  132. db.close();
  133. }
  134. }
  135. /** 页面上全部子会话入口,以及它们是否在原 Agent 卡片里。 */
  136. async function readChildEntries(): Promise<ChildEntry[]> {
  137. await expandAssistantHistoriesWithContent();
  138. return browser.execute(
  139. (prefix, agentCardTestId) =>
  140. Array.from(document.querySelectorAll<HTMLElement>(`[data-testid^="${prefix}-"]`)).map(
  141. (element) => ({
  142. childSessionId: (element.getAttribute("data-testid") ?? "").slice(prefix.length + 1),
  143. inAgentCard: element.closest(`[data-testid="${agentCardTestId}"]`) !== null,
  144. }),
  145. ),
  146. TID_V4_SUBAGENT_OPEN_SIDE_PANE,
  147. testId(TID_CHAT_TOOL_CALL_BLOCK, AGENT_CALL),
  148. );
  149. }
  150. async function waitForChildEntries(
  151. childIds: readonly string[],
  152. timeoutMsg: string,
  153. ): Promise<ChildEntry[]> {
  154. let entries: ChildEntry[] = [];
  155. await browser
  156. .waitUntil(
  157. async () => {
  158. entries = await readChildEntries();
  159. return (
  160. entries.length === childIds.length &&
  161. entries.every((entry, index) => entry.childSessionId === childIds[index])
  162. );
  163. },
  164. { timeout: 30000, timeoutMsg },
  165. )
  166. .catch(() => undefined);
  167. return entries;
  168. }
  169. /**
  170. * 没有和 Agent 卡片配对的 subagent 行只渲染 `<类型> · <状态>` 摘要。
  171. * 状态取 SubagentRow.status 的取值(running / success / failed / cancelled):
  172. * 原来写成 completed,完成后的裸行显示 `· success`,匹配不到,这个检查永远通过。
  173. */
  174. async function readBareSubagentRowTexts(): Promise<string[]> {
  175. await expandAssistantHistoriesWithContent();
  176. return browser.execute(
  177. (rowPrefix) =>
  178. Array.from(document.querySelectorAll<HTMLElement>(`[data-testid^="${rowPrefix}-"]`))
  179. .map((element) => (element.textContent ?? "").trim())
  180. .filter((text) => /^\S+ · (running|success|failed|cancelled)\b/u.test(text)),
  181. TID_V4_ROW,
  182. );
  183. }