conversation-session-agent-always-background.test.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. // AAB01–AAB02 子智能体总在后台运行开关(docs/conversation-session-case-catalog.md「子智能体总在后台运行」)。
  2. // 规格见 apps/zcode-cli/docs/design/v2/tool/07-subagent.md「ZCode 当前实现」。
  3. // 开关缺省开启,只在创建 runtime 时读取;wdio.conf.ts 为其他用例写入关闭,本用例不写,保留产品缺省。
  4. // wdio 按 worker 判定是否写入,所以本用例必须独占一个 worker:和其他 spec 同组时,它们会按开启运行,回放对不上。
  5. // 断言读取上游请求体与 Composer 的后台工作计数。不读 Agent 卡片的后台区块:V4 时间线里 Agent 有子会话时,
  6. // 点卡片打开右侧子会话,不在行内展开(ConversationAgentToolCallRow 的 agentSummaryAction)。
  7. import {
  8. TID_SETTINGS_AGENT_ALWAYS_BACKGROUND_SWITCH,
  9. TID_SETTINGS_BACK_BUTTON,
  10. TID_SETTINGS_PAGE,
  11. TID_SETTINGS_SECTION_NAV,
  12. TID_TASK_SETTINGS_BUTTON,
  13. testId,
  14. } from "@zcode/shared/test-ids";
  15. import { clearAppData, clickTestIdByDom, readSettings } from "#e2e/helpers/desktop-app";
  16. import { getUpstreamRequestEvidence } from "#e2e/helpers/conversation-session-network";
  17. import {
  18. getV4ComposerBackgroundWorkCounts,
  19. prepareV4ConversationE2E,
  20. sendV4Prompt,
  21. waitForV4Pane,
  22. waitForV4TimelineContaining,
  23. } from "#e2e/helpers/v4-conversation";
  24. type Block = Record<string, unknown> & { type?: string };
  25. type Message = { role: string; content: unknown };
  26. type Tool = { name?: string; description?: string; input_schema?: { properties?: object } };
  27. type Request = { messages: Message[]; tools?: Tool[] };
  28. const LAUNCH = "Async agent launched successfully.";
  29. const ALWAYS_BACKGROUND_LINE =
  30. "- Subagents run in the background; you'll be notified when one completes.";
  31. const OPTIONAL_BACKGROUND_LINE = "`run_in_background: true` runs the agent asynchronously";
  32. const A_AGENTS = ["toolu_aab_a_plain", "toolu_aab_a_legacy"] as const;
  33. const B_AGENT = "toolu_aab_b_plain";
  34. describe("AAB 子智能体总在后台运行开关", () => {
  35. after(async () => {
  36. await browser.electron.restoreAllMocks();
  37. await clearAppData();
  38. });
  39. it("AAB01–AAB02:缺省开启时都在后台启动;关闭后新任务回到可选前台,运行中的任务不变", async function () {
  40. this.timeout(600_000);
  41. await prepareV4ConversationE2E();
  42. // AAB01:wdio 不写这个键;app 启动时会按缺省把 true 写回 setting.json,所以只断言不是关闭。
  43. expect((await readSettings()).agentAlwaysBackgroundEnabled).not.toBe(false);
  44. await openSettings();
  45. expect(await readSwitch()).toBe(true);
  46. await closeSettings();
  47. // 一个调用没有 run_in_background,一个带遗留的 false;两个都在后台启动,A 的启动轮先结束。
  48. await sendV4Prompt("E2E_AAB_A1 Launch two helpers.");
  49. // 启动回执返回时后台任务已经登记,Composer 显示两个后台子代理。放在等收尾文字之前:子代理的
  50. // fixture 延迟(8 / 10 秒)从请求到达时起算,等完父会话的收尾回合再看,可用窗口会被吃掉一截。
  51. await browser.waitUntil(
  52. async () => (await getV4ComposerBackgroundWorkCounts())?.subagentCount === 2,
  53. { timeout: 15_000, timeoutMsg: "Composer 没有显示两个运行中的后台子代理" },
  54. );
  55. await waitForV4TimelineContaining("AAB_A_LAUNCHED", 120_000);
  56. const [a1, a2] = await requestsByFixture(["aab-a1", "aab-a2"]);
  57. expect(agentSchemaKeys(a1!)).not.toContain("run_in_background");
  58. expect(agentTool(a1!).description).toContain(ALWAYS_BACKGROUND_LINE);
  59. expect(agentTool(a1!).description).not.toContain(OPTIONAL_BACKGROUND_LINE);
  60. for (const toolCallId of A_AGENTS) {
  61. expect(toolResultText(a2!, toolCallId).startsWith(LAUNCH)).toBe(true);
  62. }
  63. // 子代理完成后,通知开启父会话新一轮;两个通知可能分两轮,也可能合为一轮。
  64. await browser.waitUntil(
  65. async () => {
  66. const text = (await recordsByFixture("aab-a-notify")).map(lastUserText).join("\n");
  67. return A_AGENTS.every((id) => text.includes(`<tool-use-id>${id}</tool-use-id>`));
  68. },
  69. { timeout: 120_000, timeoutMsg: "两个后台 Agent 没有都送回 <task-notification>" },
  70. );
  71. const taskA = await idleSessionId("A 的通知轮没有结束");
  72. // AAB02:关闭开关,不重启。运行中的 A 保持开启;之后新建的 B 回到可选 run_in_background。
  73. await openSettings();
  74. await setSwitch(false);
  75. await closeSettings(taskA);
  76. await sendV4Prompt("E2E_AAB_A3 Say done.");
  77. await waitForV4TimelineContaining("AAB_A3_DONE", 120_000);
  78. await idleSessionId("A 的第二轮没有结束");
  79. const [a3] = await requestsByFixture(["aab-a3"]);
  80. expect(agentSchemaKeys(a3!)).not.toContain("run_in_background");
  81. // 草稿在关闭开关之后创建,才会读到关闭。
  82. await prepareV4ConversationE2E({ skipProvider: true });
  83. await sendV4Prompt("E2E_AAB_B1 Run one helper.");
  84. await waitForV4TimelineContaining("AAB_B_DONE", 120_000);
  85. await idleSessionId("B 第一轮没有结束");
  86. const [b1, b2] = await requestsByFixture(["aab-b1", "aab-b2"]);
  87. expect(agentSchemaKeys(b1!)).toContain("run_in_background");
  88. expect(agentTool(b1!).description).toContain(OPTIONAL_BACKGROUND_LINE);
  89. expect(agentTool(b1!).description).not.toContain(ALWAYS_BACKGROUND_LINE);
  90. const foregroundResult = toolResultText(b2!, B_AGENT);
  91. expect(foregroundResult).toContain("E2E_AAB_CHILD_B_DONE");
  92. expect(foregroundResult).not.toContain(LAUNCH);
  93. // 前台子代理已在本轮结束,B 没有留下运行中的后台工作。
  94. expect(await getV4ComposerBackgroundWorkCounts()).toBeNull();
  95. });
  96. });
  97. async function idleSessionId(timeoutMsg: string): Promise<string> {
  98. const snapshot = await waitForV4Pane(
  99. (current) => Boolean(current.sessionId && current.sessionId !== "draft") && !current.canStop,
  100. timeoutMsg,
  101. 120_000,
  102. );
  103. return snapshot.sessionId!;
  104. }
  105. async function openSettings() {
  106. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  107. timeout: 15_000,
  108. timeoutMsg: "没有找到设置入口按钮",
  109. });
  110. await browser.waitUntil(
  111. async () =>
  112. browser.execute(
  113. (pageTestId) => Boolean(document.querySelector(`[data-testid="${pageTestId}"]`)),
  114. TID_SETTINGS_PAGE,
  115. ),
  116. { timeout: 15_000, timeoutMsg: "设置页没有打开" },
  117. );
  118. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "agentBehavior"), {
  119. timeout: 15_000,
  120. timeoutMsg: "设置页没有行为与工具分区入口",
  121. });
  122. await browser.waitUntil(async () => (await readSwitch()) !== null, {
  123. timeout: 15_000,
  124. timeoutMsg: "行为与工具设置没有子智能体后台开关",
  125. });
  126. }
  127. async function closeSettings(expectedSessionId?: string) {
  128. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  129. timeout: 15_000,
  130. timeoutMsg: "设置页返回按钮没有出现",
  131. });
  132. await waitForV4Pane(
  133. (snapshot) =>
  134. expectedSessionId ? snapshot.sessionId === expectedSessionId : snapshot.sessionId !== null,
  135. expectedSessionId ? `返回工作区后没有恢复 Session ${expectedSessionId}` : "返回工作区失败",
  136. 30_000,
  137. );
  138. }
  139. async function setSwitch(enabled: boolean) {
  140. if ((await readSwitch()) !== enabled) {
  141. await clickTestIdByDom(TID_SETTINGS_AGENT_ALWAYS_BACKGROUND_SWITCH, {
  142. timeout: 15_000,
  143. timeoutMsg: "子智能体后台开关不可点击",
  144. });
  145. }
  146. await browser.waitUntil(
  147. async () =>
  148. (await readSwitch()) === enabled &&
  149. (await readSettings()).agentAlwaysBackgroundEnabled === enabled,
  150. { timeout: 15_000, timeoutMsg: `子智能体后台设置没有保存为 ${String(enabled)}` },
  151. );
  152. }
  153. function readSwitch(): Promise<boolean | null> {
  154. return browser.execute((switchTestId) => {
  155. const control = document.querySelector<HTMLElement>(`[data-testid="${switchTestId}"]`);
  156. if (!control) return null;
  157. return (
  158. control.getAttribute("aria-checked") === "true" ||
  159. control.getAttribute("data-state") === "checked"
  160. );
  161. }, TID_SETTINGS_AGENT_ALWAYS_BACKGROUND_SWITCH);
  162. }
  163. async function recordsByFixture(fixtureId: string): Promise<Request[]> {
  164. const records = await getUpstreamRequestEvidence({});
  165. return records
  166. .filter((record) => record.fixtureId === fixtureId)
  167. .map((record) => record.requestJson as Request);
  168. }
  169. /** 按 fixture id 取上游请求;每个 fixture 取第一次匹配。 */
  170. async function requestsByFixture(ids: string[]): Promise<Request[]> {
  171. const records = await getUpstreamRequestEvidence({});
  172. return ids.map((fixtureId) => {
  173. const request = records.find((item) => item.fixtureId === fixtureId)?.requestJson as
  174. | Request
  175. | undefined;
  176. if (!request || !Array.isArray(request.messages)) throw new Error(`${fixtureId} 没有上游请求`);
  177. return request;
  178. });
  179. }
  180. function agentTool(request: Request): Tool {
  181. const tool = request.tools?.find((item) => item.name === "Agent");
  182. if (!tool) throw new Error("请求的 tools 里没有 Agent");
  183. return tool;
  184. }
  185. function agentSchemaKeys(request: Request): string[] {
  186. return Object.keys(agentTool(request).input_schema?.properties ?? {});
  187. }
  188. function toolResultText(request: Request, toolUseId: string): string {
  189. for (const message of request.messages) {
  190. if (!Array.isArray(message.content)) continue;
  191. for (const block of message.content as Block[]) {
  192. if (block.type === "tool_result" && block.tool_use_id === toolUseId) {
  193. return blocksText(block.content);
  194. }
  195. }
  196. }
  197. throw new Error(`请求里没有 ${toolUseId} 的 tool_result`);
  198. }
  199. function lastUserText(request: Request): string {
  200. const last = request.messages.findLast((message) => message.role === "user");
  201. return last ? blocksText(last.content) : "";
  202. }
  203. function blocksText(content: unknown): string {
  204. if (typeof content === "string") return content;
  205. if (!Array.isArray(content)) return "";
  206. return (content as Block[])
  207. .map((block) =>
  208. block.type === "tool_result" ? blocksText(block.content) : String(block.text ?? ""),
  209. )
  210. .join("");
  211. }