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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. import { clearAppData } from "#e2e/helpers/desktop-app";
  2. import { waitForUpstreamRequest } from "#e2e/helpers/conversation-session-network";
  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 "#e2e/helpers/v4-conversation";
  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. // Host 创建的正式 ID 使用 session_;前缀不是产品身份合同。
  78. (snapshot) => Boolean(snapshot.sessionId && snapshot.sessionId !== "draft"),
  79. "subagent AskUserQuestion case 发送后没有绑定真实 session",
  80. 30_000,
  81. );
  82. await waitForV4TimelineContaining(`${YOLO_PARENT_MARKER}_${runId}`, 30_000);
  83. // 回归原因:V4 以 parent ProductProjection.pendingInteractions 为权威,不能再读取
  84. // legacy taskUiByTaskId.elicitationRequest;父 pane 中的可见 dock 才是产品合同。
  85. const interaction = await waitForSubagentInteractionInParentDock(
  86. "elicitation",
  87. YOLO_QUESTION_MARKER,
  88. 60_000,
  89. );
  90. expect(interaction.parentSessionId).toBe(parentPane.sessionId);
  91. expect(interaction.originTitle).toContain("general-purpose");
  92. await submitCustomElicitationAnswer(answer);
  93. await waitForInteractionClosed("elicitation", 30_000);
  94. await waitForUpstreamRequest(
  95. {
  96. includes: [answer, YOLO_CHILD_MARKER, YOLO_ASK_TOOL_CALL_ID],
  97. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  98. },
  99. "child AskUserQuestion 回答没有进入 child 下一次模型请求",
  100. 60_000,
  101. );
  102. await waitForUpstreamRequest(
  103. {
  104. includes: [YOLO_PARENT_MARKER, YOLO_CHILD_DONE, YOLO_AGENT_TOOL_CALL_ID],
  105. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  106. },
  107. "child AskUserQuestion 完成后父会话没有收到 Agent tool_result continuation",
  108. 60_000,
  109. );
  110. await waitForV4AssistantMessageContaining(YOLO_PARENT_DONE, 60_000);
  111. await waitForV4Pane(
  112. (snapshot) => !snapshot.canStop,
  113. "subagent AskUserQuestion delegate case 完成后没有回到 idle",
  114. 60_000,
  115. );
  116. });
  117. it("T02: build 模式下 child Bash permission request 代理到父 task", async function () {
  118. this.timeout(180_000);
  119. await prepareConversationE2EInMode("build");
  120. const runId = Date.now();
  121. const prompt = [
  122. `${PERMISSION_PARENT_MARKER}_${runId}: Use the Agent tool with subagent_type "general-purpose".`,
  123. `Ask the child to trigger ${PERMISSION_CHILD_MARKER}, run one Bash command, and then finish.`,
  124. `After the child returns, reply with exactly ${PERMISSION_PARENT_DONE}.`,
  125. ].join(" ");
  126. await sendV4Prompt(prompt);
  127. const parentPane = await waitForV4Pane(
  128. (snapshot) => Boolean(snapshot.sessionId && snapshot.sessionId !== "draft"),
  129. "subagent permission case 发送后没有绑定真实 session",
  130. 30_000,
  131. );
  132. await waitForV4TimelineContaining(`${PERMISSION_PARENT_MARKER}_${runId}`, 30_000);
  133. const dockState = await waitForV4PermissionDialogInComposerDock(60_000);
  134. expect(dockState.inDock).toBe(true);
  135. expect(dockState.composerHidden).toBe(true);
  136. const interaction = await waitForSubagentInteractionInParentDock(
  137. "permission",
  138. PERMISSION_BASH_OUTPUT,
  139. 60_000,
  140. );
  141. expect(interaction.parentSessionId).toBe(parentPane.sessionId);
  142. expect(interaction.originTitle).toContain("general-purpose");
  143. expect(await hasInteraction("elicitation")).toBe(false);
  144. expect(await approveV4Permission()).toBe(true);
  145. await waitForInteractionClosed("permission", 30_000);
  146. await waitForUpstreamRequest(
  147. {
  148. includes: [PERMISSION_CHILD_MARKER, PERMISSION_BASH_OUTPUT, PERMISSION_BASH_TOOL_CALL_ID],
  149. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  150. },
  151. "child Bash 允许后输出没有进入 child 下一次模型请求",
  152. 60_000,
  153. );
  154. await waitForUpstreamRequest(
  155. {
  156. includes: [PERMISSION_PARENT_MARKER, PERMISSION_CHILD_DONE, PERMISSION_AGENT_TOOL_CALL_ID],
  157. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  158. },
  159. "child Bash 完成后父会话没有收到 Agent tool_result continuation",
  160. 60_000,
  161. );
  162. await waitForV4AssistantMessageContaining(PERMISSION_PARENT_DONE, 60_000);
  163. await waitForV4Pane(
  164. (snapshot) => !snapshot.canStop,
  165. "subagent permission delegate case 完成后没有回到 idle",
  166. 60_000,
  167. );
  168. });
  169. });
  170. type InteractionKind = "elicitation" | "permission";
  171. interface InteractionDockSnapshot {
  172. parentSessionId: string | null;
  173. originTitle: string;
  174. text: string;
  175. }
  176. async function prepareConversationE2EInMode(mode: "build" | "yolo") {
  177. await prepareV4ConversationE2E();
  178. await switchV4Mode(mode);
  179. await browser.waitUntil(async () => (await getV4ConfigProjection()).mode === mode, {
  180. timeout: 30_000,
  181. timeoutMsg: `subagent interaction case 没有切换到 mode=${mode}`,
  182. });
  183. }
  184. async function waitForSubagentInteractionInParentDock(
  185. kind: InteractionKind,
  186. expectedText: string,
  187. timeoutMs: number,
  188. ): Promise<InteractionDockSnapshot> {
  189. let latest: InteractionDockSnapshot | null = null;
  190. await browser.waitUntil(
  191. async () => {
  192. latest = await readInteractionDock(kind);
  193. return Boolean(
  194. latest?.parentSessionId && latest.originTitle && latest.text.includes(expectedText),
  195. );
  196. },
  197. {
  198. timeout: timeoutMs,
  199. timeoutMsg: `父 task 没有出现带 subagent 来源的 ${kind} interaction; latest=${JSON.stringify(
  200. latest,
  201. )}`,
  202. },
  203. );
  204. const snapshot = await readInteractionDock(kind);
  205. if (!snapshot) {
  206. throw new Error(`等待完成后 ${kind} interaction 仍不存在`);
  207. }
  208. return snapshot;
  209. }
  210. function readInteractionDock(kind: InteractionKind): Promise<InteractionDockSnapshot | null> {
  211. return browser.execute((kindArg) => {
  212. const normalize = (value: string | null | undefined) =>
  213. (value ?? "").replace(/\u00a0/g, " ").trim();
  214. const anchor =
  215. kindArg === "elicitation"
  216. ? document.querySelector<HTMLElement>('[data-elicitation-dialog-body="true"]')
  217. : Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).find((element) => {
  218. const label = normalize(element.getAttribute("aria-label"));
  219. return label === "Permission required" || label === "需要权限";
  220. });
  221. const dock = anchor?.closest<HTMLElement>('[data-v4-composer-dock="true"]');
  222. const pane = dock?.closest<HTMLElement>('[data-testid^="v4-session-pane-"]');
  223. const badge = dock?.querySelector<HTMLElement>('[data-interaction-origin-badge="subagent"]');
  224. if (!anchor || !dock || !pane || !badge) {
  225. return null;
  226. }
  227. return {
  228. parentSessionId: pane.getAttribute("data-session-id"),
  229. originTitle: normalize(badge.getAttribute("title")),
  230. text: normalize(dock.innerText || dock.textContent),
  231. };
  232. }, kind);
  233. }
  234. function hasInteraction(kind: InteractionKind): Promise<boolean> {
  235. return browser.execute((kindArg) => {
  236. if (kindArg === "elicitation") {
  237. return Boolean(document.querySelector<HTMLElement>('[data-elicitation-dialog-body="true"]'));
  238. }
  239. const normalize = (value: string | null | undefined) =>
  240. (value ?? "").replace(/\u00a0/g, " ").trim();
  241. return Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).some(
  242. (element) => {
  243. const label = normalize(element.getAttribute("aria-label"));
  244. return label === "Permission required" || label === "需要权限";
  245. },
  246. );
  247. }, kind);
  248. }
  249. async function waitForInteractionClosed(kind: InteractionKind, timeoutMs: number) {
  250. await browser.waitUntil(async () => !(await hasInteraction(kind)), {
  251. timeout: timeoutMs,
  252. timeoutMsg: `${kind} interaction 响应后没有从父 task 清除`,
  253. });
  254. }
  255. async function submitCustomElicitationAnswer(answer: string) {
  256. const input = await $('[data-elicitation-dialog-body="true"] textarea');
  257. await input.waitForDisplayed({
  258. timeout: 30_000,
  259. timeoutMsg: "AskUserQuestion 自定义回答输入框没有出现",
  260. });
  261. await input.setValue(answer);
  262. await browser.waitUntil(async () => (await input.getValue()) === answer, {
  263. timeout: 10_000,
  264. timeoutMsg: "AskUserQuestion 自定义回答没有写入输入框",
  265. });
  266. const submitButton = await $("//button[contains(., 'Submit') or contains(., '提交')]");
  267. await submitButton.waitForEnabled({
  268. timeout: 30_000,
  269. timeoutMsg: "AskUserQuestion 提交按钮没有启用",
  270. });
  271. await submitButton.click();
  272. }