guide-model-refresh.test.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. // 固定执行模型继续当前轮;已接受的用户 Guide 独立更新后续唤起选择。
  66. expect(runtime.getSessionModelSelection()).toEqual({
  67. ...selection,
  68. modelId: "must-not-switch",
  69. });
  70. } finally {
  71. runtime.beginShutdown();
  72. }
  73. },
  74. );
  75. it.each([
  76. { name: "same selection", guides: [selection], changes: 0 },
  77. { name: "same selection and new config", guides: [selection], changes: 0, newConfig: true },
  78. { name: "same selection and mode", guides: [selection], changes: 0, mode: "plan" as const },
  79. { name: "provider switch", guides: [{ ...selection, providerId: "other" }], changes: 1 },
  80. { name: "model switch", guides: [{ ...selection, modelId: "other" }], changes: 1 },
  81. {
  82. name: "reasoning switch",
  83. guides: [{ ...selection, options: { reasoningLevel: "low" } }],
  84. changes: 1,
  85. },
  86. {
  87. name: "A to B then B again",
  88. guides: [
  89. { ...selection, modelId: "other" },
  90. { ...selection, modelId: "other" },
  91. ],
  92. changes: 1,
  93. },
  94. { name: "Session differs from Loop", guides: [selection], changes: 0, sessionChanged: true },
  95. {
  96. name: "Session already equals new choice but Loop differs",
  97. guides: [{ ...selection, modelId: "external-session-change" }],
  98. changes: 1,
  99. sessionChanged: true,
  100. },
  101. ])("$name", async ({ guides, changes, newConfig, mode, sessionChanged }) => {
  102. const eventStore = createTestSessionEventStore();
  103. const requests: ModelRequest[] = [];
  104. let outputLimit = 8_000;
  105. const onCreate = vi.fn();
  106. const runtime = createTestAgentRuntime(
  107. createSessionId("guide-refresh"),
  108. {
  109. mode: "build",
  110. modelSelection: selection,
  111. workingDirectory: "/fixture",
  112. outputStyle: { name: "Learning", prompt: "LEARNING_STYLE_FIXTURE" },
  113. },
  114. {
  115. eventStore,
  116. modelFactory: createTestModelFactory({
  117. onCreate,
  118. maxOutputTokens: () => outputLimit,
  119. async generateText(request) {
  120. requests.push(request);
  121. const guide = guides[requests.length - 1];
  122. if (guide) {
  123. runtime.updateConfig({
  124. outputStyle: { name: "Explanatory", prompt: "EXPLANATORY_STYLE_FIXTURE" },
  125. });
  126. if (newConfig) outputLimit = 16_000;
  127. if (sessionChanged)
  128. runtime.setSessionModelSelection({
  129. ...selection,
  130. modelId: "external-session-change",
  131. });
  132. const result = await runtime.steerTurn({
  133. expectedTurnId: runtime.getActiveTurnInfo()?.turnId,
  134. input: `GUIDE_REFRESH_${requests.length}`,
  135. delivery: "guide",
  136. intent: {
  137. sourceCommandId: `guide-${requests.length}`,
  138. kind: "sendText",
  139. requestedDelivery: "guide",
  140. admittedDelivery: "guide",
  141. modelSelection: guide,
  142. ...(mode ? { mode } : {}),
  143. },
  144. });
  145. expect(result.kind).toBe("queued");
  146. }
  147. return { text: "step complete", finishReason: "stop", usage: {} };
  148. },
  149. }),
  150. },
  151. );
  152. const rebuild = vi.spyOn(
  153. runtime as never as { createContextBuilderFromSnapshot: () => unknown },
  154. "createContextBuilderFromSnapshot",
  155. );
  156. try {
  157. await runtime.executeTurn("start guide fixture");
  158. expect(requests).toHaveLength(guides.length + 1);
  159. expect(onCreate.mock.calls.length).toBeGreaterThanOrEqual(guides.length + 1);
  160. // 初始构造之外,仅真实执行选择变化才重建;单独观察新对象无法证明这个边界。
  161. expect(rebuild.mock.calls.length).toBe(changes + 1);
  162. const firstSystem = requests[0]!.messages.filter((m) => m.role === "system");
  163. if (changes === 0) {
  164. expect(requests[1]!.messages.filter((m) => m.role === "system")).toEqual(firstSystem);
  165. expect(JSON.stringify(requests[1]!.messages)).not.toContain("EXPLANATORY_STYLE_FIXTURE");
  166. }
  167. for (let index = 1; index < requests.length; index++) {
  168. expect(JSON.stringify(requests[index]!.messages)).toContain(`GUIDE_REFRESH_${index}`);
  169. expect(requests[index]!.options?.maxOutputTokens).toBe(newConfig ? 16_000 : 8_000);
  170. }
  171. if (mode) {
  172. expect(runtime.getMode()).toBe(mode === "plan" ? "build" : mode);
  173. expect(runtime.getPlanEnabled()).toBe(mode === "plan");
  174. }
  175. const events = await eventStore.getEvents(runtime.sessionId);
  176. expect(events.filter((e) => e.type === SessionEventType.TurnSteerDrained)).toHaveLength(
  177. guides.length,
  178. );
  179. } finally {
  180. runtime.beginShutdown();
  181. }
  182. });
  183. it("同一边界一起取出两条 Guide 时,后一条的选择生效", async () => {
  184. const eventStore = createTestSessionEventStore();
  185. const requestModels: string[] = [];
  186. const runtime = createTestAgentRuntime(
  187. createSessionId("guide-refresh-together"),
  188. { mode: "build", modelSelection: selection, workingDirectory: "/fixture" },
  189. {
  190. eventStore,
  191. modelFactory: createTestModelFactory({
  192. async generateText(request, observation) {
  193. requestModels.push(String(observation.model.modelId));
  194. if (requestModels.length === 1) {
  195. for (const modelId of ["first-guide", "second-guide"]) {
  196. const result = await runtime.steerTurn({
  197. expectedTurnId: runtime.getActiveTurnInfo()?.turnId,
  198. input: `GUIDE_${modelId}`,
  199. delivery: "guide",
  200. intent: {
  201. sourceCommandId: modelId,
  202. kind: "sendText",
  203. requestedDelivery: "guide",
  204. admittedDelivery: "guide",
  205. modelSelection: { ...selection, modelId },
  206. },
  207. });
  208. expect(result.kind).toBe("queued");
  209. }
  210. } else {
  211. const text = JSON.stringify(request.messages);
  212. expect(text.indexOf("GUIDE_first-guide")).toBeLessThan(
  213. text.indexOf("GUIDE_second-guide"),
  214. );
  215. }
  216. return { text: "step complete", finishReason: "stop", usage: {} };
  217. },
  218. }),
  219. },
  220. );
  221. try {
  222. await runtime.executeTurn("start guide fixture");
  223. expect(requestModels).toEqual(["original", "second-guide"]);
  224. expect(runtime.getSessionModelSelection()).toMatchObject({ modelId: "second-guide" });
  225. const events = await eventStore.getEvents(runtime.sessionId);
  226. // 两条在同一边界取出(中间没有模型请求),各自一个 drained 事件。
  227. expect(events.filter((e) => e.type === SessionEventType.TurnSteerDrained)).toHaveLength(2);
  228. } finally {
  229. runtime.beginShutdown();
  230. }
  231. });
  232. });