runtime.test.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. // Context 组成的 runtime 行为(spec §4 第 3、4、5 类):
  2. // apps/zcode-cli/docs/design/v2/model/context-composition.md。
  3. import { describe, expect, it, vi } from "vitest";
  4. import { createSessionId, type ModelRequest } from "@zcode/contracts";
  5. import { contextCompositionSchema } from "@zcode/shared/zcode-protocol-v4";
  6. import { countContextPrefixMessages } from "../../src/agent/message-history.js";
  7. import type { AgentRuntimeInternal } from "../../src/runtime/internal.js";
  8. import type { ContextCompositionChangeReason } from "../../src/runtime/context-composition/index.js";
  9. import { createTestAgentRuntime } from "../test-agent-runtime.js";
  10. import { createTestSessionEventStore } from "../test-event-store.js";
  11. import { createTestModelFactory } from "../test-runtime-model.js";
  12. import { createRecordingMessageStore } from "../runtime-output-token-continuation-test-helpers.js";
  13. const PROVIDER_INPUT_TOKENS = 1_234;
  14. const PROVIDER_OUTPUT_TOKENS = 5;
  15. const SUMMARY_MARKER = "create a detailed summary";
  16. function fixture() {
  17. const sessionId = createSessionId("context-composition");
  18. const store = createRecordingMessageStore();
  19. const createSession = vi.spyOn(store, "createSession");
  20. const requests: ModelRequest[] = [];
  21. const runtime = createTestAgentRuntime(
  22. sessionId,
  23. { mode: "yolo", compact: { enabled: false }, titleGeneration: { enabled: false } },
  24. {
  25. eventStore: createTestSessionEventStore(),
  26. sessionStore: store as never,
  27. modelFactory: createTestModelFactory({
  28. properties: { supportsMidConversationSystem: true },
  29. async generateText(request) {
  30. requests.push(request);
  31. const isCompact = JSON.stringify(request.messages.at(-1)?.content).includes(
  32. SUMMARY_MARKER,
  33. );
  34. return {
  35. finishReason: "stop",
  36. text: isCompact ? "<summary>older work</summary>" : "done",
  37. usage: {
  38. inputTokens: PROVIDER_INPUT_TOKENS,
  39. outputTokens: PROVIDER_OUTPUT_TOKENS,
  40. totalTokens: PROVIDER_INPUT_TOKENS + PROVIDER_OUTPUT_TOKENS,
  41. },
  42. };
  43. },
  44. }),
  45. },
  46. );
  47. const internal = runtime as unknown as AgentRuntimeInternal;
  48. const conversationEntries = () => {
  49. const entries = internal.messageHistory.borrowReadOnlyRuntimeEntries();
  50. return entries.slice(countContextPrefixMessages(entries));
  51. };
  52. const reasons: ContextCompositionChangeReason[] = [];
  53. runtime.subscribeContextCompositionChanged(({ reason }) => reasons.push(reason));
  54. return { runtime, store, createSession, requests, conversationEntries, reasons };
  55. }
  56. const tokensOf = (
  57. composition: { categories: Array<{ id: string; tokens: number }> } | null,
  58. id: string,
  59. ) => composition?.categories.find((category) => category.id === id)?.tokens ?? 0;
  60. describe("context composition runtime", () => {
  61. it("previews the first request of a draft without side effects", async () => {
  62. const f = fixture();
  63. const first = await f.runtime.getContextComposition();
  64. const second = await f.runtime.getContextComposition();
  65. expect(first?.phase).toBe("draft-preview");
  66. expect(tokensOf(first, "system_prompt")).toBeGreaterThan(0);
  67. expect(tokensOf(first, "system_tool_schemas")).toBeGreaterThan(0);
  68. // 首个请求前的提醒(日期、模型等)在预演里出现,但不落进历史。
  69. expect(tokensOf(first, "reminders")).toBeGreaterThan(0);
  70. expect(first!.estimatedTokens).toBe(
  71. first!.categories.reduce((sum, category) => sum + category.tokens, 0),
  72. );
  73. expect(first!.freeTokens).toBe(first!.model.contextWindow! - first!.estimatedTokens);
  74. expect(first).not.toHaveProperty("providerInputTokens");
  75. expect(first).not.toHaveProperty("providerContextTokens");
  76. expect(() =>
  77. contextCompositionSchema.parse({ ...first, sessionId: "s", revision: 0 }),
  78. ).not.toThrow();
  79. expect(second?.categories).toEqual(first?.categories);
  80. // 草稿仍是草稿:没有会话行、没有消息、对话历史为空、没有落库的公告。
  81. expect(f.runtime.isSessionPersisted()).toBe(false);
  82. expect(f.createSession).not.toHaveBeenCalled();
  83. expect(f.store.savedMessages).toEqual([]);
  84. expect(f.conversationEntries()).toEqual([]);
  85. expect(f.requests).toEqual([]);
  86. });
  87. it("returns the request composition for the same model and a preview after a model change", async () => {
  88. const f = fixture();
  89. await f.runtime.executeTurn("hello");
  90. const sameModel = await f.runtime.getContextComposition();
  91. expect(sameModel?.phase).toBe("request");
  92. expect(sameModel?.providerInputTokens).toBe(PROVIDER_INPUT_TOKENS);
  93. // 与输入框用量圆环同一个值:input + 这次回复的 output(getModelUsageContextTokens)。
  94. expect(sameModel?.providerContextTokens).toBe(PROVIDER_INPUT_TOKENS + PROVIDER_OUTPUT_TOKENS);
  95. expect(tokensOf(sameModel, "messages")).toBeGreaterThan(0);
  96. expect(tokensOf(sameModel, "reminders")).toBeGreaterThan(0);
  97. const otherModel = await f.runtime.getContextComposition({
  98. modelSelection: { providerId: "test", modelId: "other-model" },
  99. });
  100. expect(otherModel?.phase).toBe("draft-preview");
  101. expect(otherModel?.model.modelId).toBe("other-model");
  102. expect(otherModel).not.toHaveProperty("providerInputTokens");
  103. expect(otherModel).not.toHaveProperty("providerContextTokens");
  104. // 换模型让请求组成作废:同一模型也改为预演,直到下一次请求。
  105. f.runtime.markContextCompositionChanged();
  106. expect((await f.runtime.getContextComposition())?.phase).toBe("draft-preview");
  107. await f.runtime.executeTurn("again");
  108. expect((await f.runtime.getContextComposition())?.phase).toBe("request");
  109. });
  110. it("returns null when no model selection is available", async () => {
  111. const f = fixture();
  112. f.runtime.setSessionModelSelection(undefined);
  113. expect(await f.runtime.getContextComposition()).toBeNull();
  114. });
  115. it("notifies listeners on every change trigger", async () => {
  116. const f = fixture();
  117. await f.runtime.executeTurn("hello");
  118. expect(f.reasons).toEqual(["request", "request_usage"]);
  119. // 首轮走 ensureContextInitialized;之后每轮开始按本轮模型重建前缀。
  120. f.reasons.length = 0;
  121. await f.runtime.executeTurn("again");
  122. expect(f.reasons).toEqual(["context_prefix", "request", "request_usage"]);
  123. f.reasons.length = 0;
  124. f.runtime.invalidateToolCache();
  125. expect(f.reasons).toEqual(["tools"]);
  126. f.reasons.length = 0;
  127. f.runtime.updateConfig({ language: "zh-CN" });
  128. expect(f.reasons).toEqual(["context_prefix"]);
  129. f.reasons.length = 0;
  130. f.runtime.markContextCompositionChanged();
  131. expect(f.reasons).toEqual(["model"]);
  132. f.reasons.length = 0;
  133. await f.runtime.executeTurn("/compact");
  134. expect(f.reasons).toContain("compact");
  135. // compact 之后请求组成作废,预演里能看到压缩摘要。
  136. const afterCompact = await f.runtime.getContextComposition();
  137. expect(afterCompact?.phase).toBe("draft-preview");
  138. expect(tokensOf(afterCompact, "compact_summary")).toBeGreaterThan(0);
  139. });
  140. it("stops notifying after unsubscribe", () => {
  141. const f = fixture();
  142. const listener = vi.fn();
  143. const unsubscribe = f.runtime.subscribeContextCompositionChanged(listener);
  144. f.runtime.invalidateToolCache();
  145. unsubscribe();
  146. f.runtime.invalidateToolCache();
  147. expect(listener).toHaveBeenCalledTimes(1);
  148. });
  149. });