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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. // 每次产出副本:core 在收到的调用对象上写 blockIndex,不能写回 modelCall。
  89. yield { type: "tool_call", toolCall: { ...modelCall } };
  90. throw new Error("Model request timed out.");
  91. }
  92. yield { type: "text_delta", text: "done" };
  93. yield { type: "finish", finishReason: "stop", usage: {} };
  94. },
  95. }),
  96. },
  97. );
  98. let runtime = makeRuntime();
  99. const events: SessionEvent[] = [];
  100. const publisher = new ConversationTopicPublisher(sessionId, "live");
  101. const clients = (["continuous", "replayable"] as const).map((deliveryProfile) => {
  102. const subscription = publisher.subscribe({ connectionId: deliveryProfile, deliveryProfile });
  103. if (subscription.frame?.payload.kind !== "snapshot") throw new Error("expected snapshot");
  104. return {
  105. subscriptionId: subscription.ack.subscriptionId,
  106. snapshot: subscription.frame.payload.snapshot,
  107. };
  108. });
  109. runtime.subscribeEvents({
  110. onSessionEvent: async (event) => {
  111. events.push(event);
  112. publisher.ingest(event);
  113. },
  114. });
  115. try {
  116. await runtime.executeTurn("invoke the deferred tool");
  117. expect(handler).not.toHaveBeenCalled();
  118. expect(events.filter((event) => event.type === SessionEventType.ToolCallScheduled)).toEqual(
  119. [],
  120. );
  121. expect(events).toContainEqual(
  122. expect.objectContaining({
  123. type: SessionEventType.StreamingToolLedgerUpdated,
  124. payload: expect.objectContaining({
  125. toolCallId: CALL_ID,
  126. status: "tool_call_closed",
  127. toolName: TARGET,
  128. input: INPUT,
  129. }),
  130. }),
  131. );
  132. expect(events).toContainEqual(
  133. expect.objectContaining({
  134. type: SessionEventType.ModelStreaming,
  135. payload: expect.objectContaining({
  136. kind: "tool_call",
  137. toolName: modelCall.name,
  138. input: modelCall.input,
  139. }),
  140. }),
  141. );
  142. expect(
  143. requests.at(-1)?.messages.flatMap((message) => message.toolCalls ?? []),
  144. ).toContainEqual({
  145. ...modelCall,
  146. // 流式路径由 core 按到达顺序分配序号,provider 不提供(docs/design/v2/model/assistant-block-order.md)。
  147. blockIndex: 0,
  148. });
  149. const expected = {
  150. toolCallId: CALL_ID,
  151. toolName: TARGET,
  152. input: INPUT,
  153. inputText: JSON.stringify(INPUT),
  154. status: "error",
  155. };
  156. for (const client of clients) {
  157. const frame = publisher.flush(client.subscriptionId);
  158. if (frame?.payload.kind !== "deltas") throw new Error("expected live deltas");
  159. const snapshot = applyConversationDeltas(client.snapshot, frame.payload.deltas);
  160. expect(snapshot.rows.window.filter((row) => row.kind === "toolCall")).toEqual([
  161. expect.objectContaining(expected),
  162. ]);
  163. }
  164. await runtime.closeBrowserSession();
  165. store.close();
  166. store = await createSqliteSessionStore({ dbPath });
  167. runtime = makeRuntime();
  168. await runtime.resumeFromStore();
  169. const history = (
  170. runtime as unknown as AgentRuntimeInternal
  171. ).messageHistory.toRuntimeEntries();
  172. expect(
  173. history.flatMap((entry) =>
  174. entry.kind === "attachment" ? [] : (entry.message.toolCalls ?? []),
  175. ),
  176. ).toContainEqual(
  177. expect.objectContaining({
  178. id: CALL_ID,
  179. name: TARGET,
  180. input: INPUT,
  181. ...(wrapped ? { modelCallWrapper: DEFERRED_TOOL_CALL_NAME } : {}),
  182. }),
  183. );
  184. const messages = await store.messages({ sessionID: sessionId });
  185. const cold = new ProductProjection(sessionId, "cold");
  186. for (const event of synthesizeEventsFromMessages(messages, { sessionId }))
  187. cold.applyEvent(event);
  188. expect(cold.getSnapshot().rows.window.filter((row) => row.kind === "toolCall")).toEqual([
  189. expect.objectContaining(expected),
  190. ]);
  191. } finally {
  192. await runtime.closeBrowserSession();
  193. store.close();
  194. await rm(root, { recursive: true, force: true });
  195. }
  196. },
  197. );