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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. import { TID_V4_SUBAGENT_OPEN_SIDE_PANE } from "@zcode/shared/test-ids";
  2. import { clearAppData } from "../helpers/desktop-app.js";
  3. import {
  4. getUpstreamRequestEvidence,
  5. waitForUpstreamRequest,
  6. } from "../helpers/conversation-session-network.js";
  7. import {
  8. expandAssistantHistoriesWithContent,
  9. waitForToolCallBlockByToolCallId,
  10. } from "../helpers/conversation-session-tool.js";
  11. import { getToolCallDiagnostics } from "../helpers/conversation-session-tool-diagnostics.js";
  12. import {
  13. getV4PaneSnapshot,
  14. prepareV4ConversationE2E,
  15. selectV4TaskById,
  16. sendV4Prompt,
  17. startNewV4Draft,
  18. waitForV4Pane,
  19. waitForV4TimelineContaining,
  20. } from "../helpers/v4-conversation.js";
  21. import {
  22. beginConversationTelemetryCapture,
  23. readConversationReportRequests,
  24. waitForConversationReportInventory,
  25. } from "../helpers/conversation-telemetry-parity-capture.js";
  26. const BG26_TIMEOUT_MS = 240000;
  27. const PARENT_MARKER = "E2E_BACKGROUND_SUBAGENT_RATE_LIMIT_PARENT";
  28. const PARENT_DONE = "E2E_BACKGROUND_SUBAGENT_RATE_LIMIT_PARENT_DONE";
  29. const CHILD_MARKER = "E2E_BACKGROUND_SUBAGENT_RATE_LIMIT_CHILD";
  30. const TOOL_CALL_ID = "toolu_e2e_background_subagent_rate_limit_agent";
  31. const RATE_LIMIT_ERROR_PREFIX =
  32. "Requests are too frequent. Please reduce your request frequency, wait a short moment, and retry your request. Request id: ";
  33. const PROVIDER_ERROR = `${RATE_LIMIT_ERROR_PREFIX}e2e-background-subagent-rate-limit`;
  34. const MERGED_PARENT_MARKER = "E2E_BG26_MERGED_PARENT";
  35. const MERGED_PARENT_DONE = "E2E_BG26_MERGED_PARENT_DONE";
  36. const MERGED_COMPLETED_RESULT = "E2E_BG26_MERGED_COMPLETED_RESULT";
  37. const MERGED_COMPLETED_TOOL_CALL_ID = "toolu_e2e_bg26_merged_completing_agent";
  38. const MERGED_FIRST_FAILED_AGENT = {
  39. toolCallId: "toolu_e2e_bg26_merged_first_failing_agent",
  40. providerError: `${RATE_LIMIT_ERROR_PREFIX}e2e-bg26-merged-first-failure`,
  41. };
  42. const MERGED_LAST_FAILED_AGENT = {
  43. toolCallId: "toolu_e2e_bg26_merged_last_failing_agent",
  44. providerError: `${RATE_LIMIT_ERROR_PREFIX}e2e-bg26-merged-last-failure`,
  45. };
  46. interface FailedAgentExpectation {
  47. toolCallId: string;
  48. providerError: string;
  49. /** 同批其他通知的结果或原因,不能出现在这张卡的失败 hover 里。 */
  50. foreignTexts?: readonly string[];
  51. /** 单条通知的轮次:hover 只显示 provider 原文,不带 `Agent "…" failed:` 前缀。 */
  52. exactTooltip?: boolean;
  53. }
  54. describe("会话区 background subagent 429 错误展示 E2E", () => {
  55. before(async function () {
  56. this.timeout(BG26_TIMEOUT_MS);
  57. await prepareV4ConversationE2E();
  58. });
  59. after(async () => {
  60. await browser.electron.restoreAllMocks();
  61. await clearAppData();
  62. });
  63. it("BG26: 429 原始错误进入 subagent result、失败 hover 和 restore snapshot", async function () {
  64. this.timeout(BG26_TIMEOUT_MS);
  65. const telemetryCapture = await beginConversationTelemetryCapture();
  66. const prompt = `${PARENT_MARKER}: launch one background Agent and finish after its failed task notification with ${PARENT_DONE}.`;
  67. // Bug 原因:v4 已删除 chat-input/chat-view,旧 formal case 在 before hook 等待
  68. // legacy composer,真实场景从未执行。发送、timeline、session 切换统一走 v4 contract。
  69. await sendV4Prompt(prompt);
  70. await waitForV4TimelineContaining(PARENT_MARKER, 60000);
  71. await waitForToolCallBlockByToolCallId(TOOL_CALL_ID, 60000);
  72. // Bug 根因:旧断言直接等待 parent notification;失败时无法判断 child 物理请求
  73. // 是否到达 replay server。先建立 child request 屏障,让 shard 日志明确区分网络
  74. // 发送停滞与 429 terminal/notification 投影停滞。
  75. await waitForUpstreamRequest(
  76. { lastUserMessageIncludes: [CHILD_MARKER] },
  77. "background subagent child 请求没有到达 replay server",
  78. 60000,
  79. );
  80. await waitForUpstreamRequest(
  81. {
  82. includes: [
  83. `<tool-use-id>${TOOL_CALL_ID}</tool-use-id>`,
  84. "<status>failed</status>",
  85. // 失败原因只在 summary 的 "failed: " 后面,不再有 <error>。
  86. `failed: ${PROVIDER_ERROR}</summary>`,
  87. ],
  88. },
  89. "background subagent failed notification 没有透传 provider 原始错误",
  90. 90000,
  91. );
  92. // 本任务的通知块不再带 <error>;请求其他位置的同名标签不影响判断。
  93. const [notificationRequest] = await getUpstreamRequestEvidence({
  94. includes: [`<tool-use-id>${TOOL_CALL_ID}</tool-use-id>`, "<status>failed</status>"],
  95. });
  96. const notificationBlock = taskNotificationBlocks(notificationRequest!.requestJson).find(
  97. (block) => block.includes(`<tool-use-id>${TOOL_CALL_ID}</tool-use-id>`),
  98. );
  99. expect(notificationBlock).toContain(`failed: ${PROVIDER_ERROR}</summary>`);
  100. expect(notificationBlock).not.toContain("<error>");
  101. await waitForV4TimelineContaining(PARENT_DONE, 90000);
  102. await waitForConversationReportInventory(telemetryCapture, {
  103. message_completion: 2,
  104. });
  105. const reports = await readConversationReportRequests(telemetryCapture);
  106. // 早期 staging 断言没有后台 step;后续首终态结算已要求失败也报告零用量 Agent 汇总。
  107. // 请求返回 429 没有 usage,不能把失败调用计成已确认的计费用量。
  108. expect(
  109. reports.filter(
  110. (report) =>
  111. report.element_name === "agent_step" &&
  112. (report.event_extra_detail as Record<string, unknown> | undefined)?.agent_role ===
  113. "background subagent",
  114. ),
  115. ).toEqual([
  116. expect.objectContaining({
  117. event_extra_detail: expect.objectContaining({
  118. agent_role: "background subagent",
  119. tool_name: "Agent",
  120. status: "fail",
  121. // 上报按隐私契约移除错误正文;下方 UI/restore 仍验证同一 provider 原文。
  122. error_msg: "[redacted]",
  123. error_type: "TOOL_EXEC_ERROR",
  124. model_request_count: "0",
  125. token_usage_scope: "",
  126. total_tokens: "0",
  127. }),
  128. }),
  129. ]);
  130. expect(
  131. reports.filter(
  132. (report) =>
  133. report.element_name === "message_completion" &&
  134. ["child_session_id", "parent_tool_call_id"].some((key) =>
  135. Object.hasOwn(
  136. (report.event_extra_detail as Record<string, unknown> | undefined) ?? {},
  137. key,
  138. ),
  139. ),
  140. ),
  141. ).toHaveLength(0);
  142. const idleSnapshot = await waitForV4Pane(
  143. (snapshot) =>
  144. snapshot.sessionId !== null && snapshot.sessionId !== "draft" && !snapshot.canStop,
  145. "background subagent 429 notification 后父会话没有回到 idle",
  146. 60000,
  147. );
  148. if (!idleSnapshot.sessionId || idleSnapshot.sessionId === "draft") {
  149. throw new Error(`background subagent 429 case 缺少 taskId: ${JSON.stringify(idleSnapshot)}`);
  150. }
  151. const sourceTaskId = idleSnapshot.sessionId;
  152. const failedAgent = {
  153. toolCallId: TOOL_CALL_ID,
  154. providerError: PROVIDER_ERROR,
  155. exactTooltip: true,
  156. };
  157. await assertFailedAgentSurface("live", failedAgent);
  158. await switchAwayAndBack(sourceTaskId, PARENT_DONE);
  159. await assertFailedAgentSurface("restored", failedAgent);
  160. });
  161. it("BG26 合并通知:失败、完成、失败三条通知同批回传,各卡显示自己的终态", async function () {
  162. this.timeout(BG26_TIMEOUT_MS);
  163. await startNewV4Draft();
  164. await sendV4Prompt(
  165. `${MERGED_PARENT_MARKER}: launch three background Agents and finish after their task notifications with ${MERGED_PARENT_DONE}.`,
  166. );
  167. await waitForV4TimelineContaining(MERGED_PARENT_MARKER, 60000);
  168. for (const toolCallId of [
  169. MERGED_FIRST_FAILED_AGENT.toolCallId,
  170. MERGED_COMPLETED_TOOL_CALL_ID,
  171. MERGED_LAST_FAILED_AGENT.toolCallId,
  172. ]) {
  173. await waitForToolCallBlockByToolCallId(toolCallId, 60000);
  174. }
  175. // 三条通知必须进入同一个 provider request,否则测不到合并通知的投影。
  176. await waitForUpstreamRequest(
  177. {
  178. lastUserMessageIncludes: [
  179. `failed: ${MERGED_FIRST_FAILED_AGENT.providerError}</summary>`,
  180. MERGED_COMPLETED_RESULT,
  181. `failed: ${MERGED_LAST_FAILED_AGENT.providerError}</summary>`,
  182. ],
  183. },
  184. "三条 background Agent notification 没有合并到同一个 provider request",
  185. 90000,
  186. );
  187. await waitForV4TimelineContaining(MERGED_PARENT_DONE, 90000);
  188. const idleSnapshot = await waitForV4Pane(
  189. (snapshot) =>
  190. snapshot.sessionId !== null && snapshot.sessionId !== "draft" && !snapshot.canStop,
  191. "合并通知消费后父会话没有回到 idle",
  192. 60000,
  193. );
  194. if (!idleSnapshot.sessionId || idleSnapshot.sessionId === "draft") {
  195. throw new Error(`合并通知 case 缺少 taskId: ${JSON.stringify(idleSnapshot)}`);
  196. }
  197. const sourceTaskId = idleSnapshot.sessionId;
  198. await assertMergedAgentSurfaces("merged live");
  199. await switchAwayAndBack(sourceTaskId, MERGED_PARENT_DONE);
  200. await assertMergedAgentSurfaces("merged restored");
  201. });
  202. });
  203. async function switchAwayAndBack(sourceTaskId: string, doneMarker: string) {
  204. await startNewV4Draft();
  205. await selectV4TaskById(sourceTaskId);
  206. await waitForV4Pane(
  207. (snapshot) => snapshot.sessionId === sourceTaskId && !snapshot.canStop,
  208. "background subagent 429 case 切回后没有完成原 task snapshot restore",
  209. 30000,
  210. );
  211. await waitForV4TimelineContaining(doneMarker, 60000);
  212. }
  213. async function assertMergedAgentSurfaces(stage: string) {
  214. // Bug 原因:合并通知曾跨块读取标签。第一张失败卡的原因取到同批完成任务的 <result>;
  215. // 后面的通知块不更新卡片,最后一张失败卡停在 launch ACK 的 completed。
  216. await assertFailedAgentSurface(stage, {
  217. ...MERGED_FIRST_FAILED_AGENT,
  218. foreignTexts: [MERGED_COMPLETED_RESULT, MERGED_LAST_FAILED_AGENT.providerError],
  219. });
  220. await assertFailedAgentSurface(stage, {
  221. ...MERGED_LAST_FAILED_AGENT,
  222. foreignTexts: [MERGED_COMPLETED_RESULT, MERGED_FIRST_FAILED_AGENT.providerError],
  223. });
  224. await waitForAgentCardStatus(MERGED_COMPLETED_TOOL_CALL_ID, "completed", stage);
  225. }
  226. async function waitForAgentCardStatus(toolCallId: string, status: string, stage: string) {
  227. let latestDiagnostics: Awaited<ReturnType<typeof getToolCallDiagnostics>> | null = null;
  228. try {
  229. await browser.waitUntil(
  230. async () => {
  231. // Bug 根因:恢复后的 completed turn 默认折叠,失败 Agent 行尚未挂载;旧断言
  232. // 先查 block 再展开 history,因而把已持久化的 429 状态误报为 restore 丢失。
  233. await expandAssistantHistoriesWithContent();
  234. latestDiagnostics = await getToolCallDiagnostics({
  235. type: "toolCallId",
  236. value: toolCallId,
  237. });
  238. return latestDiagnostics.matchedBlock?.status === status;
  239. },
  240. {
  241. timeout: 30000,
  242. timeoutMsg: `${stage} Agent 卡没有进入 ${status}: ${toolCallId}`,
  243. },
  244. );
  245. } catch (error) {
  246. throw new Error(
  247. `${stage} Agent 卡没有进入 ${status}: ${toolCallId}; latest=${JSON.stringify(latestDiagnostics)}`,
  248. { cause: error },
  249. );
  250. }
  251. }
  252. async function assertFailedAgentSurface(stage: string, agent: FailedAgentExpectation) {
  253. // Bug 原因:child 429 与 parent failed notification 已持久化成功,但 v4 Agent
  254. // 卡片投影仍保留 completed。这里直接约束用户可见状态,避免继续依赖已删除的
  255. // legacy renderer store 投影而掩盖真实产品回归。
  256. await waitForAgentCardStatus(agent.toolCallId, "failed", stage);
  257. const blockSnapshot = await waitForToolCallBlockByToolCallId(agent.toolCallId, 30000);
  258. // Bug 根因:Agent 卡产品合同已改成“父对话单行摘要 + 右侧 child session”,
  259. // canToggle=false,不再渲染可展开的 tool-summary-trigger。旧 E2E 继续展开必然
  260. // 假失败;429 原始错误由 provider request 与失败状态 tooltip 两层证据约束。
  261. const sidePaneAction = await $(`[data-testid="${blockSnapshot.testId}"]`).$(
  262. `[data-testid^="${TID_V4_SUBAGENT_OPEN_SIDE_PANE}-"]`,
  263. );
  264. await sidePaneAction.waitForDisplayed({
  265. timeout: 10000,
  266. timeoutMsg: `${stage} Agent 卡没有右侧 child session 入口`,
  267. });
  268. // tooltip trigger 可能只渲染图标而没有可读文本;可见文案以整张 Agent 卡为准。
  269. expect(["执行失败", "Failed"].some((label) => blockSnapshot.text.includes(label))).toBe(true);
  270. const block = await $(`[data-testid="${blockSnapshot.testId}"]`);
  271. const failedStatus = await block.$('[data-slot="tooltip-trigger"]');
  272. await failedStatus.waitForDisplayed({
  273. timeout: 10000,
  274. timeoutMsg: `${stage} Agent 卡没有失败 tooltip trigger`,
  275. });
  276. // E2E 的系统语言跟随 runner;两种受支持语言都必须保留既有失败文案与同一 hover 交互。
  277. await hoverFailedAgentStatus(blockSnapshot.testId, stage, agent);
  278. await $('[data-testid^="v4-session-pane-"]').moveTo({
  279. xOffset: 20,
  280. yOffset: 20,
  281. });
  282. const current = await getV4PaneSnapshot();
  283. expect(current.canStop).toBe(false);
  284. }
  285. async function hoverFailedAgentStatus(
  286. blockTestId: string,
  287. stage: string,
  288. agent: FailedAgentExpectation,
  289. attempt = 1,
  290. ): Promise<void> {
  291. // Bug 根因:卡片展开和流式收口会让 Radix trigger 重挂载;长批次里单次 moveTo
  292. // 可能落在旧节点上,或者指针仍在相同坐标而没有新的 pointerenter。每次都从当前
  293. // DOM 重新取 trigger,先移出卡片再做真实 hover,并只接受当前可见的 tooltip。
  294. const pane = await $('[data-testid^="v4-session-pane-"]');
  295. await pane.moveTo({ xOffset: 20, yOffset: 20 });
  296. const currentBlock = await $(`[data-testid="${blockTestId}"]`);
  297. const currentTrigger = await currentBlock.$('[data-slot="tooltip-trigger"]');
  298. await currentTrigger.waitForDisplayed({ timeout: 3000 });
  299. await currentTrigger.moveTo();
  300. let latestTooltipText: string | null = null;
  301. const opened = await browser
  302. .waitUntil(
  303. async () => {
  304. latestTooltipText = await browser.execute(() => {
  305. const visibleTooltip = Array.from(
  306. document.querySelectorAll<HTMLElement>('[data-slot="tooltip-content"]'),
  307. ).find((element) => {
  308. const style = window.getComputedStyle(element);
  309. return (
  310. style.display !== "none" &&
  311. style.visibility !== "hidden" &&
  312. Number(style.opacity || "1") > 0 &&
  313. element.getClientRects().length > 0
  314. );
  315. });
  316. return visibleTooltip?.innerText ?? null;
  317. });
  318. // Radix 会同时维护展示内容和可访问性镜像,innerText 在部分 Chromium
  319. // 时序下会返回两份相同文案;产品约束是可见 tooltip 完整包含原始错误。
  320. return normalizeText(latestTooltipText ?? "").includes(normalizeText(agent.providerError));
  321. },
  322. {
  323. interval: 100,
  324. timeout: 3000,
  325. timeoutMsg: `${stage} 执行失败 hover 没有显示匹配的可见 tooltip`,
  326. },
  327. )
  328. .then(() => true)
  329. .catch(() => false);
  330. if (opened) {
  331. for (const foreignText of agent.foreignTexts ?? []) {
  332. expect(normalizeText(latestTooltipText ?? "")).not.toContain(normalizeText(foreignText));
  333. }
  334. if (agent.exactTooltip) {
  335. expect(collapseMirroredText(normalizeText(latestTooltipText ?? ""))).toBe(
  336. normalizeText(agent.providerError),
  337. );
  338. }
  339. return;
  340. }
  341. if (attempt >= 3) {
  342. throw new Error(
  343. `${stage} 执行失败 hover 没有显示可见 tooltip; latest=${JSON.stringify(latestTooltipText)}`,
  344. );
  345. }
  346. await hoverFailedAgentStatus(blockTestId, stage, agent, attempt + 1);
  347. }
  348. // Radix 的可访问性镜像会让 innerText 返回两份相同文案;精确比较前合成一份。
  349. function collapseMirroredText(value: string) {
  350. const half = value.slice(0, Math.floor((value.length - 1) / 2));
  351. return value === `${half} ${half}` ? half : value;
  352. }
  353. // 按 <task-notification> 块拆出请求里的通知,只看文本块。
  354. function taskNotificationBlocks(requestJson: unknown): string[] {
  355. const messages = (requestJson as { messages?: Array<{ content?: unknown }> }).messages ?? [];
  356. const text = messages
  357. .flatMap((message) =>
  358. typeof message.content === "string"
  359. ? [message.content]
  360. : Array.isArray(message.content)
  361. ? message.content.flatMap((block) => {
  362. const item = block as { text?: unknown; content?: unknown };
  363. if (typeof item.text === "string") return [item.text];
  364. return typeof item.content === "string" ? [item.content] : [];
  365. })
  366. : [],
  367. )
  368. .join("\n");
  369. return text.match(/<task-notification>[\s\S]*?<\/task-notification>/g) ?? [];
  370. }
  371. function normalizeText(value: string) {
  372. return value
  373. .replace(/\u00a0/g, " ")
  374. .replace(/\s+/g, " ")
  375. .trim();
  376. }