message-history.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. import { describe, expect, it } from "vitest";
  2. import { createTestModelSelection } from "./test-model-selection.js";
  3. import {
  4. MessageHistoryImpl,
  5. countContextPrefixMessages,
  6. createRuntimeAssistantEntry,
  7. } from "../src/agent/message-history.js";
  8. import { buildProviderRequestMessages } from "../src/runtime/helpers/provider-request-messages.js";
  9. import type { ContextBuildResult, ContextSection } from "../src/context/types.js";
  10. import { estimateTokens } from "../src/context/utils.js";
  11. import { buildContextHistoryEntries } from "../src/runtime/methods/context-history-entries.js";
  12. describe("message history metadata", () => {
  13. it("isolates announcement delta arrays across add, read and replace without exposing metadata", () => {
  14. const history = new MessageHistoryImpl();
  15. const delta = {
  16. addedNames: ["WebFetch"],
  17. removedNames: ["TodoWrite"],
  18. readdedNames: ["WebFetch"],
  19. };
  20. const expected = structuredClone(delta);
  21. history.addEntries([
  22. {
  23. message: { role: "user", content: "Tool availability changed." },
  24. metadata: { source: "legacy_synthetic", toolSearchAnnouncement: delta },
  25. },
  26. ]);
  27. for (const names of Object.values(delta)) names.push("source mutation");
  28. const entries = history.toRuntimeEntries();
  29. expect(entries[0]?.metadata?.toolSearchAnnouncement).toEqual(expected);
  30. history.replaceMessages(entries);
  31. for (const names of Object.values(entries[0]!.metadata!.toolSearchAnnouncement!))
  32. (names as string[]).push("copy mutation");
  33. expect(history.toRuntimeEntries()[0]?.metadata?.toolSearchAnnouncement).toEqual(expected);
  34. expect(buildProviderRequestMessages({ entries: history.toRuntimeEntries() }).messages).toEqual([
  35. { role: "user", content: "Tool availability changed." },
  36. ]);
  37. });
  38. it("preserves assistant model provenance through request-local clones", () => {
  39. const history = new MessageHistoryImpl();
  40. const model = createTestModelSelection("provider-a/model-a");
  41. history.addAssistant("answer", undefined, undefined, model);
  42. const entries = history.toRuntimeEntries();
  43. expect(entries[0]?.message).toMatchObject({ providerId: "provider-a", modelId: "model-a" });
  44. entries[0]!.message.providerId = "mutated" as never;
  45. expect(history.toRuntimeEntries()[0]?.message).toMatchObject({
  46. providerId: "provider-a",
  47. modelId: "model-a",
  48. });
  49. });
  50. it("stamps entry time from its clock and keeps it out of provider messages", () => {
  51. let now = 1_000;
  52. const history = new MessageHistoryImpl(() => now);
  53. history.addUser("prompt", { source: "real_user" });
  54. now = 2_000;
  55. history.addAssistant("answer");
  56. now = 3_000;
  57. history.addToolResult("call_1", "Read", "body", true);
  58. history.addAttachment("environment", "environment");
  59. // 已带时间的条目(冷恢复、先持久化的提醒)不改写。
  60. history.addEntries([
  61. { message: { role: "user", content: "hydrated" }, time: 500 },
  62. { message: { role: "assistant", content: "fresh" } },
  63. ]);
  64. now = 4_000;
  65. history.replaceMessages([
  66. ...history.toRuntimeEntries(),
  67. { message: { role: "user", content: "summary" } },
  68. ]);
  69. expect(history.toRuntimeEntries().map((entry) => entry.time)).toEqual([
  70. 1_000, 2_000, 3_000, 3_000, 500, 3_000, 4_000,
  71. ]);
  72. expect(
  73. JSON.stringify(
  74. buildProviderRequestMessages({ entries: history.toRuntimeEntries() }).messages,
  75. ),
  76. ).not.toContain("4000");
  77. // 没有时钟的历史(单元测试直接构造)不加时间。
  78. const untimed = new MessageHistoryImpl();
  79. untimed.addUser("prompt");
  80. expect(untimed.toRuntimeEntries()[0]).not.toHaveProperty("time");
  81. });
  82. it("preserves assistant tokens in runtime entries without exposing them to the provider", () => {
  83. const history = new MessageHistoryImpl();
  84. const tokens = {
  85. input: 100,
  86. output: 20,
  87. reasoning: 0,
  88. cache: { read: 0, write: 0 },
  89. total: 120,
  90. };
  91. history.addAssistant("answer", undefined, undefined, undefined, tokens);
  92. expect(history.toRuntimeEntries()[0]?.tokens).toEqual(tokens);
  93. expect(buildProviderRequestMessages({ entries: history.toRuntimeEntries() }).messages).toEqual([
  94. { role: "assistant", content: "answer" },
  95. ]);
  96. });
  97. it("borrows the current authoritative runtime entries without cloning the array", () => {
  98. const history = new MessageHistoryImpl();
  99. history.addUser("first prompt", { source: "real_user" });
  100. const beforeAppend = history.borrowReadOnlyRuntimeEntries();
  101. const retainedMembership = [...beforeAppend];
  102. expect(history.borrowReadOnlyRuntimeEntries()).toBe(beforeAppend);
  103. history.addAssistant("second message");
  104. expect(history.borrowReadOnlyRuntimeEntries()).toBe(beforeAppend);
  105. expect(beforeAppend).toHaveLength(2);
  106. expect(retainedMembership).toHaveLength(1);
  107. history.replaceMessages([
  108. {
  109. message: { role: "user", content: "replacement prompt" },
  110. metadata: { source: "real_user" },
  111. },
  112. ]);
  113. const afterReplace = history.borrowReadOnlyRuntimeEntries();
  114. expect(afterReplace).not.toBe(beforeAppend);
  115. expect(beforeAppend).toHaveLength(2);
  116. expect(afterReplace).toEqual([
  117. {
  118. message: { role: "user", content: "replacement prompt" },
  119. metadata: { source: "real_user" },
  120. },
  121. ]);
  122. });
  123. it("stores system reminder attachments as structured entries rendered only by provider builder", () => {
  124. const history = new MessageHistoryImpl();
  125. history.addUser("real prompt", { source: "real_user" });
  126. history.addAttachment("output_style", "style body");
  127. expect(history.toRuntimeEntries()).toEqual([
  128. {
  129. message: {
  130. role: "user",
  131. content: "real prompt",
  132. },
  133. metadata: { source: "real_user" },
  134. },
  135. {
  136. kind: "attachment",
  137. content: "style body",
  138. metadata: { source: "output_style" },
  139. },
  140. ]);
  141. expect(buildProviderRequestMessages({ entries: history.toRuntimeEntries() }).messages).toEqual([
  142. {
  143. role: "user",
  144. content: "real prompt",
  145. },
  146. {
  147. role: "system",
  148. content: "style body",
  149. },
  150. ]);
  151. });
  152. it("stores internal metadata without leaking it to provider messages", () => {
  153. const history = new MessageHistoryImpl();
  154. history.init("system prompt");
  155. history.addUser("hook context", {
  156. source: "hook_context",
  157. });
  158. const providerMessages = buildProviderRequestMessages({
  159. entries: history.toRuntimeEntries(),
  160. }).messages;
  161. expect(providerMessages).toEqual([
  162. { role: "system", content: "system prompt" },
  163. { role: "user", content: "hook context" },
  164. ]);
  165. const entries = history.toRuntimeEntries();
  166. expect(entries[1]?.metadata).toEqual({ source: "hook_context" });
  167. entries[1]!.message.content = "mutated";
  168. entries[1]!.metadata!.source = "real_user";
  169. expect(history.toRuntimeEntries()[1]).toMatchObject({
  170. message: { role: "user", content: "hook context" },
  171. metadata: { source: "hook_context" },
  172. });
  173. });
  174. it("counts only system messages and legacy unmarked reminders as request prefix", () => {
  175. const history = new MessageHistoryImpl();
  176. history.init([
  177. { role: "system", content: "system prompt" },
  178. // 指令文件是持久化公告;带来源标记的条目属于会话历史。
  179. {
  180. message: { role: "user", content: "context prefix" },
  181. metadata: {
  182. source: "context_prefix",
  183. },
  184. },
  185. {
  186. message: {
  187. role: "user",
  188. content: "<system-reminder>\nthis is a real user badcase\n</system-reminder>",
  189. },
  190. metadata: {
  191. source: "real_user",
  192. },
  193. },
  194. ]);
  195. expect(countContextPrefixMessages(history.toRuntimeEntries())).toBe(1);
  196. expect(history.getCacheStats().cachedMessages).toBe(1);
  197. expect(
  198. countContextPrefixMessages([
  199. { role: "system", content: "system prompt" },
  200. { role: "user", content: "<system-reminder>\nlegacy prefix\n</system-reminder>" },
  201. { role: "user", content: "real user prompt" },
  202. ]),
  203. ).toBe(2);
  204. });
  205. it("keeps instruction attachments out of context prefix entries", () => {
  206. const dateSection = contextSection({
  207. name: "Request User Context",
  208. source: "request_user_context",
  209. content: "# currentDate\nToday's date is 2026-06-17.",
  210. });
  211. const contextResult: ContextBuildResult = {
  212. sections: [dateSection],
  213. totalChars: dateSection.chars,
  214. totalTokens: dateSection.tokens,
  215. systemMessages: [{ role: "system", content: "system prompt" }],
  216. metaUserAttachments: [
  217. {
  218. source: "context_prefix",
  219. content:
  220. "As you answer the user's questions, you can use the following context:\n# currentDate\nToday's date is 2026-06-17.\n\n IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.",
  221. },
  222. ],
  223. };
  224. // Skill 列表与指令文件由请求前的动态公告宣告,prefix 只含 system 消息。
  225. expect(buildContextHistoryEntries(contextResult)).toEqual([
  226. { message: { role: "system", content: "system prompt" } },
  227. ]);
  228. });
  229. });
  230. function contextSection(input: {
  231. name: string;
  232. source: ContextSection["source"];
  233. content: string;
  234. }): ContextSection {
  235. return {
  236. name: input.name,
  237. source: input.source,
  238. injectionTarget: "meta_user",
  239. cacheHint: "dynamic",
  240. content: input.content,
  241. chars: input.content.length,
  242. tokens: estimateTokens(input.content),
  243. preview: input.content.slice(0, 100),
  244. };
  245. }
  246. describe("legacy assistant entries", () => {
  247. it("drop blockIndex that a non-stream result wrote onto reasoning blocks", () => {
  248. // 非流式结果会在原对象上给 reasoning 编号;旧条目不带 blockIndex,
  249. // 否则只有思考块的条目会被请求投影当成有序条目(docs/design/v2/model/assistant-block-order.md)。
  250. const reasoning = [
  251. { type: "reasoning" as const, text: "think", providerOptions: { a: 1 }, blockIndex: 0 },
  252. ];
  253. const entry = createRuntimeAssistantEntry("answer", undefined, reasoning);
  254. expect(entry.message.content).toEqual([
  255. { type: "reasoning", text: "think", providerOptions: { a: 1 } },
  256. { type: "text", text: "answer" },
  257. ]);
  258. expect(reasoning[0]).toHaveProperty("blockIndex", 0);
  259. });
  260. });