message-history.test.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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("preserves assistant tokens in runtime entries without exposing them to the provider", () => {
  51. const history = new MessageHistoryImpl();
  52. const tokens = {
  53. input: 100,
  54. output: 20,
  55. reasoning: 0,
  56. cache: { read: 0, write: 0 },
  57. total: 120,
  58. };
  59. history.addAssistant("answer", undefined, undefined, undefined, tokens);
  60. expect(history.toRuntimeEntries()[0]?.tokens).toEqual(tokens);
  61. expect(buildProviderRequestMessages({ entries: history.toRuntimeEntries() }).messages).toEqual([
  62. { role: "assistant", content: "answer" },
  63. ]);
  64. });
  65. it("borrows the current authoritative runtime entries without cloning the array", () => {
  66. const history = new MessageHistoryImpl();
  67. history.addUser("first prompt", { source: "real_user" });
  68. const beforeAppend = history.borrowReadOnlyRuntimeEntries();
  69. const retainedMembership = [...beforeAppend];
  70. expect(history.borrowReadOnlyRuntimeEntries()).toBe(beforeAppend);
  71. history.addAssistant("second message");
  72. expect(history.borrowReadOnlyRuntimeEntries()).toBe(beforeAppend);
  73. expect(beforeAppend).toHaveLength(2);
  74. expect(retainedMembership).toHaveLength(1);
  75. history.replaceMessages([
  76. {
  77. message: { role: "user", content: "replacement prompt" },
  78. metadata: { source: "real_user" },
  79. },
  80. ]);
  81. const afterReplace = history.borrowReadOnlyRuntimeEntries();
  82. expect(afterReplace).not.toBe(beforeAppend);
  83. expect(beforeAppend).toHaveLength(2);
  84. expect(afterReplace).toEqual([
  85. {
  86. message: { role: "user", content: "replacement prompt" },
  87. metadata: { source: "real_user" },
  88. },
  89. ]);
  90. });
  91. it("stores system reminder attachments as structured entries rendered only by provider builder", () => {
  92. const history = new MessageHistoryImpl();
  93. history.addUser("real prompt", { source: "real_user" });
  94. history.addAttachment("output_style", "style body");
  95. expect(history.toRuntimeEntries()).toEqual([
  96. {
  97. message: {
  98. role: "user",
  99. content: "real prompt",
  100. },
  101. metadata: { source: "real_user" },
  102. },
  103. {
  104. kind: "attachment",
  105. content: "style body",
  106. metadata: { source: "output_style" },
  107. },
  108. ]);
  109. expect(buildProviderRequestMessages({ entries: history.toRuntimeEntries() }).messages).toEqual([
  110. {
  111. role: "user",
  112. content: "real prompt",
  113. },
  114. {
  115. role: "system",
  116. content: "style body",
  117. },
  118. ]);
  119. });
  120. it("stores internal metadata without leaking it to provider messages", () => {
  121. const history = new MessageHistoryImpl();
  122. history.init("system prompt");
  123. history.addUser("hook context", {
  124. source: "hook_context",
  125. });
  126. const providerMessages = buildProviderRequestMessages({
  127. entries: history.toRuntimeEntries(),
  128. }).messages;
  129. expect(providerMessages).toEqual([
  130. { role: "system", content: "system prompt" },
  131. { role: "user", content: "hook context" },
  132. ]);
  133. const entries = history.toRuntimeEntries();
  134. expect(entries[1]?.metadata).toEqual({ source: "hook_context" });
  135. entries[1]!.message.content = "mutated";
  136. entries[1]!.metadata!.source = "real_user";
  137. expect(history.toRuntimeEntries()[1]).toMatchObject({
  138. message: { role: "user", content: "hook context" },
  139. metadata: { source: "hook_context" },
  140. });
  141. });
  142. it("counts only system messages and legacy unmarked reminders as request prefix", () => {
  143. const history = new MessageHistoryImpl();
  144. history.init([
  145. { role: "system", content: "system prompt" },
  146. // 指令文件是持久化公告;带来源标记的条目属于会话历史。
  147. {
  148. message: { role: "user", content: "context prefix" },
  149. metadata: {
  150. source: "context_prefix",
  151. },
  152. },
  153. {
  154. message: {
  155. role: "user",
  156. content: "<system-reminder>\nthis is a real user badcase\n</system-reminder>",
  157. },
  158. metadata: {
  159. source: "real_user",
  160. },
  161. },
  162. ]);
  163. expect(countContextPrefixMessages(history.toRuntimeEntries())).toBe(1);
  164. expect(history.getCacheStats().cachedMessages).toBe(1);
  165. expect(
  166. countContextPrefixMessages([
  167. { role: "system", content: "system prompt" },
  168. { role: "user", content: "<system-reminder>\nlegacy prefix\n</system-reminder>" },
  169. { role: "user", content: "real user prompt" },
  170. ]),
  171. ).toBe(2);
  172. });
  173. it("keeps skills and instruction attachments out of context prefix entries", () => {
  174. const skillsSection = contextSection({
  175. name: "Available Skills",
  176. source: "skills",
  177. content: "# Skills\n- review: Inspect code",
  178. });
  179. const dateSection = contextSection({
  180. name: "Request User Context",
  181. source: "request_user_context",
  182. content: "# currentDate\nToday's date is 2026-06-17.",
  183. });
  184. const contextResult: ContextBuildResult = {
  185. sections: [skillsSection, dateSection],
  186. totalChars: skillsSection.chars + dateSection.chars,
  187. totalTokens: skillsSection.tokens + dateSection.tokens,
  188. systemMessages: [{ role: "system", content: "system prompt" }],
  189. metaUserAttachments: [
  190. {
  191. source: "skills_listing",
  192. content: "# Skills\n- review: Inspect code",
  193. },
  194. {
  195. source: "context_prefix",
  196. content:
  197. "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.",
  198. },
  199. ],
  200. };
  201. // Skill 列表与指令文件由请求前的动态公告宣告,prefix 只含 system 消息。
  202. expect(buildContextHistoryEntries(contextResult)).toEqual([
  203. { message: { role: "system", content: "system prompt" } },
  204. ]);
  205. });
  206. });
  207. function contextSection(input: {
  208. name: string;
  209. source: ContextSection["source"];
  210. content: string;
  211. }): ContextSection {
  212. return {
  213. name: input.name,
  214. source: input.source,
  215. injectionTarget: "meta_user",
  216. cacheHint: "dynamic",
  217. content: input.content,
  218. chars: input.content.length,
  219. tokens: estimateTokens(input.content),
  220. preview: input.content.slice(0, 100),
  221. };
  222. }
  223. describe("legacy assistant entries", () => {
  224. it("drop blockIndex that a non-stream result wrote onto reasoning blocks", () => {
  225. // 非流式结果会在原对象上给 reasoning 编号;旧条目不带 blockIndex,
  226. // 否则只有思考块的条目会被请求投影当成有序条目(docs/design/v2/model/assistant-block-order.md)。
  227. const reasoning = [
  228. { type: "reasoning" as const, text: "think", providerOptions: { a: 1 }, blockIndex: 0 },
  229. ];
  230. const entry = createRuntimeAssistantEntry("answer", undefined, reasoning);
  231. expect(entry.message.content).toEqual([
  232. { type: "reasoning", text: "think", providerOptions: { a: 1 } },
  233. { type: "text", text: "answer" },
  234. ]);
  235. expect(reasoning[0]).toHaveProperty("blockIndex", 0);
  236. });
  237. });