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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. SessionEventType,
  4. createSessionId,
  5. type MessagePart,
  6. type ModelInputMessage,
  7. type ModelRequest,
  8. type ModelStreamEvent as ModelEvent,
  9. type SessionStorePort,
  10. type ToolPart,
  11. } from "@zcode/contracts";
  12. import { MessageHistoryImpl } from "../src/agent/message-history.js";
  13. import { hydrateMessageHistoryFromSession } from "../src/agent/session-history-hydrator.js";
  14. import { buildProviderRequestMessages } from "../src/runtime/helpers/provider-request-messages.js";
  15. import type { AgentRuntimeInternal } from "../src/runtime/internal.js";
  16. import { createToolRegistry } from "../src/tool/registry.js";
  17. import type { ToolExecutionContext } from "../src/tool/types.js";
  18. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  19. import { createTestSessionEventStore } from "./test-event-store.js";
  20. import { createRecordingMessageStore } from "./runtime-output-token-continuation-test-helpers.js";
  21. import { createTestModelFactory } from "./test-runtime-model.js";
  22. const CALL_ID = "stream-read";
  23. const READ_OUTPUT = "read succeeded";
  24. const READ_ERROR = "read failed";
  25. const WRITE_ERROR = "injected session write failure";
  26. const INTERRUPTED_RESULT = "[Tool execution was interrupted before resume]";
  27. type FallbackOutcome =
  28. | "success"
  29. | "tool-error"
  30. | "pending-error"
  31. | "running-error"
  32. | "result-error";
  33. function createFixture(
  34. options: {
  35. outcome?: FallbackOutcome;
  36. wrapped?: boolean;
  37. streamFailure?: boolean;
  38. earlyWriteFailure?: "pending" | "running" | false;
  39. delayEarlySchedule?: boolean;
  40. recordReadSnapshot?: boolean;
  41. } = {},
  42. ) {
  43. const sessionId = createSessionId("streaming-part-identity");
  44. const store = {
  45. ...createRecordingMessageStore(),
  46. async getProjectPermission() {
  47. return null;
  48. },
  49. };
  50. const writes: ToolPart[] = [];
  51. const requests: ModelRequest[] = [];
  52. const earlyFailure = Promise.withResolvers<void>();
  53. const scheduleStarted = Promise.withResolvers<void>();
  54. const releaseSchedule = Promise.withResolvers<void>();
  55. const lateExecutionSettled = Promise.withResolvers<void>();
  56. const registry = createToolRegistry();
  57. const handler = vi.fn(async (_input: unknown, context: ToolExecutionContext) => {
  58. if (options.outcome === "tool-error") throw new Error(READ_ERROR);
  59. if (options.recordReadSnapshot) {
  60. context.recordReadFileStateMetadata?.({
  61. content: READ_OUTPUT,
  62. isPartialView: false,
  63. mtimeMs: 1,
  64. path: "/tmp/stream-read.txt",
  65. readAtMs: 1,
  66. revisionId: "rev:stream-read",
  67. schemaVersion: 1,
  68. sizeBytes: READ_OUTPUT.length,
  69. tool: "Read",
  70. });
  71. }
  72. return READ_OUTPUT;
  73. });
  74. let earlyWriteFailed = false;
  75. const savePart = store.savePart.bind(store);
  76. store.savePart = async (part: MessagePart) => {
  77. if (part.type === "tool" && part.callID === CALL_ID) {
  78. writes.push(part);
  79. const earlyWriteFailure = options.earlyWriteFailure ?? "running";
  80. if (!earlyWriteFailed && part.state.status === earlyWriteFailure) {
  81. earlyWriteFailed = true;
  82. earlyFailure.resolve();
  83. throw new Error(WRITE_ERROR);
  84. }
  85. if (
  86. earlyWriteFailed &&
  87. ((options.outcome === "pending-error" && part.state.status === "pending") ||
  88. (options.outcome === "running-error" && part.state.status === "running") ||
  89. (options.outcome === "result-error" && part.state.status === "completed"))
  90. )
  91. throw new Error(WRITE_ERROR);
  92. }
  93. await savePart(part);
  94. };
  95. registry.register({
  96. capability: "Read fixture for streaming persistence failures",
  97. inputSchema: {},
  98. outputSchema: { type: "string" },
  99. timeout: { kind: "none" },
  100. cancellation: { supported: true, cleanup: "none", userVisibleMessage: "Read cancelled" },
  101. permission: {
  102. permission: "read",
  103. reason: "Read fixture",
  104. riskLevel: "low",
  105. sideEffectScope: "none",
  106. needsApproval: false,
  107. patternSources: ["none"],
  108. denyPriority: "beforeAsk",
  109. },
  110. resultBudget: { maxInlineBytes: 1024, maxModelBytes: 1024, strategy: "inline" },
  111. trace: {
  112. required: true,
  113. propagateToAdapters: true,
  114. recordInput: "summary",
  115. recordOutput: "summary",
  116. },
  117. metadata: {
  118. name: "StreamRead",
  119. shouldDefer: options.wrapped,
  120. concurrentSafe: true,
  121. destructive: false,
  122. needsApproval: false,
  123. readOnly: true,
  124. riskLevel: "low",
  125. sideEffectScope: "none",
  126. },
  127. handler,
  128. });
  129. const runtime = createTestAgentRuntime(
  130. sessionId,
  131. {
  132. mode: "yolo",
  133. toolSearch: { mode: options.wrapped ? "local" : "off" },
  134. modelStreaming: "on",
  135. titleGeneration: { enabled: false },
  136. },
  137. {
  138. eventStore: createTestSessionEventStore(),
  139. sessionStore: store as unknown as SessionStorePort,
  140. toolRegistry: registry,
  141. modelFactory: createTestModelFactory({
  142. async *streamText(request) {
  143. requests.push(request);
  144. if (requests.length === 1) {
  145. yield {
  146. type: "tool_call",
  147. toolCall: options.wrapped
  148. ? {
  149. id: CALL_ID,
  150. name: "DeferredToolCall",
  151. input: { name: "StreamRead", input: {} },
  152. }
  153. : { id: CALL_ID, name: "StreamRead", input: {} },
  154. };
  155. if (options.delayEarlySchedule) await scheduleStarted.promise;
  156. else if (options.earlyWriteFailure !== false) await earlyFailure.promise;
  157. if (options.streamFailure) throw new Error("Model request timed out.");
  158. yield { type: "finish", finishReason: "tool-calls", usage: {} };
  159. return;
  160. }
  161. yield { type: "text_delta", text: "done" };
  162. yield { type: "finish", finishReason: "stop", usage: {} };
  163. },
  164. }),
  165. },
  166. );
  167. if (options.delayEarlySchedule) {
  168. const internal = runtime as unknown as AgentRuntimeInternal;
  169. const scheduleTools = internal.scheduleTools.bind(internal);
  170. vi.spyOn(internal, "scheduleTools").mockImplementationOnce(async (...args) => {
  171. scheduleStarted.resolve();
  172. await releaseSchedule.promise;
  173. return scheduleTools(...args);
  174. });
  175. const executeTools = internal.executeTools.bind(internal);
  176. vi.spyOn(internal, "executeTools").mockImplementation(async (...args) => {
  177. try {
  178. return await executeTools(...args);
  179. } finally {
  180. if (args[0].some((call) => call.id === CALL_ID)) lateExecutionSettled.resolve();
  181. }
  182. });
  183. }
  184. const parts = () =>
  185. store.savedParts.filter(
  186. (part): part is ToolPart => part.type === "tool" && part.callID === CALL_ID,
  187. );
  188. const hydrate = async () => {
  189. const history = new MessageHistoryImpl();
  190. await hydrateMessageHistoryFromSession({ history, messages: await store.messages() });
  191. return buildProviderRequestMessages({ entries: history.toRuntimeEntries() }).messages;
  192. };
  193. return {
  194. runtime,
  195. parts,
  196. writes,
  197. requests,
  198. handler,
  199. hydrate,
  200. releaseSchedule,
  201. lateExecutionSettled,
  202. };
  203. }
  204. function expectSingleRead(
  205. messages: readonly ModelInputMessage[],
  206. isError: boolean,
  207. content: string,
  208. ) {
  209. expect(
  210. messages.flatMap((message) => (message.role === "assistant" ? (message.toolCalls ?? []) : [])),
  211. ).toEqual([{ id: CALL_ID, name: "StreamRead", input: {}, blockIndex: 0 }]);
  212. const results = messages.filter((message) => message.role === "tool");
  213. expect(results).toHaveLength(1);
  214. expect(results[0]).toMatchObject({ toolCallId: CALL_ID, isError });
  215. expect(JSON.stringify(results[0]?.content)).toContain(content);
  216. }
  217. describe("streaming tool attempt history", () => {
  218. it.each([
  219. { outcome: "success", status: "completed", isError: false, content: READ_OUTPUT, calls: 1 },
  220. { outcome: "tool-error", status: "error", isError: true, content: READ_ERROR, calls: 1 },
  221. {
  222. outcome: "pending-error",
  223. status: "pending",
  224. isError: true,
  225. content: INTERRUPTED_RESULT,
  226. calls: 0,
  227. },
  228. {
  229. outcome: "running-error",
  230. status: "pending",
  231. isError: true,
  232. content: INTERRUPTED_RESULT,
  233. calls: 0,
  234. },
  235. {
  236. outcome: "result-error",
  237. status: "running",
  238. isError: true,
  239. content: INTERRUPTED_RESULT,
  240. calls: 1,
  241. },
  242. ] as const)(
  243. "hydrates one call from separate attempts when fallback ends in $outcome",
  244. async ({ outcome, status, isError, content, calls }) => {
  245. const fixture = createFixture({ outcome });
  246. const turn = fixture.runtime.executeTurn("read a file");
  247. if (outcome.endsWith("-error") && outcome !== "tool-error") {
  248. await expect(turn).rejects.toBeDefined();
  249. } else {
  250. expect((await turn).response).toBe("done");
  251. expectSingleRead(fixture.requests[1]!.messages, isError, content);
  252. }
  253. expect(fixture.handler).toHaveBeenCalledTimes(calls);
  254. expect(fixture.parts()).toHaveLength(outcome === "pending-error" ? 1 : 2);
  255. expect(fixture.parts()[0]).toMatchObject({
  256. id: fixture.writes[0]!.id,
  257. blockIndex: 0,
  258. state: { status: "pending" },
  259. });
  260. expect(fixture.parts().at(-1)).toMatchObject({
  261. blockIndex: 0,
  262. state: { status },
  263. });
  264. expectSingleRead(await fixture.hydrate(), isError, content);
  265. expect(new Set(fixture.writes.map((part) => part.id)).size).toBe(2);
  266. },
  267. );
  268. it("stores the read-state snapshot index on a result settled from early execution", async () => {
  269. const fixture = createFixture({ earlyWriteFailure: false, recordReadSnapshot: true });
  270. expect((await fixture.runtime.executeTurn("read a file")).response).toBe("done");
  271. expect(fixture.handler).toHaveBeenCalledTimes(1);
  272. expect(fixture.parts()).toEqual([
  273. expect.objectContaining({
  274. id: fixture.writes[0]!.id,
  275. blockIndex: 0,
  276. state: expect.objectContaining({
  277. status: "completed",
  278. metadata: expect.objectContaining({
  279. readFileState: expect.objectContaining({ snapshotIndex: expect.any(Number) }),
  280. }),
  281. }),
  282. }),
  283. ]);
  284. });
  285. it("persists fallback when the first pending write failed", async () => {
  286. const fixture = createFixture({ earlyWriteFailure: "pending" });
  287. expect((await fixture.runtime.executeTurn("read a file")).response).toBe("done");
  288. expect(fixture.handler).toHaveBeenCalledTimes(1);
  289. expect(fixture.parts()).toHaveLength(1);
  290. expect(fixture.parts()[0]?.id).not.toBe(fixture.writes[0]?.id);
  291. expectSingleRead(await fixture.hydrate(), false, READ_OUTPUT);
  292. });
  293. it("preserves target part and wrapper model identity during failed stream recovery", async () => {
  294. const fixture = createFixture({ wrapped: true, streamFailure: true });
  295. await fixture.runtime.executeTurn("call the deferred tool");
  296. expect(fixture.handler).not.toHaveBeenCalled();
  297. const call = {
  298. id: CALL_ID,
  299. name: "DeferredToolCall",
  300. input: { name: "StreamRead", input: {} },
  301. blockIndex: 0,
  302. };
  303. for (const messages of [fixture.requests[1]!.messages, await fixture.hydrate()]) {
  304. expect(messages.flatMap((message) => message.toolCalls ?? [])).toEqual([call]);
  305. expect(messages.find((message) => message.role === "tool")).toMatchObject({
  306. toolName: "DeferredToolCall",
  307. toolCallId: CALL_ID,
  308. isError: true,
  309. });
  310. }
  311. expect(fixture.parts().at(-1)).toMatchObject({
  312. tool: "StreamRead",
  313. metadata: { modelCallWrapper: "DeferredToolCall" },
  314. state: { input: {}, status: "error" },
  315. });
  316. });
  317. it("selects the new synthetic result after stream failure", async () => {
  318. const fixture = createFixture({ streamFailure: true });
  319. expect((await fixture.runtime.executeTurn("read a file")).response).toBe("done");
  320. expect(fixture.handler).not.toHaveBeenCalled();
  321. expect(fixture.parts()).toHaveLength(2);
  322. expect(fixture.parts().at(-1)?.id).not.toBe(fixture.writes[0]!.id);
  323. expect(fixture.parts().at(-1)).toMatchObject({
  324. state: { status: "error" },
  325. });
  326. expectSingleRead(fixture.requests[1]!.messages, true, "Side effects may be unknown");
  327. expectSingleRead(await fixture.hydrate(), true, "Side effects may be unknown");
  328. });
  329. it("selects synthetic recovery even after a late update to the earlier part", async () => {
  330. const fixture = createFixture({
  331. earlyWriteFailure: false,
  332. streamFailure: true,
  333. delayEarlySchedule: true,
  334. });
  335. try {
  336. expect((await fixture.runtime.executeTurn("read a file")).response).toBe("done");
  337. const recoveredPart = structuredClone(fixture.parts().at(-1));
  338. fixture.releaseSchedule.resolve();
  339. await fixture.lateExecutionSettled.promise;
  340. expect(fixture.parts().at(-1)).toEqual(recoveredPart);
  341. expect(fixture.parts().map((part) => part.state.status)).toEqual(["running", "error"]);
  342. expect(fixture.handler).not.toHaveBeenCalled();
  343. expectSingleRead(await fixture.hydrate(), true, "Side effects may be unknown");
  344. } finally {
  345. fixture.releaseSchedule.resolve();
  346. }
  347. });
  348. });
  349. describe("assistant block index allocation", () => {
  350. async function runStream(events: ModelEvent[]) {
  351. const store = {
  352. ...createRecordingMessageStore(),
  353. async getProjectPermission() {
  354. return null;
  355. },
  356. };
  357. const requests: ModelRequest[] = [];
  358. const eventStore = createTestSessionEventStore();
  359. const sessionId = createSessionId("block-index");
  360. const runtime = createTestAgentRuntime(
  361. sessionId,
  362. { mode: "yolo", modelStreaming: "on", titleGeneration: { enabled: false } },
  363. {
  364. eventStore,
  365. sessionStore: store as unknown as SessionStorePort,
  366. toolRegistry: createToolRegistry(),
  367. modelFactory: createTestModelFactory({
  368. async *streamText(request) {
  369. requests.push(request);
  370. if (requests.length === 1) {
  371. yield* events;
  372. return;
  373. }
  374. yield { type: "text_delta", text: "done" };
  375. yield { type: "finish", finishReason: "stop", usage: {} };
  376. },
  377. }),
  378. },
  379. );
  380. await runtime.executeTurn("run");
  381. const firstAssistantId = store.savedMessages.find(
  382. (message) => message.role === "assistant",
  383. )?.id;
  384. const firstAssistantParts = store.savedParts.filter(
  385. (part: MessagePart) => part.messageID === firstAssistantId,
  386. ) as MessagePart[];
  387. const blocks = firstAssistantParts
  388. .filter((part) => part.type === "reasoning" || part.type === "text" || part.type === "tool")
  389. .map((part) => [
  390. part.type === "tool" ? part.callID : (part as { text: string }).text,
  391. (part as { blockIndex?: number }).blockIndex,
  392. ]);
  393. const streamingKinds = (await eventStore.getEvents(sessionId))
  394. .filter((event) => event.type === SessionEventType.ModelStreaming)
  395. .map((event) => (event.payload as { kind: string }).kind);
  396. return { blocks, requests, streamingKinds };
  397. }
  398. const finishToolCalls: ModelEvent = { type: "finish", finishReason: "tool-calls", usage: {} };
  399. it("shares one sequence across reasoning, text, and tools in arrival order", async () => {
  400. const { blocks, requests } = await runStream([
  401. { type: "reasoning_start", id: "r0" },
  402. { type: "reasoning_delta", id: "r0", text: "first thought" },
  403. { type: "reasoning_end", id: "r0" },
  404. { type: "text_start", id: "t0" },
  405. { type: "text_delta", id: "t0", text: "first" },
  406. { type: "text_end", id: "t0" },
  407. { type: "reasoning_start", id: "r1" },
  408. { type: "reasoning_delta", id: "r1", text: "second thought" },
  409. { type: "reasoning_end", id: "r1" },
  410. { type: "text_start", id: "t1" },
  411. { type: "text_delta", id: "t1", text: "second" },
  412. { type: "text_end", id: "t1" },
  413. { type: "tool_input_start", id: "call", toolName: "Missing" },
  414. { type: "tool_call", toolCall: { id: "call", name: "Missing", input: {} } },
  415. finishToolCalls,
  416. ]);
  417. expect(new Map(blocks as [string, number][])).toEqual(
  418. new Map([
  419. ["first thought", 0],
  420. ["first", 1],
  421. ["second thought", 2],
  422. ["second", 3],
  423. ["call", 4],
  424. ]),
  425. );
  426. expect(requests[1]?.messages.find((message) => message.role === "assistant")?.content).toEqual([
  427. expect.objectContaining({ type: "reasoning", text: "first thought", blockIndex: 0 }),
  428. { type: "text", text: "first", blockIndex: 1 },
  429. expect.objectContaining({ type: "reasoning", text: "second thought", blockIndex: 2 }),
  430. { type: "text", text: "second", blockIndex: 3 },
  431. ]);
  432. });
  433. it("opens a new text block when an id is reused after a tool call", async () => {
  434. // openai-compatible 在工具调用之后不关闭文字块,后续文字复用 txt-0。
  435. const { blocks, streamingKinds } = await runStream([
  436. { type: "text_start", id: "txt-0" },
  437. { type: "text_delta", id: "txt-0", text: "before" },
  438. { type: "tool_input_start", id: "call", toolName: "Missing" },
  439. { type: "tool_call", toolCall: { id: "call", name: "Missing", input: {} } },
  440. { type: "text_delta", id: "txt-0", text: "after" },
  441. finishToolCalls,
  442. ]);
  443. expect(new Map(blocks as [string, number][])).toEqual(
  444. new Map([
  445. ["before", 0],
  446. ["call", 1],
  447. ["after", 2],
  448. ]),
  449. );
  450. // 新块补发 text_start,live 界面和冷恢复一样分成两行。
  451. expect(streamingKinds.filter((kind) => kind === "text_start")).toHaveLength(2);
  452. });
  453. it("allocates at tool_call when there is no tool_input_start", async () => {
  454. const { blocks } = await runStream([
  455. { type: "text_delta", text: "before" },
  456. { type: "tool_call", toolCall: { id: "call", name: "Missing", input: {} } },
  457. finishToolCalls,
  458. ]);
  459. expect(new Map(blocks as [string, number][])).toEqual(
  460. new Map([
  461. ["before", 0],
  462. ["call", 1],
  463. ]),
  464. );
  465. });
  466. it("does not reset the counter across provider tool rounds", async () => {
  467. const { blocks } = await runStream([
  468. { type: "text_delta", id: "t0", text: "before" },
  469. {
  470. type: "tool_call",
  471. toolCall: { id: "server", name: "analyze_image", input: {}, providerExecuted: true },
  472. },
  473. { type: "provider_tool_result", toolCallId: "server", output: "ok", isError: false },
  474. { type: "text_delta", id: "t0", text: "after" },
  475. { type: "finish", finishReason: "stop", usage: {} },
  476. ]);
  477. expect(new Map(blocks as [string, number][])).toEqual(
  478. new Map([
  479. ["before", 0],
  480. ["server", 1],
  481. ["after", 2],
  482. ]),
  483. );
  484. });
  485. });