conversation-session-subagent-interaction-delegate.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import { clearAppData } from "../helpers/desktop-app.js";
  2. import { waitForUpstreamRequest } from "../helpers/conversation-session-network.js";
  3. import {
  4. approveV4Permission,
  5. clickV4Stop,
  6. getV4ConfigProjection,
  7. getV4PaneSnapshot,
  8. prepareV4ConversationE2E,
  9. sendV4Prompt,
  10. switchV4Mode,
  11. waitForV4AssistantMessageContaining,
  12. waitForV4Pane,
  13. waitForV4PermissionDialogInComposerDock,
  14. waitForV4TimelineContaining,
  15. } from "../helpers/v4-conversation.js";
  16. const YOLO_PARENT_MARKER = "E2E_SUBAGENT_HITL_YOLO_PARENT";
  17. const YOLO_CHILD_MARKER = "E2E_SUBAGENT_HITL_YOLO_CHILD";
  18. const YOLO_QUESTION_MARKER = "E2E_SUBAGENT_HITL_YOLO_QUESTION";
  19. const YOLO_ANSWER_MARKER = "E2E_SUBAGENT_HITL_YOLO_ANSWER";
  20. const YOLO_CHILD_DONE = "E2E_SUBAGENT_HITL_YOLO_CHILD_DONE";
  21. const YOLO_PARENT_DONE = "E2E_SUBAGENT_HITL_YOLO_PARENT_DONE";
  22. const YOLO_AGENT_TOOL_CALL_ID = "toolu_e2e_subagent_hitl_yolo_agent";
  23. const YOLO_ASK_TOOL_CALL_ID = "toolu_e2e_subagent_hitl_yolo_ask";
  24. const PERMISSION_PARENT_MARKER = "E2E_SUBAGENT_HITL_PERMISSION_PARENT";
  25. const PERMISSION_CHILD_MARKER = "E2E_SUBAGENT_HITL_PERMISSION_CHILD";
  26. const PERMISSION_BASH_OUTPUT = "E2E_SUBAGENT_HITL_PERMISSION_BASH_OUTPUT";
  27. const PERMISSION_CHILD_DONE = "E2E_SUBAGENT_HITL_PERMISSION_CHILD_DONE";
  28. const PERMISSION_PARENT_DONE = "E2E_SUBAGENT_HITL_PERMISSION_PARENT_DONE";
  29. const PERMISSION_AGENT_TOOL_CALL_ID = "toolu_e2e_subagent_hitl_permission_agent";
  30. const PERMISSION_BASH_TOOL_CALL_ID = "toolu_e2e_subagent_hitl_permission_bash";
  31. describe("会话区 subagent 人机交互代理 E2E", () => {
  32. afterEach(async () => {
  33. // 单条失败时先释放 child broker,避免仍在等待的 interaction 污染下一条 case。
  34. try {
  35. let snapshot = await getV4PaneSnapshot();
  36. if (snapshot.sessionId === "draft") {
  37. // 发送后 optimistic draft 会先渲染,真实 session 稍后才绑定;若断言恰好失败在
  38. // 这个窗口,必须等绑定完成再 stop,否则 child broker 会继续阻塞下一条 case。
  39. try {
  40. snapshot = await waitForV4Pane(
  41. (current) => current.sessionId !== "draft",
  42. "subagent interaction case teardown 等待真实 session 绑定超时",
  43. 10_000,
  44. );
  45. } catch {
  46. // draft 从未启动时无需清理。
  47. }
  48. }
  49. if (snapshot.canStop) {
  50. await clickV4Stop();
  51. await waitForV4Pane(
  52. (snapshot) => !snapshot.canStop,
  53. "subagent interaction case teardown 后仍处于运行态",
  54. 30_000,
  55. );
  56. }
  57. } catch {
  58. // teardown 只负责隔离下一条 case,不覆盖原始断言失败。
  59. }
  60. });
  61. after(async () => {
  62. await browser.electron.restoreAllMocks();
  63. await clearAppData();
  64. });
  65. it("T01: Full access 下 child AskUserQuestion 仍代理到父 task", async function () {
  66. this.timeout(180_000);
  67. await prepareConversationE2EInMode("yolo");
  68. const runId = Date.now();
  69. const prompt = [
  70. `${YOLO_PARENT_MARKER}_${runId}: Use the Agent tool with subagent_type "general-purpose".`,
  71. `Ask the child to trigger ${YOLO_CHILD_MARKER}, ask one question, and then finish.`,
  72. `After the child returns, reply with exactly ${YOLO_PARENT_DONE}.`,
  73. ].join(" ");
  74. const answer = `${YOLO_ANSWER_MARKER}_${runId}`;
  75. await sendV4Prompt(prompt);
  76. const parentPane = await waitForV4Pane(
  77. (snapshot) => snapshot.sessionId?.startsWith("sess_") === true,
  78. "subagent AskUserQuestion case 发送后没有绑定真实 session",
  79. 30_000,
  80. );
  81. await waitForV4TimelineContaining(`${YOLO_PARENT_MARKER}_${runId}`, 30_000);
  82. // 回归原因:V4 以 parent ProductProjection.pendingInteractions 为权威,不能再读取
  83. // legacy taskUiByTaskId.elicitationRequest;父 pane 中的可见 dock 才是产品合同。
  84. const interaction = await waitForSubagentInteractionInParentDock(
  85. "elicitation",
  86. YOLO_QUESTION_MARKER,
  87. 60_000,
  88. );
  89. expect(interaction.parentSessionId).toBe(parentPane.sessionId);
  90. expect(interaction.originTitle).toContain("general-purpose");
  91. await submitCustomElicitationAnswer(answer);
  92. await waitForInteractionClosed("elicitation", 30_000);
  93. await waitForUpstreamRequest(
  94. {
  95. includes: [answer, YOLO_CHILD_MARKER, YOLO_ASK_TOOL_CALL_ID],
  96. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  97. },
  98. "child AskUserQuestion 回答没有进入 child 下一次模型请求",
  99. 60_000,
  100. );
  101. await waitForUpstreamRequest(
  102. {
  103. includes: [YOLO_PARENT_MARKER, YOLO_CHILD_DONE, YOLO_AGENT_TOOL_CALL_ID],
  104. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  105. },
  106. "child AskUserQuestion 完成后父会话没有收到 Agent tool_result continuation",
  107. 60_000,
  108. );
  109. await waitForV4AssistantMessageContaining(YOLO_PARENT_DONE, 60_000);
  110. await waitForV4Pane(
  111. (snapshot) => !snapshot.canStop,
  112. "subagent AskUserQuestion delegate case 完成后没有回到 idle",
  113. 60_000,
  114. );
  115. });
  116. it("T02: build 模式下 child Bash permission request 代理到父 task", async function () {
  117. this.timeout(180_000);
  118. await prepareConversationE2EInMode("build");
  119. const runId = Date.now();
  120. const prompt = [
  121. `${PERMISSION_PARENT_MARKER}_${runId}: Use the Agent tool with subagent_type "general-purpose".`,
  122. `Ask the child to trigger ${PERMISSION_CHILD_MARKER}, run one Bash command, and then finish.`,
  123. `After the child returns, reply with exactly ${PERMISSION_PARENT_DONE}.`,
  124. ].join(" ");
  125. await sendV4Prompt(prompt);
  126. const parentPane = await waitForV4Pane(
  127. (snapshot) => snapshot.sessionId?.startsWith("sess_") === true,
  128. "subagent permission case 发送后没有绑定真实 session",
  129. 30_000,
  130. );
  131. await waitForV4TimelineContaining(`${PERMISSION_PARENT_MARKER}_${runId}`, 30_000);
  132. const dockState = await waitForV4PermissionDialogInComposerDock(60_000);
  133. expect(dockState.inDock).toBe(true);
  134. expect(dockState.composerHidden).toBe(true);
  135. const interaction = await waitForSubagentInteractionInParentDock(
  136. "permission",
  137. PERMISSION_BASH_OUTPUT,
  138. 60_000,
  139. );
  140. expect(interaction.parentSessionId).toBe(parentPane.sessionId);
  141. expect(interaction.originTitle).toContain("general-purpose");
  142. expect(await hasInteraction("elicitation")).toBe(false);
  143. expect(await approveV4Permission()).toBe(true);
  144. await waitForInteractionClosed("permission", 30_000);
  145. await waitForUpstreamRequest(
  146. {
  147. includes: [PERMISSION_CHILD_MARKER, PERMISSION_BASH_OUTPUT, PERMISSION_BASH_TOOL_CALL_ID],
  148. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  149. },
  150. "child Bash 允许后输出没有进入 child 下一次模型请求",
  151. 60_000,
  152. );
  153. await waitForUpstreamRequest(
  154. {
  155. includes: [PERMISSION_PARENT_MARKER, PERMISSION_CHILD_DONE, PERMISSION_AGENT_TOOL_CALL_ID],
  156. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  157. },
  158. "child Bash 完成后父会话没有收到 Agent tool_result continuation",
  159. 60_000,
  160. );
  161. await waitForV4AssistantMessageContaining(PERMISSION_PARENT_DONE, 60_000);
  162. await waitForV4Pane(
  163. (snapshot) => !snapshot.canStop,
  164. "subagent permission delegate case 完成后没有回到 idle",
  165. 60_000,
  166. );
  167. });
  168. });
  169. type InteractionKind = "elicitation" | "permission";
  170. interface InteractionDockSnapshot {
  171. parentSessionId: string | null;
  172. originTitle: string;
  173. text: string;
  174. }
  175. async function prepareConversationE2EInMode(mode: "build" | "yolo") {
  176. await prepareV4ConversationE2E();
  177. await switchV4Mode(mode);
  178. await browser.waitUntil(async () => (await getV4ConfigProjection()).mode === mode, {
  179. timeout: 30_000,
  180. timeoutMsg: `subagent interaction case 没有切换到 mode=${mode}`,
  181. });
  182. }
  183. async function waitForSubagentInteractionInParentDock(
  184. kind: InteractionKind,
  185. expectedText: string,
  186. timeoutMs: number,
  187. ): Promise<InteractionDockSnapshot> {
  188. let latest: InteractionDockSnapshot | null = null;
  189. await browser.waitUntil(
  190. async () => {
  191. latest = await readInteractionDock(kind);
  192. return Boolean(
  193. latest?.parentSessionId && latest.originTitle && latest.text.includes(expectedText),
  194. );
  195. },
  196. {
  197. timeout: timeoutMs,
  198. timeoutMsg: `父 task 没有出现带 subagent 来源的 ${kind} interaction; latest=${JSON.stringify(
  199. latest,
  200. )}`,
  201. },
  202. );
  203. const snapshot = await readInteractionDock(kind);
  204. if (!snapshot) {
  205. throw new Error(`等待完成后 ${kind} interaction 仍不存在`);
  206. }
  207. return snapshot;
  208. }
  209. function readInteractionDock(kind: InteractionKind): Promise<InteractionDockSnapshot | null> {
  210. return browser.execute((kindArg) => {
  211. const normalize = (value: string | null | undefined) =>
  212. (value ?? "").replace(/\u00a0/g, " ").trim();
  213. const anchor =
  214. kindArg === "elicitation"
  215. ? document.querySelector<HTMLElement>('[data-elicitation-dialog-body="true"]')
  216. : Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).find((element) => {
  217. const label = normalize(element.getAttribute("aria-label"));
  218. return label === "Permission required" || label === "需要权限";
  219. });
  220. const dock = anchor?.closest<HTMLElement>('[data-v4-composer-dock="true"]');
  221. const pane = dock?.closest<HTMLElement>('[data-testid^="v4-session-pane-"]');
  222. const badge = dock?.querySelector<HTMLElement>('[data-interaction-origin-badge="subagent"]');
  223. if (!anchor || !dock || !pane || !badge) {
  224. return null;
  225. }
  226. return {
  227. parentSessionId: pane.getAttribute("data-session-id"),
  228. originTitle: normalize(badge.getAttribute("title")),
  229. text: normalize(dock.innerText || dock.textContent),
  230. };
  231. }, kind);
  232. }
  233. function hasInteraction(kind: InteractionKind): Promise<boolean> {
  234. return browser.execute((kindArg) => {
  235. if (kindArg === "elicitation") {
  236. return Boolean(document.querySelector<HTMLElement>('[data-elicitation-dialog-body="true"]'));
  237. }
  238. const normalize = (value: string | null | undefined) =>
  239. (value ?? "").replace(/\u00a0/g, " ").trim();
  240. return Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).some(
  241. (element) => {
  242. const label = normalize(element.getAttribute("aria-label"));
  243. return label === "Permission required" || label === "需要权限";
  244. },
  245. );
  246. }, kind);
  247. }
  248. async function waitForInteractionClosed(kind: InteractionKind, timeoutMs: number) {
  249. await browser.waitUntil(async () => !(await hasInteraction(kind)), {
  250. timeout: timeoutMs,
  251. timeoutMsg: `${kind} interaction 响应后没有从父 task 清除`,
  252. });
  253. }
  254. async function submitCustomElicitationAnswer(answer: string) {
  255. const input = await $('[data-elicitation-dialog-body="true"] textarea');
  256. await input.waitForDisplayed({
  257. timeout: 30_000,
  258. timeoutMsg: "AskUserQuestion 自定义回答输入框没有出现",
  259. });
  260. await input.setValue(answer);
  261. await browser.waitUntil(async () => (await input.getValue()) === answer, {
  262. timeout: 10_000,
  263. timeoutMsg: "AskUserQuestion 自定义回答没有写入输入框",
  264. });
  265. const submitButton = await $("//button[contains(., 'Submit') or contains(., '提交')]");
  266. await submitButton.waitForEnabled({
  267. timeout: 30_000,
  268. timeoutMsg: "AskUserQuestion 提交按钮没有启用",
  269. });
  270. await submitButton.click();
  271. }