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

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