conversation-session-send-message-resume-stop.test.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. import { readFile } from "node:fs/promises";
  2. import { TID_V4_SUBAGENT_OPEN_SIDE_PANE } from "@zcode/shared/test-ids";
  3. import { clearAppData } from "#e2e/helpers/desktop-app";
  4. import { waitForToolCallBlockByToolName } from "#e2e/helpers/conversation-session-tool";
  5. import {
  6. getUpstreamRequestRecordCount,
  7. waitForUpstreamRequest,
  8. } from "#e2e/helpers/conversation-session-network";
  9. import type { E2ENetworkCaptureArtifact } from "#e2e/helpers/network-capture-proxy";
  10. import { ensureToolCrossProductFullAccessMode } from "#e2e/helpers/conversation-session-tool-cross-product";
  11. import {
  12. getV4ComposerBackgroundWorkCounts,
  13. prepareV4ConversationE2E,
  14. sendV4PromptAndWaitAccepted,
  15. waitForV4AssistantMessageContaining,
  16. waitForV4ComposerText,
  17. waitForV4ConversationState,
  18. } from "#e2e/helpers/v4-conversation";
  19. import {
  20. clickRunningSubagentStop,
  21. countVisibleSubagentTabs,
  22. openRunningSubagentCapsule,
  23. readRunningSubagentControls,
  24. type RunningSubagentControl,
  25. } from "#e2e/helpers/subagent-capsule-stop";
  26. const PARENT_MARKER = "E2E_SEND_MESSAGE_RESUME_STOP_PARENT";
  27. const FOREGROUND_DONE = "E2E_SEND_MESSAGE_RESUME_STOP_FOREGROUND_DONE";
  28. const FOREGROUND_PARENT_IDLE = "E2E_SEND_MESSAGE_RESUME_STOP_FOREGROUND_PARENT_IDLE";
  29. const RESUME_MARKER = "E2E_SEND_MESSAGE_RESUME_STOP_RESUME";
  30. const CHILD_DONE = "E2E_SEND_MESSAGE_RESUME_STOP_CHILD_DONE";
  31. const STOP_NOTIFICATION_DONE = "E2E_SEND_MESSAGE_RESUME_STOP_NOTIFICATION_DONE";
  32. describe("SendMessage resume Stop", () => {
  33. after(async () => {
  34. await browser.electron.restoreAllMocks();
  35. await clearAppData();
  36. });
  37. it("SAT12: foreground subagent 完成后由 SendMessage resume 显示 Stop 且可停止", async function () {
  38. this.timeout(240000);
  39. await prepareV4ConversationE2E();
  40. await ensureToolCrossProductFullAccessMode();
  41. const runId = Date.now();
  42. const parentRunMarker = `${PARENT_MARKER}_${runId}`;
  43. await sendV4PromptAndWaitAccepted(
  44. [
  45. `${parentRunMarker}: call Agent exactly once with run_in_background false and subagent_type "general-purpose".`,
  46. `Tell the child to reply with exactly ${FOREGROUND_DONE}_${runId} and do nothing else.`,
  47. "After that foreground Agent completes, call no more tools and finish this turn.",
  48. ].join(" "),
  49. parentRunMarker,
  50. "foreground Agent 首发后用户消息没有进入 timeline",
  51. 90000,
  52. );
  53. await waitForToolCallBlockByToolName("Agent", 90000);
  54. await waitForV4AssistantMessageContaining(FOREGROUND_PARENT_IDLE, 90000);
  55. await waitForV4ConversationState(
  56. (snapshot) => snapshot.state !== "streaming" && !snapshot.stopRequested,
  57. "foreground Agent 完成后父 turn 没有回到 idle",
  58. 90000,
  59. );
  60. expect((await waitForToolCallBlockByToolName("Agent", 30000)).status).toBe("completed");
  61. await waitForUpstreamRequest(
  62. {
  63. includes: [parentRunMarker, FOREGROUND_DONE, "agentId: agent_"],
  64. excludes: ["resumed it in the background"],
  65. },
  66. "foreground Agent 完成结果没有进入父模型请求",
  67. 90000,
  68. );
  69. // 测试修复原因:resume 会原地更新同一 subagent projection;若等 resume 后再读
  70. // identity,新建 child 也可能让 row/work 自洽通过。必须在第二个 turn 前固化原身份。
  71. const foregroundAgentId = await readForegroundAgentId(parentRunMarker);
  72. const foregroundChildSessionId = await waitForSingleSubagentSummaryChildSessionId(30000);
  73. const resumeRunMarker = `${RESUME_MARKER}_${runId}`;
  74. await sendV4PromptAndWaitAccepted(
  75. [
  76. `${resumeRunMarker}: read the agentId from the completed Agent result and call SendMessage exactly once for that same agent.`,
  77. "Omit the optional summary.",
  78. `Use this exact message verbatim: You MUST invoke the Bash tool with command "sh -c 'sleep 120'". Do not send any text before the Bash tool finishes. After it finishes, reply with exactly ${CHILD_DONE}_${runId}.`,
  79. "After SendMessage returns, call no more tools and finish this turn without waiting for the resumed agent.",
  80. ].join(" "),
  81. resumeRunMarker,
  82. "SendMessage resume 首发后用户消息没有进入 timeline",
  83. 90000,
  84. );
  85. await waitForToolCallBlockByToolName("SendMessage", 90000);
  86. await waitForV4ConversationState(
  87. (snapshot) => snapshot.state !== "streaming" && !snapshot.stopRequested,
  88. "SendMessage resume 后父 turn 没有回到 idle",
  89. 90000,
  90. );
  91. const sendMessageBlock = await waitForToolCallBlockByToolName("SendMessage", 30000);
  92. expect(sendMessageBlock.status).toBe("completed");
  93. // SendMessage 的 summary 可选:省略时卡片标题显示 message 的第一行。
  94. expect(sendMessageBlock.text).toContain(
  95. `You MUST invoke the Bash tool with command "sh -c 'sleep 120'".`,
  96. );
  97. // 第二轮会把首轮工具卡片移出虚拟列表;身份由真实 Activity 行核对,不能要求旧 DOM 常驻。
  98. await openRunningSubagentCapsule(90000);
  99. const control = await waitForSingleRunningSubagent(30000);
  100. expect(control.taskId).toBe(foregroundAgentId);
  101. expect(control.childSessionId).toBe(foregroundChildSessionId);
  102. expect(control.executionId).not.toBe("");
  103. expect(control.stopDisabled).toBe(false);
  104. expect((await getV4ComposerBackgroundWorkCounts())?.subagentCount).toBe(1);
  105. expect(await countVisibleSubagentTabs()).toBe(0);
  106. const requestCountBeforeStop = await getUpstreamRequestRecordCount();
  107. // Stop 必须携带本次执行 token;不能再从 backgroundWorks 猜测控制身份。
  108. const ack = await clickRunningSubagentStop(control);
  109. expect(ack.status).toBe("accepted");
  110. // 测试修复原因:running row 会早于后台 completion notification turn 收口;只等
  111. // UI 消失会让晚到的 provider 失败漏检。先观察 notification request 与唯一完成文本。
  112. await waitForUpstreamRequest(
  113. {
  114. includes: [
  115. PARENT_MARKER,
  116. "<task-notification>",
  117. "<tool-use-id>toolu_e2e_send_message_resume_stop_send_message</tool-use-id>",
  118. // 停止状态词是 killed,summary 写明是用户停止的。
  119. "<status>killed</status>",
  120. "was stopped by user</summary>",
  121. ],
  122. lastUserMessageIncludes: ["<task-notification>", "<status>killed</status>"],
  123. },
  124. "Stop 后 resumed subagent completion notification 没有进入父模型请求",
  125. 60000,
  126. { afterIndex: requestCountBeforeStop - 1 },
  127. );
  128. await waitForV4AssistantMessageContaining(STOP_NOTIFICATION_DONE, 60000);
  129. await waitForV4ConversationState(
  130. (snapshot) => snapshot.state !== "streaming" && !snapshot.stopRequested,
  131. "Stop completion notification turn 没有回到 idle",
  132. 60000,
  133. );
  134. await waitForResumedSubagentStopped(control.childSessionId, 60000);
  135. expect(await countVisibleSubagentTabs()).toBe(0);
  136. });
  137. });
  138. async function readForegroundAgentId(runMarker: string): Promise<string> {
  139. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH?.trim();
  140. if (!capturePath) {
  141. throw new Error("E2E_PROVIDER_CAPTURE_PATH 未配置,无法读取 foreground agentId");
  142. }
  143. const artifact = JSON.parse(await readFile(capturePath, "utf8")) as E2ENetworkCaptureArtifact;
  144. for (const record of artifact.records) {
  145. const requestText = JSON.stringify(record.requestJson ?? null);
  146. if (!requestText.includes(runMarker) || !requestText.includes(FOREGROUND_DONE)) continue;
  147. const agentId = /agentId:\s*(agent_[A-Za-z0-9_-]+)/u.exec(requestText)?.[1];
  148. if (agentId) return agentId;
  149. }
  150. throw new Error(`没有从 foreground Agent tool result 读取到 agentId: ${runMarker}`);
  151. }
  152. async function waitForSingleRunningSubagent(timeout: number): Promise<RunningSubagentControl> {
  153. let running: RunningSubagentControl[] = [];
  154. await browser.waitUntil(
  155. async () => {
  156. running = await readRunningSubagentControls();
  157. return running.length === 1 && Boolean(running[0]?.executionId);
  158. },
  159. {
  160. timeout,
  161. timeoutMsg: "没有等到唯一且带 execution token 的 resumed subagent",
  162. },
  163. );
  164. return running[0]!;
  165. }
  166. async function waitForSingleSubagentSummaryChildSessionId(timeout: number): Promise<string> {
  167. let childSessionIds: string[] = [];
  168. await browser.waitUntil(
  169. async () => {
  170. childSessionIds = await browser.execute(
  171. (prefix) =>
  172. Array.from(document.querySelectorAll<HTMLElement>(`[data-testid^="${prefix}-"]`)).map(
  173. (element) => (element.getAttribute("data-testid") ?? "").slice(prefix.length + 1),
  174. ),
  175. TID_V4_SUBAGENT_OPEN_SIDE_PANE,
  176. );
  177. return childSessionIds.length === 1 && Boolean(childSessionIds[0]);
  178. },
  179. {
  180. timeout,
  181. timeoutMsg: "没有等到唯一的 foreground subagent child identity",
  182. },
  183. );
  184. return childSessionIds[0]!;
  185. }
  186. async function waitForResumedSubagentStopped(
  187. childSessionId: string,
  188. timeout: number,
  189. ): Promise<void> {
  190. await browser.waitUntil(
  191. async () => {
  192. const [running, composerCounts] = await Promise.all([
  193. readRunningSubagentControls(),
  194. getV4ComposerBackgroundWorkCounts(),
  195. ]);
  196. return (
  197. !running.some((item) => item.childSessionId === childSessionId) &&
  198. composerCounts === null &&
  199. (await $(
  200. '[data-status-capsule-content="activity"] [data-activity-result="stopped"]',
  201. ).isDisplayed())
  202. );
  203. },
  204. {
  205. timeout,
  206. timeoutMsg: "点击 Stop 后 resumed subagent 的运行计数、停止结果或 running row 没有收口",
  207. },
  208. );
  209. }