runtime-tool-result-settlement.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. createSessionId,
  4. SessionEventType,
  5. type MessagePart,
  6. type ModelInputMessage,
  7. type SessionStorePort,
  8. type ToolArtifactStorePort,
  9. } from "@zcode/contracts";
  10. import { createToolRegistry } from "../src/tool/registry.js";
  11. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  12. import { createTestSessionEventStore } from "./test-event-store.js";
  13. import { createTestModelFactory } from "./test-runtime-model.js";
  14. import { createRecordingMessageStore } from "./runtime-output-token-continuation-test-helpers.js";
  15. const CALL_IDS = ["settlement-first", "settlement-second", "settlement-third"];
  16. const OUTPUTS = ["first output", "second output", "third output"];
  17. const IMAGE_DATA = "data:image/png;base64,c2V0dGxlbWVudA==";
  18. const IMAGE_CONTENT = [{ type: "image" as const, mediaType: "image/png", dataUrl: IMAGE_DATA }];
  19. const INTERRUPTED_RESULT = "[Tool execution was interrupted before resume]";
  20. type Failure = "part" | "media" | "usage";
  21. function createFixture(
  22. options: { failure?: Failure; image?: boolean; blockSiblings?: boolean } = {},
  23. ) {
  24. const sessionId = createSessionId("tool-result-settlement");
  25. const failure = new Error(`injected ${options.failure} persistence failure`);
  26. const store = {
  27. ...createRecordingMessageStore(),
  28. async getProjectPermission() {
  29. return null;
  30. },
  31. };
  32. const eventStore = createTestSessionEventStore();
  33. const firstCompleted = Promise.withResolvers<void>();
  34. const siblingsStarted = [Promise.withResolvers<void>(), Promise.withResolvers<void>()];
  35. const requests: Array<readonly ModelInputMessage[]> = [];
  36. const registry = createToolRegistry();
  37. const artifacts = new Map<string, string>();
  38. let injectFailure = Boolean(options.failure);
  39. const savePart = store.savePart.bind(store);
  40. store.savePart = async (part: MessagePart) => {
  41. if (
  42. injectFailure &&
  43. options.failure === "part" &&
  44. part.type === "tool" &&
  45. part.callID === CALL_IDS[1] &&
  46. part.state.status === "completed"
  47. )
  48. throw failure;
  49. await savePart(part);
  50. };
  51. const append = eventStore.append.bind(eventStore);
  52. vi.spyOn(eventStore, "append").mockImplementation(async (event) => {
  53. if (
  54. injectFailure &&
  55. options.failure === "usage" &&
  56. event.type === SessionEventType.ModelComplete &&
  57. (event.payload as { stopReason?: string }).stopReason === "tool_internal"
  58. )
  59. throw failure;
  60. const stored = await append(event);
  61. if (
  62. event.type === SessionEventType.ToolCallResult &&
  63. (event.payload as { toolCallId?: string }).toolCallId === CALL_IDS[0]
  64. )
  65. firstCompleted.resolve();
  66. return stored;
  67. });
  68. const writeArtifact = vi.fn<ToolArtifactStorePort["writeToolResultArtifact"]>(
  69. async (request, writeOptions) => {
  70. if (writeOptions?.signal?.aborted) throw writeOptions.signal.reason;
  71. if (injectFailure && options.failure === "media") throw failure;
  72. const uri = `zcode-artifact://settlement/${artifacts.size}`;
  73. artifacts.set(uri, request.content);
  74. return {
  75. id: uri,
  76. uri,
  77. path: uri,
  78. bytes: request.content.length,
  79. contentType: request.contentType ?? "text/plain",
  80. createdAt: new Date(),
  81. };
  82. },
  83. );
  84. const artifactStore: ToolArtifactStorePort = {
  85. writeToolResultArtifact: writeArtifact,
  86. async readToolResultArtifact({ uri }) {
  87. const content = artifacts.get(uri);
  88. if (!content) throw new Error(`Missing artifact ${uri}`);
  89. return { uri, content, bytes: content.length, contentType: "text/plain" };
  90. },
  91. };
  92. const handlers = CALL_IDS.map((id, index) => {
  93. const handler = vi.fn(async (_input, context) => {
  94. if (options.blockSiblings && index > 0) {
  95. siblingsStarted[index - 1]!.resolve();
  96. await new Promise<void>((_resolve, reject) => {
  97. if (context.abortSignal.aborted) reject(context.abortSignal.reason);
  98. else
  99. context.abortSignal.addEventListener(
  100. "abort",
  101. () => reject(context.abortSignal.reason),
  102. { once: true },
  103. );
  104. });
  105. }
  106. return options.failure === "usage" && index === 0
  107. ? { text: OUTPUTS[index], modelUsage: { inputTokens: 1, outputTokens: 1 } }
  108. : OUTPUTS[index];
  109. });
  110. registry.register({
  111. inputSchema: {},
  112. metadata: {
  113. name: `Read${index}`,
  114. concurrentSafe: true,
  115. destructive: false,
  116. needsApproval: false,
  117. readOnly: true,
  118. riskLevel: "low",
  119. sideEffectScope: "none",
  120. },
  121. handler,
  122. ...(options.image && index === 0 ? { formatModelContent: () => IMAGE_CONTENT } : {}),
  123. });
  124. return handler;
  125. });
  126. const modelFactory = createTestModelFactory({
  127. async generateText(request) {
  128. requests.push(structuredClone(request.messages));
  129. if (requests.length === 1)
  130. return {
  131. text: "",
  132. finishReason: "tool-calls",
  133. usage: {},
  134. toolCalls: CALL_IDS.map((id, index) => ({ id, name: `Read${index}`, input: {} })),
  135. };
  136. return { text: "done", finishReason: "stop", usage: {} };
  137. },
  138. });
  139. const buildRuntime = (events = eventStore) =>
  140. createTestAgentRuntime(
  141. sessionId,
  142. { mode: "yolo", modelStreaming: "off", titleGeneration: { enabled: false } },
  143. {
  144. eventStore: events,
  145. sessionStore: store as unknown as SessionStorePort,
  146. artifactStore,
  147. toolRegistry: registry,
  148. modelFactory,
  149. },
  150. );
  151. return {
  152. runtime: buildRuntime(),
  153. requests,
  154. handlers,
  155. failure,
  156. store,
  157. writeArtifact,
  158. readyToStop: () =>
  159. Promise.all([firstCompleted.promise, ...siblingsStarted.map((item) => item.promise)]),
  160. recoverStorage: () => {
  161. injectFailure = false;
  162. },
  163. async durableCallIds() {
  164. const events = await eventStore.getEvents(sessionId);
  165. return {
  166. anchors: events
  167. .filter((event) => event.type === SessionEventType.StreamRecoveryAnchorCreated)
  168. .map((event) => (event.payload as { toolCallId: string }).toolCallId),
  169. committed: events
  170. .filter(
  171. (event) =>
  172. event.type === SessionEventType.StreamingToolLedgerUpdated &&
  173. (event.payload as { status: string }).status === "tool_result_committed",
  174. )
  175. .map((event) => (event.payload as { toolCallId: string }).toolCallId),
  176. };
  177. },
  178. async coldResume() {
  179. const resumed = buildRuntime(createTestSessionEventStore());
  180. await resumed.resumeFromStore();
  181. await resumed.executeTurn("continue after restart");
  182. return requests.at(-1)!;
  183. },
  184. };
  185. }
  186. const TOOL_INTERRUPT_MARKER = "[Request interrupted by user for tool use]";
  187. // 用户停止时被取消的工具统一给模型这段文字。
  188. const USER_STOPPED_TOOL_RESULT =
  189. "The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). STOP what you are doing and wait for the user to tell you how to proceed.";
  190. function userTextsAfterResults(messages: readonly ModelInputMessage[]): string[] {
  191. const lastResult = messages.findLastIndex((message) => message.role === "tool");
  192. return messages
  193. .slice(lastResult + 1)
  194. .filter((message) => message.role === "user")
  195. .map((message) =>
  196. typeof message.content === "string"
  197. ? message.content
  198. : message.content.map((block) => (block.type === "text" ? block.text : "")).join(""),
  199. )
  200. .filter((text) => !text.startsWith("<system-reminder>"));
  201. }
  202. function pairedResults(messages: readonly ModelInputMessage[]) {
  203. const calls = messages.flatMap((message) =>
  204. message.role === "assistant" ? (message.toolCalls ?? []) : [],
  205. );
  206. const results = messages.filter((message) => message.role === "tool");
  207. expect(calls.map((call) => call.id)).toEqual(CALL_IDS);
  208. expect(results.map((result) => result.toolCallId)).toEqual(CALL_IDS);
  209. return results;
  210. }
  211. describe("runtime tool result settlement", () => {
  212. it.each<Failure>(["part", "media", "usage"])(
  213. "retains the whole batch after %s persistence fails",
  214. async (failure) => {
  215. const fixture = createFixture({ failure, image: failure === "media" });
  216. await expect(fixture.runtime.executeTurn("run tools")).rejects.toMatchObject({
  217. cause: fixture.failure,
  218. });
  219. expect(fixture.requests).toHaveLength(1);
  220. const durableIds = failure === "part" ? [CALL_IDS[0]] : [];
  221. expect(await fixture.durableCallIds()).toEqual({
  222. anchors: durableIds,
  223. committed: durableIds,
  224. });
  225. fixture.recoverStorage();
  226. await expect(fixture.runtime.executeTurn("continue after recovery")).resolves.toMatchObject({
  227. response: "done",
  228. });
  229. const results = pairedResults(fixture.requests[1]!);
  230. expect(results.every((result) => !result.isError)).toBe(true);
  231. if (failure === "media") expect(results[0]!.content).toEqual(IMAGE_CONTENT);
  232. else expect(JSON.stringify(results[0]!.content)).toContain(OUTPUTS[0]);
  233. expect(results.slice(1).map((result) => result.content)).toEqual(OUTPUTS.slice(1));
  234. for (const handler of fixture.handlers) expect(handler).toHaveBeenCalledTimes(1);
  235. expect(await fixture.durableCallIds()).toEqual({
  236. anchors: durableIds,
  237. committed: durableIds,
  238. });
  239. if (failure === "part") {
  240. const cold = pairedResults(await fixture.coldResume());
  241. expect(cold[0]!.content).toBe(OUTPUTS[0]);
  242. expect(cold.slice(1).map((result) => [result.isError, result.content])).toEqual([
  243. [true, INTERRUPTED_RESULT],
  244. [true, INTERRUPTED_RESULT],
  245. ]);
  246. for (const handler of fixture.handlers) expect(handler).toHaveBeenCalledTimes(1);
  247. }
  248. },
  249. );
  250. it("preserves successful image and cancelled siblings across Stop and cold resume", async () => {
  251. const fixture = createFixture({ image: true, blockSiblings: true });
  252. const controller = new AbortController();
  253. const turn = fixture.runtime.executeTurn("read image and siblings", undefined, {
  254. abortSignal: controller.signal,
  255. });
  256. const rejection = expect(turn).rejects.toMatchObject({ type: "turn_cancelled" });
  257. try {
  258. await fixture.readyToStop();
  259. controller.abort(new Error("user stop"));
  260. await rejection;
  261. expect(fixture.requests).toHaveLength(1);
  262. expect(fixture.writeArtifact).toHaveBeenCalledTimes(1);
  263. expect(await fixture.durableCallIds()).toEqual({ anchors: CALL_IDS, committed: CALL_IDS });
  264. await fixture.runtime.executeTurn("continue after stop");
  265. const live = pairedResults(fixture.requests[1]!);
  266. expect(live[0]).toMatchObject({ content: IMAGE_CONTENT, isError: false });
  267. expect(live.slice(1).map((result) => [result.isError, result.content])).toEqual([
  268. [true, USER_STOPPED_TOOL_RESULT],
  269. [true, USER_STOPPED_TOOL_RESULT],
  270. ]);
  271. // 只换模型文字;工具卡片仍显示各工具自己的取消原因。
  272. const cancelledErrors = (await fixture.store.messages())
  273. .flatMap((message) => message.parts)
  274. .flatMap((part) =>
  275. part.type === "tool" && part.callID !== CALL_IDS[0] && part.state.status === "error"
  276. ? [part.state.error]
  277. : [],
  278. );
  279. expect(cancelledErrors).toHaveLength(2);
  280. expect(cancelledErrors).not.toContain(USER_STOPPED_TOOL_RESULT);
  281. // 工具执行中停止:tool result 之后是工具阶段的中断标记,紧接下一条输入。
  282. // 默认测试模型不合并相邻 user 内容,标记不补换行。
  283. expect(userTextsAfterResults(fixture.requests[1]!)).toEqual([
  284. TOOL_INTERRUPT_MARKER,
  285. "continue after stop",
  286. ]);
  287. const coldRequest = await fixture.coldResume();
  288. const cold = pairedResults(coldRequest);
  289. expect(cold[0]).toMatchObject({ content: IMAGE_CONTENT, isError: false });
  290. expect(cold.slice(1).map((result) => [result.isError, result.content])).toEqual([
  291. [true, USER_STOPPED_TOOL_RESULT],
  292. [true, USER_STOPPED_TOOL_RESULT],
  293. ]);
  294. expect(userTextsAfterResults(coldRequest).slice(0, 2)).toEqual([
  295. TOOL_INTERRUPT_MARKER,
  296. "continue after stop",
  297. ]);
  298. for (const handler of fixture.handlers) expect(handler).toHaveBeenCalledTimes(1);
  299. } finally {
  300. controller.abort(new Error("test cleanup"));
  301. await turn.catch(() => undefined);
  302. }
  303. });
  304. it("returns a guide queued during a stopped tool batch to the queue", async () => {
  305. const fixture = createFixture({ blockSiblings: true });
  306. const controller = new AbortController();
  307. const turn = fixture.runtime.executeTurn("run tools", undefined, {
  308. abortSignal: controller.signal,
  309. });
  310. const rejection = expect(turn).rejects.toMatchObject({ type: "turn_cancelled" });
  311. try {
  312. await fixture.readyToStop();
  313. const guide = await fixture.runtime.steerTurn({
  314. delivery: "guide",
  315. input: "guide while tools run",
  316. intent: {
  317. sourceCommandId: "command-guide-tool-stop",
  318. queueItemId: "queue-guide-tool-stop",
  319. clientId: "desktop",
  320. kind: "sendText",
  321. admissionSeq: 1,
  322. admittedAt: 1,
  323. requestedDelivery: "guide",
  324. admittedDelivery: "guide",
  325. },
  326. });
  327. expect(guide.kind).toBe("queued");
  328. controller.abort(new Error("user stop"));
  329. await rejection;
  330. // 停止后不再消费挂起的 guide:它退回队列,不进入已停止的轮次。
  331. const projection = await fixture.runtime.getProjection();
  332. expect(projection.pendingSteerInputs.map((input) => input.intent)).toEqual([
  333. expect.objectContaining({
  334. queueItemId: "queue-guide-tool-stop",
  335. admittedDelivery: "queue",
  336. fallbackReasonCode: "guide.turnInterrupted",
  337. }),
  338. ]);
  339. await fixture.runtime.executeTurn("continue after stop");
  340. expect(userTextsAfterResults(fixture.requests[1]!)).toEqual([
  341. TOOL_INTERRUPT_MARKER,
  342. "continue after stop",
  343. ]);
  344. } finally {
  345. controller.abort(new Error("test cleanup"));
  346. await turn.catch(() => undefined);
  347. }
  348. });
  349. });