v4-native-model-config.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. // L2:v4 原生 switchModelConfig——验证自旧 server-operations.switchModelConfig 搬运的
  2. // 决策语义在原生层保真:previous 在 setModel 之前从 getSessionModelSelection 快照、
  3. // 跨模型由 setModel 解析目标兼容 thought、同模型显式 thought 才调 setThoughtLevel、
  4. // session 不存在拒绝。08-phasing M4 完成定义的 L2 层。
  5. // R-19(10 §4.2.3)追加:同值切换 → V4CommandNoopError(config.unchanged);
  6. // applyRequestedSessionConfig(createSession.config 消费共用件)。
  7. import { describe, expect, it, vi } from "vitest";
  8. import { parseCommandEnvelope, type CommandEnvelope } from "@zcode/shared/zcode-protocol-v4";
  9. import {
  10. V4CommandExecutor,
  11. V4SessionNotFoundError,
  12. } from "../src/zcode-protocol-v4/commands/executor.js";
  13. import { applyRequestedSessionConfig } from "../src/zcode-protocol-v4/commands/handlers/model-config.js";
  14. import { V4CommandNoopError } from "../src/zcode-protocol-v4/index.js";
  15. import type {
  16. V4CommandCoreHost,
  17. V4SessionRecordView,
  18. } from "../src/zcode-protocol-v4/commands/types.js";
  19. /** 切换前的结构化选型。 */
  20. const PREVIOUS_SELECTION = { providerId: "prov-a", modelId: "old-model" };
  21. const TRACE = { traceId: "trace-1", sessionId: "s1" };
  22. const SUPPORTED_THOUGHT_LEVELS = ["low", "medium", "high", "max"];
  23. function makeApp() {
  24. // calls 记录跨方法调用顺序(顺序本身是搬运语义:先快照 previous,再切模型,最后补发事件)。
  25. const calls: string[] = [];
  26. return {
  27. calls,
  28. sessionId: "s1",
  29. runtime: {
  30. getPlanEnabled: vi.fn(() => false),
  31. setExecutionState: vi.fn(async () => {}),
  32. getSessionModelSelection: vi.fn(() => {
  33. calls.push("getSessionModelSelection");
  34. return PREVIOUS_SELECTION;
  35. }),
  36. emitModelSelected: vi.fn(async () => {
  37. calls.push("emitModelSelected");
  38. }),
  39. emitModeChanged: vi.fn(async () => {
  40. calls.push("emitModeChanged");
  41. }),
  42. },
  43. setModel: vi.fn(async () => {
  44. calls.push("setModel");
  45. return { thoughtLevel: undefined };
  46. }),
  47. setThoughtLevel: vi.fn(async (level: string) => {
  48. calls.push("setThoughtLevel");
  49. return { thoughtLevel: level };
  50. }),
  51. getThoughtLevel: vi.fn((): string | undefined => undefined),
  52. getModelOption: vi.fn(() => ({ reasoning: { defaultLevel: "high" } })),
  53. listThoughtLevels: vi.fn(() => ["low", "medium", "high", "max"]),
  54. getMode: vi.fn(() => {
  55. calls.push("getMode");
  56. return "build";
  57. }),
  58. setMode: vi.fn(async () => {
  59. calls.push("setMode");
  60. return {};
  61. }),
  62. setFollowupMode: vi.fn(async () => {
  63. calls.push("setFollowupMode");
  64. }),
  65. };
  66. }
  67. function makeRecord(app: ReturnType<typeof makeApp>): V4SessionRecordView {
  68. return {
  69. app: app as unknown as V4SessionRecordView["app"],
  70. workspace: { workspacePath: "/w" },
  71. persistence: "immediate",
  72. traceContext: TRACE,
  73. } as V4SessionRecordView;
  74. }
  75. function makeHost(record: V4SessionRecordView): V4CommandCoreHost {
  76. return {
  77. getRecord: (id) => (id === "s1" ? record : undefined),
  78. };
  79. }
  80. function envelope(sessionId: string, payload: unknown): CommandEnvelope {
  81. return {
  82. type: "switchModelConfig",
  83. payload,
  84. sessionId,
  85. commandId: "cmd-1",
  86. baseRevision: 0,
  87. } as unknown as CommandEnvelope;
  88. }
  89. describe("v4 原生 switchModelConfig", () => {
  90. it("跨模型一次提交完整选择,不在换模后另写档位", async () => {
  91. const app = makeApp();
  92. const selection = {
  93. providerId: "prov-b",
  94. modelId: "new-model",
  95. options: { reasoningLevel: "high" },
  96. };
  97. await new V4CommandExecutor(makeHost(makeRecord(app))).execute(
  98. envelope("s1", { provider: selection.providerId, model: selection.modelId, thought: "high" }),
  99. );
  100. expect(app.setModel).toHaveBeenCalledWith(selection);
  101. expect(app.setThoughtLevel).not.toHaveBeenCalled();
  102. expect(app.runtime.emitModelSelected).toHaveBeenCalledWith(
  103. expect.objectContaining({
  104. modelSelection: selection,
  105. previousModelSelection: PREVIOUS_SELECTION,
  106. }),
  107. );
  108. });
  109. it("目标档位校验失败不发布成功事件、不执行第二次部分配置", async () => {
  110. const app = makeApp();
  111. app.setModel.mockRejectedValueOnce(new Error("Unsupported reasoning effort"));
  112. await expect(
  113. new V4CommandExecutor(makeHost(makeRecord(app))).execute(
  114. envelope("s1", { provider: "prov-b", model: "new-model", thought: "invalid" }),
  115. ),
  116. ).rejects.toThrow("Unsupported reasoning effort");
  117. expect(app.setModel).toHaveBeenCalledWith({
  118. providerId: "prov-b",
  119. modelId: "new-model",
  120. options: { reasoningLevel: "invalid" },
  121. });
  122. expect(app.setThoughtLevel).not.toHaveBeenCalled();
  123. expect(app.runtime.emitModelSelected).not.toHaveBeenCalled();
  124. });
  125. it("同模型显式切 thought:只调 setThoughtLevel,再发布实际档位", async () => {
  126. const app = makeApp();
  127. const record = makeRecord(app);
  128. await new V4CommandExecutor(makeHost(record)).execute(
  129. envelope("s1", { provider: "prov-a", model: "old-model", thought: "max" }),
  130. );
  131. expect(app.setModel).not.toHaveBeenCalled();
  132. expect(app.setThoughtLevel).toHaveBeenCalledWith("max");
  133. expect(app.calls).toEqual(["getSessionModelSelection", "setThoughtLevel", "emitModelSelected"]);
  134. expect(app.runtime.emitModelSelected).toHaveBeenCalledWith({
  135. modelSelection: {
  136. providerId: "prov-a",
  137. modelId: "old-model",
  138. options: { reasoningLevel: "max" },
  139. },
  140. effectiveReasoningLevel: "max",
  141. previousModelSelection: PREVIOUS_SELECTION,
  142. supportedThoughtLevels: SUPPORTED_THOUGHT_LEVELS,
  143. traceContext: TRACE,
  144. });
  145. });
  146. it("同模型显式选择 effective 默认档位仍保存为稀疏 Selection pin", async () => {
  147. const app = makeApp();
  148. app.getThoughtLevel.mockReturnValue("high");
  149. const record = makeRecord(app);
  150. await new V4CommandExecutor(makeHost(record)).execute(
  151. envelope("s1", { provider: "prov-a", model: "old-model", thought: "high" }),
  152. );
  153. expect(app.setThoughtLevel).toHaveBeenCalledWith("high");
  154. expect(app.runtime.emitModelSelected).toHaveBeenCalledWith(
  155. expect.objectContaining({
  156. modelSelection: {
  157. providerId: "prov-a",
  158. modelId: "old-model",
  159. options: { reasoningLevel: "high" },
  160. },
  161. effectiveReasoningLevel: "high",
  162. }),
  163. );
  164. });
  165. it("同模型显式切到不支持的 thought:失败且不触碰模型身份", async () => {
  166. const app = makeApp();
  167. app.setThoughtLevel.mockRejectedValueOnce(new Error("Unsupported reasoning effort: enabled"));
  168. const record = makeRecord(app);
  169. await expect(
  170. new V4CommandExecutor(makeHost(record)).execute(
  171. envelope("s1", { provider: "prov-a", model: "old-model", thought: "enabled" }),
  172. ),
  173. ).rejects.toThrow("Unsupported reasoning effort: enabled");
  174. expect(app.setModel).not.toHaveBeenCalled();
  175. expect(app.runtime.emitModelSelected).not.toHaveBeenCalled();
  176. });
  177. it("thought 缺省(空串):一次提交目标 Registry 默认档位,不另调 setThoughtLevel", async () => {
  178. const app = makeApp();
  179. const record = makeRecord(app);
  180. await new V4CommandExecutor(makeHost(record)).execute(
  181. envelope("s1", { provider: "prov-a", model: "new-model", thought: "" }),
  182. );
  183. expect(app.setThoughtLevel).not.toHaveBeenCalled();
  184. expect(app.calls).toEqual(["getSessionModelSelection", "setModel", "emitModelSelected"]);
  185. expect(app.runtime.emitModelSelected).toHaveBeenCalledWith({
  186. modelSelection: {
  187. providerId: "prov-a",
  188. modelId: "new-model",
  189. options: { reasoningLevel: "high" },
  190. },
  191. effectiveReasoningLevel: "high",
  192. previousModelSelection: PREVIOUS_SELECTION,
  193. supportedThoughtLevels: SUPPORTED_THOUGHT_LEVELS,
  194. traceContext: TRACE,
  195. });
  196. });
  197. it("session 不存在:拒绝且不触碰任何 core 方法", async () => {
  198. const app = makeApp();
  199. const record = makeRecord(app);
  200. await expect(
  201. new V4CommandExecutor(makeHost(record)).execute(
  202. envelope("missing", { provider: "p", model: "m", thought: "" }),
  203. ),
  204. ).rejects.toThrow(V4SessionNotFoundError);
  205. expect(app.setModel).not.toHaveBeenCalled();
  206. expect(app.runtime.emitModelSelected).not.toHaveBeenCalled();
  207. });
  208. // R-19:同值切换不得以 accepted 静默吞掉——UI 需要区分「已生效」与「本来就是这个值」。
  209. it("同值切换:抛 V4CommandNoopError(config.unchanged),不切模型不补发事件", async () => {
  210. const app = makeApp();
  211. const record = makeRecord(app);
  212. await expect(
  213. new V4CommandExecutor(makeHost(record)).execute(
  214. envelope("s1", { provider: "prov-a", model: "old-model", thought: "" }),
  215. ),
  216. ).rejects.toThrow(V4CommandNoopError);
  217. expect(app.setModel).not.toHaveBeenCalled();
  218. expect(app.setThoughtLevel).not.toHaveBeenCalled();
  219. expect(app.runtime.emitModelSelected).not.toHaveBeenCalled();
  220. });
  221. it("同模型显式选择 effective 值:仍固定为 option pin", async () => {
  222. const app = makeApp();
  223. app.getThoughtLevel.mockReturnValue("max");
  224. const record = makeRecord(app);
  225. await new V4CommandExecutor(makeHost(record)).execute(
  226. envelope("s1", { provider: "prov-a", model: "old-model", thought: "max" }),
  227. );
  228. expect(app.setModel).not.toHaveBeenCalled();
  229. expect(app.setThoughtLevel).toHaveBeenCalledWith("max");
  230. });
  231. });
  232. // M5 additive:switchCollaborationMode(UI 模式选择器 → app.setMode + SessionModeChanged 补发)。
  233. describe("v4 原生 switchCollaborationMode", () => {
  234. it("guarded 经同一模式命令切换,未知值报错而不降级", async () => {
  235. const app = makeApp();
  236. const executor = new V4CommandExecutor(makeHost(makeRecord(app)));
  237. const requested = {
  238. ...modeEnvelope("s1", { mode: "guarded" }),
  239. clientId: "test",
  240. issuedAt: Date.now(),
  241. };
  242. const parsed = parseCommandEnvelope(requested);
  243. if (!parsed.ok) throw parsed.error;
  244. await executor.execute(parsed.envelope);
  245. expect(app.setMode).toHaveBeenCalledWith("guarded");
  246. // executor 只消费协议边界已经校验的 envelope,未知模式应在同一边界被拒绝。
  247. expect(parseCommandEnvelope({ ...requested, payload: { mode: "unsupported" } }).ok).toBe(false);
  248. expect(app.setMode).toHaveBeenCalledTimes(1);
  249. });
  250. function modeEnvelope(sessionId: string, payload: unknown): CommandEnvelope {
  251. return {
  252. type: "switchCollaborationMode",
  253. payload,
  254. sessionId,
  255. commandId: "cmd-mode-1",
  256. baseRevision: 0,
  257. } as unknown as CommandEnvelope;
  258. }
  259. it("正路径:setMode 内部统一更新状态和事件,命令层不重复补发", async () => {
  260. const app = makeApp();
  261. const record = makeRecord(app);
  262. await new V4CommandExecutor(makeHost(record)).execute(modeEnvelope("s1", { mode: "plan" }));
  263. expect(app.calls).toEqual(["getMode", "setMode"]);
  264. expect(app.setMode).toHaveBeenCalledWith("plan");
  265. expect(app.runtime.emitModeChanged).not.toHaveBeenCalled();
  266. });
  267. // R-19:同值切换从静默 return(被当 accepted)改为显式 noop——旧行为与投影种子缺失
  268. // 叠加成过「点完全访问没反应」的用户可见 bug(runtime 已是 yolo、投影种子还是 build)。
  269. it("同值切换:抛 V4CommandNoopError(config.unchanged)——不调 setMode、不补发事件(不 bump revision)", async () => {
  270. const app = makeApp();
  271. const record = makeRecord(app);
  272. await expect(
  273. new V4CommandExecutor(makeHost(record)).execute(modeEnvelope("s1", { mode: "build" })),
  274. ).rejects.toThrow(V4CommandNoopError);
  275. expect(app.setMode).not.toHaveBeenCalled();
  276. expect(app.runtime.emitModeChanged).not.toHaveBeenCalled();
  277. });
  278. it("session 不存在:拒绝且不触碰任何 core 方法", async () => {
  279. const app = makeApp();
  280. const record = makeRecord(app);
  281. await expect(
  282. new V4CommandExecutor(makeHost(record)).execute(modeEnvelope("missing", { mode: "plan" })),
  283. ).rejects.toThrow(V4SessionNotFoundError);
  284. expect(app.setMode).not.toHaveBeenCalled();
  285. });
  286. it("supports 分流:switchCollaborationMode 已原生", () => {
  287. const executor = new V4CommandExecutor(makeHost(makeRecord(makeApp())));
  288. expect(executor.supports("switchCollaborationMode")).toBe(true);
  289. });
  290. });
  291. // R-19:createSession.config 消费共用件——请求 config 覆盖 runtime 缺省,
  292. // 只对差异部分生效并补发与 switch 命令同源的事件(日志自足)。
  293. describe("切模型前校验当前 Environment Provider", () => {
  294. function makeResolvingHost(
  295. record: V4SessionRecordView,
  296. outcome: { available: boolean; reason?: string },
  297. captured: string[],
  298. ): V4CommandCoreHost {
  299. return {
  300. getRecord: (id) => (id === "s1" ? record : undefined),
  301. ensureProviderAvailable: async (_sessionId, providerId) => {
  302. captured.push(providerId);
  303. return outcome;
  304. },
  305. };
  306. }
  307. it("provider 已在 registry:setModel 之前解析放行,跨 provider 切换生效", async () => {
  308. const app = makeApp();
  309. const record = makeRecord(app);
  310. const captured: string[] = [];
  311. await new V4CommandExecutor(makeResolvingHost(record, { available: true }, captured)).execute(
  312. envelope("s1", { provider: "prov-b", model: "new-model", thought: "" }),
  313. );
  314. expect(captured).toEqual(["prov-b"]);
  315. expect(app.setModel).toHaveBeenCalledWith({
  316. providerId: "prov-b",
  317. modelId: "new-model",
  318. options: { reasoningLevel: "high" },
  319. });
  320. expect(app.runtime.emitModelSelected).toHaveBeenCalled();
  321. });
  322. it("provider 不在 registry(applied:false):failed reasonCode=provider.notInRegistry,不切模型/不补发", async () => {
  323. const app = makeApp();
  324. const record = makeRecord(app);
  325. const captured: string[] = [];
  326. await expect(
  327. new V4CommandExecutor(
  328. makeResolvingHost(
  329. record,
  330. { available: false, reason: "provider_not_in_registry" },
  331. captured,
  332. ),
  333. ).execute(envelope("s1", { provider: "prov-x", model: "m", thought: "" })),
  334. ).rejects.toMatchObject({ reasonCode: "provider.notInRegistry" });
  335. expect(app.setModel).not.toHaveBeenCalled();
  336. expect(app.runtime.emitModelSelected).not.toHaveBeenCalled();
  337. });
  338. });
  339. describe("applyRequestedSessionConfig(createSession.config 消费)", () => {
  340. it("模型差异:setModel → setThoughtLevel → emitModelSelected(previous 保真)", async () => {
  341. const app = makeApp();
  342. app.setModel.mockImplementationOnce(async () => {
  343. app.calls.push("setModel");
  344. return { thoughtLevel: "medium" };
  345. });
  346. const record = makeRecord(app);
  347. await applyRequestedSessionConfig(makeHost(record), record, {
  348. provider: "prov-b",
  349. model: "new-model",
  350. thought: "high",
  351. });
  352. expect(app.setModel).toHaveBeenCalledWith("prov-b/new-model");
  353. expect(app.setThoughtLevel).toHaveBeenCalledWith("high");
  354. expect(app.runtime.emitModelSelected).toHaveBeenCalledWith({
  355. modelSelection: {
  356. providerId: "prov-b",
  357. modelId: "new-model",
  358. options: { reasoningLevel: "high" },
  359. },
  360. effectiveReasoningLevel: "high",
  361. previousModelSelection: PREVIOUS_SELECTION,
  362. supportedThoughtLevels: SUPPORTED_THOUGHT_LEVELS,
  363. traceContext: TRACE,
  364. });
  365. });
  366. it("模型差异且 thought 不受目标支持:保留 setModel 实际档位并照常发布目标模型", async () => {
  367. const app = makeApp();
  368. app.setModel.mockImplementationOnce(async () => {
  369. app.calls.push("setModel");
  370. return { thoughtLevel: "max" };
  371. });
  372. const record = makeRecord(app);
  373. await applyRequestedSessionConfig(makeHost(record), record, {
  374. provider: "default-deepseek",
  375. model: "deepseek-v4-flash",
  376. thought: "enabled",
  377. });
  378. expect(app.setThoughtLevel).not.toHaveBeenCalled();
  379. expect(app.runtime.emitModelSelected).toHaveBeenCalledWith({
  380. modelSelection: {
  381. providerId: "default-deepseek",
  382. modelId: "deepseek-v4-flash",
  383. },
  384. effectiveReasoningLevel: "max",
  385. previousModelSelection: PREVIOUS_SELECTION,
  386. supportedThoughtLevels: SUPPORTED_THOUGHT_LEVELS,
  387. traceContext: TRACE,
  388. });
  389. });
  390. it("部分字段(只给 thought):provider/model 回落 runtime 当前值", async () => {
  391. const app = makeApp();
  392. const record = makeRecord(app);
  393. await applyRequestedSessionConfig(makeHost(record), record, { thought: "max" });
  394. expect(app.setModel).not.toHaveBeenCalled();
  395. expect(app.setThoughtLevel).toHaveBeenCalledWith("max");
  396. expect(app.runtime.emitModelSelected).toHaveBeenCalledWith({
  397. modelSelection: {
  398. providerId: "prov-a",
  399. modelId: "old-model",
  400. options: { reasoningLevel: "max" },
  401. },
  402. effectiveReasoningLevel: "max",
  403. previousModelSelection: PREVIOUS_SELECTION,
  404. supportedThoughtLevels: SUPPORTED_THOUGHT_LEVELS,
  405. traceContext: TRACE,
  406. });
  407. });
  408. it("与 runtime 全同值:零调用零事件(不产空转 delta)", async () => {
  409. const app = makeApp();
  410. const record = makeRecord(app);
  411. await applyRequestedSessionConfig(makeHost(record), record, {
  412. provider: "prov-a",
  413. model: "old-model",
  414. thought: "",
  415. mode: "build",
  416. followupMode: "queue",
  417. });
  418. expect(app.setModel).not.toHaveBeenCalled();
  419. expect(app.setMode).not.toHaveBeenCalled();
  420. expect(app.setFollowupMode).not.toHaveBeenCalled();
  421. expect(app.runtime.emitModelSelected).not.toHaveBeenCalled();
  422. expect(app.runtime.emitModeChanged).not.toHaveBeenCalled();
  423. });
  424. it("mode 差异由 Runtime 原子更新;非法 mode 值被值域收口忽略", async () => {
  425. const app = makeApp();
  426. const record = makeRecord(app);
  427. await applyRequestedSessionConfig(makeHost(record), record, { mode: "yolo" });
  428. expect(app.runtime.setExecutionState).toHaveBeenCalledWith({ mode: "yolo" }, TRACE);
  429. expect(app.runtime.emitModeChanged).not.toHaveBeenCalled();
  430. const app2 = makeApp();
  431. const record2 = makeRecord(app2);
  432. await applyRequestedSessionConfig(makeHost(record2), record2, { mode: "auto" });
  433. expect(app2.setMode).not.toHaveBeenCalled();
  434. expect(app2.runtime.emitModeChanged).not.toHaveBeenCalled();
  435. });
  436. it("followupMode=guide 显式写;queue(缺省同值)跳过避免空转事件", async () => {
  437. const app = makeApp();
  438. const record = makeRecord(app);
  439. await applyRequestedSessionConfig(makeHost(record), record, { followupMode: "guide" });
  440. expect(app.setFollowupMode).toHaveBeenCalledWith("guide");
  441. });
  442. });