runtime-streaming-tool-part-identity.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. createSessionId,
  4. type MessagePart,
  5. type ModelInputMessage,
  6. type ModelRequest,
  7. type SessionStorePort,
  8. type ToolPart,
  9. } from "@zcode/contracts";
  10. import { MessageHistoryImpl } from "../src/agent/message-history.js";
  11. import { hydrateMessageHistoryFromSession } from "../src/agent/session-history-hydrator.js";
  12. import { buildProviderRequestMessages } from "../src/runtime/helpers/provider-request-messages.js";
  13. import type { AgentRuntimeInternal } from "../src/runtime/internal.js";
  14. import { createToolRegistry } from "../src/tool/registry.js";
  15. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  16. import { createTestSessionEventStore } from "./test-event-store.js";
  17. import { createRecordingMessageStore } from "./runtime-output-token-continuation-test-helpers.js";
  18. import { createTestModelFactory } from "./test-runtime-model.js";
  19. const CALL_ID = "stream-read";
  20. const READ_OUTPUT = "read succeeded";
  21. const READ_ERROR = "read failed";
  22. const WRITE_ERROR = "injected session write failure";
  23. const INTERRUPTED_RESULT = "[Tool execution was interrupted before resume]";
  24. type FallbackOutcome =
  25. | "success"
  26. | "tool-error"
  27. | "pending-error"
  28. | "running-error"
  29. | "result-error";
  30. function createFixture(
  31. options: {
  32. outcome?: FallbackOutcome;
  33. wrapped?: boolean;
  34. streamFailure?: boolean;
  35. earlyWriteFailure?: "pending" | "running" | false;
  36. delayEarlySchedule?: boolean;
  37. } = {},
  38. ) {
  39. const sessionId = createSessionId("streaming-part-identity");
  40. const store = {
  41. ...createRecordingMessageStore(),
  42. async getProjectPermission() {
  43. return null;
  44. },
  45. };
  46. const writes: ToolPart[] = [];
  47. const requests: ModelRequest[] = [];
  48. const earlyFailure = Promise.withResolvers<void>();
  49. const scheduleStarted = Promise.withResolvers<void>();
  50. const releaseSchedule = Promise.withResolvers<void>();
  51. const lateExecutionSettled = Promise.withResolvers<void>();
  52. const registry = createToolRegistry();
  53. const handler = vi.fn(async () => {
  54. if (options.outcome === "tool-error") throw new Error(READ_ERROR);
  55. return READ_OUTPUT;
  56. });
  57. let earlyWriteFailed = false;
  58. const savePart = store.savePart.bind(store);
  59. store.savePart = async (part: MessagePart) => {
  60. if (part.type === "tool" && part.callID === CALL_ID) {
  61. writes.push(part);
  62. const earlyWriteFailure = options.earlyWriteFailure ?? "running";
  63. if (!earlyWriteFailed && part.state.status === earlyWriteFailure) {
  64. earlyWriteFailed = true;
  65. earlyFailure.resolve();
  66. throw new Error(WRITE_ERROR);
  67. }
  68. if (
  69. earlyWriteFailed &&
  70. ((options.outcome === "pending-error" && part.state.status === "pending") ||
  71. (options.outcome === "running-error" && part.state.status === "running") ||
  72. (options.outcome === "result-error" && part.state.status === "completed"))
  73. )
  74. throw new Error(WRITE_ERROR);
  75. }
  76. await savePart(part);
  77. };
  78. registry.register({
  79. capability: "Read fixture for streaming persistence failures",
  80. inputSchema: {},
  81. outputSchema: { type: "string" },
  82. timeout: { kind: "none" },
  83. cancellation: { supported: true, cleanup: "none", userVisibleMessage: "Read cancelled" },
  84. permission: {
  85. permission: "read",
  86. reason: "Read fixture",
  87. riskLevel: "low",
  88. sideEffectScope: "none",
  89. needsApproval: false,
  90. patternSources: ["none"],
  91. denyPriority: "beforeAsk",
  92. },
  93. resultBudget: { maxInlineBytes: 1024, maxModelBytes: 1024, strategy: "inline" },
  94. trace: {
  95. required: true,
  96. propagateToAdapters: true,
  97. recordInput: "summary",
  98. recordOutput: "summary",
  99. },
  100. metadata: {
  101. name: "StreamRead",
  102. shouldDefer: options.wrapped,
  103. concurrentSafe: true,
  104. destructive: false,
  105. needsApproval: false,
  106. readOnly: true,
  107. riskLevel: "low",
  108. sideEffectScope: "none",
  109. },
  110. handler,
  111. });
  112. const runtime = createTestAgentRuntime(
  113. sessionId,
  114. {
  115. mode: "yolo",
  116. toolSearch: { mode: options.wrapped ? "local" : "off" },
  117. modelStreaming: "on",
  118. titleGeneration: { enabled: false },
  119. },
  120. {
  121. eventStore: createTestSessionEventStore(),
  122. sessionStore: store as unknown as SessionStorePort,
  123. toolRegistry: registry,
  124. modelFactory: createTestModelFactory({
  125. async *streamText(request) {
  126. requests.push(request);
  127. if (requests.length === 1) {
  128. yield {
  129. type: "tool_call",
  130. toolCall: options.wrapped
  131. ? {
  132. id: CALL_ID,
  133. name: "DeferredToolCall",
  134. input: { name: "StreamRead", input: {} },
  135. }
  136. : { id: CALL_ID, name: "StreamRead", input: {} },
  137. };
  138. if (options.delayEarlySchedule) await scheduleStarted.promise;
  139. else if (options.earlyWriteFailure !== false) await earlyFailure.promise;
  140. if (options.streamFailure) throw new Error("Model request timed out.");
  141. yield { type: "finish", finishReason: "tool-calls", usage: {} };
  142. return;
  143. }
  144. yield { type: "text_delta", text: "done" };
  145. yield { type: "finish", finishReason: "stop", usage: {} };
  146. },
  147. }),
  148. },
  149. );
  150. if (options.delayEarlySchedule) {
  151. const internal = runtime as unknown as AgentRuntimeInternal;
  152. const scheduleTools = internal.scheduleTools.bind(internal);
  153. vi.spyOn(internal, "scheduleTools").mockImplementationOnce(async (...args) => {
  154. scheduleStarted.resolve();
  155. await releaseSchedule.promise;
  156. return scheduleTools(...args);
  157. });
  158. const executeTools = internal.executeTools.bind(internal);
  159. vi.spyOn(internal, "executeTools").mockImplementation(async (...args) => {
  160. try {
  161. return await executeTools(...args);
  162. } finally {
  163. if (args[0].some((call) => call.id === CALL_ID)) lateExecutionSettled.resolve();
  164. }
  165. });
  166. }
  167. const parts = () =>
  168. store.savedParts.filter(
  169. (part): part is ToolPart => part.type === "tool" && part.callID === CALL_ID,
  170. );
  171. const hydrate = async () => {
  172. const history = new MessageHistoryImpl();
  173. await hydrateMessageHistoryFromSession({ history, messages: await store.messages() });
  174. return buildProviderRequestMessages({ entries: history.toRuntimeEntries() }).messages;
  175. };
  176. return {
  177. runtime,
  178. parts,
  179. writes,
  180. requests,
  181. handler,
  182. hydrate,
  183. releaseSchedule,
  184. lateExecutionSettled,
  185. };
  186. }
  187. function expectSingleRead(
  188. messages: readonly ModelInputMessage[],
  189. isError: boolean,
  190. content: string,
  191. ) {
  192. expect(
  193. messages.flatMap((message) => (message.role === "assistant" ? (message.toolCalls ?? []) : [])),
  194. ).toEqual([{ id: CALL_ID, name: "StreamRead", input: {} }]);
  195. const results = messages.filter((message) => message.role === "tool");
  196. expect(results).toHaveLength(1);
  197. expect(results[0]).toMatchObject({ toolCallId: CALL_ID, isError });
  198. expect(JSON.stringify(results[0]?.content)).toContain(content);
  199. }
  200. describe("streaming tool attempt history", () => {
  201. it.each([
  202. { outcome: "success", status: "completed", isError: false, content: READ_OUTPUT, calls: 1 },
  203. { outcome: "tool-error", status: "error", isError: true, content: READ_ERROR, calls: 1 },
  204. {
  205. outcome: "pending-error",
  206. status: "pending",
  207. isError: true,
  208. content: INTERRUPTED_RESULT,
  209. calls: 0,
  210. },
  211. {
  212. outcome: "running-error",
  213. status: "pending",
  214. isError: true,
  215. content: INTERRUPTED_RESULT,
  216. calls: 0,
  217. },
  218. {
  219. outcome: "result-error",
  220. status: "running",
  221. isError: true,
  222. content: INTERRUPTED_RESULT,
  223. calls: 1,
  224. },
  225. ] as const)(
  226. "hydrates one call from separate attempts when fallback ends in $outcome",
  227. async ({ outcome, status, isError, content, calls }) => {
  228. const fixture = createFixture({ outcome });
  229. const turn = fixture.runtime.executeTurn("read a file");
  230. if (outcome.endsWith("-error") && outcome !== "tool-error") {
  231. await expect(turn).rejects.toBeDefined();
  232. } else {
  233. expect((await turn).response).toBe("done");
  234. expectSingleRead(fixture.requests[1]!.messages, isError, content);
  235. }
  236. expect(fixture.handler).toHaveBeenCalledTimes(calls);
  237. expect(fixture.parts()).toHaveLength(outcome === "pending-error" ? 1 : 2);
  238. expect(fixture.parts()[0]).toMatchObject({
  239. id: fixture.writes[0]!.id,
  240. declarationIndex: 0,
  241. state: { status: "pending" },
  242. });
  243. expect(fixture.parts().at(-1)).toMatchObject({
  244. declarationIndex: 0,
  245. state: { status },
  246. });
  247. expectSingleRead(await fixture.hydrate(), isError, content);
  248. expect(new Set(fixture.writes.map((part) => part.id)).size).toBe(2);
  249. },
  250. );
  251. it("persists fallback when the first pending write failed", async () => {
  252. const fixture = createFixture({ earlyWriteFailure: "pending" });
  253. expect((await fixture.runtime.executeTurn("read a file")).response).toBe("done");
  254. expect(fixture.handler).toHaveBeenCalledTimes(1);
  255. expect(fixture.parts()).toHaveLength(1);
  256. expect(fixture.parts()[0]?.id).not.toBe(fixture.writes[0]?.id);
  257. expectSingleRead(await fixture.hydrate(), false, READ_OUTPUT);
  258. });
  259. it("preserves target part and wrapper model identity during failed stream recovery", async () => {
  260. const fixture = createFixture({ wrapped: true, streamFailure: true });
  261. await fixture.runtime.executeTurn("call the deferred tool");
  262. expect(fixture.handler).not.toHaveBeenCalled();
  263. const call = {
  264. id: CALL_ID,
  265. name: "DeferredToolCall",
  266. input: { name: "StreamRead", input: {} },
  267. };
  268. for (const messages of [fixture.requests[1]!.messages, await fixture.hydrate()]) {
  269. expect(messages.flatMap((message) => message.toolCalls ?? [])).toEqual([call]);
  270. expect(messages.find((message) => message.role === "tool")).toMatchObject({
  271. toolName: "DeferredToolCall",
  272. toolCallId: CALL_ID,
  273. isError: true,
  274. });
  275. }
  276. expect(fixture.parts().at(-1)).toMatchObject({
  277. tool: "StreamRead",
  278. metadata: { modelCallWrapper: "DeferredToolCall" },
  279. state: { input: {}, status: "error" },
  280. });
  281. });
  282. it("selects the new synthetic result after stream failure", async () => {
  283. const fixture = createFixture({ streamFailure: true });
  284. expect((await fixture.runtime.executeTurn("read a file")).response).toBe("done");
  285. expect(fixture.handler).not.toHaveBeenCalled();
  286. expect(fixture.parts()).toHaveLength(2);
  287. expect(fixture.parts().at(-1)?.id).not.toBe(fixture.writes[0]!.id);
  288. expect(fixture.parts().at(-1)).toMatchObject({
  289. state: { status: "error" },
  290. });
  291. expectSingleRead(fixture.requests[1]!.messages, true, "Side effects may be unknown");
  292. expectSingleRead(await fixture.hydrate(), true, "Side effects may be unknown");
  293. });
  294. it("selects synthetic recovery even after a late update to the earlier part", async () => {
  295. const fixture = createFixture({
  296. earlyWriteFailure: false,
  297. streamFailure: true,
  298. delayEarlySchedule: true,
  299. });
  300. try {
  301. expect((await fixture.runtime.executeTurn("read a file")).response).toBe("done");
  302. const recoveredPart = structuredClone(fixture.parts().at(-1));
  303. fixture.releaseSchedule.resolve();
  304. await fixture.lateExecutionSettled.promise;
  305. expect(fixture.parts().at(-1)).toEqual(recoveredPart);
  306. expect(fixture.parts().map((part) => part.state.status)).toEqual(["running", "error"]);
  307. expect(fixture.handler).not.toHaveBeenCalled();
  308. expectSingleRead(await fixture.hydrate(), true, "Side effects may be unknown");
  309. } finally {
  310. fixture.releaseSchedule.resolve();
  311. }
  312. });
  313. });