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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. import { TID_V4_SUBAGENT_OPEN_SIDE_PANE } from "@zcode/shared/test-ids";
  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. // 上报按隐私契约移除错误正文;下方 UI/restore 仍验证同一 provider 原文。
  89. error_msg: "[redacted]",
  90. error_type: "TOOL_EXEC_ERROR",
  91. model_request_count: "0",
  92. token_usage_scope: "",
  93. total_tokens: "0",
  94. }),
  95. }),
  96. ]);
  97. expect(
  98. reports.filter(
  99. (report) =>
  100. report.element_name === "message_completion" &&
  101. ["child_session_id", "parent_tool_call_id"].some((key) =>
  102. Object.hasOwn(
  103. (report.event_extra_detail as Record<string, unknown> | undefined) ?? {},
  104. key,
  105. ),
  106. ),
  107. ),
  108. ).toHaveLength(0);
  109. const idleSnapshot = await waitForV4Pane(
  110. (snapshot) =>
  111. snapshot.sessionId !== null && snapshot.sessionId !== "draft" && !snapshot.canStop,
  112. "background subagent 429 notification 后父会话没有回到 idle",
  113. 60000,
  114. );
  115. if (!idleSnapshot.sessionId || idleSnapshot.sessionId === "draft") {
  116. throw new Error(`background subagent 429 case 缺少 taskId: ${JSON.stringify(idleSnapshot)}`);
  117. }
  118. const sourceTaskId = idleSnapshot.sessionId;
  119. await assertFailedAgentSurface("live");
  120. await startNewV4Draft();
  121. await selectV4TaskById(sourceTaskId);
  122. await waitForV4Pane(
  123. (snapshot) => snapshot.sessionId === sourceTaskId && !snapshot.canStop,
  124. "background subagent 429 case 切回后没有完成原 task snapshot restore",
  125. 30000,
  126. );
  127. await waitForV4TimelineContaining(PARENT_DONE, 60000);
  128. await assertFailedAgentSurface("restored");
  129. });
  130. });
  131. async function assertFailedAgentSurface(stage: "live" | "restored") {
  132. // Bug 原因:child 429 与 parent failed notification 已持久化成功,但 v4 Agent
  133. // 卡片投影仍保留 completed。这里直接约束用户可见状态,避免继续依赖已删除的
  134. // legacy renderer store 投影而掩盖真实产品回归。
  135. let latestDiagnostics: Awaited<ReturnType<typeof getToolCallDiagnostics>> | null = null;
  136. try {
  137. await browser.waitUntil(
  138. async () => {
  139. // Bug 根因:恢复后的 completed turn 默认折叠,失败 Agent 行尚未挂载;旧断言
  140. // 先查 block 再展开 history,因而把已持久化的 429 状态误报为 restore 丢失。
  141. await expandAssistantHistoriesWithContent();
  142. latestDiagnostics = await getToolCallDiagnostics({
  143. type: "toolCallId",
  144. value: TOOL_CALL_ID,
  145. });
  146. return latestDiagnostics.matchedBlock?.status === "failed";
  147. },
  148. {
  149. timeout: 30000,
  150. timeoutMsg: `${stage} Agent 卡没有进入 failed`,
  151. },
  152. );
  153. } catch (error) {
  154. throw new Error(
  155. `${stage} Agent 卡没有进入 failed; latest=${JSON.stringify(latestDiagnostics)}`,
  156. { cause: error },
  157. );
  158. }
  159. const blockSnapshot = await waitForToolCallBlockByToolCallId(TOOL_CALL_ID, 30000);
  160. // Bug 根因:Agent 卡产品合同已改成“父对话单行摘要 + 右侧 child session”,
  161. // canToggle=false,不再渲染可展开的 tool-summary-trigger。旧 E2E 继续展开必然
  162. // 假失败;429 原始错误由 provider request 与失败状态 tooltip 两层证据约束。
  163. const sidePaneAction = await $(`[data-testid="${blockSnapshot.testId}"]`).$(
  164. `[data-testid^="${TID_V4_SUBAGENT_OPEN_SIDE_PANE}-"]`,
  165. );
  166. await sidePaneAction.waitForDisplayed({
  167. timeout: 10000,
  168. timeoutMsg: `${stage} Agent 卡没有右侧 child session 入口`,
  169. });
  170. // tooltip trigger 可能只渲染图标而没有可读文本;可见文案以整张 Agent 卡为准。
  171. expect(["执行失败", "Failed"].some((label) => blockSnapshot.text.includes(label))).toBe(true);
  172. const block = await $(`[data-testid="${blockSnapshot.testId}"]`);
  173. const failedStatus = await block.$('[data-slot="tooltip-trigger"]');
  174. await failedStatus.waitForDisplayed({
  175. timeout: 10000,
  176. timeoutMsg: `${stage} Agent 卡没有失败 tooltip trigger`,
  177. });
  178. // E2E 的系统语言跟随 runner;两种受支持语言都必须保留既有失败文案与同一 hover 交互。
  179. await hoverFailedAgentStatus(blockSnapshot.testId, stage);
  180. await $('[data-testid^="v4-session-pane-"]').moveTo({
  181. xOffset: 20,
  182. yOffset: 20,
  183. });
  184. const current = await getV4PaneSnapshot();
  185. expect(current.canStop).toBe(false);
  186. }
  187. async function hoverFailedAgentStatus(
  188. blockTestId: string,
  189. stage: "live" | "restored",
  190. attempt = 1,
  191. ): Promise<void> {
  192. // Bug 根因:卡片展开和流式收口会让 Radix trigger 重挂载;长批次里单次 moveTo
  193. // 可能落在旧节点上,或者指针仍在相同坐标而没有新的 pointerenter。每次都从当前
  194. // DOM 重新取 trigger,先移出卡片再做真实 hover,并只接受当前可见的 tooltip。
  195. const pane = await $('[data-testid^="v4-session-pane-"]');
  196. await pane.moveTo({ xOffset: 20, yOffset: 20 });
  197. const currentBlock = await $(`[data-testid="${blockTestId}"]`);
  198. const currentTrigger = await currentBlock.$('[data-slot="tooltip-trigger"]');
  199. await currentTrigger.waitForDisplayed({ timeout: 3000 });
  200. await currentTrigger.moveTo();
  201. let latestTooltipText: string | null = null;
  202. const opened = await browser
  203. .waitUntil(
  204. async () => {
  205. latestTooltipText = await browser.execute(() => {
  206. const visibleTooltip = Array.from(
  207. document.querySelectorAll<HTMLElement>('[data-slot="tooltip-content"]'),
  208. ).find((element) => {
  209. const style = window.getComputedStyle(element);
  210. return (
  211. style.display !== "none" &&
  212. style.visibility !== "hidden" &&
  213. Number(style.opacity || "1") > 0 &&
  214. element.getClientRects().length > 0
  215. );
  216. });
  217. return visibleTooltip?.innerText ?? null;
  218. });
  219. // Radix 会同时维护展示内容和可访问性镜像,innerText 在部分 Chromium
  220. // 时序下会返回两份相同文案;产品约束是可见 tooltip 完整包含原始错误。
  221. return normalizeText(latestTooltipText ?? "").includes(normalizeText(PROVIDER_ERROR));
  222. },
  223. {
  224. interval: 100,
  225. timeout: 3000,
  226. timeoutMsg: `${stage} 执行失败 hover 没有显示匹配的可见 tooltip`,
  227. },
  228. )
  229. .then(() => true)
  230. .catch(() => false);
  231. if (opened) {
  232. return;
  233. }
  234. if (attempt >= 3) {
  235. throw new Error(
  236. `${stage} 执行失败 hover 没有显示可见 tooltip; latest=${JSON.stringify(latestTooltipText)}`,
  237. );
  238. }
  239. await hoverFailedAgentStatus(blockTestId, stage, attempt + 1);
  240. }
  241. function normalizeText(value: string) {
  242. return value
  243. .replace(/\u00a0/g, " ")
  244. .replace(/\s+/g, " ")
  245. .trim();
  246. }