provider-builtin-tool-rounds.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. // 服务端内置工具(analyze_image)多轮回放:真实 GLM 流(脱敏 fixture)经 compat → AI SDK → Runtime,
  2. // 验证下一次请求、持久化顺序和冷恢复回放。背景见 docs/design/v2/model/anthropic-stream-compat.md。
  3. import { mkdtemp, readFile, rm } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { describe, expect, it, vi } from "vitest";
  7. import {
  8. CompactTrigger,
  9. InMemorySessionEventStore,
  10. SessionEventType,
  11. createRootTraceContext,
  12. createSessionId,
  13. } from "@zcode/contracts";
  14. import { createSqliteSessionStore } from "../src/storage/session-store/sqlite-session-store.js";
  15. import { AgentRuntime } from "../../core/src/runtime.js";
  16. import { OUTPUT_TOKEN_CONTINUE_PROMPT } from "../../core/src/runtime/methods/turn-output-token-continuation.js";
  17. import { PROVIDER_TOOL_INTERRUPTED_RESULT } from "../../core/src/runtime/provider-tool-rounds/contract.js";
  18. import { MessageHistoryImpl } from "../../core/src/agent/message-history.js";
  19. import { hydrateMessageHistoryFromSession } from "../../core/src/agent/session-history-hydrator.js";
  20. import { compactActiveConversation } from "../../core/src/runtime/methods/compact-active.js";
  21. import { buildProviderRequestMessages } from "../../core/src/runtime/helpers/provider-request-messages.js";
  22. import { findLatestCommittedAssistantUsage } from "../../core/src/runtime/methods/turn-model-step-usage.js";
  23. import {
  24. eventStream,
  25. plainReply,
  26. sse,
  27. openScenario,
  28. createRuntime,
  29. FIXTURE,
  30. type WireBody,
  31. type WireMessage,
  32. } from "./provider-builtin-tool-rounds-fixture.js";
  33. // 服务端新格式(直接下发 mcp_tool_use / mcp_tool_result):由 FIXTURE 按服务端文档改造,其余帧相同。
  34. const MCP_FIXTURE = join(import.meta.dirname, "fixtures", "provider-builtin-analyze-image-mcp.sse");
  35. const TOOL_CALL_ID = "call_93e9e7ad911f4b1799a6c543";
  36. const asIs = (fixture: string) => fixture;
  37. /** 2026-11-05 线上漏发 server_name 的形态:其余帧与 MCP_FIXTURE 相同。 */
  38. function withoutServerName(fixture: string): string {
  39. const edited = fixture.replace('"server_name": "4_5v_mcp", ', "");
  40. if (edited === fixture) throw new Error("MCP fixture has no server_name to drop");
  41. return edited;
  42. }
  43. function conversation(body: WireBody | undefined): WireMessage[] {
  44. // 去掉 system 和 cache_control 标记,只比较对话本身。
  45. return JSON.parse(
  46. JSON.stringify((body?.messages ?? []).filter((message) => message.role !== "system")),
  47. (key, value) => (key === "cache_control" ? undefined : value),
  48. );
  49. }
  50. describe("provider built-in tool rounds", () => {
  51. it.each([
  52. ["server_tool_use", FIXTURE, asIs],
  53. ["mcp_tool_use", MCP_FIXTURE, asIs],
  54. // AI SDK schema 要求 server_name,漏发时整轮报错;兼容层补齐后这一轮必须照常完成。
  55. ["mcp_tool_use without server_name", MCP_FIXTURE, withoutServerName],
  56. ])(
  57. "replays a server-executed analyze_image (%s) as its own round, live and after cold resume",
  58. async (_format, fixturePath, edit) => {
  59. const root = await mkdtemp(join(tmpdir(), "zcode-provider-builtin-"));
  60. const sessionID = createSessionId("provider-builtin");
  61. const fixture = edit(await readFile(fixturePath, "utf8"));
  62. const bodies: WireBody[] = [];
  63. let store = await createSqliteSessionStore({ dbPath: join(root, "session.sqlite") });
  64. const events = new InMemorySessionEventStore({ retention: "unbounded" });
  65. let runtime: AgentRuntime | undefined;
  66. try {
  67. vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
  68. bodies.push(await new Request(input, init).json());
  69. return bodies.length === 1
  70. ? new Response(fixture, { headers: { "content-type": "text/event-stream" } })
  71. : plainReply(`reply ${bodies.length}`);
  72. });
  73. runtime = createRuntime(root, sessionID, store, events);
  74. await runtime.executeTurn("识别 shot.png 里的文字");
  75. await runtime.executeTurn("再说一遍");
  76. // 下一次请求:服务端工具独立成一轮(方案 A),不再出现 markdown 渲染。
  77. const live = conversation(bodies[1]);
  78. expect(live.map((message) => message.role)).toEqual([
  79. "user",
  80. "assistant",
  81. "user",
  82. "assistant",
  83. "user",
  84. ]);
  85. expect(live[1]!.content).toEqual([
  86. expect.objectContaining({ type: "thinking" }),
  87. { type: "text", text: "图片已上传为远程 URL,现在用视觉分析工具识别其中文字。" },
  88. expect.objectContaining({ type: "tool_use", id: TOOL_CALL_ID, name: "analyze_image" }),
  89. ]);
  90. expect(live[2]!.content).toEqual([
  91. expect.objectContaining({
  92. type: "tool_result",
  93. tool_use_id: TOOL_CALL_ID,
  94. content: expect.stringContaining("Error 1302: request rate limit exceeded"),
  95. }),
  96. ]);
  97. expect(live[3]!.content).toEqual([
  98. { type: "text", text: expect.stringMatching(/^图片中的文字为/) },
  99. ]);
  100. expect(JSON.stringify(bodies[1])).not.toContain("**🌐");
  101. expect(JSON.stringify(bodies[1])).not.toContain("analyze_image_result_summary");
  102. // 持久化按流顺序:本轮正文 → 服务端工具卡片 → 下一轮正文。
  103. const assistant = (await store.messages({ sessionID })).find(
  104. (message) => message.info.role === "assistant",
  105. );
  106. const parts = assistant!.parts.filter(
  107. (part) => part.type !== "step-start" && part.type !== "step-finish",
  108. );
  109. expect(parts.map((part) => part.type)).toEqual(["reasoning", "text", "tool", "text"]);
  110. expect(parts[2]).toMatchObject({
  111. type: "tool",
  112. callID: TOOL_CALL_ID,
  113. tool: "analyze_image",
  114. metadata: { providerExecuted: true },
  115. state: { status: "completed", output: expect.stringContaining("Order Console") },
  116. });
  117. // 实时卡片:Scheduled → Started → Result,结果是服务端返回的识别文本。
  118. const toolEvents = (await events.getEvents(sessionID)).filter(
  119. (event) =>
  120. (event.payload as { toolCallId?: string } | undefined)?.toolCallId === TOOL_CALL_ID &&
  121. event.type !== SessionEventType.ModelStreaming,
  122. );
  123. expect(toolEvents.map((event) => event.type)).toEqual([
  124. SessionEventType.ToolCallScheduled,
  125. SessionEventType.ToolCallStarted,
  126. SessionEventType.ToolCallResult,
  127. ]);
  128. // 冷恢复后回放出完全相同的对话。
  129. runtime.beginShutdown();
  130. store.close();
  131. store = await createSqliteSessionStore({ dbPath: join(root, "session.sqlite") });
  132. runtime = createRuntime(
  133. root,
  134. sessionID,
  135. store,
  136. new InMemorySessionEventStore({ retention: "unbounded" }),
  137. );
  138. await runtime.resumeFromStore();
  139. await runtime.executeTurn("第三句");
  140. const cold = conversation(bodies[2]);
  141. expect(cold.slice(0, live.length + 1)).toEqual([
  142. ...live,
  143. { role: "assistant", content: [{ type: "text", text: "reply 2" }] },
  144. ]);
  145. } finally {
  146. runtime?.beginShutdown();
  147. vi.unstubAllGlobals();
  148. store.close();
  149. await rm(root, { recursive: true, force: true });
  150. }
  151. },
  152. );
  153. });
  154. // ─── 评审回归:终态判断、断流作废、缺少结果 ────────────────────────────────────
  155. function fixtureFrames(fixture: string): string[] {
  156. return fixture.split("\n\n").filter((frame) => frame.trim().length > 0);
  157. }
  158. function frameData(frame: string): Record<string, unknown> | undefined {
  159. const line = frame.split("\n").find((candidate) => candidate.startsWith("data:"));
  160. return line ? (JSON.parse(line.slice("data:".length)) as Record<string, unknown>) : undefined;
  161. }
  162. function sseBody(frames: string[]): string {
  163. return frames.map((frame) => `${frame}\n\n`).join("");
  164. }
  165. /** 再发一句拿 live history,冷恢复后再发一句拿冷恢复 history,两者必须一致。 */
  166. async function expectColdResumeMatchesLive(scenario: Awaited<ReturnType<typeof openScenario>>) {
  167. await scenario.runtime.executeTurn("再说一遍");
  168. const live = conversation(scenario.bodies.at(-1));
  169. await scenario.coldResume();
  170. await scenario.runtime.executeTurn("第三句");
  171. const cold = conversation(scenario.bodies.at(-1));
  172. expect(cold.slice(0, live.length)).toEqual(live);
  173. return live;
  174. }
  175. describe("provider built-in tool rounds (review regressions)", () => {
  176. const formats = [
  177. ["server_tool_use", FIXTURE],
  178. ["mcp_tool_use", MCP_FIXTURE],
  179. ];
  180. it.each(formats)(
  181. "still continues a truncated answer after a server-executed tool round (%s)",
  182. async (_format, fixturePath) => {
  183. const scenario = await openScenario(
  184. (index, fixture) =>
  185. index === 0
  186. ? eventStream(
  187. fixture.replace(/"stop_reason": "end_turn"/u, '"stop_reason": "max_tokens"'),
  188. )
  189. : plainReply(`reply ${index}`),
  190. fixturePath,
  191. );
  192. try {
  193. await scenario.runtime.executeTurn("识别 shot.png 里的文字");
  194. // 服务端工具不算待执行调用:max_tokens 必须触发续写请求。
  195. expect(scenario.bodies).toHaveLength(2);
  196. const continuation = conversation(scenario.bodies[1]);
  197. expect(JSON.stringify(continuation.at(-1))).toContain(OUTPUT_TOKEN_CONTINUE_PROMPT);
  198. expect(continuation.some((message) => JSON.stringify(message).includes(TOOL_CALL_ID))).toBe(
  199. true,
  200. );
  201. } finally {
  202. await scenario.close();
  203. }
  204. },
  205. );
  206. it.each(formats)(
  207. "keeps a discarded stream attempt out of both live and cold-resumed history (%s)",
  208. async (_format, fixturePath) => {
  209. const scenario = await openScenario((index, fixture) => {
  210. if (index !== 0) return plainReply(`reply ${index}`);
  211. // 服务端工具与结果已下发、最后一轮正文写到一半时断流(可重试)。
  212. const frames = fixtureFrames(fixture);
  213. const cut = frames.findIndex((frame) => {
  214. const data = frameData(frame);
  215. return data?.type === "content_block_delta" && data.index === 6;
  216. });
  217. const encoder = new TextEncoder();
  218. let delivered = false;
  219. return new Response(
  220. new ReadableStream<Uint8Array>({
  221. // 先交付已收到的帧,等下游消费后再断流:源流出错时,下游 TransformStream 里尚未读取的数据会被丢弃。
  222. async pull(controller) {
  223. if (!delivered) {
  224. delivered = true;
  225. controller.enqueue(encoder.encode(sseBody(frames.slice(0, cut + 1))));
  226. return;
  227. }
  228. await new Promise((resolve) => setTimeout(resolve, 50));
  229. // 与 Node 真实 socket 错误一致带 code,adapter 才会归类为网络断流。
  230. controller.error(Object.assign(new Error("read ECONNRESET"), { code: "ECONNRESET" }));
  231. },
  232. }),
  233. { headers: { "content-type": "text/event-stream" } },
  234. );
  235. }, fixturePath);
  236. try {
  237. await scenario.runtime.executeTurn("识别 shot.png 里的文字");
  238. const live = await expectColdResumeMatchesLive(scenario);
  239. // 作废的 attempt 不进任何 history:只剩重试后的回答。
  240. expect(JSON.stringify(live)).not.toContain(TOOL_CALL_ID);
  241. expect(live.map((message) => message.role)).toEqual(["user", "assistant", "user"]);
  242. } finally {
  243. await scenario.close();
  244. }
  245. },
  246. );
  247. it("drops an MCP result that no call paired and settles the call as interrupted, live and cold", async () => {
  248. // AI SDK 遇到未配对的 mcp_tool_result 会抛 TypeError,整轮失败;兼容层丢弃它后,调用按中断收口。
  249. const scenario = await openScenario(
  250. (index, fixture) =>
  251. index === 0
  252. ? eventStream(
  253. fixture.replace(`"tool_use_id": "${TOOL_CALL_ID}"`, '"tool_use_id": "call_unpaired"'),
  254. )
  255. : plainReply(`reply ${index}`),
  256. MCP_FIXTURE,
  257. );
  258. try {
  259. await scenario.runtime.executeTurn("识别 shot.png 里的文字");
  260. const live = await expectColdResumeMatchesLive(scenario);
  261. expect(live[2]!.content).toEqual([
  262. expect.objectContaining({
  263. type: "tool_result",
  264. tool_use_id: TOOL_CALL_ID,
  265. is_error: true,
  266. content: PROVIDER_TOOL_INTERRUPTED_RESULT,
  267. }),
  268. ]);
  269. } finally {
  270. await scenario.close();
  271. }
  272. });
  273. // 新格式合成流:调用、结果和文字块按服务端文档的形态构造。
  274. const textEvents = (index: number, value: string) => [
  275. { type: "content_block_start", index, content_block: { type: "text", text: "" } },
  276. { type: "content_block_delta", index, delta: { type: "text_delta", text: value } },
  277. { type: "content_block_stop", index },
  278. ];
  279. const mcpCallEvents = (index: number, id: string, name: string) => [
  280. {
  281. type: "content_block_start",
  282. index,
  283. content_block: { type: "mcp_tool_use", id, name, server_name: "4_5v_mcp", input: { name } },
  284. },
  285. { type: "content_block_stop", index },
  286. ];
  287. const mcpResultEvents = (index: number, id: string, value: string, isError: boolean) => [
  288. {
  289. type: "content_block_start",
  290. index,
  291. content_block: {
  292. type: "mcp_tool_result",
  293. tool_use_id: id,
  294. content: [{ type: "text", text: value }],
  295. is_error: isError,
  296. },
  297. },
  298. { type: "content_block_stop", index },
  299. ];
  300. const mcpReply = (blocks: Array<Record<string, unknown>>) =>
  301. sse([
  302. {
  303. type: "message_start",
  304. message: {
  305. id: "msg_mcp",
  306. type: "message",
  307. role: "assistant",
  308. model: "glm-5.3",
  309. content: [],
  310. stop_reason: null,
  311. stop_sequence: null,
  312. usage: { input_tokens: 10, output_tokens: 0 },
  313. },
  314. },
  315. ...blocks,
  316. {
  317. type: "message_delta",
  318. delta: { stop_reason: "end_turn", stop_sequence: null },
  319. usage: { output_tokens: 1 },
  320. },
  321. { type: "message_stop" },
  322. ]);
  323. it("keeps a model answer labelled **Output:** when the server sends no summary, live and cold", async () => {
  324. // 评审 CR-01:结果后没有服务端摘要,模型回答以 **Output:** 开头;兼容层不能把整段回答删掉。
  325. const answer = "**Output:** 正常最终回答";
  326. const scenario = await openScenario((index) =>
  327. index === 0
  328. ? mcpReply([
  329. ...mcpCallEvents(0, "call_a", "analyze_image"),
  330. ...mcpResultEvents(1, "call_a", "图片结果", false),
  331. ...textEvents(2, answer),
  332. ])
  333. : plainReply(`reply ${index}`),
  334. );
  335. try {
  336. await scenario.runtime.executeTurn("看图");
  337. const assistant = (await scenario.store.messages({ sessionID: scenario.sessionID })).find(
  338. (message) => message.info.role === "assistant",
  339. );
  340. expect(assistant!.parts).toContainEqual(
  341. expect.objectContaining({ type: "text", text: answer }),
  342. );
  343. const live = await expectColdResumeMatchesLive(scenario);
  344. expect(live[3]!.content).toEqual([{ type: "text", text: answer }]);
  345. } finally {
  346. await scenario.close();
  347. }
  348. });
  349. it("replays parallel MCP calls, including an error result, as rounds in call order, live and cold", async () => {
  350. // 新格式并行:调用都在前、结果都在后,按 id 配对回各自的轮次;方案 A 回放成先后两轮。
  351. const scenario = await openScenario((index) =>
  352. index === 0
  353. ? mcpReply([
  354. ...textEvents(0, "**🌐 Built-in Tool: analyze_image**"),
  355. ...mcpCallEvents(1, "call_a", "analyze_image"),
  356. ...textEvents(2, "**🌐 Built-in Tool: webReader**"),
  357. ...mcpCallEvents(3, "call_b", "webReader"),
  358. ...mcpResultEvents(4, "call_a", "图片结果", false),
  359. ...textEvents(5, "**Output:**\n**analyze_image_result_summary:** 图片结果"),
  360. ...mcpResultEvents(6, "call_b", "MCP error 400", true),
  361. ...textEvents(7, "**Output:**\n**webReader_result_summary:** MCP error 400"),
  362. ...textEvents(8, "最终回答"),
  363. ])
  364. : plainReply(`reply ${index}`),
  365. );
  366. try {
  367. await scenario.runtime.executeTurn("看图并读网页");
  368. const toolEvents = (await scenario.events.getEvents(scenario.sessionID)).filter(
  369. (event) =>
  370. ["call_a", "call_b"].includes(
  371. (event.payload as { toolCallId?: string } | undefined)?.toolCallId ?? "",
  372. ) && event.type !== SessionEventType.ModelStreaming,
  373. );
  374. expect(
  375. toolEvents.map((event) => [
  376. event.type,
  377. (event.payload as { toolCallId: string }).toolCallId,
  378. ]),
  379. ).toEqual([
  380. [SessionEventType.ToolCallScheduled, "call_a"],
  381. [SessionEventType.ToolCallStarted, "call_a"],
  382. [SessionEventType.ToolCallScheduled, "call_b"],
  383. [SessionEventType.ToolCallStarted, "call_b"],
  384. [SessionEventType.ToolCallResult, "call_a"],
  385. [SessionEventType.ToolCallResult, "call_b"],
  386. ]);
  387. expect(toolEvents.at(-1)!.payload).toMatchObject({ result: { success: false } });
  388. const live = await expectColdResumeMatchesLive(scenario);
  389. const wire = JSON.stringify(live);
  390. expect(wire).not.toContain("**🌐");
  391. expect(wire).not.toContain("**Output:**");
  392. expect(live.map((message) => message.role)).toEqual([
  393. "user",
  394. "assistant",
  395. "user",
  396. "assistant",
  397. "user",
  398. "assistant",
  399. "user",
  400. ]);
  401. expect(live[1]!.content).toEqual([
  402. expect.objectContaining({ type: "tool_use", id: "call_a", name: "analyze_image" }),
  403. ]);
  404. expect(live[2]!.content).toEqual([
  405. expect.objectContaining({
  406. type: "tool_result",
  407. tool_use_id: "call_a",
  408. content: "图片结果",
  409. }),
  410. ]);
  411. expect(live[3]!.content).toEqual([
  412. expect.objectContaining({ type: "tool_use", id: "call_b", name: "webReader" }),
  413. ]);
  414. expect(live[4]!.content).toEqual([
  415. expect.objectContaining({
  416. type: "tool_result",
  417. tool_use_id: "call_b",
  418. is_error: true,
  419. content: "MCP error 400",
  420. }),
  421. ]);
  422. expect(live[5]!.content).toEqual([{ type: "text", text: "最终回答" }]);
  423. } finally {
  424. await scenario.close();
  425. }
  426. });
  427. it("settles a server tool whose result never arrives as interrupted, live and cold", async () => {
  428. const scenario = await openScenario((index, fixture) => {
  429. if (index !== 0) return plainReply(`reply ${index}`);
  430. const frames = fixtureFrames(fixture).filter((frame) => {
  431. const data = frameData(frame);
  432. const block = data?.content_block as { type?: string } | undefined;
  433. return !(
  434. (data?.type === "content_block_start" && block?.type === "tool_result") ||
  435. (data?.type === "content_block_stop" && data.index === 5)
  436. );
  437. });
  438. return eventStream(sseBody(frames));
  439. });
  440. try {
  441. await scenario.runtime.executeTurn("识别 shot.png 里的文字");
  442. const toolEvents = (await scenario.events.getEvents(scenario.sessionID)).filter(
  443. (event) =>
  444. (event.payload as { toolCallId?: string } | undefined)?.toolCallId === TOOL_CALL_ID &&
  445. event.type !== SessionEventType.ModelStreaming,
  446. );
  447. expect(toolEvents.map((event) => event.type)).toEqual([
  448. SessionEventType.ToolCallScheduled,
  449. SessionEventType.ToolCallStarted,
  450. SessionEventType.ToolCallResult,
  451. ]);
  452. expect(toolEvents[2]!.payload).toMatchObject({ result: { success: false } });
  453. const live = await expectColdResumeMatchesLive(scenario);
  454. expect(live[2]!.content).toEqual([
  455. expect.objectContaining({
  456. type: "tool_result",
  457. tool_use_id: TOOL_CALL_ID,
  458. is_error: true,
  459. content: PROVIDER_TOOL_INTERRUPTED_RESULT,
  460. }),
  461. ]);
  462. } finally {
  463. await scenario.close();
  464. }
  465. });
  466. it("keeps one compact group per stored response, live and after cold resume", async () => {
  467. const scenario = await openScenario((_index, fixture, body) => {
  468. const text = JSON.stringify(body.messages);
  469. if (text.includes("create a detailed summary")) {
  470. return plainReply("<summary>older work summary</summary>");
  471. }
  472. return text.includes("识别 shot.png") && !text.includes(TOOL_CALL_ID)
  473. ? eventStream(fixture)
  474. : plainReply("earlier reply");
  475. });
  476. try {
  477. await scenario.runtime.executeTurn("old setup");
  478. await scenario.runtime.executeTurn("识别 shot.png 里的文字");
  479. // 一条持久化 assistant 拆成了 round + 最后一轮;compact 保留最近一组时必须整条保留或整条摘要。
  480. await compactActiveConversation.call(
  481. scenario.runtime as never,
  482. undefined,
  483. createRootTraceContext({ sessionId: scenario.sessionID }),
  484. [],
  485. { trigger: CompactTrigger.Auto },
  486. );
  487. const project = (entries: ReturnType<MessageHistoryImpl["toRuntimeEntries"]>) =>
  488. buildProviderRequestMessages({
  489. entries,
  490. useMidConversationSystem: false,
  491. applyCacheControl: false,
  492. }).messages.filter((message) => message.toolCalls?.length || message.role === "tool");
  493. const live = project(
  494. (
  495. scenario.runtime as unknown as { messageHistory: MessageHistoryImpl }
  496. ).messageHistory.toRuntimeEntries(),
  497. );
  498. const restored = new MessageHistoryImpl();
  499. await hydrateMessageHistoryFromSession({
  500. history: restored,
  501. messages: await scenario.store.messages({ sessionID: scenario.sessionID }),
  502. });
  503. expect(project(restored.toRuntimeEntries())).toEqual(live);
  504. // 最近一组是整条服务端工具响应:调用与结果随最后一轮一起保留。
  505. expect(JSON.stringify(live)).toContain(TOOL_CALL_ID);
  506. } finally {
  507. await scenario.close();
  508. }
  509. });
  510. it.each(["with", "without"] as const)(
  511. "does not anchor context usage on a server tool response %s trailing text, live and cold",
  512. async (trailing) => {
  513. // 服务端多轮请求的 usage 是合计(fixture 约 37k,单次上下文约一半),不能当估算锚点。
  514. const fixtureFor = (fixture: string) =>
  515. trailing === "with"
  516. ? fixture
  517. : sseBody(fixtureFrames(fixture).filter((frame) => frameData(frame)?.index !== 6));
  518. const scenario = await openScenario((_index, fixture, body) => {
  519. const text = JSON.stringify(body.messages);
  520. return text.includes("识别 shot.png") && !text.includes(TOOL_CALL_ID)
  521. ? eventStream(fixtureFor(fixture))
  522. : plainReply("earlier reply");
  523. });
  524. try {
  525. await scenario.runtime.executeTurn("old setup");
  526. await scenario.runtime.executeTurn("识别 shot.png 里的文字");
  527. const anchorOf = (entries: ReturnType<MessageHistoryImpl["toRuntimeEntries"]>) => {
  528. const anchor = findLatestCommittedAssistantUsage(entries);
  529. const entry = anchor ? entries[anchor.messageIndex] : undefined;
  530. return {
  531. baseline: anchor?.baseline,
  532. message: entry && "message" in entry ? entry.message.content : undefined,
  533. };
  534. };
  535. const live = anchorOf(
  536. (
  537. scenario.runtime as unknown as { messageHistory: MessageHistoryImpl }
  538. ).messageHistory.toRuntimeEntries(),
  539. );
  540. const restored = new MessageHistoryImpl();
  541. await hydrateMessageHistoryFromSession({
  542. history: restored,
  543. messages: await scenario.store.messages({ sessionID: scenario.sessionID }),
  544. });
  545. expect(anchorOf(restored.toRuntimeEntries())).toEqual(live);
  546. // 锚点仍是上一轮的真实 usage,而不是服务端合计。
  547. expect(JSON.stringify(live.message)).toContain("earlier reply");
  548. await expectColdResumeMatchesLive(scenario);
  549. } finally {
  550. await scenario.close();
  551. }
  552. },
  553. );
  554. });