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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import { readFile } from "node:fs/promises";
  2. import {
  3. TID_CHAT_SUMMARY_PANEL,
  4. TID_V4_BACKGROUND_WORK_CANCEL,
  5. TID_V4_BACKGROUND_WORK_ITEM,
  6. TID_V4_SUBAGENT_OPEN_SIDE_PANE,
  7. } from "@zcode/shared/test-ids";
  8. import { clearAppData } from "../helpers/desktop-app.js";
  9. import { waitForToolCallBlockByToolName } from "../helpers/conversation-session-tool.js";
  10. import {
  11. getUpstreamRequestRecordCount,
  12. waitForUpstreamRequest,
  13. } from "../helpers/conversation-session-network.js";
  14. import type { E2ENetworkCaptureArtifact } from "../helpers/network-capture-proxy.js";
  15. import { ensureToolCrossProductFullAccessMode } from "../helpers/conversation-session-tool-cross-product.js";
  16. import {
  17. clickV4BackgroundWorkCancel,
  18. getV4BackgroundWorks,
  19. getV4ComposerBackgroundWorkCounts,
  20. openV4RunningBackgroundWorks,
  21. prepareV4ConversationE2E,
  22. sendV4Prompt,
  23. waitForLatestV4CommandAck,
  24. waitForV4AssistantMessageContaining,
  25. waitForV4ComposerText,
  26. waitForV4ConversationState,
  27. } from "../helpers/v4-conversation.js";
  28. const PARENT_MARKER = "E2E_SEND_MESSAGE_RESUME_STOP_PARENT";
  29. const FOREGROUND_DONE = "E2E_SEND_MESSAGE_RESUME_STOP_FOREGROUND_DONE";
  30. const FOREGROUND_PARENT_IDLE = "E2E_SEND_MESSAGE_RESUME_STOP_FOREGROUND_PARENT_IDLE";
  31. const RESUME_MARKER = "E2E_SEND_MESSAGE_RESUME_STOP_RESUME";
  32. const CHILD_DONE = "E2E_SEND_MESSAGE_RESUME_STOP_CHILD_DONE";
  33. const STOP_NOTIFICATION_DONE = "E2E_SEND_MESSAGE_RESUME_STOP_NOTIFICATION_DONE";
  34. describe("SendMessage resume Stop", () => {
  35. after(async () => {
  36. await browser.electron.restoreAllMocks();
  37. await clearAppData();
  38. });
  39. it("SAT12: foreground subagent 完成后由 SendMessage resume 显示 Stop 且可停止", async function () {
  40. this.timeout(240000);
  41. await prepareV4ConversationE2E();
  42. await ensureToolCrossProductFullAccessMode();
  43. const runId = Date.now();
  44. const parentRunMarker = `${PARENT_MARKER}_${runId}`;
  45. await sendV4Prompt(
  46. [
  47. `${parentRunMarker}: call Agent exactly once with run_in_background false and subagent_type "general-purpose".`,
  48. `Tell the child to reply with exactly ${FOREGROUND_DONE}_${runId} and do nothing else.`,
  49. "After that foreground Agent completes, call no more tools and finish this turn.",
  50. ].join(" "),
  51. );
  52. await waitForV4ComposerText("", "foreground Agent 首发后输入框没有清空");
  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 sendV4Prompt(
  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 "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. );
  82. await waitForV4ComposerText("", "SendMessage resume 首发后输入框没有清空");
  83. await waitForToolCallBlockByToolName("SendMessage", 90000);
  84. await waitForV4ConversationState(
  85. (snapshot) => snapshot.state !== "streaming" && !snapshot.stopRequested,
  86. "SendMessage resume 后父 turn 没有回到 idle",
  87. 90000,
  88. );
  89. const sendMessageBlock = await waitForToolCallBlockByToolName("SendMessage", 30000);
  90. expect(sendMessageBlock.status).toBe("completed");
  91. // SendMessage 的 summary 可选:省略时卡片标题显示 message 的第一行。
  92. expect(sendMessageBlock.text).toContain(
  93. 'You MUST invoke the Bash tool with command "sleep 120".',
  94. );
  95. expect(await waitForSingleSubagentSummaryChildSessionId(30000)).toBe(
  96. foregroundChildSessionId,
  97. );
  98. await openV4RunningBackgroundWorks(90000);
  99. const runningWork = await waitForSingleRunningBackgroundWork(30000);
  100. expect(runningWork.workId).toBe(foregroundAgentId);
  101. const control = await readRunningSubagentControl(runningWork.workId);
  102. expect(control).not.toBeNull();
  103. expect(control?.kind).toBe("agent");
  104. expect(control?.childSessionId).toBe(foregroundChildSessionId);
  105. expect(control?.stopVisible).toBe(true);
  106. expect((await getV4ComposerBackgroundWorkCounts())?.subagentCount).toBe(1);
  107. expect(await countVisibleSubagentTabs()).toBe(0);
  108. const requestCountBeforeStop = await getUpstreamRequestRecordCount();
  109. expect(await clickV4BackgroundWorkCancel(runningWork.workId)).toBe(true);
  110. const ack = await waitForLatestV4CommandAck("cancelBackgroundWork", 30000);
  111. expect(ack.status).toBe("accepted");
  112. // 测试修复原因:running row 会早于后台 completion notification turn 收口;只等
  113. // UI 消失会让晚到的 provider 失败漏检。先观察 notification request 与唯一完成文本。
  114. await waitForUpstreamRequest(
  115. {
  116. includes: [
  117. PARENT_MARKER,
  118. "<task-notification>",
  119. "<tool-use-id>toolu_e2e_send_message_resume_stop_send_message</tool-use-id>",
  120. // 停止状态词是 killed,summary 写明是用户停止的。
  121. "<status>killed</status>",
  122. "was stopped by user</summary>",
  123. ],
  124. lastUserMessageIncludes: ["<task-notification>", "<status>killed</status>"],
  125. },
  126. "Stop 后 resumed subagent completion notification 没有进入父模型请求",
  127. 60000,
  128. { afterIndex: requestCountBeforeStop - 1 },
  129. );
  130. await waitForV4AssistantMessageContaining(STOP_NOTIFICATION_DONE, 60000);
  131. await waitForV4ConversationState(
  132. (snapshot) => snapshot.state !== "streaming" && !snapshot.stopRequested,
  133. "Stop completion notification turn 没有回到 idle",
  134. 60000,
  135. );
  136. await waitForResumedSubagentStopped(runningWork.workId, 60000);
  137. expect(await countVisibleSubagentTabs()).toBe(0);
  138. });
  139. });
  140. async function readForegroundAgentId(runMarker: string): Promise<string> {
  141. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH?.trim();
  142. if (!capturePath) {
  143. throw new Error("E2E_PROVIDER_CAPTURE_PATH 未配置,无法读取 foreground agentId");
  144. }
  145. const artifact = JSON.parse(
  146. await readFile(capturePath, "utf8"),
  147. ) as E2ENetworkCaptureArtifact;
  148. for (const record of artifact.records) {
  149. const requestText = JSON.stringify(record.requestJson ?? null);
  150. if (!requestText.includes(runMarker) || !requestText.includes(FOREGROUND_DONE)) continue;
  151. const agentId = /agentId:\s*(agent_[A-Za-z0-9_-]+)/u.exec(requestText)?.[1];
  152. if (agentId) return agentId;
  153. }
  154. throw new Error(`没有从 foreground Agent tool result 读取到 agentId: ${runMarker}`);
  155. }
  156. async function waitForSingleRunningBackgroundWork(
  157. timeout: number,
  158. ): Promise<{ workId: string; status: string | null }> {
  159. let running: Array<{ workId: string; status: string | null }> = [];
  160. await browser.waitUntil(
  161. async () => {
  162. running = (await getV4BackgroundWorks()).filter((work) => work.status === "running");
  163. return running.length === 1 && Boolean(running[0]?.workId);
  164. },
  165. {
  166. timeout,
  167. timeoutMsg: "没有等到唯一的 resumed subagent background work",
  168. },
  169. );
  170. return running[0]!;
  171. }
  172. async function waitForSingleSubagentSummaryChildSessionId(timeout: number): Promise<string> {
  173. let childSessionIds: string[] = [];
  174. await browser.waitUntil(
  175. async () => {
  176. childSessionIds = await browser.execute(
  177. (prefix) =>
  178. Array.from(document.querySelectorAll<HTMLElement>(`[data-testid^="${prefix}-"]`)).map(
  179. (element) => (element.getAttribute("data-testid") ?? "").slice(prefix.length + 1),
  180. ),
  181. TID_V4_SUBAGENT_OPEN_SIDE_PANE,
  182. );
  183. return childSessionIds.length === 1 && Boolean(childSessionIds[0]);
  184. },
  185. {
  186. timeout,
  187. timeoutMsg: "没有等到唯一的 foreground subagent child identity",
  188. },
  189. );
  190. return childSessionIds[0]!;
  191. }
  192. async function readRunningSubagentControl(workId: string): Promise<{
  193. kind: string | null;
  194. childSessionId: string | null;
  195. stopVisible: boolean;
  196. } | null> {
  197. return browser.execute(
  198. (itemPrefix, cancelPrefix, id) => {
  199. const row = document.querySelector<HTMLElement>(`[data-testid="${itemPrefix}-${id}"]`);
  200. if (!row) return null;
  201. const stop = row.querySelector<HTMLElement>(`[data-testid="${cancelPrefix}-${id}"]`);
  202. return {
  203. kind: row.dataset.backgroundTaskKind ?? null,
  204. childSessionId: row.dataset.childSessionId ?? null,
  205. stopVisible: Boolean(stop && getComputedStyle(stop).display !== "none"),
  206. };
  207. },
  208. TID_V4_BACKGROUND_WORK_ITEM,
  209. TID_V4_BACKGROUND_WORK_CANCEL,
  210. workId,
  211. );
  212. }
  213. async function waitForResumedSubagentStopped(workId: string, timeout: number): Promise<void> {
  214. await browser.waitUntil(
  215. async () => {
  216. const [works, composerCounts, runningAgentCount] = await Promise.all([
  217. getV4BackgroundWorks(),
  218. getV4ComposerBackgroundWorkCounts(),
  219. readStatusPanelRunningAgentCount(),
  220. ]);
  221. return (
  222. !works.some((work) => work.workId === workId) &&
  223. composerCounts === null &&
  224. runningAgentCount === 0
  225. );
  226. },
  227. {
  228. timeout,
  229. timeoutMsg: "点击 Stop 后 resumed subagent 的 work、右上角入口或 running row 没有收口",
  230. },
  231. );
  232. }
  233. async function readStatusPanelRunningAgentCount(): Promise<number> {
  234. return browser.execute((panelTestId) => {
  235. const panel = document.querySelector<HTMLElement>(`[data-testid="${panelTestId}"]`);
  236. return Number(panel?.dataset.runningAgentCount ?? "0");
  237. }, TID_CHAT_SUMMARY_PANEL);
  238. }
  239. async function countVisibleSubagentTabs(): Promise<number> {
  240. return browser.execute(
  241. () => document.querySelectorAll('[data-side-pane-tab-id^="subagent-session:"]').length,
  242. );
  243. }