conversation-session-background-subagent-rate-limit.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. import { TID_V4_SUBAGENT_OPEN_SIDE_PANE } from "@zcode/shared";
  2. import { clearAppData } from "../helpers/desktop-app.js";
  3. import { waitForUpstreamRequest } from "../helpers/conversation-session-network.js";
  4. import {
  5. expandAssistantHistoriesWithContent,
  6. waitForToolCallBlockByToolCallId,
  7. } from "../helpers/conversation-session-tool.js";
  8. import { getToolCallDiagnostics } from "../helpers/conversation-session-tool-diagnostics.js";
  9. import {
  10. getV4PaneSnapshot,
  11. prepareV4ConversationE2E,
  12. selectV4TaskById,
  13. sendV4Prompt,
  14. startNewV4Draft,
  15. waitForV4Pane,
  16. waitForV4TimelineContaining,
  17. } from "../helpers/v4-conversation.js";
  18. import {
  19. beginConversationTelemetryCapture,
  20. readConversationReportRequests,
  21. waitForConversationReportInventory,
  22. } from "../helpers/conversation-telemetry-parity-capture.js";
  23. const BG26_TIMEOUT_MS = 240000;
  24. const PARENT_MARKER = "E2E_BACKGROUND_SUBAGENT_RATE_LIMIT_PARENT";
  25. const PARENT_DONE = "E2E_BACKGROUND_SUBAGENT_RATE_LIMIT_PARENT_DONE";
  26. const CHILD_MARKER = "E2E_BACKGROUND_SUBAGENT_RATE_LIMIT_CHILD";
  27. const TOOL_CALL_ID = "toolu_e2e_background_subagent_rate_limit_agent";
  28. const PROVIDER_ERROR =
  29. "Requests are too frequent. Please reduce your request frequency, wait a short moment, and retry your request. Request id: e2e-background-subagent-rate-limit";
  30. describe("会话区 background subagent 429 错误展示 E2E", () => {
  31. before(async function () {
  32. this.timeout(BG26_TIMEOUT_MS);
  33. await prepareV4ConversationE2E();
  34. });
  35. after(async () => {
  36. await browser.electron.restoreAllMocks();
  37. await clearAppData();
  38. });
  39. it("BG26: 429 原始错误进入 subagent result、失败 hover 和 restore snapshot", async function () {
  40. this.timeout(BG26_TIMEOUT_MS);
  41. const telemetryCapture = await beginConversationTelemetryCapture();
  42. const prompt = `${PARENT_MARKER}: launch one background Agent and finish after its failed task notification with ${PARENT_DONE}.`;
  43. // Bug 原因:v4 已删除 chat-input/chat-view,旧 formal case 在 before hook 等待
  44. // legacy composer,真实场景从未执行。发送、timeline、session 切换统一走 v4 contract。
  45. await sendV4Prompt(prompt);
  46. await waitForV4TimelineContaining(PARENT_MARKER, 60000);
  47. await waitForToolCallBlockByToolCallId(TOOL_CALL_ID, 60000);
  48. // Bug 根因:旧断言直接等待 parent notification;失败时无法判断 child 物理请求
  49. // 是否到达 replay server。先建立 child request 屏障,让 shard 日志明确区分网络
  50. // 发送停滞与 429 terminal/notification 投影停滞。
  51. await waitForUpstreamRequest(
  52. { lastUserMessageIncludes: [CHILD_MARKER] },
  53. "background subagent child 请求没有到达 replay server",
  54. 60000,
  55. );
  56. await waitForUpstreamRequest(
  57. {
  58. includes: [
  59. `<tool-use-id>${TOOL_CALL_ID}</tool-use-id>`,
  60. "<status>failed</status>",
  61. `<error>${PROVIDER_ERROR}</error>`,
  62. `failed. ${PROVIDER_ERROR}`,
  63. ],
  64. },
  65. "background subagent failed notification 没有透传 provider 原始错误",
  66. 90000,
  67. );
  68. await waitForV4TimelineContaining(PARENT_DONE, 90000);
  69. await waitForConversationReportInventory(telemetryCapture, {
  70. message_completion: 2,
  71. });
  72. const reports = await readConversationReportRequests(telemetryCapture);
  73. // 早期 staging 断言没有后台 step;后续首终态结算已要求失败也报告零用量 Agent 汇总。
  74. // 请求返回 429 没有 usage,不能把失败调用计成已确认的计费用量。
  75. expect(
  76. reports.filter(
  77. (report) =>
  78. report.element_name === "agent_step" &&
  79. (report.event_extra_detail as Record<string, unknown> | undefined)?.agent_role ===
  80. "background subagent",
  81. ),
  82. ).toEqual([
  83. expect.objectContaining({
  84. event_extra_detail: expect.objectContaining({
  85. agent_role: "background subagent",
  86. tool_name: "Agent",
  87. status: "fail",
  88. error_msg: expect.stringContaining(PROVIDER_ERROR),
  89. model_request_count: "0",
  90. token_usage_scope: "",
  91. total_tokens: "0",
  92. }),
  93. }),
  94. ]);
  95. expect(
  96. reports.filter(
  97. (report) =>
  98. report.element_name === "message_completion" &&
  99. ["child_session_id", "parent_tool_call_id"].some((key) =>
  100. Object.hasOwn(
  101. (report.event_extra_detail as Record<string, unknown> | undefined) ?? {},
  102. key,
  103. ),
  104. ),
  105. ),
  106. ).toHaveLength(0);
  107. const idleSnapshot = await waitForV4Pane(
  108. (snapshot) =>
  109. snapshot.sessionId !== null && snapshot.sessionId !== "draft" && !snapshot.canStop,
  110. "background subagent 429 notification 后父会话没有回到 idle",
  111. 60000,
  112. );
  113. if (!idleSnapshot.sessionId || idleSnapshot.sessionId === "draft") {
  114. throw new Error(`background subagent 429 case 缺少 taskId: ${JSON.stringify(idleSnapshot)}`);
  115. }
  116. const sourceTaskId = idleSnapshot.sessionId;
  117. await assertFailedAgentSurface("live");
  118. await startNewV4Draft();
  119. await selectV4TaskById(sourceTaskId);
  120. await waitForV4Pane(
  121. (snapshot) => snapshot.sessionId === sourceTaskId && !snapshot.canStop,
  122. "background subagent 429 case 切回后没有完成原 task snapshot restore",
  123. 30000,
  124. );
  125. await waitForV4TimelineContaining(PARENT_DONE, 60000);
  126. await assertFailedAgentSurface("restored");
  127. });
  128. });
  129. async function assertFailedAgentSurface(stage: "live" | "restored") {
  130. // Bug 原因:child 429 与 parent failed notification 已持久化成功,但 v4 Agent
  131. // 卡片投影仍保留 completed。这里直接约束用户可见状态,避免继续依赖已删除的
  132. // legacy renderer store 投影而掩盖真实产品回归。
  133. let latestDiagnostics: Awaited<ReturnType<typeof getToolCallDiagnostics>> | null = null;
  134. try {
  135. await browser.waitUntil(
  136. async () => {
  137. // Bug 根因:恢复后的 completed turn 默认折叠,失败 Agent 行尚未挂载;旧断言
  138. // 先查 block 再展开 history,因而把已持久化的 429 状态误报为 restore 丢失。
  139. await expandAssistantHistoriesWithContent();
  140. latestDiagnostics = await getToolCallDiagnostics({
  141. type: "toolCallId",
  142. value: TOOL_CALL_ID,
  143. });
  144. return latestDiagnostics.matchedBlock?.status === "failed";
  145. },
  146. {
  147. timeout: 30000,
  148. timeoutMsg: `${stage} Agent 卡没有进入 failed`,
  149. },
  150. );
  151. } catch (error) {
  152. throw new Error(
  153. `${stage} Agent 卡没有进入 failed; latest=${JSON.stringify(latestDiagnostics)}`,
  154. { cause: error },
  155. );
  156. }
  157. const blockSnapshot = await waitForToolCallBlockByToolCallId(TOOL_CALL_ID, 30000);
  158. // Bug 根因:Agent 卡产品合同已改成“父对话单行摘要 + 右侧 child session”,
  159. // canToggle=false,不再渲染可展开的 tool-summary-trigger。旧 E2E 继续展开必然
  160. // 假失败;429 原始错误由 provider request 与失败状态 tooltip 两层证据约束。
  161. const sidePaneAction = await $(`[data-testid="${blockSnapshot.testId}"]`).$(
  162. `[data-testid^="${TID_V4_SUBAGENT_OPEN_SIDE_PANE}-"]`,
  163. );
  164. await sidePaneAction.waitForDisplayed({
  165. timeout: 10000,
  166. timeoutMsg: `${stage} Agent 卡没有右侧 child session 入口`,
  167. });
  168. // tooltip trigger 可能只渲染图标而没有可读文本;可见文案以整张 Agent 卡为准。
  169. expect(["执行失败", "Failed"].some((label) => blockSnapshot.text.includes(label))).toBe(true);
  170. const block = await $(`[data-testid="${blockSnapshot.testId}"]`);
  171. const failedStatus = await block.$('[data-slot="tooltip-trigger"]');
  172. await failedStatus.waitForDisplayed({
  173. timeout: 10000,
  174. timeoutMsg: `${stage} Agent 卡没有失败 tooltip trigger`,
  175. });
  176. // E2E 的系统语言跟随 runner;两种受支持语言都必须保留既有失败文案与同一 hover 交互。
  177. await hoverFailedAgentStatus(blockSnapshot.testId, stage);
  178. await $('[data-testid^="v4-session-pane-"]').moveTo({
  179. xOffset: 20,
  180. yOffset: 20,
  181. });
  182. const current = await getV4PaneSnapshot();
  183. expect(current.canStop).toBe(false);
  184. }
  185. async function hoverFailedAgentStatus(
  186. blockTestId: string,
  187. stage: "live" | "restored",
  188. attempt = 1,
  189. ): Promise<void> {
  190. // Bug 根因:卡片展开和流式收口会让 Radix trigger 重挂载;长批次里单次 moveTo
  191. // 可能落在旧节点上,或者指针仍在相同坐标而没有新的 pointerenter。每次都从当前
  192. // DOM 重新取 trigger,先移出卡片再做真实 hover,并只接受当前可见的 tooltip。
  193. const pane = await $('[data-testid^="v4-session-pane-"]');
  194. await pane.moveTo({ xOffset: 20, yOffset: 20 });
  195. const currentBlock = await $(`[data-testid="${blockTestId}"]`);
  196. const currentTrigger = await currentBlock.$('[data-slot="tooltip-trigger"]');
  197. await currentTrigger.waitForDisplayed({ timeout: 3000 });
  198. await currentTrigger.moveTo();
  199. let latestTooltipText: string | null = null;
  200. const opened = await browser
  201. .waitUntil(
  202. async () => {
  203. latestTooltipText = await browser.execute(() => {
  204. const visibleTooltip = Array.from(
  205. document.querySelectorAll<HTMLElement>('[data-slot="tooltip-content"]'),
  206. ).find((element) => {
  207. const style = window.getComputedStyle(element);
  208. return (
  209. style.display !== "none" &&
  210. style.visibility !== "hidden" &&
  211. Number(style.opacity || "1") > 0 &&
  212. element.getClientRects().length > 0
  213. );
  214. });
  215. return visibleTooltip?.innerText ?? null;
  216. });
  217. // Radix 会同时维护展示内容和可访问性镜像,innerText 在部分 Chromium
  218. // 时序下会返回两份相同文案;产品约束是可见 tooltip 完整包含原始错误。
  219. return normalizeText(latestTooltipText ?? "").includes(normalizeText(PROVIDER_ERROR));
  220. },
  221. {
  222. interval: 100,
  223. timeout: 3000,
  224. timeoutMsg: `${stage} 执行失败 hover 没有显示匹配的可见 tooltip`,
  225. },
  226. )
  227. .then(() => true)
  228. .catch(() => false);
  229. if (opened) {
  230. return;
  231. }
  232. if (attempt >= 3) {
  233. throw new Error(
  234. `${stage} 执行失败 hover 没有显示可见 tooltip; latest=${JSON.stringify(latestTooltipText)}`,
  235. );
  236. }
  237. await hoverFailedAgentStatus(blockTestId, stage, attempt + 1);
  238. }
  239. function normalizeText(value: string) {
  240. return value
  241. .replace(/\u00a0/g, " ")
  242. .replace(/\s+/g, " ")
  243. .trim();
  244. }