conversation-session-subagent-compact-delivery.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  4. import { releaseControlledReplay } from "#e2e/helpers/controlled-replay";
  5. import {
  6. refreshSeededOpenAIProvidersThroughSettings,
  7. seedCustomAnthropicMessagesProvider,
  8. } from "#e2e/helpers/custom-openai-provider";
  9. import {
  10. getUpstreamRequestEvidence,
  11. getUpstreamRequestRecordCount,
  12. type UpstreamRequestEvidence,
  13. } from "#e2e/helpers/conversation-session-network";
  14. import { startConversationModelProviderReplayServer } from "#e2e/helpers/model-provider-replay";
  15. import {
  16. clickV4Stop,
  17. getV4ComposerBackgroundWorkCounts,
  18. getV4PaneSnapshot,
  19. prepareV4ConversationE2E,
  20. sendV4Prompt,
  21. startNewV4Draft,
  22. switchV4Model,
  23. switchV4Mode,
  24. waitForV4AssistantMessageContaining,
  25. waitForV4CompactMarker,
  26. waitForV4Pane,
  27. waitForV4QueueCount,
  28. } from "#e2e/helpers/v4-conversation";
  29. const CASE_NAME = "conversation-session-subagent-compact-delivery";
  30. const MODEL_ID = "e2e-subagent-delivery-model";
  31. const PROVIDER_ID = "e2e-subagent-delivery-provider";
  32. const CHILDREN = [1, 2] as const;
  33. const TIMEOUT_MS = 180_000;
  34. const ORDERS = [
  35. ["before", "before"],
  36. ["before", "during"],
  37. ["before", "after"],
  38. ["during", "during"],
  39. ["during", "after"],
  40. ["after", "after"],
  41. ["consumed", "consumed"],
  42. ] as const;
  43. const SCENARIOS = [
  44. ...(["manual", "auto", "reactive"] as const).flatMap((trigger) =>
  45. (["completion", "reply"] as const).flatMap((kind) =>
  46. ORDERS.map((order) => ({ trigger, kind, order })),
  47. ),
  48. ),
  49. { trigger: "none", kind: "reply", order: ["during", "during"] } as const,
  50. ];
  51. let replay: Awaited<ReturnType<typeof startConversationModelProviderReplayServer>>;
  52. describe("BG46/BG47 子代理回传与压缩交错", () => {
  53. before(async function () {
  54. this.timeout(240_000);
  55. replay = await startConversationModelProviderReplayServer(CASE_NAME);
  56. await prepareV4ConversationE2E({ skipProvider: true });
  57. await seedCustomAnthropicMessagesProvider({
  58. baseURL: replay.baseUrl,
  59. modelId: MODEL_ID,
  60. providerId: PROVIDER_ID,
  61. providerName: "Subagent delivery E2E",
  62. });
  63. await refreshSeededOpenAIProvidersThroughSettings(["Subagent delivery E2E"]);
  64. await prepareV4ConversationE2E({ skipProvider: true });
  65. });
  66. after(async () => {
  67. await replay?.stop();
  68. });
  69. for (const { trigger, kind, order } of SCENARIOS) {
  70. const orderName = order.join("-");
  71. it(`${trigger === "none" ? "BG47" : "BG46"}: ${trigger} / ${kind} / ${orderName}`, async function () {
  72. this.timeout(TIMEOUT_MS);
  73. const scenario = `${trigger}-${kind}`;
  74. const marker = `E2E_SUBAGENT_DELIVERY_${scenario.toUpperCase().replaceAll("-", "_")}`;
  75. const results = CHILDREN.map((index) => `${marker}_RESULT_${index}`);
  76. const afterIndex = (await getUpstreamRequestRecordCount()) - 1;
  77. const evidence = () => getUpstreamRequestEvidence({ includes: [marker] }, { afterIndex });
  78. const waitStage = (stage: string, complete = false) =>
  79. waitForStage(`${scenario}-${stage}`, evidence, complete);
  80. const milestones: Array<{ event: string; at: string }> = [];
  81. let timingEvents: DeliveryTimingEvent[] = [];
  82. const note = (event: string) => milestones.push({ event, at: new Date().toISOString() });
  83. const released = new Set<number>();
  84. const waitCompactEvent = async (status: "started" | "completed") => {
  85. const sessionId = (await getV4PaneSnapshot()).sessionId!;
  86. await browser.waitUntil(
  87. async () =>
  88. (await readDeliveryTimingEvents(sessionId)).some((event) =>
  89. event.event.endsWith(`.${status}`),
  90. ),
  91. { timeout: 15_000, timeoutMsg: `运行时 compact ${status} 事件缺失` },
  92. );
  93. };
  94. const deliver = async (phase: (typeof order)[number]) => {
  95. const children = CHILDREN.filter((index) => order[index - 1] === phase);
  96. if (children.length === 0) return;
  97. await Promise.all(
  98. children.map((index) => releaseControlledReplay(`${scenario}-child-${index}`)),
  99. );
  100. for (const index of children) {
  101. released.add(index);
  102. if (kind === "reply") {
  103. const continued = await waitStage(`child-${index}-continued`);
  104. expect(requestMessages(continued)).toContain("was queued for the coordinator");
  105. } else {
  106. await waitStage(`child-${index}`, true);
  107. }
  108. note(`child-${index}-${phase}-returned`);
  109. }
  110. if (kind === "completion") await waitForChildCount(CHILDREN.length - released.size);
  111. };
  112. const waitForResults = async (expected: readonly number[]) => {
  113. await browser.waitUntil(
  114. async () =>
  115. (await evidence()).some(
  116. (record) =>
  117. isParentDelivery(record, kind) &&
  118. record.status === "complete" &&
  119. expected.every((index) => requestMessages(record).includes(results[index - 1]!)),
  120. ),
  121. { timeout: 30_000, timeoutMsg: `父模型未消费结果 ${expected.join(",")}` },
  122. );
  123. };
  124. try {
  125. await startNewV4Draft();
  126. await switchV4Model(PROVIDER_ID, MODEL_ID, "");
  127. await switchV4Mode("yolo");
  128. for (const index of CHILDREN) {
  129. await sendV4Prompt(`${marker}_SEED_${index}: Establish completed history.`);
  130. await waitForV4AssistantMessageContaining(`${marker}_SEEDED_${index}`);
  131. await waitForIdle();
  132. }
  133. await sendV4Prompt(
  134. `${marker}_LAUNCH: Start two background agents and await their results.`,
  135. );
  136. for (const index of CHILDREN) await waitStage(`child-${index}`);
  137. await waitForV4AssistantMessageContaining(`${marker}_LAUNCHED`);
  138. await waitForIdle();
  139. await waitForChildCount(CHILDREN.length);
  140. expect(
  141. JSON.stringify((await waitStage("launch-ack", true)).requestJson).match(
  142. /"run_in_background":true/gu,
  143. ),
  144. ).toHaveLength(CHILDREN.length);
  145. if (order[0] === "consumed") {
  146. await deliver("consumed");
  147. await waitForResults(CHILDREN);
  148. await waitForIdle();
  149. note("both-consumed-before-compact");
  150. }
  151. await sendV4Prompt(`${marker}_ARM: Hold the parent request before compaction.`);
  152. const arm = await waitStage("arm");
  153. expect(arm.status).toBe("pending");
  154. await deliver("before");
  155. if (order[0] === "before") {
  156. expect(
  157. (await evidence()).filter((record) => isParentDelivery(record, kind)),
  158. ).toHaveLength(0);
  159. expect((await waitStage("arm")).status).toBe("pending");
  160. note("returned-but-not-consumed");
  161. }
  162. // before 场景必须先证明回传到达,再入 compact FIFO / 放行超限响应。
  163. // 禁止直接注入 runtime 队列;仅通过真实 composer、子工具和 provider 屏障排序。
  164. if (trigger === "manual" || trigger === "auto") {
  165. await sendV4Prompt(trigger === "manual" ? "/compact" : `${marker}_TRIGGER: Continue.`);
  166. await waitForV4QueueCount(1, 15_000);
  167. }
  168. if (trigger === "none") {
  169. await deliver("during");
  170. expect((await waitStage("arm")).status).toBe("pending");
  171. await releaseControlledReplay(`${scenario}-arm`);
  172. } else {
  173. await releaseControlledReplay(`${scenario}-arm`);
  174. let compact: UpstreamRequestEvidence | undefined;
  175. await browser.waitUntil(
  176. async () => {
  177. compact = (await evidence()).find((record) =>
  178. record.fixtureId?.startsWith(`${scenario}-compact-`),
  179. );
  180. return Boolean(compact);
  181. },
  182. { timeout: 45_000, timeoutMsg: "没有开始实际 compact 请求" },
  183. );
  184. expect(compact!.status).toBe("pending");
  185. // 后台通知轮触发的 compact 标记可能不在当前可见 timeline;入队与压缩顺序以 Core 日志为准。
  186. await waitCompactEvent("started");
  187. if (trigger !== "auto" || order[0] !== "before") {
  188. await waitForV4CompactMarker(
  189. { status: "running", origin: trigger === "manual" ? "manual" : "auto" },
  190. 15_000,
  191. );
  192. }
  193. note("compact-running");
  194. for (const [offset, result] of results.entries()) {
  195. if (order[offset] === "during" || order[offset] === "after") {
  196. expect(requestMessages(compact!)).not.toContain(result);
  197. }
  198. }
  199. const requestsBeforeDuring = (await evidence()).filter((record) =>
  200. isParentDelivery(record, kind),
  201. ).length;
  202. await deliver("during");
  203. expect(
  204. (await evidence()).filter((record) => isParentDelivery(record, kind)),
  205. ).toHaveLength(requestsBeforeDuring);
  206. expect(
  207. (await evidence()).find((record) => record.fixtureId === compact!.fixtureId)?.status,
  208. ).toBe("pending");
  209. await releaseControlledReplay(compact!.fixtureId!);
  210. await waitCompactEvent("completed");
  211. if (trigger !== "auto" || order[0] !== "before") {
  212. await waitForV4CompactMarker(
  213. { status: "success", origin: trigger === "manual" ? "manual" : "auto" },
  214. 15_000,
  215. );
  216. }
  217. note("compact-completed");
  218. await waitForIdle();
  219. await waitForV4QueueCount(0, 15_000);
  220. await deliver("after");
  221. }
  222. // 不以 UI 出现固定回答判定成功;等待最后一份真实结果进入父请求。
  223. await browser.waitUntil(
  224. async () =>
  225. (await evidence()).some(
  226. (record) =>
  227. !isCompactRequest(record) &&
  228. isParentDelivery(record, kind) &&
  229. record.status === "complete" &&
  230. CHILDREN.every((index) => hasResult(record, marker, index)),
  231. ),
  232. { timeout: 30_000, timeoutMsg: "两份结果没有全部进入同一父请求(原文或摘要)" },
  233. );
  234. await waitForIdle();
  235. await waitForV4QueueCount(0, 15_000);
  236. await sendV4Prompt(`${marker}_PROBE: Verify both child results after the handoff.`);
  237. const probe = await waitStage("probe", true);
  238. for (const index of CHILDREN) expect(hasResult(probe, marker, index)).toBe(true);
  239. if (order[0] === "consumed") {
  240. const compact = (await evidence()).find(isCompactRequest)!;
  241. for (const result of results) {
  242. // reactive 会把 recent 原文留在摘要分区之外;这时必须在最终请求验证原文保留,不能强求摘要读到它。
  243. if (!requestMessages(compact).includes(result)) {
  244. expect(requestMessages(probe)).toContain(result);
  245. }
  246. }
  247. }
  248. if (trigger !== "none") expect(requestMessages(probe)).toContain(`${marker}_SUMMARY`);
  249. await waitForV4AssistantMessageContaining(`${marker}_PROBED`);
  250. await waitForIdle();
  251. const sessionId = (await getV4PaneSnapshot()).sessionId!;
  252. const enqueueEvent =
  253. kind === "reply"
  254. ? "subagent.response.runtime_enqueued"
  255. : "background_task.notification.runtime_enqueued";
  256. await browser.waitUntil(
  257. async () => {
  258. timingEvents = await readDeliveryTimingEvents(sessionId);
  259. return (
  260. timingEvents.filter((event) => event.event === enqueueEvent).length === 2 &&
  261. (trigger === "none" ||
  262. timingEvents.some((event) => event.event.endsWith(".completed")))
  263. );
  264. },
  265. { timeout: 15_000, timeoutMsg: "运行日志缺少回传入队或压缩终态证据" },
  266. );
  267. const enqueued = timingEvents.filter((event) => event.event === enqueueEvent);
  268. expect(new Set(enqueued.map((event) => event.context?.commandId)).size).toBe(2);
  269. if (trigger !== "none") {
  270. const started = timingEvents.find((event) => event.event.endsWith(".started"))!.timestamp;
  271. const completed = timingEvents.find((event) =>
  272. event.event.endsWith(".completed"),
  273. )!.timestamp;
  274. for (const index of CHILDREN) {
  275. const event = enqueued.find(
  276. (item) => item.context?.parentToolCallId === `toolu_${scenario}_agent_${index}`,
  277. )!;
  278. expect(event).toBeDefined();
  279. const phase = order[index - 1];
  280. if (phase === "before" || phase === "consumed")
  281. expect(event.timestamp < started).toBe(true);
  282. if (phase === "during")
  283. expect(event.timestamp >= started && event.timestamp < completed).toBe(true);
  284. if (phase === "after") expect(event.timestamp >= completed).toBe(true);
  285. }
  286. }
  287. // 摘要表示可与保留原文并存;正文重复才是重复投递,不能把摘要表示算作第二次入队。
  288. for (const record of (await evidence()).filter((item) => isParentDelivery(item, kind))) {
  289. for (const result of results)
  290. expect(requestMessages(record).split(result).length).toBeLessThanOrEqual(2);
  291. }
  292. if (kind === "reply") {
  293. await Promise.all(
  294. CHILDREN.map((index) =>
  295. releaseControlledReplay(`${scenario}-child-${index}-continued`),
  296. ),
  297. );
  298. await waitForChildCount(0);
  299. await browser.waitUntil(
  300. async () =>
  301. (await evidence()).some(
  302. (record) =>
  303. record.fixtureId === `${scenario}-final-notice` &&
  304. record.status === "complete" &&
  305. CHILDREN.every((index) =>
  306. requestMessages(record).includes(`${marker}_CHILD_FINAL_${index}`),
  307. ),
  308. ),
  309. { timeout: 30_000, timeoutMsg: "主动回复后两个 child 终态未全部送达父模型" },
  310. );
  311. await waitForIdle();
  312. }
  313. const trajectory = await evidence();
  314. expect(trajectory.filter((record) => record.fixtureId === null)).toHaveLength(0);
  315. expect(trajectory.filter(isCompactRequest)).toHaveLength(trigger === "none" ? 0 : 1);
  316. if (trigger === "reactive") expect((await waitStage("arm", true)).statusCode).toBe(400);
  317. } finally {
  318. const artifactDir = process.env.ZCODE_E2E_ARTIFACT_DIR;
  319. if (artifactDir) {
  320. await mkdir(join(artifactDir, "subagent-delivery"), { recursive: true });
  321. await writeFile(
  322. join(artifactDir, "subagent-delivery", `${scenario}-${orderName}.json`),
  323. JSON.stringify(
  324. {
  325. trigger,
  326. kind,
  327. order,
  328. milestones,
  329. timingEvents,
  330. records: await evidence(),
  331. pane: await getV4PaneSnapshot().catch(() => null),
  332. background: await getV4ComposerBackgroundWorkCounts().catch(() => null),
  333. },
  334. null,
  335. 2,
  336. ),
  337. );
  338. }
  339. const response = await fetch(`${replay.baseUrl}/__e2e__/gates`);
  340. const gates = (await response.json()) as string[];
  341. for (const gate of gates.filter((id) => id.startsWith(scenario))) {
  342. await fetch(`${replay.baseUrl}/__e2e__/release/${encodeURIComponent(gate)}`, {
  343. method: "POST",
  344. });
  345. }
  346. if ((await getV4PaneSnapshot()).canStop) await clickV4Stop();
  347. }
  348. });
  349. }
  350. });
  351. function isCompactRequest(record: UpstreamRequestEvidence) {
  352. return record.fixtureId?.includes("-compact-") ?? false;
  353. }
  354. interface DeliveryTimingEvent {
  355. event: string;
  356. timestamp: string;
  357. sessionId?: string;
  358. context?: { parentSessionId?: string; parentToolCallId?: string; commandId?: string };
  359. }
  360. async function readDeliveryTimingEvents(sessionId: string): Promise<DeliveryTimingEvent[]> {
  361. const logDir = process.env.ZCODE_LOG_DIR?.trim() || join(resolveE2EStorageRoot(), "cli", "log");
  362. const names = (await readdir(logDir)).filter((name) => name.endsWith(".jsonl"));
  363. const files = await Promise.all(names.map((name) => readFile(join(logDir, name), "utf8")));
  364. return files
  365. .flatMap((file) => file.split("\n").slice(0, -1))
  366. .filter((line) => line.includes(sessionId))
  367. .map((line) => JSON.parse(line) as DeliveryTimingEvent)
  368. .filter(
  369. (event) =>
  370. (event.sessionId === sessionId || event.context?.parentSessionId === sessionId) &&
  371. (/^compact(?:\.(?:auto|reactive))?\.(?:started|completed)$/u.test(event.event) ||
  372. event.event === "subagent.response.runtime_enqueued" ||
  373. event.event === "background_task.notification.runtime_enqueued"),
  374. );
  375. }
  376. function hasResult(record: UpstreamRequestEvidence, marker: string, index: number) {
  377. const text = requestMessages(record);
  378. return (
  379. text.includes(`${marker}_RESULT_${index}`) || text.includes(`${marker}_SUMMARIZED_${index}`)
  380. );
  381. }
  382. async function waitForStage(
  383. id: string,
  384. read: () => Promise<UpstreamRequestEvidence[]>,
  385. complete = false,
  386. ) {
  387. let found: UpstreamRequestEvidence | undefined;
  388. await browser.waitUntil(
  389. async () => {
  390. found = (await read()).find(
  391. (record) => record.fixtureId === id && (!complete || record.status === "complete"),
  392. );
  393. return Boolean(found);
  394. },
  395. {
  396. timeout: 45_000,
  397. interval: 100,
  398. timeoutMsg: `未到达 provider 阶段 ${id} complete=${complete}`,
  399. },
  400. );
  401. return found!;
  402. }
  403. function requestMessages(record: UpstreamRequestEvidence) {
  404. return JSON.stringify((record.requestJson as { messages?: unknown }).messages);
  405. }
  406. function isParentDelivery(record: UpstreamRequestEvidence, kind: "reply" | "completion") {
  407. const text = requestMessages(record);
  408. return (
  409. text.includes(kind === "reply" ? "<subagent-message>" : "<task-notification>") &&
  410. !text.includes("CRITICAL: Respond with TEXT ONLY")
  411. );
  412. }
  413. async function waitForIdle() {
  414. await waitForV4Pane((pane) => !pane.canStop, "父会话未恢复 idle", 45_000);
  415. }
  416. async function waitForChildCount(expected: number) {
  417. await browser.waitUntil(
  418. async () => ((await getV4ComposerBackgroundWorkCounts())?.subagentCount ?? 0) === expected,
  419. {
  420. timeout: 30_000,
  421. interval: 100,
  422. timeoutMsg: `运行中 child 数量未变为 ${expected}`,
  423. },
  424. );
  425. }