hydration.test.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. STREAM_RECOVERY_DISCARDED_ERROR_NAME,
  4. createMessageId,
  5. createModelId,
  6. createModelProviderId,
  7. createPartId,
  8. createSessionId,
  9. type MessagePart,
  10. type MessageWithParts,
  11. } from "@zcode/contracts";
  12. import { MessageHistoryImpl } from "../../src/agent/message-history.js";
  13. import { hydrateMessageHistoryFromSession } from "../../src/agent/session-history-hydrator.js";
  14. // 冷恢复边界:一条持久化 assistant 里服务端内置工具轮次与本地工具、正文、作废标记、异常结果的组合。
  15. // 实时流切轮的端到端对照见 adapters/tests/provider-builtin-tool-rounds.test.ts。
  16. const sessionID = createSessionId("provider-round-hydration");
  17. const userID = createMessageId("provider-round-user");
  18. const assistantID = createMessageId("provider-round-assistant");
  19. const modelID = createModelId("glm-test");
  20. const providerID = createModelProviderId("zai");
  21. const tokens = {
  22. input: 36_999,
  23. output: 277,
  24. reasoning: 0,
  25. cache: { read: 0, write: 0 },
  26. total: 37_276,
  27. };
  28. function user(): MessageWithParts {
  29. return {
  30. info: {
  31. id: userID,
  32. sessionID,
  33. role: "user",
  34. time: { created: 1 },
  35. agent: "zcode-agent",
  36. model: { providerID, modelID },
  37. },
  38. parts: [{ id: createPartId("u"), messageID: userID, sessionID, type: "text", text: "看图" }],
  39. };
  40. }
  41. function assistant(parts: MessagePart[], extra: Record<string, unknown> = {}): MessageWithParts {
  42. return {
  43. info: {
  44. id: assistantID,
  45. sessionID,
  46. role: "assistant",
  47. time: { created: 2, completed: 3 },
  48. parentID: userID,
  49. modelID,
  50. providerID,
  51. mode: "build",
  52. agent: "zcode-agent",
  53. path: { cwd: "/tmp/project", root: "/tmp/project" },
  54. cost: 0,
  55. tokens,
  56. ...extra,
  57. } as MessageWithParts["info"],
  58. parts,
  59. };
  60. }
  61. let partSeq = 0;
  62. const text = (value: string): MessagePart => ({
  63. id: createPartId(`text-${++partSeq}`),
  64. messageID: assistantID,
  65. sessionID,
  66. type: "text",
  67. text: value,
  68. });
  69. const providerTool = (state: "completed" | "error"): MessagePart => ({
  70. id: createPartId(`provider-${++partSeq}`),
  71. messageID: assistantID,
  72. sessionID,
  73. type: "tool",
  74. callID: "call_image",
  75. tool: "analyze_image",
  76. metadata: { providerExecuted: true },
  77. state:
  78. state === "completed"
  79. ? {
  80. status: "completed",
  81. input: { imageSource: "https://cdn.example.test/shot.png" },
  82. output: "Order Console",
  83. title: "analyze_image",
  84. metadata: {},
  85. time: { start: 1, end: 2 },
  86. }
  87. : {
  88. status: "error",
  89. input: { imageSource: "https://cdn.example.test/shot.png" },
  90. error: "[Server-side tool execution was interrupted before its result arrived]",
  91. metadata: {},
  92. time: { start: 1, end: 2 },
  93. },
  94. });
  95. const localRead = (): MessagePart => ({
  96. id: createPartId(`read-${++partSeq}`),
  97. messageID: assistantID,
  98. sessionID,
  99. type: "tool",
  100. callID: "call_read",
  101. tool: "Read",
  102. state: {
  103. status: "completed",
  104. input: { file_path: "README.md" },
  105. output: "# Demo",
  106. title: "Read",
  107. metadata: {},
  108. time: { start: 2, end: 3 },
  109. },
  110. });
  111. async function hydrate(message: MessageWithParts) {
  112. const history = new MessageHistoryImpl();
  113. await hydrateMessageHistoryFromSession({ history, messages: [user(), message] });
  114. return history
  115. .toRuntimeEntries()
  116. .filter((entry) => "message" in entry && entry.message.role !== "user");
  117. }
  118. describe("provider tool round hydration", () => {
  119. it.each([
  120. [
  121. "local tool before the trailing text",
  122. () => [text("先看图"), providerTool("completed"), localRead(), text("再读文件")],
  123. ],
  124. [
  125. "local tool after the trailing text",
  126. () => [text("先看图"), providerTool("completed"), text("再读文件"), localRead()],
  127. ],
  128. ])("splits a round followed by a local tool call (%s)", async (_name, parts) => {
  129. const entries = await hydrate(assistant(parts()));
  130. expect(entries.map((entry) => "message" in entry && entry.message)).toEqual([
  131. expect.objectContaining({
  132. role: "assistant",
  133. content: "先看图",
  134. toolCalls: [expect.objectContaining({ id: "call_image", name: "analyze_image" })],
  135. }),
  136. expect.objectContaining({ role: "tool", toolCallId: "call_image", content: "Order Console" }),
  137. expect.objectContaining({
  138. role: "assistant",
  139. content: "再读文件",
  140. toolCalls: [expect.objectContaining({ id: "call_read", name: "Read" })],
  141. }),
  142. expect.objectContaining({ role: "tool", toolCallId: "call_read" }),
  143. ]);
  144. // 两条 assistant 属于同一条持久化消息:同一个 compact 分组键,且不挂合计 usage。
  145. const assistants = entries.filter(
  146. (entry) => "message" in entry && entry.message.role === "assistant",
  147. );
  148. expect(
  149. new Set(assistants.map((entry) => "compactGroupKey" in entry && entry.compactGroupKey)),
  150. ).toEqual(new Set([assistantID]));
  151. expect(entries.some((entry) => "tokens" in entry && entry.tokens)).toBe(false);
  152. });
  153. it("replays an interrupted server tool as an error result", async () => {
  154. const entries = await hydrate(
  155. assistant([text("先看图"), providerTool("error"), text("没拿到结果")]),
  156. );
  157. expect(entries[1]).toMatchObject({
  158. message: {
  159. role: "tool",
  160. toolCallId: "call_image",
  161. isError: true,
  162. content: "[Server-side tool execution was interrupted before its result arrived]",
  163. },
  164. });
  165. });
  166. it("keeps no empty usage anchor when a round has no trailing text", async () => {
  167. const entries = await hydrate(assistant([text("先看图"), providerTool("completed")]));
  168. expect(entries.map((entry) => "message" in entry && entry.message.role)).toEqual([
  169. "assistant",
  170. "tool",
  171. ]);
  172. expect(entries.some((entry) => "tokens" in entry && entry.tokens)).toBe(false);
  173. });
  174. it("drops rounds and text of a discarded attempt but keeps its settled local tool", async () => {
  175. const entries = await hydrate(
  176. assistant([text("先看图"), providerTool("completed"), text("再读文件"), localRead()], {
  177. error: { name: STREAM_RECOVERY_DISCARDED_ERROR_NAME, data: { message: "discarded" } },
  178. }),
  179. );
  180. expect(JSON.stringify(entries)).not.toContain("call_image");
  181. expect(JSON.stringify(entries)).not.toContain("先看图");
  182. expect(entries.map((entry) => "message" in entry && entry.message.role)).toEqual([
  183. "assistant",
  184. "tool",
  185. ]);
  186. expect(entries[0]).toMatchObject({
  187. message: { toolCalls: [expect.objectContaining({ id: "call_read" })] },
  188. });
  189. });
  190. });