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

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