guide-model-refresh.test.ts 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. createSessionId,
  4. SessionEventType,
  5. type ModelRequest,
  6. type ModelSelection,
  7. } from "@zcode/contracts";
  8. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  9. import { createTestModelFactory } from "./test-runtime-model.js";
  10. import { createTestSessionEventStore } from "./test-event-store.js";
  11. const selection: ModelSelection = {
  12. providerId: "fixture",
  13. modelId: "original",
  14. options: { reasoningLevel: "high" },
  15. };
  16. describe("Guide refresh versus model switching", () => {
  17. it.each([false, true])(
  18. "固定执行模型的 Guide 仍应用 Plan=%s 和权限,但不切模型",
  19. async (planEnabled) => {
  20. const observed: { mode: string; plan: boolean }[] = [];
  21. const onCreate = vi.fn();
  22. const runtime = createTestAgentRuntime(
  23. createSessionId("fixed-guide-plan"),
  24. {
  25. mode: "build",
  26. planEnabled: !planEnabled,
  27. modelSelection: selection,
  28. workingDirectory: "/fixture",
  29. },
  30. {
  31. eventStore: createTestSessionEventStore(),
  32. modelFactory: createTestModelFactory({
  33. onCreate,
  34. async generateText() {
  35. observed.push({ mode: runtime.getMode(), plan: runtime.getPlanEnabled() });
  36. if (observed.length === 1)
  37. await runtime.steerTurn({
  38. expectedTurnId: runtime.getActiveTurnInfo()?.turnId,
  39. input: "guide",
  40. delivery: "guide",
  41. intent: {
  42. sourceCommandId: "guide",
  43. kind: "sendText",
  44. requestedDelivery: "guide",
  45. admittedDelivery: "guide",
  46. mode: "yolo",
  47. planEnabled,
  48. modelSelection: { ...selection, modelId: "must-not-switch" },
  49. },
  50. });
  51. return { text: "done", finishReason: "stop", usage: {} };
  52. },
  53. }),
  54. },
  55. );
  56. try {
  57. await runtime.executeTurn("start", undefined, {
  58. modelExecution: { selectionScope: "execution" },
  59. });
  60. expect(observed).toEqual([
  61. { mode: "build", plan: !planEnabled },
  62. { mode: "yolo", plan: planEnabled },
  63. ]);
  64. expect(onCreate).toHaveBeenCalledTimes(1);
  65. expect(runtime.getSessionModelSelection()).toEqual(selection);
  66. } finally {
  67. runtime.beginShutdown();
  68. }
  69. },
  70. );
  71. it.each([
  72. { name: "same selection", guides: [selection], changes: 0 },
  73. { name: "same selection and new config", guides: [selection], changes: 0, newConfig: true },
  74. { name: "same selection and mode", guides: [selection], changes: 0, mode: "plan" as const },
  75. { name: "provider switch", guides: [{ ...selection, providerId: "other" }], changes: 1 },
  76. { name: "model switch", guides: [{ ...selection, modelId: "other" }], changes: 1 },
  77. {
  78. name: "reasoning switch",
  79. guides: [{ ...selection, options: { reasoningLevel: "low" } }],
  80. changes: 1,
  81. },
  82. {
  83. name: "A to B then B again",
  84. guides: [
  85. { ...selection, modelId: "other" },
  86. { ...selection, modelId: "other" },
  87. ],
  88. changes: 1,
  89. },
  90. { name: "Session differs from Loop", guides: [selection], changes: 0, sessionChanged: true },
  91. {
  92. name: "Session already equals new choice but Loop differs",
  93. guides: [{ ...selection, modelId: "external-session-change" }],
  94. changes: 1,
  95. sessionChanged: true,
  96. },
  97. ])("$name", async ({ guides, changes, newConfig, mode, sessionChanged }) => {
  98. const eventStore = createTestSessionEventStore();
  99. const requests: ModelRequest[] = [];
  100. let outputLimit = 8_000;
  101. const onCreate = vi.fn();
  102. const runtime = createTestAgentRuntime(
  103. createSessionId("guide-refresh"),
  104. {
  105. mode: "build",
  106. modelSelection: selection,
  107. workingDirectory: "/fixture",
  108. outputStyle: { name: "Learning", prompt: "LEARNING_STYLE_FIXTURE" },
  109. },
  110. {
  111. eventStore,
  112. modelFactory: createTestModelFactory({
  113. onCreate,
  114. maxOutputTokens: () => outputLimit,
  115. async generateText(request) {
  116. requests.push(request);
  117. const guide = guides[requests.length - 1];
  118. if (guide) {
  119. runtime.updateConfig({
  120. outputStyle: { name: "Explanatory", prompt: "EXPLANATORY_STYLE_FIXTURE" },
  121. });
  122. if (newConfig) outputLimit = 16_000;
  123. if (sessionChanged)
  124. runtime.setSessionModelSelection({
  125. ...selection,
  126. modelId: "external-session-change",
  127. });
  128. const result = await runtime.steerTurn({
  129. expectedTurnId: runtime.getActiveTurnInfo()?.turnId,
  130. input: `GUIDE_REFRESH_${requests.length}`,
  131. delivery: "guide",
  132. intent: {
  133. sourceCommandId: `guide-${requests.length}`,
  134. kind: "sendText",
  135. requestedDelivery: "guide",
  136. admittedDelivery: "guide",
  137. modelSelection: guide,
  138. ...(mode ? { mode } : {}),
  139. },
  140. });
  141. expect(result.kind).toBe("queued");
  142. }
  143. return { text: "step complete", finishReason: "stop", usage: {} };
  144. },
  145. }),
  146. },
  147. );
  148. const rebuild = vi.spyOn(
  149. runtime as never as { createContextBuilderFromSnapshot: () => unknown },
  150. "createContextBuilderFromSnapshot",
  151. );
  152. try {
  153. await runtime.executeTurn("start guide fixture");
  154. expect(requests).toHaveLength(guides.length + 1);
  155. expect(onCreate.mock.calls.length).toBeGreaterThanOrEqual(guides.length + 1);
  156. // 初始构造之外,仅真实执行选择变化才重建;单独观察新对象无法证明这个边界。
  157. expect(rebuild.mock.calls.length).toBe(changes + 1);
  158. const firstSystem = requests[0]!.messages.filter((m) => m.role === "system");
  159. if (changes === 0) {
  160. expect(requests[1]!.messages.filter((m) => m.role === "system")).toEqual(firstSystem);
  161. expect(JSON.stringify(requests[1]!.messages)).not.toContain("EXPLANATORY_STYLE_FIXTURE");
  162. }
  163. for (let index = 1; index < requests.length; index++) {
  164. expect(JSON.stringify(requests[index]!.messages)).toContain(`GUIDE_REFRESH_${index}`);
  165. expect(requests[index]!.options?.maxOutputTokens).toBe(newConfig ? 16_000 : 8_000);
  166. }
  167. if (mode) {
  168. expect(runtime.getMode()).toBe(mode === "plan" ? "build" : mode);
  169. expect(runtime.getPlanEnabled()).toBe(mode === "plan");
  170. }
  171. const events = await eventStore.getEvents(runtime.sessionId);
  172. expect(events.filter((e) => e.type === SessionEventType.TurnSteerDrained)).toHaveLength(
  173. guides.length,
  174. );
  175. } finally {
  176. runtime.beginShutdown();
  177. }
  178. });
  179. });