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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. aliases: undefined,
  41. metadata: {
  42. ...toolSearchToolEntry.metadata,
  43. name: TARGET,
  44. shouldDefer: true,
  45. readOnly: false,
  46. concurrentSafe: false,
  47. },
  48. inputSchema: { type: "object" },
  49. runtimeInputSchema: undefined,
  50. runtimeOutputSchema: undefined,
  51. outputSchema: {},
  52. permission: undefined,
  53. formatModelContent: undefined,
  54. handler,
  55. });
  56. const modelCall = {
  57. id: CALL_ID,
  58. name: wrapped ? DEFERRED_TOOL_CALL_NAME : TARGET,
  59. input: wrapped ? { name: TARGET, input: INPUT } : INPUT,
  60. };
  61. const requests: ModelRequest[] = [];
  62. const makeRuntime = () =>
  63. createTestAgentRuntime(
  64. sessionId,
  65. {
  66. mode: "yolo",
  67. toolSearch: { mode: wrapped ? "local" : "off" },
  68. modelStreaming: "on",
  69. titleGeneration: { enabled: false },
  70. workspacePath: root,
  71. },
  72. {
  73. sessionStore: store,
  74. eventStore: createTestSessionEventStore(),
  75. toolRegistry: registry,
  76. modelFactory: createTestModelFactory({
  77. async *streamText(request) {
  78. requests.push(request);
  79. if (requests.length === 1) {
  80. if (inputDeltas) {
  81. const json = JSON.stringify(modelCall.input);
  82. const half = Math.ceil(json.length / 2);
  83. yield { type: "tool_input_start", id: CALL_ID, toolName: modelCall.name };
  84. yield { type: "tool_input_delta", id: CALL_ID, delta: json.slice(0, half) };
  85. yield { type: "tool_input_delta", id: CALL_ID, delta: json.slice(half) };
  86. yield { type: "tool_input_end", id: CALL_ID };
  87. }
  88. yield { type: "tool_call", toolCall: modelCall };
  89. throw new Error("Model request timed out.");
  90. }
  91. yield { type: "text_delta", text: "done" };
  92. yield { type: "finish", finishReason: "stop", usage: {} };
  93. },
  94. }),
  95. },
  96. );
  97. let runtime = makeRuntime();
  98. const events: SessionEvent[] = [];
  99. const publisher = new ConversationTopicPublisher(sessionId, "live");
  100. const clients = (["continuous", "replayable"] as const).map((deliveryProfile) => {
  101. const subscription = publisher.subscribe({ connectionId: deliveryProfile, deliveryProfile });
  102. if (subscription.frame?.payload.kind !== "snapshot") throw new Error("expected snapshot");
  103. return {
  104. subscriptionId: subscription.ack.subscriptionId,
  105. snapshot: subscription.frame.payload.snapshot,
  106. };
  107. });
  108. runtime.subscribeEvents({
  109. onSessionEvent: async (event) => {
  110. events.push(event);
  111. publisher.ingest(event);
  112. },
  113. });
  114. try {
  115. await runtime.executeTurn("invoke the deferred tool");
  116. expect(handler).not.toHaveBeenCalled();
  117. expect(events.filter((event) => event.type === SessionEventType.ToolCallScheduled)).toEqual(
  118. [],
  119. );
  120. expect(events).toContainEqual(
  121. expect.objectContaining({
  122. type: SessionEventType.StreamingToolLedgerUpdated,
  123. payload: expect.objectContaining({
  124. toolCallId: CALL_ID,
  125. status: "tool_call_closed",
  126. toolName: TARGET,
  127. input: INPUT,
  128. }),
  129. }),
  130. );
  131. expect(events).toContainEqual(
  132. expect.objectContaining({
  133. type: SessionEventType.ModelStreaming,
  134. payload: expect.objectContaining({
  135. kind: "tool_call",
  136. toolName: modelCall.name,
  137. input: modelCall.input,
  138. }),
  139. }),
  140. );
  141. expect(
  142. requests.at(-1)?.messages.flatMap((message) => message.toolCalls ?? []),
  143. ).toContainEqual(modelCall);
  144. const expected = {
  145. toolCallId: CALL_ID,
  146. toolName: TARGET,
  147. input: INPUT,
  148. inputText: JSON.stringify(INPUT),
  149. status: "error",
  150. };
  151. for (const client of clients) {
  152. const frame = publisher.flush(client.subscriptionId);
  153. if (frame?.payload.kind !== "deltas") throw new Error("expected live deltas");
  154. const snapshot = applyConversationDeltas(client.snapshot, frame.payload.deltas);
  155. expect(snapshot.rows.window.filter((row) => row.kind === "toolCall")).toEqual([
  156. expect.objectContaining(expected),
  157. ]);
  158. }
  159. await runtime.closeBrowserSession();
  160. store.close();
  161. store = await createSqliteSessionStore({ dbPath });
  162. runtime = makeRuntime();
  163. await runtime.resumeFromStore();
  164. const history = (
  165. runtime as unknown as AgentRuntimeInternal
  166. ).messageHistory.toRuntimeEntries();
  167. expect(
  168. history.flatMap((entry) =>
  169. entry.kind === "attachment" ? [] : (entry.message.toolCalls ?? []),
  170. ),
  171. ).toContainEqual(
  172. expect.objectContaining({
  173. id: CALL_ID,
  174. name: TARGET,
  175. input: INPUT,
  176. ...(wrapped ? { modelCallWrapper: DEFERRED_TOOL_CALL_NAME } : {}),
  177. }),
  178. );
  179. const messages = await store.messages({ sessionID: sessionId });
  180. const cold = new ProductProjection(sessionId, "cold");
  181. for (const event of synthesizeEventsFromMessages(messages, { sessionId }))
  182. cold.applyEvent(event);
  183. expect(cold.getSnapshot().rows.window.filter((row) => row.kind === "toolCall")).toEqual([
  184. expect.objectContaining(expected),
  185. ]);
  186. } finally {
  187. await runtime.closeBrowserSession();
  188. store.close();
  189. await rm(root, { recursive: true, force: true });
  190. }
  191. },
  192. );