conversation-session-subagent-respond-to-coordinator.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. import { registerIncomingMessageActiveCases } from "../helpers/incoming-message-active-cases.js";
  2. import {
  3. INCOMING_MESSAGE_MODES,
  4. prepareIncomingMessageCapability,
  5. } from "../helpers/incoming-message-capability.js";
  6. import { assertIncomingMessage } from "../helpers/incoming-message-evidence.js";
  7. import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
  8. import { join } from "node:path";
  9. import { TID_TOOL_SUMMARY_TRIGGER, TID_V4_SUBAGENT_OPEN_SIDE_PANE } from "@zcode/shared";
  10. import { clearAppData } from "../helpers/desktop-app.js";
  11. import type { E2ENetworkCaptureArtifact } from "../helpers/network-capture-proxy.js";
  12. import {
  13. findFirstUpstreamRequestIndex,
  14. getUpstreamRequestEvidence,
  15. getUpstreamRequestRecordCount,
  16. waitForUpstreamRequest,
  17. } from "../helpers/conversation-session-network.js";
  18. import { resolveE2ERuntimePath } from "../helpers/e2e-runtime-paths.js";
  19. import {
  20. getToolCallBlockByToolCallId,
  21. waitForToolCallBlockByToolCallId,
  22. } from "../helpers/conversation-session-tool.js";
  23. import {
  24. clickV4Stop,
  25. getV4PaneSnapshot,
  26. getV4ConfigProjection,
  27. prepareV4ConversationE2E,
  28. sendV4Prompt,
  29. startNewV4Draft,
  30. switchV4Mode,
  31. waitForV4Pane,
  32. waitForV4TimelineContaining,
  33. } from "../helpers/v4-conversation.js";
  34. const E2E_TIMEOUT_MS = 240_000;
  35. const E2E_ROOT = resolveE2ERuntimePath("conversation-session-subagent-respond-to-coordinator");
  36. const RELEASE_FILE = join(E2E_ROOT, "release-child-bash");
  37. const FINAL_RELEASE_FILE = join(E2E_ROOT, "release-child-final");
  38. const ERROR_CHILD_RELEASE_FILE = join(E2E_ROOT, "release-error-child");
  39. const CONTINUED_WORK_FILE = join(E2E_ROOT, "continued-work.txt");
  40. const PARENT_AGENT_TOOL_CALL_ID = "toolu_e2e_subagent_response_agent";
  41. const RESPOND_TO_COORDINATOR_TOOL_CALL_ID = "toolu_e2e_subagent_respond_to_coordinator";
  42. const TASK_OUTPUT_TOOL_CALL_ID = "toolu_e2e_task_output_card";
  43. const ERROR_AGENT_TOOL_CALL_ID = "toolu_e2e_error_agent";
  44. const ERROR_RESPOND_TO_COORDINATOR_TOOL_CALL_ID = "toolu_e2e_error_respond_to_coordinator";
  45. const ERROR_TASK_OUTPUT_TOOL_CALL_ID = "toolu_e2e_error_task_output";
  46. const MISSING_TASK_ID = "task_e2e_missing";
  47. // Bug 原因:工具执行失败已经统一使用通用生命周期文案;旧断言仍期待 TaskOutput / RespondToCoordinator
  48. // 的专属失败文案,导致产品正确显示“执行失败”时 E2E 误报。中英文都按共享状态文案校验。
  49. const TOOL_EXECUTION_FAILURE_LABELS = ["执行失败", "Failed"] as const;
  50. describe("会话区 BG25/O18/O19 coordinator 与 TaskOutput 专属卡片 E2E", () => {
  51. before(async function () {
  52. this.timeout(E2E_TIMEOUT_MS);
  53. await prepareV4ConversationE2E();
  54. });
  55. beforeEach(async function () {
  56. this.timeout(E2E_TIMEOUT_MS);
  57. await mkdir(E2E_ROOT, { recursive: true });
  58. await rm(RELEASE_FILE, { force: true });
  59. await rm(FINAL_RELEASE_FILE, { force: true });
  60. await rm(ERROR_CHILD_RELEASE_FILE, { force: true });
  61. await writeFile(CONTINUED_WORK_FILE, "E2E_SUBAGENT_CONTINUED_WORK\n", "utf-8");
  62. await startNewV4Draft();
  63. // Bug 原因:legacy helper 会遍历所有 workspace,只要任一旧 workspace 是 yolo
  64. // 就误判当前 v4 draft 已切换,实际 session 仍以 build 启动,child Bash 永久等权限。
  65. // 必须通过当前 v4 composer 明确写入 draft mode,再启动本 case 的 session。
  66. await selectCurrentV4FullAccessMode();
  67. });
  68. afterEach(async () => {
  69. await writeFile(RELEASE_FILE, "release\n", "utf-8").catch(() => undefined);
  70. await writeFile(FINAL_RELEASE_FILE, "release\n", "utf-8").catch(() => undefined);
  71. await writeFile(ERROR_CHILD_RELEASE_FILE, "release\n", "utf-8").catch(() => undefined);
  72. await stopIfBusy();
  73. await rm(E2E_ROOT, { recursive: true, force: true }).catch(() => undefined);
  74. });
  75. after(async () => {
  76. await browser.electron.restoreAllMocks();
  77. await clearAppData();
  78. });
  79. for (const { label, mcs } of INCOMING_MESSAGE_MODES) {
  80. it(`${label} 渲染 child coordinator 回复与 completed TaskOutput,同时保持父子可见性边界`, async function () {
  81. this.timeout(E2E_TIMEOUT_MS);
  82. await prepareIncomingMessageCapability(mcs);
  83. await selectCurrentV4FullAccessMode();
  84. const prompt =
  85. "E2E_SUBAGENT_RESPOND_TO_COORDINATOR: Launch a background agent, ask it E2E_SUBAGENT_COORDINATOR_QUESTION while it is running, consume its response, and wait for E2E_SUBAGENT_FINAL_RESULT.";
  86. const requestCountBefore = await getUpstreamRequestRecordCount();
  87. // Bug 原因:v4 已删除 legacy chat-input/chat-view;旧 BG25 在 before hook
  88. // 结束,RespondToCoordinator 主链路实际未运行。这里统一改读 v4 pane/timeline。
  89. await sendV4Prompt(prompt);
  90. await waitForV4TimelineContaining("E2E_SUBAGENT_RESPOND_TO_COORDINATOR", 60000);
  91. await waitForToolCallBlockByToolCallId(PARENT_AGENT_TOOL_CALL_ID, 60_000);
  92. const sendMessageResultIndex = await waitForFirstRequestIndex(
  93. {
  94. includes: [
  95. "E2E_SUBAGENT_RESPOND_TO_COORDINATOR",
  96. "E2E_SUBAGENT_COORDINATOR_QUESTION",
  97. "sent to its active turn",
  98. ],
  99. },
  100. requestCountBefore,
  101. "SendMessage delivery result 没有进入 parent provider request",
  102. );
  103. await waitForV4Pane(
  104. (snapshot) => !snapshot.canStop,
  105. "parent SendMessage ack 没有完成",
  106. 30000,
  107. );
  108. await writeFile(RELEASE_FILE, "release\n", "utf-8");
  109. const childResponseToolsIndex = await waitForFirstRequestIndex(
  110. {
  111. includes: [
  112. "E2E_SUBAGENT_CHILD_BASH_RELEASED",
  113. "The coordinator sent a message while you were working:",
  114. "E2E_SUBAGENT_COORDINATOR_QUESTION",
  115. "E2E_SUBAGENT_COORDINATOR_QUESTION_PAYLOAD",
  116. ],
  117. },
  118. sendMessageResultIndex,
  119. "child 没有在 Bash tool result 后收到 coordinator question",
  120. );
  121. const childContinuedWorkIndex = await waitForFirstRequestIndex(
  122. {
  123. includes: [
  124. "E2E_SUBAGENT_RESPONSE_QUEUED",
  125. "was queued for the coordinator",
  126. "E2E_SUBAGENT_CONTINUED_WORK",
  127. ],
  128. },
  129. childResponseToolsIndex,
  130. "RespondToCoordinator 与 Read tool result 没有共同进入 child 后续 request",
  131. );
  132. const parentResponseIndex = await waitForFirstRequestIndex(
  133. {
  134. includes: [
  135. "<subagent-message>",
  136. "E2E_SUBAGENT_RESPONSE_QUEUED",
  137. "E2E_SUBAGENT_COORDINATOR_QUESTION_PAYLOAD",
  138. ],
  139. },
  140. sendMessageResultIndex,
  141. "parent provider request 没有消费 model-only subagent response",
  142. );
  143. await waitForV4TimelineContaining("E2E_SUBAGENT_COORDINATOR_CONSUMED", 90000);
  144. await waitForV4Pane(
  145. (snapshot) => !snapshot.canStop,
  146. "parent 消费 coordinator response 后没有回到 idle",
  147. 90_000,
  148. );
  149. // Bug 原因:child 原来固定 sleep 1 秒后结束,慢机器上 completion notification
  150. // 会先并入 parent response turn,使 strict replay 无法分别验证两次 provider request。
  151. // 只有 parent 已消费 response 且回到 idle 后才放行 child 终态,固定产品要求的顺序。
  152. await writeFile(FINAL_RELEASE_FILE, "release\n", "utf-8");
  153. const childFinalIndex = await waitForFirstRequestIndex(
  154. { includes: ["E2E_SUBAGENT_CONTINUED_WORK_TOOL_DONE"] },
  155. childContinuedWorkIndex,
  156. "child 回复 coordinator 后没有继续执行普通工作 tool",
  157. );
  158. const notificationIndex = await waitForFirstRequestIndex(
  159. {
  160. includes: ["<task-notification>", "E2E_SUBAGENT_FINAL_RESULT"],
  161. lastUserMessageIncludes: ["<task-notification>"],
  162. },
  163. Math.min(parentResponseIndex, childFinalIndex),
  164. "child final completion notification 没有进入 parent provider request",
  165. );
  166. const childEvidence = await getUpstreamRequestEvidence(
  167. {
  168. includes: [
  169. "The coordinator sent a message while you were working:",
  170. "E2E_SUBAGENT_COORDINATOR_QUESTION_PAYLOAD",
  171. ],
  172. },
  173. { afterIndex: childResponseToolsIndex - 1, beforeIndex: childResponseToolsIndex + 1 },
  174. );
  175. await assertIncomingMessage(childEvidence[0]!.requestJson, {
  176. presentation: "coordinator_steer",
  177. marker: "E2E_SUBAGENT_COORDINATOR_QUESTION_PAYLOAD",
  178. role: mcs ? "system" : "user",
  179. evidenceLabel: label,
  180. body: "E2E_SUBAGENT_COORDINATOR_QUESTION\n\nE2E_SUBAGENT_COORDINATOR_QUESTION_PAYLOAD",
  181. });
  182. const peerEvidence = await getUpstreamRequestEvidence(
  183. { includes: ["<subagent-message>"] },
  184. { afterIndex: parentResponseIndex - 1, beforeIndex: parentResponseIndex + 1 },
  185. );
  186. await assertIncomingMessage(peerEvidence[0]!.requestJson, {
  187. presentation: "subagent_reply",
  188. evidenceLabel: label,
  189. marker: "E2E_SUBAGENT_RESPONSE_QUEUED",
  190. role: "user",
  191. });
  192. const notificationEvidence = await getUpstreamRequestEvidence(
  193. { includes: ["<task-notification>", "E2E_SUBAGENT_FINAL_RESULT"] },
  194. { afterIndex: notificationIndex - 1, beforeIndex: notificationIndex + 1 },
  195. );
  196. await assertIncomingMessage(notificationEvidence[0]!.requestJson, {
  197. presentation: "task_notification",
  198. evidenceLabel: label,
  199. marker: "E2E_SUBAGENT_FINAL_RESULT",
  200. role: "user",
  201. });
  202. const responsePosition = await getRequestMarkerPosition(
  203. parentResponseIndex,
  204. "<subagent-message>",
  205. );
  206. const notificationPosition = await getRequestMarkerPosition(
  207. notificationIndex,
  208. "<task-notification>",
  209. );
  210. expect(compareRequestPositions(responsePosition, notificationPosition)).toBeLessThan(0);
  211. // v4 P9 只在父 timeline 保留 Agent/subagent 摘要,child tool rows 归 child
  212. // conversation,不再嵌进父 Agent 卡。BG25 的产品语义是双向消息链与 child
  213. // 继续执行,前面的 provider request 顺序已覆盖;旧 renderer-store 镜像断言应移除。
  214. const timeline = await getV4PaneSnapshot();
  215. expect(timeline.timelineText).not.toContain("E2E_SUBAGENT_RESPONSE_QUEUED");
  216. expect(timeline.timelineText).not.toContain("<subagent-message>");
  217. expect(await getToolCallBlockByToolCallId(RESPOND_TO_COORDINATOR_TOOL_CALL_ID)).toBeNull();
  218. await waitForV4Pane(
  219. (snapshot) => !snapshot.canStop,
  220. "RespondToCoordinator completion 后 parent 会话没有回到 idle",
  221. 90_000,
  222. );
  223. await assertTaskOutputCard();
  224. await assertRespondToCoordinatorCard();
  225. // 修复原因:BG25 不覆盖 compact;若 spec 误回 manual-review,小窗口配置会插入无关 divider。
  226. const compactMarkerCount = await browser.execute(
  227. () =>
  228. document.querySelectorAll('[data-row-kind="timelineMarker"][data-marker-type="compact"]')
  229. .length,
  230. );
  231. expect(compactMarkerCount).toBe(0);
  232. });
  233. }
  234. it("组合渲染 TaskOutput 未知 ID 与 child RespondToCoordinator 输入错误", async function () {
  235. this.timeout(E2E_TIMEOUT_MS);
  236. const requestCountBefore = await getUpstreamRequestRecordCount();
  237. await sendV4Prompt(
  238. "E2E_TOOL_RENDERER_ERROR_CARDS: Launch the controlled background child and wait for E2E_ERROR_AGENT_COMPLETED.",
  239. );
  240. await waitForV4TimelineContaining("E2E_TOOL_RENDERER_ERROR_CARDS", 60_000);
  241. await waitForToolCallBlockByToolCallId(ERROR_AGENT_TOOL_CALL_ID, 60_000);
  242. const agentLaunchResultIndex = await waitForFirstRequestIndex(
  243. {
  244. includes: [
  245. "E2E_TOOL_RENDERER_ERROR_CARDS",
  246. "E2E_RESPOND_ERROR_CHILD",
  247. "Async agent launched successfully",
  248. ],
  249. },
  250. requestCountBefore,
  251. "错误卡片 case 的 background Agent 启动结果没有进入 parent provider request",
  252. );
  253. await waitForV4TimelineContaining("E2E_ERROR_AGENT_STARTED", 60_000);
  254. await waitForV4Pane(
  255. (snapshot) => !snapshot.canStop,
  256. "错误卡片 case 的 Agent 启动 turn 没有回到 idle",
  257. 60_000,
  258. );
  259. await writeFile(ERROR_CHILD_RELEASE_FILE, "release\n", "utf-8");
  260. const childValidationErrorIndex = await waitForFirstRequestIndex(
  261. {
  262. includes: [
  263. ERROR_RESPOND_TO_COORDINATOR_TOOL_CALL_ID,
  264. "InputValidationError: RespondToCoordinator failed due to the following issue:",
  265. "The required parameter `message` is missing",
  266. ],
  267. lastUserMessageIncludes: [
  268. "InputValidationError: RespondToCoordinator failed due to the following issue:",
  269. ],
  270. },
  271. agentLaunchResultIndex,
  272. "RespondToCoordinator 输入校验错误没有进入 child provider continuation",
  273. );
  274. await waitForFirstRequestIndex(
  275. {
  276. includes: ["<task-notification>", "E2E_RESPOND_ERROR_CHILD_DONE"],
  277. lastUserMessageIncludes: ["<task-notification>", "E2E_RESPOND_ERROR_CHILD_DONE"],
  278. },
  279. childValidationErrorIndex,
  280. "错误 child 的完成通知没有进入 parent provider request",
  281. );
  282. await waitForV4TimelineContaining("E2E_ERROR_AGENT_COMPLETED", 60_000);
  283. await waitForV4Pane(
  284. (snapshot) => !snapshot.canStop,
  285. "错误 child 完成后 parent 没有回到 idle",
  286. 60_000,
  287. );
  288. expect(
  289. await getToolCallBlockByToolCallId(ERROR_RESPOND_TO_COORDINATOR_TOOL_CALL_ID),
  290. ).toBeNull();
  291. await assertTaskOutputErrorCard();
  292. await assertRespondToCoordinatorErrorCard();
  293. });
  294. registerIncomingMessageActiveCases();
  295. });
  296. async function assertTaskOutputCard(): Promise<void> {
  297. const requestCountBefore = await getUpstreamRequestRecordCount();
  298. await sendV4Prompt(
  299. "E2E_TASK_OUTPUT_TOOL_CARD: Call TaskOutput with block=false and timeout=0 for the completed background agent, then report E2E_TASK_OUTPUT_TOOL_CARD_DONE.",
  300. );
  301. await waitForFirstRequestIndex(
  302. {
  303. includes: [
  304. "toolu_e2e_task_output_card",
  305. "<retrieval_status>success</retrieval_status>",
  306. "<task_id>agent_",
  307. "<status>completed</status>",
  308. "E2E_SUBAGENT_FINAL_RESULT",
  309. ],
  310. },
  311. requestCountBefore,
  312. "TaskOutput completed result 没有进入 parent provider request",
  313. );
  314. await waitForV4TimelineContaining("E2E_TASK_OUTPUT_TOOL_CARD_DONE", 60_000);
  315. await waitForV4Pane(
  316. (snapshot) => !snapshot.canStop,
  317. "TaskOutput tool turn 没有回到 idle",
  318. 60_000,
  319. );
  320. const collapsed = await waitForToolCallBlockByToolCallId(TASK_OUTPUT_TOOL_CALL_ID, 30_000);
  321. expect(collapsed.status).toBe("completed");
  322. expect(collapsed.text).toMatch(/agent_[A-Za-z0-9_-]+/u);
  323. expect(["已获取", "Output retrieved"].some((label) => collapsed.text.includes(label))).toBe(true);
  324. expect(collapsed.text).not.toContain("E2E_SUBAGENT_FINAL_RESULT");
  325. assertTaskOutputProviderFieldsHidden(collapsed.text);
  326. const collapsedState = await readToolCardState(collapsed.testId);
  327. expect(collapsedState.ariaExpanded).toBe("false");
  328. expect(collapsedState.hasCollapsibleContent).toBe(true);
  329. await browser.execute(
  330. (blockTestId, summaryTriggerPrefix) => {
  331. const block = document.querySelector<HTMLElement>(`[data-testid="${blockTestId}"]`);
  332. block?.querySelector<HTMLElement>(`[data-testid^="${summaryTriggerPrefix}-"]`)?.click();
  333. },
  334. collapsed.testId,
  335. TID_TOOL_SUMMARY_TRIGGER,
  336. );
  337. await browser.waitUntil(
  338. async () => {
  339. const state = await readToolCardState(collapsed.testId);
  340. return state.ariaExpanded === "true" && state.text.includes("E2E_SUBAGENT_FINAL_RESULT");
  341. },
  342. {
  343. timeout: 10_000,
  344. timeoutMsg: "TaskOutput 卡片展开后没有显示 task output",
  345. },
  346. );
  347. const expandedState = await readToolCardState(collapsed.testId);
  348. assertTaskOutputProviderFieldsHidden(expandedState.text);
  349. }
  350. async function assertRespondToCoordinatorCard(): Promise<void> {
  351. await openSubagentSidePane(PARENT_AGENT_TOOL_CALL_ID);
  352. const responseCard = await waitForToolCallBlockByToolCallId(
  353. RESPOND_TO_COORDINATOR_TOOL_CALL_ID,
  354. 30_000,
  355. );
  356. expect(responseCard.status).toBe("completed");
  357. expect(responseCard.text).toContain("E2E_SUBAGENT_RESPONSE_QUEUED");
  358. expect(["回复已排队", "Reply queued"].some((label) => responseCard.text.includes(label))).toBe(
  359. true,
  360. );
  361. expect(responseCard.text).not.toContain("E2E_SUBAGENT_COORDINATOR_QUESTION_PAYLOAD");
  362. expect(responseCard.text).not.toContain("was queued for the coordinator");
  363. expect(responseCard.text).not.toMatch(/response_[A-Za-z0-9_-]+/u);
  364. const responseCardState = await readToolCardState(responseCard.testId);
  365. expect(responseCardState.ariaExpanded).toBeNull();
  366. expect(responseCardState.hasCollapsibleContent).toBe(false);
  367. }
  368. async function assertTaskOutputErrorCard(): Promise<void> {
  369. const requestCountBefore = await getUpstreamRequestRecordCount();
  370. await sendV4Prompt(
  371. `E2E_TASK_OUTPUT_ERROR_CARD: Call TaskOutput for ${MISSING_TASK_ID}, then report E2E_TASK_OUTPUT_ERROR_DONE.`,
  372. );
  373. await waitForFirstRequestIndex(
  374. {
  375. includes: [
  376. ERROR_TASK_OUTPUT_TOOL_CALL_ID,
  377. `<tool_use_error>No task found with ID: ${MISSING_TASK_ID}</tool_use_error>`,
  378. ],
  379. lastUserMessageIncludes: [`No task found with ID: ${MISSING_TASK_ID}`],
  380. },
  381. requestCountBefore,
  382. "TaskOutput 未知 ID 错误没有进入 parent provider continuation",
  383. );
  384. await waitForV4TimelineContaining("E2E_TASK_OUTPUT_ERROR_DONE", 60_000);
  385. await waitForV4Pane(
  386. (snapshot) => !snapshot.canStop,
  387. "TaskOutput 错误 turn 没有回到 idle",
  388. 60_000,
  389. );
  390. const card = await waitForToolCallBlockByToolCallId(ERROR_TASK_OUTPUT_TOOL_CALL_ID, 30_000);
  391. expect(card.status).toBe("failed");
  392. expect(card.text).toContain(MISSING_TASK_ID);
  393. expect(TOOL_EXECUTION_FAILURE_LABELS.some((label) => card.text.includes(label))).toBe(true);
  394. expect(card.text).not.toContain("No task found with ID");
  395. expect(card.text).not.toContain("<tool_use_error>");
  396. const state = await readToolCardState(card.testId);
  397. expect(state.ariaExpanded).toBeNull();
  398. expect(state.hasCollapsibleContent).toBe(false);
  399. }
  400. async function assertRespondToCoordinatorErrorCard(): Promise<void> {
  401. await openSubagentSidePane(ERROR_AGENT_TOOL_CALL_ID);
  402. const card = await waitForToolCallBlockByToolCallId(
  403. ERROR_RESPOND_TO_COORDINATOR_TOOL_CALL_ID,
  404. 30_000,
  405. );
  406. expect(card.status).toBe("failed");
  407. expect(card.text).toContain("E2E_RESPOND_ERROR_SUMMARY");
  408. expect(TOOL_EXECUTION_FAILURE_LABELS.some((label) => card.text.includes(label))).toBe(true);
  409. expect(card.text).not.toContain("InputValidationError");
  410. expect(card.text).not.toContain("The required parameter");
  411. expect(card.text).not.toContain("<tool_use_error>");
  412. const state = await readToolCardState(card.testId);
  413. expect(state.ariaExpanded).toBeNull();
  414. expect(state.hasCollapsibleContent).toBe(false);
  415. }
  416. async function openSubagentSidePane(parentAgentToolCallId: string): Promise<void> {
  417. const parentAgent = await waitForToolCallBlockByToolCallId(parentAgentToolCallId, 30_000);
  418. const parentAgentElement = await $(`[data-testid="${parentAgent.testId}"]`);
  419. const openChildAction = await parentAgentElement.$(
  420. `[data-testid^="${TID_V4_SUBAGENT_OPEN_SIDE_PANE}-"]`,
  421. );
  422. await openChildAction.waitForDisplayed({
  423. timeout: 10_000,
  424. timeoutMsg: "BG25 parent Agent 卡没有 child conversation 入口",
  425. });
  426. const actionTestId = await openChildAction.getAttribute("data-testid");
  427. const childSessionId = actionTestId?.slice(`${TID_V4_SUBAGENT_OPEN_SIDE_PANE}-`.length);
  428. if (!childSessionId) {
  429. throw new Error("BG25 parent Agent 卡的 child session 入口缺少 session id");
  430. }
  431. // 测试原因:生产包中的 Agent 摘要可能在 completion 投影时重挂载,单次
  432. // WebDriver element click 会落到旧节点。每轮都从当前 DOM 重新定位并点击,
  433. // 只以目标 child session pane 真正可见作为成功条件,不改生产交互。
  434. for (let attempt = 0; attempt < 3; attempt += 1) {
  435. await browser.execute(
  436. (blockTestId, actionId) => {
  437. document
  438. .querySelector<HTMLElement>(`[data-testid="${blockTestId}"] [data-testid="${actionId}"]`)
  439. ?.click();
  440. },
  441. parentAgent.testId,
  442. actionTestId,
  443. );
  444. try {
  445. await browser.waitUntil(
  446. () =>
  447. browser.execute(
  448. (expectedChildSessionId) =>
  449. Boolean(
  450. document.querySelector(
  451. '[data-side-pane-tab-id^="subagent-session:"][data-state="active"]',
  452. ),
  453. ) &&
  454. Array.from(
  455. document.querySelectorAll<HTMLElement>(
  456. `[data-session-id="${expectedChildSessionId}"]`,
  457. ),
  458. ).some((pane) => pane.offsetParent !== null),
  459. childSessionId,
  460. ),
  461. {
  462. timeout: 10_000,
  463. timeoutMsg: "BG25 child conversation 没有在右侧面板打开",
  464. },
  465. );
  466. return;
  467. } catch {
  468. if (attempt === 2) {
  469. throw new Error("BG25 child conversation 没有在右侧面板打开");
  470. }
  471. }
  472. }
  473. }
  474. function assertTaskOutputProviderFieldsHidden(text: string): void {
  475. expect(text).not.toContain("<retrieval_status>");
  476. expect(text).not.toContain("<task_id>");
  477. expect(text).not.toContain("<task_type>");
  478. expect(text).not.toContain("<status>");
  479. expect(text).not.toContain("<exit_code>");
  480. expect(text).not.toContain("<output>");
  481. expect(text).not.toContain("<error>");
  482. expect(text).not.toContain("<persisted-output>");
  483. expect(text).not.toContain("E2E RespondToCoordinator background child");
  484. }
  485. function readToolCardState(blockTestId: string): Promise<{
  486. ariaExpanded: string | null;
  487. hasCollapsibleContent: boolean;
  488. text: string;
  489. }> {
  490. return browser.execute(
  491. (toolBlockTestId, summaryTriggerPrefix) => {
  492. const block = document.querySelector<HTMLElement>(`[data-testid="${toolBlockTestId}"]`);
  493. const summary = block?.querySelector<HTMLElement>(
  494. `[data-testid^="${summaryTriggerPrefix}-"]`,
  495. );
  496. return {
  497. ariaExpanded: summary?.getAttribute("aria-expanded") ?? null,
  498. hasCollapsibleContent: Boolean(block?.querySelector('[data-slot="collapsible-content"]')),
  499. text: block?.innerText.replace(/\u00a0/g, " ").trim() ?? "",
  500. };
  501. },
  502. blockTestId,
  503. TID_TOOL_SUMMARY_TRIGGER,
  504. );
  505. }
  506. async function waitForFirstRequestIndex(
  507. query: Parameters<typeof waitForUpstreamRequest>[0],
  508. afterIndex: number,
  509. timeoutMsg: string,
  510. ) {
  511. await waitForUpstreamRequest(query, timeoutMsg, 60_000, { afterIndex });
  512. const index = await findFirstUpstreamRequestIndex(query, { afterIndex });
  513. if (index === null) {
  514. throw new Error(`${timeoutMsg}; request disappeared after wait`);
  515. }
  516. return index;
  517. }
  518. async function getRequestMarkerPosition(requestIndex: number, marker: string) {
  519. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH?.trim();
  520. if (!capturePath) {
  521. throw new Error("E2E_PROVIDER_CAPTURE_PATH is required for request ordering assertions");
  522. }
  523. const artifact = JSON.parse(await readFile(capturePath, "utf-8")) as E2ENetworkCaptureArtifact;
  524. const body = JSON.stringify(artifact.records[requestIndex]?.requestJson ?? "");
  525. const contentIndex = body.indexOf(marker);
  526. if (contentIndex < 0) {
  527. throw new Error(`request ${requestIndex} does not contain marker ${marker}`);
  528. }
  529. return { requestIndex, contentIndex };
  530. }
  531. function compareRequestPositions(
  532. left: { requestIndex: number; contentIndex: number },
  533. right: { requestIndex: number; contentIndex: number },
  534. ) {
  535. return left.requestIndex === right.requestIndex
  536. ? left.contentIndex - right.contentIndex
  537. : left.requestIndex - right.requestIndex;
  538. }
  539. async function selectCurrentV4FullAccessMode() {
  540. // Bug 根因:legacy session store 的 workspace configOptions 已不是 V4 草稿模式的
  541. // 权威投影,且 DOM element.click() 无法稳定确认 Radix Select。复用 V4 helper 的
  542. // 键盘确认链路,并以 composer 的 data-mode 投影判断配置命令已经回流。
  543. await switchV4Mode("yolo");
  544. await browser.waitUntil(async () => (await getV4ConfigProjection()).mode === "yolo", {
  545. timeout: 30_000,
  546. timeoutMsg: "BG25 当前 v4 composer 没有收敛到 Full access mode",
  547. });
  548. }
  549. async function stopIfBusy() {
  550. const snapshot = await getV4PaneSnapshot();
  551. if (!snapshot.canStop) return;
  552. await clickV4Stop();
  553. await waitForV4Pane(
  554. (state) => !state.canStop,
  555. "RespondToCoordinator E2E teardown stop 后没有回到 idle",
  556. 60_000,
  557. );
  558. }