conversation-session-background-notification-batch.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. import {
  2. INCOMING_MESSAGE_MODES,
  3. prepareIncomingMessageCapability,
  4. } from "#e2e/helpers/incoming-message-capability";
  5. import {
  6. readBackgroundContextUsage,
  7. assertBackgroundUsageInV4,
  8. } from "#e2e/helpers/background-notification-usage";
  9. import { assertIncomingMessage } from "#e2e/helpers/incoming-message-evidence";
  10. import { readFile, writeFile } from "node:fs/promises";
  11. import { join } from "node:path";
  12. import { TID_CHAT_BACKGROUND_RESULT_TITLE, TID_V4_TIMELINE } from "@zcode/shared/test-ids";
  13. import { clearAppData } from "#e2e/helpers/desktop-app";
  14. import {
  15. countUpstreamRequests,
  16. findFirstUpstreamRequestIndex,
  17. getUpstreamRequestRecordCount,
  18. waitForUpstreamRequest,
  19. } from "#e2e/helpers/conversation-session-network";
  20. import { waitForToolCallBlockByToolCallId } from "#e2e/helpers/conversation-session-tool";
  21. import { respondToToolCrossProductBlockers } from "#e2e/helpers/conversation-session-tool-cross-product";
  22. import {
  23. clickV4Stop,
  24. getV4PaneSnapshot,
  25. sendV4Prompt,
  26. waitForV4Pane,
  27. waitForV4QueueCount,
  28. } from "#e2e/helpers/v4-conversation";
  29. const BACKGROUND_NOTIFICATION_BATCH_TIMEOUT_MS = 180000;
  30. const CASE_MARKER = "E2E_BACKGROUND_NOTIFICATION_BATCH";
  31. const CHILD_ONE_RESULT = "E2E_BG_BATCH_CHILD_ONE_DONE";
  32. const CHILD_TWO_RESULT = "E2E_BG_BATCH_CHILD_TWO_DONE";
  33. const CHILD_THREE_RESULT = "E2E_BG_BATCH_CHILD_THREE_DONE";
  34. const BACKGROUND_AGENT_LAUNCHES = [
  35. {
  36. promptMarker: "E2E_BG_BATCH_CHILD_ONE",
  37. toolCallId: "toolu_e2e_bg_batch_agent_one",
  38. },
  39. {
  40. promptMarker: "E2E_BG_BATCH_CHILD_TWO",
  41. toolCallId: "toolu_e2e_bg_batch_agent_two",
  42. },
  43. {
  44. promptMarker: "E2E_BG_BATCH_CHILD_THREE",
  45. toolCallId: "toolu_e2e_bg_batch_agent_three",
  46. },
  47. ] as const;
  48. describe("会话区 Background Notification Batch E2E", () => {
  49. afterEach(async () => {
  50. await stopIfBusy();
  51. });
  52. after(async () => {
  53. await browser.electron.restoreAllMocks();
  54. await clearAppData();
  55. });
  56. for (const { label, mcs } of INCOMING_MESSAGE_MODES) {
  57. it(`BG36 ${label}: 第一条 notification request 处理中完成的其余 Agent 应在下一次 available drain 合为一轮`, async function () {
  58. this.timeout(BACKGROUND_NOTIFICATION_BATCH_TIMEOUT_MS);
  59. await prepareIncomingMessageCapability(mcs);
  60. const runMarker = `${CASE_MARKER}_${Date.now()}`;
  61. const firstExistingRecordIndex = (await getUpstreamRequestRecordCount()) - 1;
  62. await sendV4Prompt(
  63. `${runMarker}: Launch exactly three background Agents and process every completion notification.`,
  64. );
  65. await waitForVisibleV4MessageContaining("user", runMarker);
  66. for (const { toolCallId } of BACKGROUND_AGENT_LAUNCHES) {
  67. await waitForToolCallBlockByToolCallId(toolCallId, 60000);
  68. }
  69. await respondToToolCrossProductBlockers();
  70. await waitForVisibleV4MessageContaining(
  71. "assistant",
  72. "background-notification-batch-agents-launched-ok",
  73. );
  74. const firstNotificationQuery = {
  75. includes: [CASE_MARKER, "<task-notification>", CHILD_ONE_RESULT],
  76. lastUserMessageExcludes: [CHILD_TWO_RESULT, CHILD_THREE_RESULT],
  77. lastUserMessageIncludes: ["<task-notification>", CHILD_ONE_RESULT],
  78. };
  79. const launchAckRequestIndex = await waitForRequestIndex(
  80. {
  81. includes: [
  82. CASE_MARKER,
  83. "Async agent launched successfully",
  84. ...BACKGROUND_AGENT_LAUNCHES.map(({ toolCallId }) => toolCallId),
  85. ],
  86. lastUserMessageExcludes: ["<task-notification>"],
  87. },
  88. firstExistingRecordIndex,
  89. "BG36 没有捕获到三个 background Agent 的 launch ack request",
  90. );
  91. await assertBackgroundAgentLaunches(launchAckRequestIndex);
  92. await waitForChildAgentRequests(firstExistingRecordIndex);
  93. await waitForBackgroundOnlyMainIdle();
  94. const launchUsage = await readBackgroundContextUsage();
  95. expect(
  96. await findFirstUpstreamRequestIndex(firstNotificationQuery, {
  97. afterIndex: firstExistingRecordIndex,
  98. }),
  99. ).toBeNull();
  100. const firstNotificationIndex = await waitForRequestIndex(
  101. firstNotificationQuery,
  102. firstExistingRecordIndex,
  103. "BG36 第一条 Agent completion notification 没有独立启动 provider request",
  104. );
  105. const batchNotificationIndex = await waitForRequestIndex(
  106. {
  107. includes: [CASE_MARKER, "<task-notification>", CHILD_TWO_RESULT, CHILD_THREE_RESULT],
  108. lastUserMessageIncludes: ["<task-notification>", CHILD_TWO_RESULT, CHILD_THREE_RESULT],
  109. },
  110. firstNotificationIndex,
  111. "BG36 第二、三条 completion notification 没有在同一 provider request 中消费",
  112. );
  113. await assertIncomingMessage(await readRequestJsonAt(firstNotificationIndex), {
  114. presentation: "task_notification",
  115. evidenceLabel: label,
  116. marker: CHILD_ONE_RESULT,
  117. role: "user",
  118. });
  119. await assertIncomingMessage(await readRequestJsonAt(batchNotificationIndex), {
  120. presentation: "task_notification",
  121. evidenceLabel: label,
  122. marker: CHILD_TWO_RESULT,
  123. role: "user",
  124. });
  125. const batchInput = await readLatestUserMessageAt(batchNotificationIndex);
  126. // 每条通知各自一个标题:两条通知共三段。
  127. expect(batchInput.split("[SYSTEM NOTIFICATION - NOT USER INPUT]")).toHaveLength(3);
  128. // 两条通知是同一条 user 消息的两个 text block。
  129. const batchBlocks = await readLatestUserTextBlocksAt(batchNotificationIndex);
  130. expect(batchBlocks).toHaveLength(2);
  131. // 修复原因:两个 child 的 fixture 延迟只差 500ms(8000/8500),Windows 上子代理
  132. // 启动开销差异超过该间隔,完成顺序会互换(本地两种模式都是 THREE 先到)。本用例证明的是
  133. // "其余 Agent 在下一次 drain 合为一轮、各占一个 text block",与两者先后无关,按集合校验。
  134. const blockResults = batchBlocks.map((block) =>
  135. [CHILD_TWO_RESULT, CHILD_THREE_RESULT].filter((result) => block.text.includes(result)),
  136. );
  137. expect(blockResults.map((results) => results.length)).toEqual([1, 1]);
  138. expect(blockResults.flat().sort()).toEqual([CHILD_THREE_RESULT, CHILD_TWO_RESULT].sort());
  139. await waitForVisibleV4MessageContaining(
  140. "assistant",
  141. "background-notification-batch-consumed-ok",
  142. );
  143. await waitForBackgroundResultTitle(
  144. "BG36 second background Agent · BG36 third background Agent",
  145. );
  146. await waitForV4Pane(
  147. (snapshot) =>
  148. snapshot.sessionId !== null && snapshot.sessionId !== "draft" && !snapshot.canStop,
  149. "BG36 notification batch 完成后 V4 main 没有回到 idle",
  150. 90000,
  151. );
  152. await waitForV4QueueCount(0, 30000);
  153. const batchUsage = await readBackgroundContextUsage();
  154. const firstNotificationInput = await readLatestUserMessageAt(firstNotificationIndex);
  155. // 根因:通知加 wrapper 后曾被 Messages 当成已计入 sections 的上下文跳过。
  156. // 两次请求之间只新增两个 assistant 和两条通知,直接对账 CLI 实际统计的字符增量。
  157. // 修复原因:assistant 回复改为按块保存后,content 是带块序号的文本块数组;Messages
  158. // 按历史里保存的形态估算,块序号不发给 provider,但计入估算,旧的字符串期望因此少算。
  159. const assistantBlocks = (text: string) => [{ type: "text", text, blockIndex: 0 }];
  160. const addedMessages = [
  161. {
  162. role: "assistant",
  163. content: assistantBlocks("background-notification-batch-agents-launched-ok"),
  164. },
  165. { role: "user", content: firstNotificationInput },
  166. {
  167. role: "assistant",
  168. content: assistantBlocks("background-notification-batch-first-consumed-ok"),
  169. },
  170. // 通知按历史形态估算:单条是字符串,整批是 text block 数组。
  171. { role: "user", content: batchBlocks },
  172. ];
  173. const expectedIncrease = addedMessages.reduce(
  174. (sum, message) => sum + JSON.stringify(message).length,
  175. 0,
  176. );
  177. if (process.env.ZCODE_E2E_ARTIFACT_DIR) {
  178. await writeFile(
  179. join(process.env.ZCODE_E2E_ARTIFACT_DIR, `task-notification-usage-${label}.json`),
  180. JSON.stringify({ launchUsage, batchUsage, expectedIncrease }, null, 2),
  181. "utf8",
  182. );
  183. }
  184. expect(
  185. batchUsage.find((item) => item.source === "messages")!.chars -
  186. launchUsage.find((item) => item.source === "messages")!.chars,
  187. ).toBe(expectedIncrease);
  188. // 修复原因:MCP 改为异步启动后,server 可能晚于 launch 请求连上,其工具在下一 step 才计入
  189. // mcp_tool_schemas(docs/mcp-async-tool-catalog-cache.md)。Windows CI 日志显示 launch 快照时
  190. // 6 个 server 只连上 3 个(16487 → 35372),与通知统计无关。这里只核对通知不会混入其他固定段。
  191. const stableSections = (usage: typeof launchUsage) =>
  192. usage.filter((item) => item.source !== "messages" && item.source !== "mcp_tool_schemas");
  193. expect(stableSections(batchUsage)).toEqual(stableSections(launchUsage));
  194. await assertBackgroundUsageInV4(batchUsage);
  195. await browser.pause(1000);
  196. expect(
  197. await countUpstreamRequests(
  198. {
  199. excludes: ["CRITICAL: Respond with TEXT ONLY"],
  200. lastUserMessageIncludes: ["<task-notification>"],
  201. },
  202. { afterIndex: firstExistingRecordIndex },
  203. ),
  204. ).toBe(2);
  205. expect(
  206. await countUpstreamRequests(
  207. {
  208. lastUserMessageExcludes: [CHILD_THREE_RESULT],
  209. lastUserMessageIncludes: [CHILD_TWO_RESULT],
  210. },
  211. { afterIndex: firstNotificationIndex },
  212. ),
  213. ).toBe(0);
  214. expect(
  215. await countUpstreamRequests(
  216. {
  217. lastUserMessageExcludes: [CHILD_TWO_RESULT],
  218. lastUserMessageIncludes: [CHILD_THREE_RESULT],
  219. },
  220. { afterIndex: firstNotificationIndex },
  221. ),
  222. ).toBe(0);
  223. await assertVisibleV4UserRowsNotContaining("<task-notification>");
  224. await assertVisibleV4UserRowsNotContaining("<system-reminder>");
  225. await assertVisibleV4UserRowsNotContaining("[SYSTEM NOTIFICATION - NOT USER INPUT]");
  226. await assertVisibleV4UserRowsNotContaining(CHILD_ONE_RESULT);
  227. await assertVisibleV4UserRowsNotContaining(CHILD_TWO_RESULT);
  228. await assertVisibleV4UserRowsNotContaining(CHILD_THREE_RESULT);
  229. });
  230. }
  231. });
  232. async function waitForRequestIndex(
  233. query: Parameters<typeof waitForUpstreamRequest>[0],
  234. afterIndex: number,
  235. timeoutMsg: string,
  236. ) {
  237. await waitForUpstreamRequest(query, timeoutMsg, 60000, { afterIndex });
  238. const index = await findFirstUpstreamRequestIndex(query, { afterIndex });
  239. if (index === null) {
  240. throw new Error(`${timeoutMsg}; request disappeared after wait`);
  241. }
  242. return index;
  243. }
  244. async function readLatestUserMessageAt(recordIndex: number): Promise<string> {
  245. const requestJson = await readRequestJsonAt(recordIndex);
  246. const messages =
  247. requestJson && typeof requestJson === "object"
  248. ? (requestJson as { messages?: unknown }).messages
  249. : undefined;
  250. if (!Array.isArray(messages)) return "";
  251. for (let index = messages.length - 1; index >= 0; index -= 1) {
  252. const message = messages[index];
  253. if (!message || typeof message !== "object") continue;
  254. if ((message as { role?: unknown }).role !== "user") continue;
  255. return contentToText((message as { content?: unknown }).content);
  256. }
  257. return "";
  258. }
  259. async function readLatestUserTextBlocksAt(
  260. recordIndex: number,
  261. ): Promise<Array<{ type: "text"; text: string }>> {
  262. const requestJson = await readRequestJsonAt(recordIndex);
  263. const messages =
  264. requestJson && typeof requestJson === "object"
  265. ? (requestJson as { messages?: unknown }).messages
  266. : undefined;
  267. if (!Array.isArray(messages)) return [];
  268. const message = [...messages]
  269. .reverse()
  270. .find(
  271. (item) => !!item && typeof item === "object" && (item as { role?: unknown }).role === "user",
  272. ) as { content?: unknown } | undefined;
  273. if (!Array.isArray(message?.content)) return [];
  274. // wire 上的 cache_control 等字段不属于 CLI 的消息内容,只保留 type 与 text。
  275. return message.content.flatMap((block: unknown) =>
  276. block &&
  277. typeof block === "object" &&
  278. (block as { type?: unknown }).type === "text" &&
  279. typeof (block as { text?: unknown }).text === "string"
  280. ? [{ type: "text" as const, text: (block as { text: string }).text }]
  281. : [],
  282. );
  283. }
  284. async function readRequestJsonAt(recordIndex: number): Promise<unknown> {
  285. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH?.trim();
  286. if (!capturePath) {
  287. throw new Error("BG36 缺少 E2E_PROVIDER_CAPTURE_PATH,无法验证 batch admission 顺序");
  288. }
  289. const artifact = JSON.parse(await readFile(capturePath, "utf-8")) as {
  290. records?: Array<{ requestJson?: unknown }>;
  291. };
  292. return artifact.records?.[recordIndex]?.requestJson;
  293. }
  294. function contentToText(content: unknown): string {
  295. if (typeof content === "string") return content;
  296. if (Array.isArray(content)) return content.map(contentToText).join("\n");
  297. if (!content || typeof content !== "object") return "";
  298. if ("text" in content && typeof content.text === "string") return content.text;
  299. return Object.values(content).map(contentToText).join("\n");
  300. }
  301. async function stopIfBusy() {
  302. const snapshot = await getV4PaneSnapshot().catch(() => null);
  303. if (!snapshot?.canStop) return;
  304. await clickV4Stop().catch(() => undefined);
  305. await waitForV4Pane(
  306. (candidate) => !candidate.canStop,
  307. "BG36 清理阶段 V4 main 没有退出 running",
  308. 30000,
  309. ).catch(() => undefined);
  310. }
  311. async function waitForBackgroundOnlyMainIdle(): Promise<void> {
  312. await waitForV4Pane(
  313. (snapshot) =>
  314. snapshot.sessionId !== null && snapshot.sessionId !== "draft" && !snapshot.canStop,
  315. "BG36 background Agent launch 后 V4 main 没有先回到 idle",
  316. 45000,
  317. );
  318. // Bug 原因:旧 case 只在全部 notification 消费后读取 legacy runtime store,
  319. // 即使 background-only 窗口的 V4 Composer 从未 idle 也会通过。这里保留一个稳定采样窗口,
  320. // 锁定真实产品面的 canStop=false;Agent 是否真实后台运行已由 provider-visible
  321. // run_in_background tool input 和三个尚未完成的 child request 直接证明,不能依赖异步目录计数。
  322. await browser.pause(500);
  323. const stablePane = await getV4PaneSnapshot();
  324. expect(stablePane.canStop).toBe(false);
  325. }
  326. async function waitForChildAgentRequests(afterIndex: number): Promise<void> {
  327. for (const { promptMarker } of BACKGROUND_AGENT_LAUNCHES) {
  328. await waitForRequestIndex(
  329. {
  330. lastUserMessageExcludes: [CASE_MARKER],
  331. lastUserMessageIncludes: [promptMarker],
  332. },
  333. afterIndex,
  334. `BG36 child provider request 没有开始:${promptMarker}`,
  335. );
  336. }
  337. }
  338. async function assertBackgroundAgentLaunches(recordIndex: number): Promise<void> {
  339. const requestJson = await readRequestJsonAt(recordIndex);
  340. for (const { promptMarker, toolCallId } of BACKGROUND_AGENT_LAUNCHES) {
  341. const toolUse = findToolUse(requestJson, toolCallId);
  342. expect(toolUse?.name).toBe("Agent");
  343. expect(toolUse?.input?.prompt).toContain(promptMarker);
  344. expect(toolUse?.input?.run_in_background).toBe(true);
  345. }
  346. }
  347. function findToolUse(
  348. value: unknown,
  349. toolCallId: string,
  350. ): { input?: Record<string, unknown>; name?: unknown } | null {
  351. if (Array.isArray(value)) {
  352. for (const item of value) {
  353. const matched = findToolUse(item, toolCallId);
  354. if (matched) return matched;
  355. }
  356. return null;
  357. }
  358. if (!value || typeof value !== "object") return null;
  359. const candidate = value as Record<string, unknown>;
  360. if (candidate.id === toolCallId && candidate.type === "tool_use") {
  361. const input =
  362. candidate.input && typeof candidate.input === "object"
  363. ? (candidate.input as Record<string, unknown>)
  364. : null;
  365. return {
  366. ...(input ? { input } : {}),
  367. name: candidate.name,
  368. };
  369. }
  370. for (const child of Object.values(candidate)) {
  371. const matched = findToolUse(child, toolCallId);
  372. if (matched) return matched;
  373. }
  374. return null;
  375. }
  376. async function waitForBackgroundResultTitle(expectedTitle: string): Promise<void> {
  377. await browser.waitUntil(
  378. () =>
  379. browser.execute(
  380. (titleTestId, title) =>
  381. Array.from(
  382. document.querySelectorAll<HTMLElement>(`[data-testid^="${titleTestId}-"]`),
  383. ).some((node) => node.textContent?.trim() === title),
  384. TID_CHAT_BACKGROUND_RESULT_TITLE,
  385. expectedTitle,
  386. ),
  387. {
  388. timeout: 60000,
  389. timeoutMsg: `BG36 没有显示合成后的后台结果标题:${expectedTitle}`,
  390. },
  391. );
  392. }
  393. async function waitForVisibleV4MessageContaining(
  394. role: "assistant" | "user",
  395. text: string,
  396. ): Promise<void> {
  397. await browser.waitUntil(
  398. async () => (await getVisibleV4MessageTexts(role)).some((message) => message.includes(text)),
  399. {
  400. timeout: 90000,
  401. timeoutMsg: `BG36 ${role} 消息中没有出现:${text}`,
  402. },
  403. );
  404. }
  405. async function assertVisibleV4UserRowsNotContaining(text: string): Promise<void> {
  406. expect((await getVisibleV4MessageTexts("user")).join("\n")).not.toContain(text);
  407. }
  408. function getVisibleV4MessageTexts(role: "assistant" | "user"): Promise<string[]> {
  409. return browser.execute(
  410. (timelineTestId, selectedRole) => {
  411. const timeline = document.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  412. return Array.from(timeline?.querySelectorAll<HTMLElement>("[data-row-id]") ?? [])
  413. .filter((element) => element.classList.contains(`group/${selectedRole}-row`))
  414. .map((element) => element.innerText.replace(/\u00a0/g, " ").trim());
  415. },
  416. TID_V4_TIMELINE,
  417. role,
  418. );
  419. }