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

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