deferred-call-product-projection.test.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  1. import { expect, it } from "vitest";
  2. import { DEFERRED_TOOL_CALL_NAME, SessionEventType, type SessionEvent } from "@zcode/contracts";
  3. import { ConversationTopicPublisher, ProductProjection } from "../src/zcode-protocol-v4/index.js";
  4. import {
  5. subagentProjectionStateSchema,
  6. applyConversationDeltas,
  7. encodeTopicWireFrames,
  8. measureTopicNotificationEnvelopeBytes,
  9. type ConversationSnapshot,
  10. } from "@zcode/shared/zcode-protocol-v4";
  11. it.each([false, true])(
  12. "scheduled identity owns tool rows and plan/CUA consumers (wrapped=%s)",
  13. (wrapped) => {
  14. const projection = new ProductProjection("session", "epoch");
  15. const publisher = new ConversationTopicPublisher("session", "epoch");
  16. let sequence = 0;
  17. const apply = (type: SessionEvent["type"], payload: unknown) => {
  18. const event = {
  19. id: `event-${++sequence}`,
  20. sessionId: "session",
  21. turnId: "turn",
  22. traceId: "trace",
  23. timestamp: new Date(1700000000000 + sequence),
  24. sequenceNumber: sequence,
  25. type,
  26. payload,
  27. } as SessionEvent;
  28. projection.applyEvent(event);
  29. publisher.ingest(event);
  30. };
  31. apply(SessionEventType.SessionCreated, { mode: "plan", contextWindow: 200000 });
  32. apply(SessionEventType.TurnStarted, { turnNumber: 1, input: "plan", messageId: "user" });
  33. const clients = (["continuous", "replayable"] as const).map((deliveryProfile) => {
  34. const subscription = publisher.subscribe({ connectionId: deliveryProfile, deliveryProfile });
  35. if (subscription.frame?.payload.kind !== "snapshot")
  36. throw new Error("expected initial snapshot");
  37. return {
  38. deliveryProfile,
  39. subscriptionId: subscription.ack.subscriptionId,
  40. snapshot: subscription.frame.payload.snapshot,
  41. };
  42. });
  43. const run = (name: string, input: Record<string, unknown>, content: string) => {
  44. const id = `call-${sequence}`;
  45. const raw = {
  46. kind: "tool_call",
  47. toolCallId: id,
  48. toolName: wrapped ? "DeferredToolCall" : name,
  49. input: wrapped ? { name, input } : input,
  50. done: false,
  51. delta: "",
  52. };
  53. apply(SessionEventType.ModelStreaming, { ...raw, kind: "tool_input_start" });
  54. apply(SessionEventType.ModelStreaming, raw);
  55. apply(SessionEventType.ToolCallScheduled, {
  56. toolCallId: id,
  57. toolName: name,
  58. input,
  59. schedule: { parallelGroups: [[id]], executionOrder: [id] },
  60. });
  61. // 重放/流式终稿不能把已准入的目标输入重新覆盖成包装参数。
  62. apply(SessionEventType.ModelStreaming, raw);
  63. apply(SessionEventType.ToolCallStarted, { toolCallId: id, toolName: name });
  64. apply(SessionEventType.ToolCallResult, {
  65. toolCallId: id,
  66. toolName: name,
  67. result: { success: true, content },
  68. duration: 1,
  69. });
  70. const row = projection
  71. .getSnapshot()
  72. .rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === id);
  73. expect(row).toMatchObject({ toolName: name, input, status: "success" });
  74. for (const client of clients) {
  75. const frame = publisher.flush(client.subscriptionId);
  76. if (frame?.payload.kind !== "deltas") throw new Error("expected live tool deltas");
  77. client.snapshot = {
  78. ...applyConversationDeltas(client.snapshot, frame.payload.deltas),
  79. seq: frame.toSeq,
  80. } as ConversationSnapshot;
  81. expect(
  82. client.snapshot.rows.window.find(
  83. (row) => row.kind === "toolCall" && row.toolCallId === id,
  84. ),
  85. ).toMatchObject({ toolName: name, input, status: "success" });
  86. }
  87. return row;
  88. };
  89. run("ExitPlanMode", { plan: "# Plan\nImplement it" }, "Approved");
  90. expect(publisher.getPlans().plans).toHaveLength(1);
  91. run(
  92. "mcp__computer-use__list_apps",
  93. {},
  94. JSON.stringify({ apps: [{ pid: 123, name: "Browser", bundle_id: "demo.browser" }] }),
  95. );
  96. const click = run("mcp__computer-use__click", { app_ref: { pid: 123 }, x: 1, y: 2 }, "Clicked");
  97. expect(click).toMatchObject({
  98. cuaApp: { pid: 123, name: "Browser", bundleId: "demo.browser" },
  99. });
  100. for (const client of clients) {
  101. const frame = publisher.subscribe({
  102. connectionId: `${client.deliveryProfile}-cold`,
  103. deliveryProfile: client.deliveryProfile,
  104. }).frame;
  105. if (frame?.payload.kind !== "snapshot") throw new Error("expected recovery snapshot");
  106. expect(frame.payload.snapshot.rows.window).toEqual(client.snapshot.rows.window);
  107. }
  108. },
  109. );
  110. function createIdentityFixture(toolName = DEFERRED_TOOL_CALL_NAME) {
  111. const projection = new ProductProjection("session", "epoch");
  112. const publisher = new ConversationTopicPublisher("session", "epoch");
  113. let sequence = 0;
  114. const emit = (type: SessionEvent["type"], payload: unknown, turnId = "turn") => {
  115. const event = {
  116. id: `identity-${++sequence}`,
  117. sessionId: "session",
  118. turnId,
  119. traceId: "trace",
  120. timestamp: new Date(1700000000000 + sequence),
  121. sequenceNumber: sequence,
  122. type,
  123. payload,
  124. } as SessionEvent;
  125. const deltas = projection.applyEvent(event);
  126. publisher.ingest(event);
  127. return deltas;
  128. };
  129. emit(SessionEventType.SessionCreated, { mode: "plan", contextWindow: 200000 });
  130. emit(SessionEventType.TurnStarted, { turnNumber: 1, input: "plan", messageId: "user" });
  131. const raw = {
  132. assistantMessageId: "assistant",
  133. kind: "tool_call",
  134. toolCallId: "wrapped",
  135. toolName,
  136. input: { name: "TodoWrite", input: { todos: [] } },
  137. done: false,
  138. delta: "",
  139. };
  140. emit(SessionEventType.ModelStreaming, { ...raw, input: undefined, kind: "tool_input_start" });
  141. emit(SessionEventType.ModelStreaming, raw);
  142. const closed = {
  143. assistantMessageId: "assistant",
  144. attemptId: "attempt",
  145. toolCallId: "wrapped",
  146. toolName: "TodoWrite",
  147. input: { todos: [{ content: "next", status: "pending", priority: "medium" }] },
  148. status: "tool_call_closed",
  149. executionTiming: "during_stream",
  150. };
  151. const row = () => projection.getSnapshot().rows.window.find((item) => item.kind === "toolCall");
  152. return { projection, publisher, emit, raw, closed, row };
  153. }
  154. it("closed target identity updates only the wrapper row and reaches both delivery profiles", () => {
  155. const { projection, publisher, emit, raw, closed, row } = createIdentityFixture();
  156. const clients = (["continuous", "replayable"] as const).map((deliveryProfile) => {
  157. const subscription = publisher.subscribe({ connectionId: deliveryProfile, deliveryProfile });
  158. if (subscription.frame?.payload.kind !== "snapshot") throw new Error("expected snapshot");
  159. return {
  160. subscriptionId: subscription.ack.subscriptionId,
  161. snapshot: subscription.frame.payload.snapshot,
  162. };
  163. });
  164. const before = projection.getSnapshot();
  165. const previousRow = row();
  166. const expected = {
  167. ...previousRow,
  168. toolName: closed.toolName,
  169. input: closed.input,
  170. inputText: JSON.stringify(closed.input),
  171. };
  172. expect(emit(SessionEventType.StreamingToolLedgerUpdated, closed)).toEqual([
  173. { op: "row.upserted", row: expected },
  174. { op: "state.updated", patch: { revision: before.revision + 1 } },
  175. ]);
  176. expect(row()).toEqual(expected);
  177. expect(projection.getSnapshot().plan).toEqual(before.plan);
  178. expect(projection.getSnapshot().goal).toEqual(before.goal);
  179. expect(projection.getSnapshot().control).toEqual(before.control);
  180. expect(emit(SessionEventType.StreamingToolLedgerUpdated, closed)).toEqual([]);
  181. emit(SessionEventType.ModelStreaming, { ...raw, kind: "tool_input_delta", delta: "late" });
  182. emit(SessionEventType.ModelStreaming, raw);
  183. expect(row()).toEqual(expected);
  184. expect(raw.toolName).toBe(DEFERRED_TOOL_CALL_NAME);
  185. for (const client of clients) {
  186. const frame = publisher.flush(client.subscriptionId);
  187. if (frame?.payload.kind !== "deltas") throw new Error("expected identity deltas");
  188. const snapshot = applyConversationDeltas(client.snapshot, frame.payload.deltas);
  189. expect(snapshot.rows.window.find((item) => item.kind === "toolCall")).toEqual(expected);
  190. }
  191. });
  192. it.each([
  193. "ordinary",
  194. "missing-row",
  195. "rejected",
  196. "missing-input",
  197. "wrong-status",
  198. "old-turn",
  199. "mirrored",
  200. "settled-turn",
  201. "scheduled",
  202. ])("closed identity leaves %s events unchanged", (scenario) => {
  203. const { emit, closed, row } = createIdentityFixture(scenario === "ordinary" ? "Read" : undefined);
  204. if (scenario === "settled-turn") emit(SessionEventType.TurnComplete, { result: "success" });
  205. if (scenario === "scheduled") {
  206. emit(SessionEventType.ToolCallScheduled, {
  207. ...closed,
  208. schedule: { parallelGroups: [[closed.toolCallId]], executionOrder: [closed.toolCallId] },
  209. });
  210. }
  211. const before = row();
  212. expect(
  213. emit(
  214. SessionEventType.StreamingToolLedgerUpdated,
  215. {
  216. ...closed,
  217. ...(scenario === "missing-row" ? { toolCallId: "missing" } : {}),
  218. ...(scenario === "rejected" ? { toolName: DEFERRED_TOOL_CALL_NAME } : {}),
  219. ...(scenario === "missing-input" ? { input: undefined } : {}),
  220. ...(scenario === "wrong-status" ? { status: "tool_started" } : {}),
  221. ...(scenario === "mirrored" ? { source: "subagent" } : {}),
  222. ...(scenario === "scheduled" ? { toolName: "different" } : {}),
  223. },
  224. scenario === "old-turn" ? "previous-turn" : "turn",
  225. ),
  226. ).toEqual([]);
  227. expect(row()).toEqual(before);
  228. });
  229. it("identity completion preserves an existing tool error", () => {
  230. const { emit, closed, row } = createIdentityFixture();
  231. emit(SessionEventType.ToolCallError, {
  232. toolCallId: closed.toolCallId,
  233. error: { type: "interrupted", message: "interrupted" },
  234. });
  235. const before = row();
  236. emit(SessionEventType.StreamingToolLedgerUpdated, closed);
  237. expect(row()).toEqual({
  238. ...before,
  239. toolName: closed.toolName,
  240. input: closed.input,
  241. inputText: JSON.stringify(closed.input),
  242. });
  243. expect(row()).toMatchObject({ status: "error", error: { message: "interrupted" } });
  244. });
  245. it.each(["completed", "in_progress"])("next real input retains session Todo (%s)", (status) => {
  246. const projection = new ProductProjection("session", "epoch");
  247. const events: SessionEvent[] = [];
  248. const apply = (type: SessionEvent["type"], payload: unknown, turnId = "turn") => {
  249. const sequence = events.length + 1;
  250. const event = {
  251. id: `todo-${sequence}`,
  252. sessionId: "session",
  253. turnId,
  254. traceId: "trace",
  255. timestamp: new Date(1700000000000 + sequence),
  256. sequenceNumber: sequence,
  257. type,
  258. payload,
  259. } as SessionEvent;
  260. events.push(event);
  261. projection.applyEvent(event);
  262. };
  263. apply(SessionEventType.SessionCreated, { mode: "build", contextWindow: 200000 });
  264. apply(SessionEventType.TurnStarted, { turnNumber: 1, input: "first", messageId: "u1" });
  265. const write = (id: string, content = "step") =>
  266. apply(SessionEventType.ToolCallScheduled, {
  267. toolCallId: id,
  268. toolName: "TodoWrite",
  269. input: { todos: [{ content, status, activeForm: "working" }] },
  270. schedule: { parallelGroups: [[id]], executionOrder: [id] },
  271. });
  272. write("todo1");
  273. expect(projection.getSnapshot().plan?.items).toHaveLength(1);
  274. write("replacement", "new task before next message");
  275. expect(projection.getSnapshot().plan?.items.map((item) => item.content)).toEqual([
  276. "new task before next message",
  277. ]);
  278. apply(SessionEventType.TurnComplete, { turnNumber: 1 });
  279. expect(projection.getSnapshot().plan?.items).toHaveLength(1);
  280. apply(SessionEventType.TurnStarted, { turnNumber: 2, input: "next", messageId: "u2" }, "turn2");
  281. expect(projection.getSnapshot().plan?.items).toHaveLength(1);
  282. const cold = new ProductProjection("session", "epoch");
  283. cold.beginHydrationReplay();
  284. for (const event of events) cold.applyHydrationEvent(event);
  285. cold.completeHydrationReplay();
  286. expect(cold.getSnapshot().plan).toEqual(projection.getSnapshot().plan);
  287. write("todo2");
  288. expect(projection.getSnapshot().plan?.items).toHaveLength(1);
  289. });
  290. it.each(["complete", "active", "paused"])("next input retains session Goal (%s)", (status) => {
  291. const p = new ProductProjection("session", "epoch");
  292. const events: SessionEvent[] = [];
  293. const send = (type: SessionEvent["type"], payload: unknown) => {
  294. const n = events.length + 1;
  295. const event = {
  296. id: `g${n}`,
  297. sessionId: "session",
  298. turnId: "turn",
  299. traceId: "trace",
  300. timestamp: new Date(1700000000000 + n),
  301. sequenceNumber: n,
  302. type,
  303. payload,
  304. } as SessionEvent;
  305. events.push(event);
  306. p.applyEvent(event);
  307. };
  308. const target = {
  309. sessionID: "session",
  310. targetID: "goal",
  311. objective: "Goal history",
  312. summaryTitle: null,
  313. status,
  314. tokenBudget: null,
  315. tokensUsed: 0,
  316. timeUsedSeconds: 44,
  317. time: { created: 0, updated: 0 },
  318. };
  319. send(SessionEventType.SessionCreated, { mode: "build", contextWindow: 200000 });
  320. send(SessionEventType.TargetChanged, {
  321. action: "set",
  322. source: "command",
  323. target,
  324. previousTarget: null,
  325. });
  326. expect(p.getSnapshot().goal?.summaryHidden).not.toBe(true);
  327. send(SessionEventType.TurnStarted, { turnNumber: 1, input: "next", messageId: "u1" });
  328. expect(p.getSnapshot().goal?.summaryHidden).not.toBe(true);
  329. expect(p.getSnapshot().goal?.objective).toBe("Goal history");
  330. const cold = new ProductProjection("session", "epoch");
  331. cold.beginHydrationReplay();
  332. events.forEach((e) => cold.applyHydrationEvent(e));
  333. cold.completeHydrationReplay();
  334. expect(cold.getSnapshot().goal).toEqual(p.getSnapshot().goal);
  335. send(SessionEventType.TargetChanged, {
  336. action: "set",
  337. source: "command",
  338. target: { ...target, targetID: "new", status: "active" },
  339. previousTarget: target,
  340. });
  341. expect(p.getSnapshot().goal?.summaryHidden).not.toBe(true);
  342. });
  343. it("activity archives ended details on accepted input and replays the boundary", () => {
  344. const p = new ProductProjection("session", "epoch");
  345. const events: SessionEvent[] = [];
  346. const send = (type: SessionEventType, payload: unknown) => {
  347. const n = events.length + 1;
  348. const event = {
  349. eventId: `activity-${n}`,
  350. sessionId: "session",
  351. turnId: "turn",
  352. traceId: "trace",
  353. timestamp: new Date(1700000000000 + n),
  354. sequenceNumber: n,
  355. type,
  356. payload,
  357. } as SessionEvent;
  358. events.push(event);
  359. p.applyEvent(event);
  360. };
  361. send(SessionEventType.SessionCreated, { mode: "build", contextWindow: 200000 });
  362. send(SessionEventType.BackgroundTaskStarted, {
  363. taskId: "bash",
  364. taskKind: "bash",
  365. command: "echo test",
  366. status: "running",
  367. });
  368. send(SessionEventType.TurnStarted, { turnNumber: 1, input: "while running", messageId: "u1" });
  369. expect(p.getSnapshot().activitySummaryDismissed?.workIds).toEqual([]);
  370. send(SessionEventType.BackgroundTaskCompleted, {
  371. taskId: "bash",
  372. taskKind: "bash",
  373. status: "completed",
  374. });
  375. expect(p.getSnapshot().backgroundWorks[0]?.status).toBe("resultPending");
  376. expect(p.getSnapshot().activitySummaryDismissed?.workIds).toEqual([]);
  377. const beforeFailure = p.getSnapshot().activitySummaryDismissed;
  378. send(SessionEventType.TurnError, { error: { message: "send failed" } });
  379. expect(p.getSnapshot().activitySummaryDismissed).toEqual(beforeFailure);
  380. send(SessionEventType.BackgroundTaskStarted, {
  381. taskId: "still-running",
  382. taskKind: "bash",
  383. command: "wait",
  384. status: "running",
  385. });
  386. send(SessionEventType.TurnStarted, { turnNumber: 2, input: "next", messageId: "u2" });
  387. expect(p.getSnapshot().activitySummaryDismissed?.workIds).toEqual(["bash"]);
  388. const cold = new ProductProjection("session", "epoch");
  389. cold.beginHydrationReplay();
  390. events.forEach((e) => cold.applyHydrationEvent(e));
  391. cold.completeHydrationReplay();
  392. expect(cold.getSnapshot().activitySummaryDismissed).toEqual(
  393. p.getSnapshot().activitySummaryDismissed,
  394. );
  395. });
  396. it.each(["success", "failed", "cancelled"])(
  397. "ended subagent %s retains result across accepted input, including resume",
  398. (status) => {
  399. const p = new ProductProjection("session", "epoch");
  400. const events: SessionEvent[] = [];
  401. const send = (type: SessionEventType, payload: unknown) => {
  402. const n = events.length + 1;
  403. const event = {
  404. eventId: `ended-agent-${n}`,
  405. sessionId: "session",
  406. turnId: `turn-${n}`,
  407. traceId: "trace",
  408. timestamp: new Date(1700000000000),
  409. sequenceNumber: n,
  410. type,
  411. payload,
  412. } as SessionEvent;
  413. events.push(event);
  414. p.applyEvent(event);
  415. };
  416. send(SessionEventType.SessionCreated, { mode: "build", contextWindow: 200000 });
  417. send(SessionEventType.SubagentSpawned, {
  418. agentId: "agent",
  419. childSessionId: "child",
  420. agentType: "Explore",
  421. description: "Inspect project",
  422. });
  423. send(SessionEventType.SubagentStopped, {
  424. agentId: "agent",
  425. childSessionId: "child",
  426. status,
  427. summaryText: "Actual result",
  428. });
  429. expect(p.getSnapshot().subagents?.ended?.[0]).toMatchObject({
  430. title: "Inspect project",
  431. summary: "Actual result",
  432. status,
  433. });
  434. send(SessionEventType.TurnStarted, { turnNumber: 1, input: "next", messageId: "u1" });
  435. expect(p.getSnapshot().subagents?.ended).toHaveLength(1);
  436. expect(p.getSnapshot().activitySummaryDismissed?.subagentIds).toContain("child");
  437. // 连续普通输入不得清除会话内的结束结果。
  438. send(SessionEventType.TurnStarted, { turnNumber: 2, input: "again", messageId: "u2" });
  439. send(SessionEventType.TurnComplete, { status: "success" });
  440. expect(p.getSnapshot().subagents?.ended).toHaveLength(1);
  441. const cleared = new ProductProjection("session", "epoch");
  442. cleared.beginHydrationReplay();
  443. events.forEach((event) => cleared.applyHydrationEvent(event));
  444. cleared.completeHydrationReplay();
  445. cleared.seedSubagents({ revision: 1, childSessionIds: ["child"], running: [] });
  446. expect(cleared.getSnapshot().subagents?.ended).toHaveLength(1);
  447. send(SessionEventType.SubagentSpawned, {
  448. agentId: "agent",
  449. childSessionId: "child",
  450. agentType: "Explore",
  451. description: "Resume project",
  452. resumed: true,
  453. });
  454. send(SessionEventType.SubagentStopped, {
  455. agentId: "agent",
  456. childSessionId: "child",
  457. status: "success",
  458. summaryText: "New result",
  459. });
  460. expect(p.getSnapshot().subagents?.ended?.[0]?.summary).toBe("New result");
  461. expect(p.getSnapshot().activitySummaryDismissed?.subagentIds).not.toContain("child");
  462. const cold = new ProductProjection("session", "epoch");
  463. cold.beginHydrationReplay();
  464. events.forEach((event) => cold.applyHydrationEvent(event));
  465. cold.completeHydrationReplay();
  466. // 桌面重启先回放事件,再用持久化 child 目录校验;不能在第二步丢掉结束摘要。
  467. cold.seedSubagents({ revision: 1, childSessionIds: ["child"], running: [] });
  468. expect(cold.getSnapshot().subagents?.ended).toEqual(p.getSnapshot().subagents?.ended);
  469. cold.seedSubagents({ revision: 2, childSessionIds: [], running: [] });
  470. expect(cold.getSnapshot().subagents?.ended).toEqual([]);
  471. },
  472. );
  473. it.each(["success", "failed", "cancelled"] as const)(
  474. "cold seed archives older %s results and retains new results",
  475. (status) => {
  476. const projection = new ProductProjection("session", "epoch");
  477. const events: SessionEvent[] = [];
  478. const apply = (event: SessionEvent) => {
  479. events.push(event);
  480. projection.applyEvent(event);
  481. };
  482. for (const [type, payload] of [
  483. [
  484. SessionEventType.SubagentSpawned,
  485. { agentId: "agent", childSessionId: "resumed", agentType: "Explore" },
  486. ],
  487. [
  488. SessionEventType.SubagentStopped,
  489. { agentId: "agent", childSessionId: "resumed", status: "success", summaryText: "Old" },
  490. ],
  491. ] as const)
  492. apply({
  493. eventId: type,
  494. sessionId: "session",
  495. turnId: "old",
  496. traceId: "trace",
  497. timestamp: new Date(1000),
  498. sequenceNumber: 0,
  499. type,
  500. payload,
  501. } as SessionEvent);
  502. apply({
  503. eventId: "accepted",
  504. sessionId: "session",
  505. turnId: "turn",
  506. traceId: "trace",
  507. timestamp: new Date(2000),
  508. sequenceNumber: 1,
  509. type: SessionEventType.TurnStarted,
  510. payload: { turnNumber: 1, input: "next", messageId: "next" },
  511. } as SessionEvent);
  512. const ended = subagentProjectionStateSchema.shape.ended.unwrap().parse([
  513. {
  514. childSessionId: "resumed",
  515. subagentType: "Explore",
  516. title: "Resumed",
  517. status,
  518. endedAt: 3000,
  519. },
  520. {
  521. childSessionId: "old",
  522. subagentType: "Explore",
  523. title: "Old",
  524. status,
  525. endedAt: 1000,
  526. },
  527. ]);
  528. projection.seedSubagents({
  529. revision: 1,
  530. childSessionIds: ["resumed", "old"],
  531. running: [],
  532. ended,
  533. });
  534. expect(projection.getSnapshot().subagents?.ended?.map((item) => item.childSessionId)).toEqual([
  535. "resumed",
  536. "old",
  537. ]);
  538. expect(projection.getSnapshot().subagents?.ended?.map((item) => item.status)).toEqual([
  539. status,
  540. status,
  541. ]);
  542. expect(projection.getSnapshot().activitySummaryDismissed?.subagentIds).toContain("old");
  543. expect(projection.getSnapshot().activitySummaryDismissed?.at).toBe(2000);
  544. apply({
  545. eventId: "complete",
  546. sessionId: "session",
  547. turnId: "turn",
  548. traceId: "trace",
  549. timestamp: new Date(3500),
  550. sequenceNumber: 2,
  551. type: SessionEventType.TurnComplete,
  552. payload: { status: "success" },
  553. } as SessionEvent);
  554. expect(projection.getSnapshot().subagents?.ended?.[0]?.endedAt).toBe(3000);
  555. apply({
  556. eventId: "clear-again",
  557. sessionId: "session",
  558. turnId: "turn2",
  559. traceId: "trace",
  560. timestamp: new Date(4000),
  561. sequenceNumber: 2,
  562. type: SessionEventType.TurnStarted,
  563. payload: { turnNumber: 2, input: "clear", messageId: "clear" },
  564. } as SessionEvent);
  565. expect(projection.getSnapshot().subagents?.ended).toHaveLength(2);
  566. projection.seedSubagents({
  567. revision: 2,
  568. childSessionIds: ["resumed", "old"],
  569. running: [],
  570. ended,
  571. });
  572. expect(projection.getSnapshot().subagents?.ended).toHaveLength(2);
  573. expect(projection.getSnapshot().activitySummaryDismissed?.subagentIds).toEqual(
  574. expect.arrayContaining(["resumed", "old"]),
  575. );
  576. expect(projection.getSnapshot().activitySummaryDismissed?.at).toBe(4000);
  577. const cold = new ProductProjection("session", "epoch");
  578. cold.beginHydrationReplay();
  579. events.forEach((event) => cold.applyHydrationEvent(event));
  580. cold.completeHydrationReplay();
  581. cold.seedSubagents({ revision: 2, childSessionIds: ["resumed", "old"], running: [], ended });
  582. expect(cold.getSnapshot().subagents?.ended).toEqual(projection.getSnapshot().subagents?.ended);
  583. expect(cold.getSnapshot().activitySummaryDismissed).toEqual(
  584. projection.getSnapshot().activitySummaryDismissed,
  585. );
  586. },
  587. );
  588. it.each(["completed", "stopped", "errored"])(
  589. "resumed workflow retains its new %s result alongside session siblings",
  590. (status) => {
  591. const projection = new ProductProjection("session", "epoch");
  592. const events: SessionEvent[] = [];
  593. const send = (type: SessionEventType, payload: unknown) => {
  594. const n = events.length + 1;
  595. const event = {
  596. eventId: `workflow-${n}`,
  597. sessionId: "session",
  598. turnId: "turn",
  599. traceId: "trace",
  600. timestamp: new Date(1700000000000 + n),
  601. sequenceNumber: n,
  602. type,
  603. payload,
  604. } as SessionEvent;
  605. events.push(event);
  606. projection.applyEvent(event);
  607. };
  608. const progress = (runId: string, sequence: number, eventType: string, payload: unknown) =>
  609. send(SessionEventType.DynamicWorkflowRunProgress, {
  610. runId,
  611. toolCallId: runId,
  612. sequence,
  613. eventType,
  614. payload,
  615. });
  616. send(SessionEventType.SessionCreated, { mode: "build", contextWindow: 200000 });
  617. for (const runId of ["resumed", "sibling"]) {
  618. progress(runId, 0, "run-started", { runId, caps: { maxConcurrency: 1 } });
  619. progress(runId, 1, "run-settled", { status: "stopped", stopReason: "interrupted" });
  620. }
  621. send(SessionEventType.TurnStarted, { turnNumber: 1, input: "resume", messageId: "u1" });
  622. expect(projection.getSnapshot().activitySummaryDismissed?.workflowRunIds).toEqual([
  623. "resumed",
  624. "sibling",
  625. ]);
  626. progress("resumed", 1, "run-settled", { status: "stopped", stopReason: "interrupted" });
  627. progress("resumed", 2, "run-started", { runId: "resumed", caps: { maxConcurrency: 1 } });
  628. progress("resumed", 3, "run-settled", { status });
  629. expect(
  630. projection.getSnapshot().workflowRuns?.runs.find((run) => run.runId === "resumed")?.status,
  631. ).toBe(status);
  632. expect(projection.getSnapshot().activitySummaryDismissed?.workflowRunIds).toEqual(["sibling"]);
  633. const cold = new ProductProjection("session", "epoch");
  634. cold.beginHydrationReplay();
  635. events.forEach((event) => cold.applyHydrationEvent(event));
  636. cold.completeHydrationReplay();
  637. expect(cold.getSnapshot().activitySummaryDismissed).toEqual(
  638. projection.getSnapshot().activitySummaryDismissed,
  639. );
  640. expect(cold.getSnapshot().workflowRuns).toEqual(projection.getSnapshot().workflowRuns);
  641. send(SessionEventType.TurnStarted, { turnNumber: 2, input: "clear", messageId: "u2" });
  642. expect(projection.getSnapshot().workflowRuns?.runs).toHaveLength(2);
  643. },
  644. );
  645. // 旧会话没有清除时间时,全部长结果曾进入快照并触发 16 MiB 逻辑帧拒绝。
  646. it.each(["continuous", "replayable"] as const)(
  647. "bounds cold subagent outcomes for %s subscription and reconnect",
  648. (deliveryProfile) => {
  649. const publisher = new ConversationTopicPublisher("session", "epoch");
  650. const ended = Array.from({ length: 180 }, (_, index) => ({
  651. childSessionId: `child-${index}`,
  652. subagentType: "Explore",
  653. title: "标题".repeat(500),
  654. summary: "结果".repeat(40000),
  655. status: "success" as const,
  656. endedAt: index + 1,
  657. }));
  658. expect(Buffer.byteLength(JSON.stringify(ended))).toBeGreaterThan(16 * 1024 * 1024);
  659. publisher.seedSubagents({
  660. revision: 1,
  661. childSessionIds: ended.map((item) => item.childSessionId),
  662. running: [],
  663. ended,
  664. });
  665. for (const connectionId of ["initial", "reconnected"]) {
  666. const { frame } = publisher.subscribe({ connectionId, deliveryProfile });
  667. if (frame?.payload.kind !== "snapshot") throw new Error("expected snapshot");
  668. const state = frame.payload.snapshot.subagents!;
  669. expect(() =>
  670. encodeTopicWireFrames(frame, {
  671. deliveryKind: connectionId === "initial" ? "initial" : "recovery",
  672. topic: "conversation/session",
  673. subscriptionId: connectionId,
  674. logicalFrameId: connectionId,
  675. logicalFrameOrdinal: 1,
  676. measurePhysicalFrameBytes: (wire) => measureTopicNotificationEnvelopeBytes(wire).maxBytes,
  677. }),
  678. ).not.toThrow();
  679. expect(state.endedTotal).toBe(180);
  680. expect(frame.payload.snapshot.completedActivityCount).toBe(180);
  681. expect(state.childSessionIds).toHaveLength(180);
  682. expect(state.ended).toHaveLength(100);
  683. expect(state.ended?.[0]?.childSessionId).toBe("child-179");
  684. expect(
  685. state.ended?.every((item) => item.summary!.length <= 4096 && item.title.length <= 256),
  686. ).toBe(true);
  687. }
  688. // 容量裁剪不可修改供历史目录使用的原始结果。
  689. expect(ended[0]!.summary).toHaveLength(80000);
  690. },
  691. );
  692. it("retains a bounded session preview across messages and resumed children", () => {
  693. const projection = new ProductProjection("session", "epoch");
  694. const events: SessionEvent[] = [];
  695. const send = (type: SessionEventType, payload: unknown) => {
  696. const n = events.length + 1;
  697. const event = {
  698. eventId: `bounded-${n}`,
  699. sessionId: "session",
  700. turnId: "turn",
  701. traceId: "trace",
  702. timestamp: new Date(n * 1000),
  703. sequenceNumber: n,
  704. type,
  705. payload,
  706. } as SessionEvent;
  707. events.push(event);
  708. projection.applyEvent(event);
  709. };
  710. for (let index = 0; index < 105; index += 1) {
  711. send(SessionEventType.SubagentSpawned, {
  712. agentId: `agent-${index}`,
  713. childSessionId: `child-${index}`,
  714. agentType: "Explore",
  715. description: "Inspect",
  716. });
  717. send(SessionEventType.SubagentStopped, {
  718. agentId: `agent-${index}`,
  719. childSessionId: `child-${index}`,
  720. status: "success",
  721. summaryText: "Result".repeat(1000),
  722. });
  723. }
  724. expect(projection.getSnapshot().subagents?.ended).toHaveLength(100);
  725. expect(projection.getSnapshot().subagents?.endedTotal).toBe(105);
  726. expect(projection.getSnapshot().completedActivityCount).toBe(105);
  727. expect(projection.getSnapshot().subagents?.ended?.[0]?.childSessionId).toBe("child-104");
  728. send(SessionEventType.TurnStarted, { turnNumber: 1, input: "next", messageId: "next" });
  729. expect(projection.getSnapshot().subagents?.ended).toHaveLength(100);
  730. expect(projection.getSnapshot().activitySummaryDismissed?.subagentIds).toHaveLength(105);
  731. // 新执行更新同一 child,结束预览仍受容量上限约束。
  732. send(SessionEventType.SubagentSpawned, {
  733. agentId: "agent-0",
  734. childSessionId: "child-0",
  735. agentType: "Explore",
  736. description: "Resume",
  737. });
  738. expect(projection.getSnapshot().subagents?.ended).toHaveLength(100);
  739. send(SessionEventType.SubagentStopped, {
  740. agentId: "agent-0",
  741. childSessionId: "child-0",
  742. status: "success",
  743. summaryText: "Resumed result",
  744. });
  745. expect(projection.getSnapshot().subagents?.ended).toHaveLength(100);
  746. expect(projection.getSnapshot().subagents?.ended?.[0]?.childSessionId).toBe("child-0");
  747. const cold = new ProductProjection("session", "epoch");
  748. for (const event of events) cold.applyEvent(event);
  749. expect(cold.getSnapshot().subagents).toEqual(projection.getSnapshot().subagents);
  750. expect(cold.getSnapshot().completedActivityCount).toBe(
  751. projection.getSnapshot().completedActivityCount,
  752. );
  753. });
  754. // 成功总数不能取自只保留最近 8 条的 run 预览;索引属于原子投影事务。
  755. it("counts workflow history beyond previews without duplicate or rejected updates", () => {
  756. const projection = new ProductProjection("session", "epoch");
  757. const events: SessionEvent[] = [];
  758. const event = (runId: string, sequence: number, eventType: string) =>
  759. ({
  760. id: `event-${events.length + 1}`,
  761. sessionId: "session",
  762. traceId: "trace",
  763. timestamp: new Date(),
  764. sequenceNumber: events.length + 1,
  765. type: SessionEventType.DynamicWorkflowRunProgress,
  766. payload: {
  767. runId,
  768. sequence,
  769. eventType: eventType === "run-started" ? eventType : "run-settled",
  770. payload: eventType === "run-started" ? {} : { status: eventType.slice(4) },
  771. },
  772. }) as SessionEvent;
  773. const send = (runId: string, sequence: number, eventType: string) => {
  774. const next = event(runId, sequence, eventType);
  775. events.push(next);
  776. projection.applyEventAtomically(next, () => true);
  777. };
  778. for (let i = 0; i < 9; i++) {
  779. send(`run-${i}`, 1, "run-started");
  780. send(`run-${i}`, 2, "run-completed");
  781. }
  782. expect(projection.getSnapshot().workflowRuns?.runs).toHaveLength(8);
  783. expect(projection.getSnapshot().completedActivityCount).toBe(9);
  784. send("failed", 1, "run-started");
  785. send("failed", 2, "run-failed");
  786. send("stopped", 1, "run-started");
  787. send("stopped", 2, "run-stopped");
  788. send("run-0", 2, "run-completed");
  789. send("run-0", 1, "run-started");
  790. expect(projection.getSnapshot().completedActivityCount).toBe(9);
  791. expect(projection.applyEventAtomically(event("run-0", 3, "run-started"), () => false)).toBeNull();
  792. expect(projection.getSnapshot().completedActivityCount).toBe(9);
  793. send("run-0", 3, "run-started");
  794. expect(projection.getSnapshot().completedActivityCount).toBe(8);
  795. send("run-0", 4, "run-completed");
  796. expect(projection.getSnapshot().completedActivityCount).toBe(9);
  797. const cold = new ProductProjection("session", "epoch");
  798. for (const next of events) cold.applyEvent(next);
  799. expect(cold.getSnapshot().completedActivityCount).toBe(9);
  800. expect(new ProductProjection("other", "epoch").getSnapshot().completedActivityCount).toBe(0);
  801. });
  802. it.each(["continuous", "replayable"] as const)(
  803. "cold complete history survives %s snapshots and reconnect",
  804. (deliveryProfile) => {
  805. const publisher = new ConversationTopicPublisher("session", "epoch");
  806. publisher.seedSubagents(undefined, {
  807. runs: Array.from({ length: 11 }, (_, i) => ({
  808. runId: `run-${i}`,
  809. status: i < 9 ? "completed" : "stopped",
  810. sequence: 4,
  811. })),
  812. childSessionIds: ["actor"],
  813. });
  814. const ended = Array.from({ length: 106 }, (_, i) => ({
  815. childSessionId: i === 105 ? "actor" : `child-${i}`,
  816. subagentType: "Explore",
  817. title: "done",
  818. status: "success" as const,
  819. endedAt: 1,
  820. }));
  821. publisher.seedSubagents({
  822. revision: 1,
  823. childSessionIds: ended.map((x) => x.childSessionId),
  824. running: [],
  825. ended,
  826. });
  827. for (const connectionId of ["initial", "reconnected"]) {
  828. const { frame } = publisher.subscribe({ connectionId, deliveryProfile });
  829. if (frame?.payload.kind !== "snapshot") throw new Error("expected snapshot");
  830. expect(frame.payload.snapshot.completedActivityCount).toBe(114);
  831. expect(frame.payload.snapshot.subagents?.ended).toHaveLength(100);
  832. }
  833. },
  834. );
  835. it.each([false, true])(
  836. "newer cold history count does not swallow buffered preview completion (existing=%s)",
  837. (existing) => {
  838. const projection = new ProductProjection("session", "epoch");
  839. const progress = (sequence: number, eventType: string, payload: unknown) =>
  840. ({
  841. id: `buffer-${sequence}`,
  842. sessionId: "session",
  843. traceId: "trace",
  844. timestamp: new Date(),
  845. sequenceNumber: sequence + 1,
  846. type: SessionEventType.DynamicWorkflowRunProgress,
  847. payload: { runId: "run", sequence, eventType, payload },
  848. }) as SessionEvent;
  849. if (existing) projection.applyEvent(progress(0, "run-started", {}));
  850. projection.seedWorkflowActivityHistory({
  851. runs: [{ runId: "run", status: "completed", sequence: 2 }],
  852. childSessionIds: [],
  853. });
  854. projection.applyEvent(
  855. progress(1, "node-queued", { instance: { siteId: "ask", ordinal: 1 }, kind: "ask" }),
  856. );
  857. expect(projection.getSnapshot().completedActivityCount).toBe(1);
  858. projection.applyEvent(progress(2, "run-settled", { status: "completed" }));
  859. expect(projection.getSnapshot().workflowRuns?.runs[0]?.status).toBe("completed");
  860. expect(projection.getSnapshot().completedActivityCount).toBe(1);
  861. projection.seedWorkflowActivityHistory({
  862. runs: [{ runId: "run", status: "running", sequence: 1 }],
  863. childSessionIds: [],
  864. });
  865. expect(projection.getSnapshot().completedActivityCount).toBe(1);
  866. },
  867. );
  868. it.each(["continuous", "replayable"] as const)(
  869. "unknown total survives live events and reconnect until a complete seed (%s)",
  870. (deliveryProfile) => {
  871. const publisher = new ConversationTopicPublisher("session", "epoch");
  872. publisher.seedSubagents(undefined, null);
  873. publisher.ingest({
  874. id: "done",
  875. sessionId: "session",
  876. traceId: "trace",
  877. timestamp: new Date(),
  878. sequenceNumber: 1,
  879. type: SessionEventType.DynamicWorkflowRunProgress,
  880. payload: {
  881. runId: "run",
  882. sequence: 1,
  883. eventType: "run-settled",
  884. payload: { status: "completed" },
  885. },
  886. } as SessionEvent);
  887. for (const connectionId of ["first", "reconnect"]) {
  888. const { frame } = publisher.subscribe({ connectionId, deliveryProfile });
  889. if (frame?.payload.kind !== "snapshot") throw new Error("expected snapshot");
  890. expect(frame.payload.snapshot.completedActivityCount).toBeNull();
  891. expect(frame.payload.snapshot.workflowRuns?.runs[0]?.status).toBe("completed");
  892. }
  893. publisher.seedSubagents(undefined, {
  894. runs: [{ runId: "run", sequence: 1, status: "completed" }],
  895. childSessionIds: [],
  896. });
  897. const { frame } = publisher.subscribe({ connectionId: "recovered", deliveryProfile });
  898. if (frame?.payload.kind !== "snapshot") throw new Error("expected snapshot");
  899. expect(frame.payload.snapshot.completedActivityCount).toBe(1);
  900. },
  901. );