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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. applyConversationDeltas,
  6. type ConversationSnapshot,
  7. } from "@zcode/shared/zcode-protocol-v4";
  8. it.each([false, true])(
  9. "scheduled identity owns tool rows and plan/CUA consumers (wrapped=%s)",
  10. (wrapped) => {
  11. const projection = new ProductProjection("session", "epoch");
  12. const publisher = new ConversationTopicPublisher("session", "epoch");
  13. let sequence = 0;
  14. const apply = (type: SessionEvent["type"], payload: unknown) => {
  15. const event = {
  16. id: `event-${++sequence}`,
  17. sessionId: "session",
  18. turnId: "turn",
  19. traceId: "trace",
  20. timestamp: new Date(1700000000000 + sequence),
  21. sequenceNumber: sequence,
  22. type,
  23. payload,
  24. } as SessionEvent;
  25. projection.applyEvent(event);
  26. publisher.ingest(event);
  27. };
  28. apply(SessionEventType.SessionCreated, { mode: "plan", contextWindow: 200000 });
  29. apply(SessionEventType.TurnStarted, { turnNumber: 1, input: "plan", messageId: "user" });
  30. const clients = (["continuous", "replayable"] as const).map((deliveryProfile) => {
  31. const subscription = publisher.subscribe({ connectionId: deliveryProfile, deliveryProfile });
  32. if (subscription.frame?.payload.kind !== "snapshot")
  33. throw new Error("expected initial snapshot");
  34. return {
  35. deliveryProfile,
  36. subscriptionId: subscription.ack.subscriptionId,
  37. snapshot: subscription.frame.payload.snapshot,
  38. };
  39. });
  40. const run = (name: string, input: Record<string, unknown>, content: string) => {
  41. const id = `call-${sequence}`;
  42. const raw = {
  43. kind: "tool_call",
  44. toolCallId: id,
  45. toolName: wrapped ? "DeferredToolCall" : name,
  46. input: wrapped ? { name, input } : input,
  47. done: false,
  48. delta: "",
  49. };
  50. apply(SessionEventType.ModelStreaming, { ...raw, kind: "tool_input_start" });
  51. apply(SessionEventType.ModelStreaming, raw);
  52. apply(SessionEventType.ToolCallScheduled, {
  53. toolCallId: id,
  54. toolName: name,
  55. input,
  56. schedule: { parallelGroups: [[id]], executionOrder: [id] },
  57. });
  58. // 重放/流式终稿不能把已准入的目标输入重新覆盖成包装参数。
  59. apply(SessionEventType.ModelStreaming, raw);
  60. apply(SessionEventType.ToolCallStarted, { toolCallId: id, toolName: name });
  61. apply(SessionEventType.ToolCallResult, {
  62. toolCallId: id,
  63. toolName: name,
  64. result: { success: true, content },
  65. duration: 1,
  66. });
  67. const row = projection
  68. .getSnapshot()
  69. .rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === id);
  70. expect(row).toMatchObject({ toolName: name, input, status: "success" });
  71. for (const client of clients) {
  72. const frame = publisher.flush(client.subscriptionId);
  73. if (frame?.payload.kind !== "deltas") throw new Error("expected live tool deltas");
  74. client.snapshot = {
  75. ...applyConversationDeltas(client.snapshot, frame.payload.deltas),
  76. seq: frame.toSeq,
  77. } as ConversationSnapshot;
  78. expect(
  79. client.snapshot.rows.window.find(
  80. (row) => row.kind === "toolCall" && row.toolCallId === id,
  81. ),
  82. ).toMatchObject({ toolName: name, input, status: "success" });
  83. }
  84. return row;
  85. };
  86. run("ExitPlanMode", { plan: "# Plan\nImplement it" }, "Approved");
  87. expect(publisher.getPlans().plans).toHaveLength(1);
  88. run(
  89. "mcp__computer-use__list_apps",
  90. {},
  91. JSON.stringify({ apps: [{ pid: 123, name: "Browser", bundle_id: "demo.browser" }] }),
  92. );
  93. const click = run("mcp__computer-use__click", { app_ref: { pid: 123 }, x: 1, y: 2 }, "Clicked");
  94. expect(click).toMatchObject({
  95. cuaApp: { pid: 123, name: "Browser", bundleId: "demo.browser" },
  96. });
  97. for (const client of clients) {
  98. const frame = publisher.subscribe({
  99. connectionId: `${client.deliveryProfile}-cold`,
  100. deliveryProfile: client.deliveryProfile,
  101. }).frame;
  102. if (frame?.payload.kind !== "snapshot") throw new Error("expected recovery snapshot");
  103. expect(frame.payload.snapshot.rows.window).toEqual(client.snapshot.rows.window);
  104. }
  105. },
  106. );
  107. function createIdentityFixture(toolName = DEFERRED_TOOL_CALL_NAME) {
  108. const projection = new ProductProjection("session", "epoch");
  109. const publisher = new ConversationTopicPublisher("session", "epoch");
  110. let sequence = 0;
  111. const emit = (type: SessionEvent["type"], payload: unknown, turnId = "turn") => {
  112. const event = {
  113. id: `identity-${++sequence}`,
  114. sessionId: "session",
  115. turnId,
  116. traceId: "trace",
  117. timestamp: new Date(1700000000000 + sequence),
  118. sequenceNumber: sequence,
  119. type,
  120. payload,
  121. } as SessionEvent;
  122. const deltas = projection.applyEvent(event);
  123. publisher.ingest(event);
  124. return deltas;
  125. };
  126. emit(SessionEventType.SessionCreated, { mode: "plan", contextWindow: 200000 });
  127. emit(SessionEventType.TurnStarted, { turnNumber: 1, input: "plan", messageId: "user" });
  128. const raw = {
  129. assistantMessageId: "assistant",
  130. kind: "tool_call",
  131. toolCallId: "wrapped",
  132. toolName,
  133. input: { name: "TodoWrite", input: { todos: [] } },
  134. done: false,
  135. delta: "",
  136. };
  137. emit(SessionEventType.ModelStreaming, { ...raw, input: undefined, kind: "tool_input_start" });
  138. emit(SessionEventType.ModelStreaming, raw);
  139. const closed = {
  140. assistantMessageId: "assistant",
  141. attemptId: "attempt",
  142. toolCallId: "wrapped",
  143. toolName: "TodoWrite",
  144. input: { todos: [{ content: "next", status: "pending", priority: "medium" }] },
  145. status: "tool_call_closed",
  146. executionTiming: "during_stream",
  147. };
  148. const row = () => projection.getSnapshot().rows.window.find((item) => item.kind === "toolCall");
  149. return { projection, publisher, emit, raw, closed, row };
  150. }
  151. it("closed target identity updates only the wrapper row and reaches both delivery profiles", () => {
  152. const { projection, publisher, emit, raw, closed, row } = createIdentityFixture();
  153. const clients = (["continuous", "replayable"] as const).map((deliveryProfile) => {
  154. const subscription = publisher.subscribe({ connectionId: deliveryProfile, deliveryProfile });
  155. if (subscription.frame?.payload.kind !== "snapshot") throw new Error("expected snapshot");
  156. return {
  157. subscriptionId: subscription.ack.subscriptionId,
  158. snapshot: subscription.frame.payload.snapshot,
  159. };
  160. });
  161. const before = projection.getSnapshot();
  162. const previousRow = row();
  163. const expected = {
  164. ...previousRow,
  165. toolName: closed.toolName,
  166. input: closed.input,
  167. inputText: JSON.stringify(closed.input),
  168. };
  169. expect(emit(SessionEventType.StreamingToolLedgerUpdated, closed)).toEqual([
  170. { op: "row.upserted", row: expected },
  171. { op: "state.updated", patch: { revision: before.revision + 1 } },
  172. ]);
  173. expect(row()).toEqual(expected);
  174. expect(projection.getSnapshot().plan).toEqual(before.plan);
  175. expect(projection.getSnapshot().goal).toEqual(before.goal);
  176. expect(projection.getSnapshot().control).toEqual(before.control);
  177. expect(emit(SessionEventType.StreamingToolLedgerUpdated, closed)).toEqual([]);
  178. emit(SessionEventType.ModelStreaming, { ...raw, kind: "tool_input_delta", delta: "late" });
  179. emit(SessionEventType.ModelStreaming, raw);
  180. expect(row()).toEqual(expected);
  181. expect(raw.toolName).toBe(DEFERRED_TOOL_CALL_NAME);
  182. for (const client of clients) {
  183. const frame = publisher.flush(client.subscriptionId);
  184. if (frame?.payload.kind !== "deltas") throw new Error("expected identity deltas");
  185. const snapshot = applyConversationDeltas(client.snapshot, frame.payload.deltas);
  186. expect(snapshot.rows.window.find((item) => item.kind === "toolCall")).toEqual(expected);
  187. }
  188. });
  189. it.each([
  190. "ordinary",
  191. "missing-row",
  192. "rejected",
  193. "missing-input",
  194. "wrong-status",
  195. "old-turn",
  196. "mirrored",
  197. "settled-turn",
  198. "scheduled",
  199. ])("closed identity leaves %s events unchanged", (scenario) => {
  200. const { emit, closed, row } = createIdentityFixture(scenario === "ordinary" ? "Read" : undefined);
  201. if (scenario === "settled-turn") emit(SessionEventType.TurnComplete, { result: "success" });
  202. if (scenario === "scheduled") {
  203. emit(SessionEventType.ToolCallScheduled, {
  204. ...closed,
  205. schedule: { parallelGroups: [[closed.toolCallId]], executionOrder: [closed.toolCallId] },
  206. });
  207. }
  208. const before = row();
  209. expect(
  210. emit(
  211. SessionEventType.StreamingToolLedgerUpdated,
  212. {
  213. ...closed,
  214. ...(scenario === "missing-row" ? { toolCallId: "missing" } : {}),
  215. ...(scenario === "rejected" ? { toolName: DEFERRED_TOOL_CALL_NAME } : {}),
  216. ...(scenario === "missing-input" ? { input: undefined } : {}),
  217. ...(scenario === "wrong-status" ? { status: "tool_started" } : {}),
  218. ...(scenario === "mirrored" ? { source: "subagent" } : {}),
  219. ...(scenario === "scheduled" ? { toolName: "different" } : {}),
  220. },
  221. scenario === "old-turn" ? "previous-turn" : "turn",
  222. ),
  223. ).toEqual([]);
  224. expect(row()).toEqual(before);
  225. });
  226. it("identity completion preserves an existing tool error", () => {
  227. const { emit, closed, row } = createIdentityFixture();
  228. emit(SessionEventType.ToolCallError, {
  229. toolCallId: closed.toolCallId,
  230. error: { type: "interrupted", message: "interrupted" },
  231. });
  232. const before = row();
  233. emit(SessionEventType.StreamingToolLedgerUpdated, closed);
  234. expect(row()).toEqual({
  235. ...before,
  236. toolName: closed.toolName,
  237. input: closed.input,
  238. inputText: JSON.stringify(closed.input),
  239. });
  240. expect(row()).toMatchObject({ status: "error", error: { message: "interrupted" } });
  241. });