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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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. expect(batchInput.indexOf(CHILD_TWO_RESULT)).toBeGreaterThanOrEqual(0);
  132. expect(batchInput.indexOf(CHILD_THREE_RESULT)).toBeGreaterThan(
  133. batchInput.indexOf(CHILD_TWO_RESULT),
  134. );
  135. await waitForVisibleV4MessageContaining(
  136. "assistant",
  137. "background-notification-batch-consumed-ok",
  138. );
  139. await waitForBackgroundResultTitle(
  140. "BG36 second background Agent · BG36 third background Agent",
  141. );
  142. await waitForV4Pane(
  143. (snapshot) =>
  144. snapshot.sessionId !== null && snapshot.sessionId !== "draft" && !snapshot.canStop,
  145. "BG36 notification batch 完成后 V4 main 没有回到 idle",
  146. 90000,
  147. );
  148. await waitForV4QueueCount(0, 30000);
  149. const batchUsage = await readBackgroundContextUsage();
  150. const firstNotificationInput = await readLatestUserMessageAt(firstNotificationIndex);
  151. // 根因:通知加 wrapper 后曾被 Messages 当成已计入 sections 的上下文跳过。
  152. // 两次请求之间只新增两个 assistant 和两条通知,直接对账 CLI 实际统计的字符增量。
  153. // 修复原因:assistant 回复改为按块保存后,content 是带块序号的文本块数组;Messages
  154. // 按历史里保存的形态估算,块序号不发给 provider,但计入估算,旧的字符串期望因此少算。
  155. const assistantBlocks = (text: string) => [{ type: "text", text, blockIndex: 0 }];
  156. const addedMessages = [
  157. {
  158. role: "assistant",
  159. content: assistantBlocks("background-notification-batch-agents-launched-ok"),
  160. },
  161. { role: "user", content: firstNotificationInput },
  162. {
  163. role: "assistant",
  164. content: assistantBlocks("background-notification-batch-first-consumed-ok"),
  165. },
  166. // 通知按历史形态估算:单条是字符串,整批是 text block 数组。
  167. { role: "user", content: batchBlocks },
  168. ];
  169. const expectedIncrease = addedMessages.reduce(
  170. (sum, message) => sum + JSON.stringify(message).length,
  171. 0,
  172. );
  173. if (process.env.ZCODE_E2E_ARTIFACT_DIR) {
  174. await writeFile(
  175. join(process.env.ZCODE_E2E_ARTIFACT_DIR, `task-notification-usage-${label}.json`),
  176. JSON.stringify({ launchUsage, batchUsage, expectedIncrease }, null, 2),
  177. "utf8",
  178. );
  179. }
  180. expect(
  181. batchUsage.find((item) => item.source === "messages")!.chars -
  182. launchUsage.find((item) => item.source === "messages")!.chars,
  183. ).toBe(expectedIncrease);
  184. expect(batchUsage.filter((item) => item.source !== "messages")).toEqual(
  185. launchUsage.filter((item) => item.source !== "messages"),
  186. );
  187. await assertBackgroundUsageInV4(batchUsage);
  188. await browser.pause(1000);
  189. expect(
  190. await countUpstreamRequests(
  191. {
  192. excludes: ["CRITICAL: Respond with TEXT ONLY"],
  193. lastUserMessageIncludes: ["<task-notification>"],
  194. },
  195. { afterIndex: firstExistingRecordIndex },
  196. ),
  197. ).toBe(2);
  198. expect(
  199. await countUpstreamRequests(
  200. {
  201. lastUserMessageExcludes: [CHILD_THREE_RESULT],
  202. lastUserMessageIncludes: [CHILD_TWO_RESULT],
  203. },
  204. { afterIndex: firstNotificationIndex },
  205. ),
  206. ).toBe(0);
  207. expect(
  208. await countUpstreamRequests(
  209. {
  210. lastUserMessageExcludes: [CHILD_TWO_RESULT],
  211. lastUserMessageIncludes: [CHILD_THREE_RESULT],
  212. },
  213. { afterIndex: firstNotificationIndex },
  214. ),
  215. ).toBe(0);
  216. await assertVisibleV4UserRowsNotContaining("<task-notification>");
  217. await assertVisibleV4UserRowsNotContaining("<system-reminder>");
  218. await assertVisibleV4UserRowsNotContaining("[SYSTEM NOTIFICATION - NOT USER INPUT]");
  219. await assertVisibleV4UserRowsNotContaining(CHILD_ONE_RESULT);
  220. await assertVisibleV4UserRowsNotContaining(CHILD_TWO_RESULT);
  221. await assertVisibleV4UserRowsNotContaining(CHILD_THREE_RESULT);
  222. });
  223. }
  224. });
  225. async function waitForRequestIndex(
  226. query: Parameters<typeof waitForUpstreamRequest>[0],
  227. afterIndex: number,
  228. timeoutMsg: string,
  229. ) {
  230. await waitForUpstreamRequest(query, timeoutMsg, 60000, { afterIndex });
  231. const index = await findFirstUpstreamRequestIndex(query, { afterIndex });
  232. if (index === null) {
  233. throw new Error(`${timeoutMsg}; request disappeared after wait`);
  234. }
  235. return index;
  236. }
  237. async function readLatestUserMessageAt(recordIndex: number): Promise<string> {
  238. const requestJson = await readRequestJsonAt(recordIndex);
  239. const messages =
  240. requestJson && typeof requestJson === "object"
  241. ? (requestJson as { messages?: unknown }).messages
  242. : undefined;
  243. if (!Array.isArray(messages)) return "";
  244. for (let index = messages.length - 1; index >= 0; index -= 1) {
  245. const message = messages[index];
  246. if (!message || typeof message !== "object") continue;
  247. if ((message as { role?: unknown }).role !== "user") continue;
  248. return contentToText((message as { content?: unknown }).content);
  249. }
  250. return "";
  251. }
  252. async function readLatestUserTextBlocksAt(
  253. recordIndex: number,
  254. ): Promise<Array<{ type: "text"; text: string }>> {
  255. const requestJson = await readRequestJsonAt(recordIndex);
  256. const messages =
  257. requestJson && typeof requestJson === "object"
  258. ? (requestJson as { messages?: unknown }).messages
  259. : undefined;
  260. if (!Array.isArray(messages)) return [];
  261. const message = [...messages]
  262. .reverse()
  263. .find(
  264. (item) => !!item && typeof item === "object" && (item as { role?: unknown }).role === "user",
  265. ) as { content?: unknown } | undefined;
  266. if (!Array.isArray(message?.content)) return [];
  267. // wire 上的 cache_control 等字段不属于 CLI 的消息内容,只保留 type 与 text。
  268. return message.content.flatMap((block: unknown) =>
  269. block &&
  270. typeof block === "object" &&
  271. (block as { type?: unknown }).type === "text" &&
  272. typeof (block as { text?: unknown }).text === "string"
  273. ? [{ type: "text" as const, text: (block as { text: string }).text }]
  274. : [],
  275. );
  276. }
  277. async function readRequestJsonAt(recordIndex: number): Promise<unknown> {
  278. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH?.trim();
  279. if (!capturePath) {
  280. throw new Error("BG36 缺少 E2E_PROVIDER_CAPTURE_PATH,无法验证 batch admission 顺序");
  281. }
  282. const artifact = JSON.parse(await readFile(capturePath, "utf-8")) as {
  283. records?: Array<{ requestJson?: unknown }>;
  284. };
  285. return artifact.records?.[recordIndex]?.requestJson;
  286. }
  287. function contentToText(content: unknown): string {
  288. if (typeof content === "string") return content;
  289. if (Array.isArray(content)) return content.map(contentToText).join("\n");
  290. if (!content || typeof content !== "object") return "";
  291. if ("text" in content && typeof content.text === "string") return content.text;
  292. return Object.values(content).map(contentToText).join("\n");
  293. }
  294. async function stopIfBusy() {
  295. const snapshot = await getV4PaneSnapshot().catch(() => null);
  296. if (!snapshot?.canStop) return;
  297. await clickV4Stop().catch(() => undefined);
  298. await waitForV4Pane(
  299. (candidate) => !candidate.canStop,
  300. "BG36 清理阶段 V4 main 没有退出 running",
  301. 30000,
  302. ).catch(() => undefined);
  303. }
  304. async function waitForBackgroundOnlyMainIdle(): Promise<void> {
  305. await waitForV4Pane(
  306. (snapshot) =>
  307. snapshot.sessionId !== null && snapshot.sessionId !== "draft" && !snapshot.canStop,
  308. "BG36 background Agent launch 后 V4 main 没有先回到 idle",
  309. 45000,
  310. );
  311. // Bug 原因:旧 case 只在全部 notification 消费后读取 legacy runtime store,
  312. // 即使 background-only 窗口的 V4 Composer 从未 idle 也会通过。这里保留一个稳定采样窗口,
  313. // 锁定真实产品面的 canStop=false;Agent 是否真实后台运行已由 provider-visible
  314. // run_in_background tool input 和三个尚未完成的 child request 直接证明,不能依赖异步目录计数。
  315. await browser.pause(500);
  316. const stablePane = await getV4PaneSnapshot();
  317. expect(stablePane.canStop).toBe(false);
  318. }
  319. async function waitForChildAgentRequests(afterIndex: number): Promise<void> {
  320. for (const { promptMarker } of BACKGROUND_AGENT_LAUNCHES) {
  321. await waitForRequestIndex(
  322. {
  323. lastUserMessageExcludes: [CASE_MARKER],
  324. lastUserMessageIncludes: [promptMarker],
  325. },
  326. afterIndex,
  327. `BG36 child provider request 没有开始:${promptMarker}`,
  328. );
  329. }
  330. }
  331. async function assertBackgroundAgentLaunches(recordIndex: number): Promise<void> {
  332. const requestJson = await readRequestJsonAt(recordIndex);
  333. for (const { promptMarker, toolCallId } of BACKGROUND_AGENT_LAUNCHES) {
  334. const toolUse = findToolUse(requestJson, toolCallId);
  335. expect(toolUse?.name).toBe("Agent");
  336. expect(toolUse?.input?.prompt).toContain(promptMarker);
  337. expect(toolUse?.input?.run_in_background).toBe(true);
  338. }
  339. }
  340. function findToolUse(
  341. value: unknown,
  342. toolCallId: string,
  343. ): { input?: Record<string, unknown>; name?: unknown } | null {
  344. if (Array.isArray(value)) {
  345. for (const item of value) {
  346. const matched = findToolUse(item, toolCallId);
  347. if (matched) return matched;
  348. }
  349. return null;
  350. }
  351. if (!value || typeof value !== "object") return null;
  352. const candidate = value as Record<string, unknown>;
  353. if (candidate.id === toolCallId && candidate.type === "tool_use") {
  354. const input =
  355. candidate.input && typeof candidate.input === "object"
  356. ? (candidate.input as Record<string, unknown>)
  357. : null;
  358. return {
  359. ...(input ? { input } : {}),
  360. name: candidate.name,
  361. };
  362. }
  363. for (const child of Object.values(candidate)) {
  364. const matched = findToolUse(child, toolCallId);
  365. if (matched) return matched;
  366. }
  367. return null;
  368. }
  369. async function waitForBackgroundResultTitle(expectedTitle: string): Promise<void> {
  370. await browser.waitUntil(
  371. () =>
  372. browser.execute(
  373. (titleTestId, title) =>
  374. Array.from(
  375. document.querySelectorAll<HTMLElement>(`[data-testid^="${titleTestId}-"]`),
  376. ).some((node) => node.textContent?.trim() === title),
  377. TID_CHAT_BACKGROUND_RESULT_TITLE,
  378. expectedTitle,
  379. ),
  380. {
  381. timeout: 60000,
  382. timeoutMsg: `BG36 没有显示合成后的后台结果标题:${expectedTitle}`,
  383. },
  384. );
  385. }
  386. async function waitForVisibleV4MessageContaining(
  387. role: "assistant" | "user",
  388. text: string,
  389. ): Promise<void> {
  390. await browser.waitUntil(
  391. async () => (await getVisibleV4MessageTexts(role)).some((message) => message.includes(text)),
  392. {
  393. timeout: 90000,
  394. timeoutMsg: `BG36 ${role} 消息中没有出现:${text}`,
  395. },
  396. );
  397. }
  398. async function assertVisibleV4UserRowsNotContaining(text: string): Promise<void> {
  399. expect((await getVisibleV4MessageTexts("user")).join("\n")).not.toContain(text);
  400. }
  401. function getVisibleV4MessageTexts(role: "assistant" | "user"): Promise<string[]> {
  402. return browser.execute(
  403. (timelineTestId, selectedRole) => {
  404. const timeline = document.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  405. return Array.from(timeline?.querySelectorAll<HTMLElement>("[data-row-id]") ?? [])
  406. .filter((element) => element.classList.contains(`group/${selectedRole}-row`))
  407. .map((element) => element.innerText.replace(/\u00a0/g, " ").trim());
  408. },
  409. TID_V4_TIMELINE,
  410. role,
  411. );
  412. }