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

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