deferred-call-stream-recovery-projection.test.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. import { mkdtemp, rm } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { expect, it, vi } from "vitest";
  5. import {
  6. createSessionId,
  7. DEFERRED_TOOL_CALL_NAME,
  8. SessionEventType,
  9. type ModelRequest,
  10. type SessionEvent,
  11. } from "@zcode/contracts";
  12. import { applyConversationDeltas } from "@zcode/shared/zcode-protocol-v4";
  13. import { createSqliteSessionStore } from "../../adapters/src/storage/session-store/sqlite-session-store.js";
  14. import type { AgentRuntimeInternal } from "../../core/src/runtime/internal.js";
  15. import { createToolRegistry } from "../../core/src/tool/registry.js";
  16. import { toolSearchToolEntry } from "../../core/src/tool/handlers/tool-search.js";
  17. import { createTestAgentRuntime } from "../../core/tests/test-agent-runtime.js";
  18. import { createTestModelFactory } from "../../core/tests/test-runtime-model.js";
  19. import { createTestSessionEventStore } from "../../core/tests/test-event-store.js";
  20. import { ConversationTopicPublisher, ProductProjection } from "../src/zcode-protocol-v4/index.js";
  21. import { synthesizeEventsFromMessages } from "../src/zcode-protocol-v4/transcript-hydration.js";
  22. const TARGET = "DeferredMutation";
  23. const CALL_ID = "interrupted-call";
  24. const INPUT = { value: 7 };
  25. it.each([
  26. { wrapped: true, inputDeltas: true },
  27. { wrapped: true, inputDeltas: false },
  28. { wrapped: false, inputDeltas: true },
  29. ])(
  30. "completed call interrupted before scheduling keeps live and cold identity ($wrapped/$inputDeltas)",
  31. async ({ wrapped, inputDeltas }) => {
  32. const root = await mkdtemp(join(tmpdir(), "deferred-display-"));
  33. const dbPath = join(root, "session.sqlite");
  34. const sessionId = createSessionId("deferred-display");
  35. let store = await createSqliteSessionStore({ dbPath });
  36. const handler = vi.fn(async () => "executed");
  37. const registry = createToolRegistry();
  38. registry.register({
  39. ...toolSearchToolEntry,
  40. metadata: {
  41. ...toolSearchToolEntry.metadata,
  42. name: TARGET,
  43. shouldDefer: true,
  44. readOnly: false,
  45. concurrentSafe: false,
  46. },
  47. inputSchema: { type: "object" },
  48. runtimeInputSchema: undefined,
  49. runtimeOutputSchema: undefined,
  50. outputSchema: {},
  51. permission: undefined,
  52. formatModelContent: undefined,
  53. handler,
  54. });
  55. const modelCall = {
  56. id: CALL_ID,
  57. name: wrapped ? DEFERRED_TOOL_CALL_NAME : TARGET,
  58. input: wrapped ? { name: TARGET, input: INPUT } : INPUT,
  59. };
  60. const requests: ModelRequest[] = [];
  61. const makeRuntime = () =>
  62. createTestAgentRuntime(
  63. sessionId,
  64. {
  65. mode: "yolo",
  66. toolSearch: { mode: wrapped ? "local" : "off" },
  67. modelStreaming: "on",
  68. titleGeneration: { enabled: false },
  69. workspacePath: root,
  70. },
  71. {
  72. sessionStore: store,
  73. eventStore: createTestSessionEventStore(),
  74. toolRegistry: registry,
  75. modelFactory: createTestModelFactory({
  76. async *streamText(request) {
  77. requests.push(request);
  78. if (requests.length === 1) {
  79. if (inputDeltas) {
  80. const json = JSON.stringify(modelCall.input);
  81. const half = Math.ceil(json.length / 2);
  82. yield { type: "tool_input_start", id: CALL_ID, toolName: modelCall.name };
  83. yield { type: "tool_input_delta", id: CALL_ID, delta: json.slice(0, half) };
  84. yield { type: "tool_input_delta", id: CALL_ID, delta: json.slice(half) };
  85. yield { type: "tool_input_end", id: CALL_ID };
  86. }
  87. yield { type: "tool_call", toolCall: modelCall };
  88. throw new Error("Model request timed out.");
  89. }
  90. yield { type: "text_delta", text: "done" };
  91. yield { type: "finish", finishReason: "stop", usage: {} };
  92. },
  93. }),
  94. },
  95. );
  96. let runtime = makeRuntime();
  97. const events: SessionEvent[] = [];
  98. const publisher = new ConversationTopicPublisher(sessionId, "live");
  99. const clients = (["continuous", "replayable"] as const).map((deliveryProfile) => {
  100. const subscription = publisher.subscribe({ connectionId: deliveryProfile, deliveryProfile });
  101. if (subscription.frame?.payload.kind !== "snapshot") throw new Error("expected snapshot");
  102. return {
  103. subscriptionId: subscription.ack.subscriptionId,
  104. snapshot: subscription.frame.payload.snapshot,
  105. };
  106. });
  107. runtime.subscribeEvents({
  108. onSessionEvent: async (event) => {
  109. events.push(event);
  110. publisher.ingest(event);
  111. },
  112. });
  113. try {
  114. await runtime.executeTurn("invoke the deferred tool");
  115. expect(handler).not.toHaveBeenCalled();
  116. expect(events.filter((event) => event.type === SessionEventType.ToolCallScheduled)).toEqual(
  117. [],
  118. );
  119. expect(events).toContainEqual(
  120. expect.objectContaining({
  121. type: SessionEventType.StreamingToolLedgerUpdated,
  122. payload: expect.objectContaining({
  123. toolCallId: CALL_ID,
  124. status: "tool_call_closed",
  125. toolName: TARGET,
  126. input: INPUT,
  127. }),
  128. }),
  129. );
  130. expect(events).toContainEqual(
  131. expect.objectContaining({
  132. type: SessionEventType.ModelStreaming,
  133. payload: expect.objectContaining({
  134. kind: "tool_call",
  135. toolName: modelCall.name,
  136. input: modelCall.input,
  137. }),
  138. }),
  139. );
  140. expect(
  141. requests.at(-1)?.messages.flatMap((message) => message.toolCalls ?? []),
  142. ).toContainEqual(modelCall);
  143. const expected = {
  144. toolCallId: CALL_ID,
  145. toolName: TARGET,
  146. input: INPUT,
  147. inputText: JSON.stringify(INPUT),
  148. status: "error",
  149. };
  150. for (const client of clients) {
  151. const frame = publisher.flush(client.subscriptionId);
  152. if (frame?.payload.kind !== "deltas") throw new Error("expected live deltas");
  153. const snapshot = applyConversationDeltas(client.snapshot, frame.payload.deltas);
  154. expect(snapshot.rows.window.filter((row) => row.kind === "toolCall")).toEqual([
  155. expect.objectContaining(expected),
  156. ]);
  157. }
  158. await runtime.closeBrowserSession();
  159. store.close();
  160. store = await createSqliteSessionStore({ dbPath });
  161. runtime = makeRuntime();
  162. await runtime.resumeFromStore();
  163. const history = (
  164. runtime as unknown as AgentRuntimeInternal
  165. ).messageHistory.toRuntimeEntries();
  166. expect(
  167. history.flatMap((entry) =>
  168. entry.kind === "attachment" ? [] : (entry.message.toolCalls ?? []),
  169. ),
  170. ).toContainEqual(
  171. expect.objectContaining({
  172. id: CALL_ID,
  173. name: TARGET,
  174. input: INPUT,
  175. ...(wrapped ? { modelCallWrapper: DEFERRED_TOOL_CALL_NAME } : {}),
  176. }),
  177. );
  178. const messages = await store.messages({ sessionID: sessionId });
  179. const cold = new ProductProjection(sessionId, "cold");
  180. for (const event of synthesizeEventsFromMessages(messages, { sessionId }))
  181. cold.applyEvent(event);
  182. expect(cold.getSnapshot().rows.window.filter((row) => row.kind === "toolCall")).toEqual([
  183. expect.objectContaining(expected),
  184. ]);
  185. } finally {
  186. await runtime.closeBrowserSession();
  187. store.close();
  188. await rm(root, { recursive: true, force: true });
  189. }
  190. },
  191. );