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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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";
  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. 'Use summary "resume stopped agent for stop check".',
  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. expect((await waitForToolCallBlockByToolName("SendMessage", 30000)).status).toBe("completed");
  90. expect(await waitForSingleSubagentSummaryChildSessionId(30000)).toBe(
  91. foregroundChildSessionId,
  92. );
  93. await openV4RunningBackgroundWorks(90000);
  94. const runningWork = await waitForSingleRunningBackgroundWork(30000);
  95. expect(runningWork.workId).toBe(foregroundAgentId);
  96. const control = await readRunningSubagentControl(runningWork.workId);
  97. expect(control).not.toBeNull();
  98. expect(control?.kind).toBe("agent");
  99. expect(control?.childSessionId).toBe(foregroundChildSessionId);
  100. expect(control?.stopVisible).toBe(true);
  101. expect((await getV4ComposerBackgroundWorkCounts())?.subagentCount).toBe(1);
  102. expect(await countVisibleSubagentTabs()).toBe(0);
  103. const requestCountBeforeStop = await getUpstreamRequestRecordCount();
  104. expect(await clickV4BackgroundWorkCancel(runningWork.workId)).toBe(true);
  105. const ack = await waitForLatestV4CommandAck("cancelBackgroundWork", 30000);
  106. expect(ack.status).toBe("accepted");
  107. // 测试修复原因:running row 会早于后台 completion notification turn 收口;只等
  108. // UI 消失会让晚到的 provider 失败漏检。先观察 notification request 与唯一完成文本。
  109. await waitForUpstreamRequest(
  110. {
  111. includes: [
  112. PARENT_MARKER,
  113. "<task-notification>",
  114. "<tool-use-id>toolu_e2e_send_message_resume_stop_send_message</tool-use-id>",
  115. "<status>stopped</status>",
  116. ],
  117. lastUserMessageIncludes: ["<task-notification>", "<status>stopped</status>"],
  118. },
  119. "Stop 后 resumed subagent completion notification 没有进入父模型请求",
  120. 60000,
  121. { afterIndex: requestCountBeforeStop - 1 },
  122. );
  123. await waitForV4AssistantMessageContaining(STOP_NOTIFICATION_DONE, 60000);
  124. await waitForV4ConversationState(
  125. (snapshot) => snapshot.state !== "streaming" && !snapshot.stopRequested,
  126. "Stop completion notification turn 没有回到 idle",
  127. 60000,
  128. );
  129. await waitForResumedSubagentStopped(runningWork.workId, 60000);
  130. expect(await countVisibleSubagentTabs()).toBe(0);
  131. });
  132. });
  133. async function readForegroundAgentId(runMarker: string): Promise<string> {
  134. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH?.trim();
  135. if (!capturePath) {
  136. throw new Error("E2E_PROVIDER_CAPTURE_PATH 未配置,无法读取 foreground agentId");
  137. }
  138. const artifact = JSON.parse(
  139. await readFile(capturePath, "utf8"),
  140. ) as E2ENetworkCaptureArtifact;
  141. for (const record of artifact.records) {
  142. const requestText = JSON.stringify(record.requestJson ?? null);
  143. if (!requestText.includes(runMarker) || !requestText.includes(FOREGROUND_DONE)) continue;
  144. const agentId = /agentId:\s*(agent_[A-Za-z0-9_-]+)/u.exec(requestText)?.[1];
  145. if (agentId) return agentId;
  146. }
  147. throw new Error(`没有从 foreground Agent tool result 读取到 agentId: ${runMarker}`);
  148. }
  149. async function waitForSingleRunningBackgroundWork(
  150. timeout: number,
  151. ): Promise<{ workId: string; status: string | null }> {
  152. let running: Array<{ workId: string; status: string | null }> = [];
  153. await browser.waitUntil(
  154. async () => {
  155. running = (await getV4BackgroundWorks()).filter((work) => work.status === "running");
  156. return running.length === 1 && Boolean(running[0]?.workId);
  157. },
  158. {
  159. timeout,
  160. timeoutMsg: "没有等到唯一的 resumed subagent background work",
  161. },
  162. );
  163. return running[0]!;
  164. }
  165. async function waitForSingleSubagentSummaryChildSessionId(timeout: number): Promise<string> {
  166. let childSessionIds: string[] = [];
  167. await browser.waitUntil(
  168. async () => {
  169. childSessionIds = await browser.execute(
  170. (prefix) =>
  171. Array.from(document.querySelectorAll<HTMLElement>(`[data-testid^="${prefix}-"]`)).map(
  172. (element) => (element.getAttribute("data-testid") ?? "").slice(prefix.length + 1),
  173. ),
  174. TID_V4_SUBAGENT_OPEN_SIDE_PANE,
  175. );
  176. return childSessionIds.length === 1 && Boolean(childSessionIds[0]);
  177. },
  178. {
  179. timeout,
  180. timeoutMsg: "没有等到唯一的 foreground subagent child identity",
  181. },
  182. );
  183. return childSessionIds[0]!;
  184. }
  185. async function readRunningSubagentControl(workId: string): Promise<{
  186. kind: string | null;
  187. childSessionId: string | null;
  188. stopVisible: boolean;
  189. } | null> {
  190. return browser.execute(
  191. (itemPrefix, cancelPrefix, id) => {
  192. const row = document.querySelector<HTMLElement>(`[data-testid="${itemPrefix}-${id}"]`);
  193. if (!row) return null;
  194. const stop = row.querySelector<HTMLElement>(`[data-testid="${cancelPrefix}-${id}"]`);
  195. return {
  196. kind: row.dataset.backgroundTaskKind ?? null,
  197. childSessionId: row.dataset.childSessionId ?? null,
  198. stopVisible: Boolean(stop && getComputedStyle(stop).display !== "none"),
  199. };
  200. },
  201. TID_V4_BACKGROUND_WORK_ITEM,
  202. TID_V4_BACKGROUND_WORK_CANCEL,
  203. workId,
  204. );
  205. }
  206. async function waitForResumedSubagentStopped(workId: string, timeout: number): Promise<void> {
  207. await browser.waitUntil(
  208. async () => {
  209. const [works, composerCounts, runningAgentCount] = await Promise.all([
  210. getV4BackgroundWorks(),
  211. getV4ComposerBackgroundWorkCounts(),
  212. readStatusPanelRunningAgentCount(),
  213. ]);
  214. return (
  215. !works.some((work) => work.workId === workId) &&
  216. composerCounts === null &&
  217. runningAgentCount === 0
  218. );
  219. },
  220. {
  221. timeout,
  222. timeoutMsg: "点击 Stop 后 resumed subagent 的 work、右上角入口或 running row 没有收口",
  223. },
  224. );
  225. }
  226. async function readStatusPanelRunningAgentCount(): Promise<number> {
  227. return browser.execute((panelTestId) => {
  228. const panel = document.querySelector<HTMLElement>(`[data-testid="${panelTestId}"]`);
  229. return Number(panel?.dataset.runningAgentCount ?? "0");
  230. }, TID_CHAT_SUMMARY_PANEL);
  231. }
  232. async function countVisibleSubagentTabs(): Promise<number> {
  233. return browser.execute(
  234. () => document.querySelectorAll('[data-side-pane-tab-id^="subagent-session:"]').length,
  235. );
  236. }