registry.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. ModelConfig,
  4. ModelOptionSpecsConfig,
  5. ModelPropertiesConfig,
  6. ProviderRegistry,
  7. type ModelSelection,
  8. type Provider,
  9. } from "../src/index.js";
  10. import { createApiKeyProviderConfig } from "./provider-config-fixtures.js";
  11. import { resolveEffectiveModelSelection } from "../src/effective-model-selection.js";
  12. function provider(
  13. providerId: string,
  14. modelId: string,
  15. reasoningValues: readonly string[] = ["low", "high"],
  16. ): Provider {
  17. return {
  18. providerId,
  19. config: createApiKeyProviderConfig({
  20. apiFormat: "anthropic-messages",
  21. baseURL: "https://api.example.com",
  22. apiKey: "test-key",
  23. models: [modelId],
  24. }),
  25. models: [
  26. {
  27. modelId,
  28. config: new ModelConfig({
  29. properties: new ModelPropertiesConfig({
  30. requiresMfjsToolSchema: false,
  31. contextWindow: 200_000,
  32. inputFormat: {
  33. supportsText: true,
  34. supportsImage: false,
  35. supportsVideo: false,
  36. supportsAudio: false,
  37. supportsPdf: false,
  38. },
  39. outputFormat: { supportsText: true },
  40. supportsToolCall: true,
  41. supportsJsonSchemaOutput: true,
  42. supportsNativeWebSearch: false,
  43. supportsMidConversationSystem: false,
  44. }),
  45. optionSpecs: new ModelOptionSpecsConfig({
  46. reasoningLevel: {
  47. values: reasoningValues,
  48. map:
  49. reasoningValues.length === 1 && reasoningValues[0] === "disabled"
  50. ? "{}"
  51. : "{'thinking': {'effort': value}}",
  52. },
  53. maxOutputTokens: {
  54. max: 32_000,
  55. map: "{'max_tokens': maxOutputTokens}",
  56. },
  57. }),
  58. }),
  59. },
  60. ],
  61. };
  62. }
  63. describe("当前有效选择只读解析", () => {
  64. const classifyProvider = (id: string) =>
  65. ["old-account", "new-account"].includes(id)
  66. ? ("account-plan" as const)
  67. : id === "idle"
  68. ? ("account-offpeak" as const)
  69. : ("ordinary" as const);
  70. const original = Object.freeze({
  71. providerId: "old-account",
  72. modelId: "same",
  73. options: Object.freeze({ reasoningLevel: "high" }),
  74. });
  75. const resolve = (
  76. providers: Provider[],
  77. selection: ModelSelection = original,
  78. current = "new-account",
  79. ) =>
  80. resolveEffectiveModelSelection({
  81. registry: { revision: 1, providers },
  82. selection,
  83. classifyProvider,
  84. accountStates: { [current]: { availability: "available", entitled: true, current: true } },
  85. });
  86. it("即使旧账号仍在候选中,也按当前账号保留同模型同档位;原意图不改", () => {
  87. const result = resolve([provider("old-account", "same"), provider("new-account", "same")]);
  88. expect(result).toEqual({ effectiveSelection: { ...original, providerId: "new-account" } });
  89. expect(original.providerId).toBe("old-account");
  90. expect(result.effectiveSelection?.options).not.toBe(original.options);
  91. });
  92. it("只缺档位时保留模型,不按位置或最高值替换", () => {
  93. expect(resolve([provider("new-account", "same", ["low", "max"])])).toEqual({
  94. effectiveSelection: { providerId: "new-account", modelId: "same" },
  95. selectionIssue: "reasoning-level-not-supported",
  96. });
  97. });
  98. it("缺同模型时留空,不找首模型、不归一大小写", () => {
  99. expect(resolve([provider("new-account", "SAME")])).toEqual({
  100. effectiveSelection: null,
  101. selectionIssue: "model-not-found",
  102. });
  103. });
  104. it("普通供应商不会因账号切换而替换", () => {
  105. const selection = { ...original, providerId: "personal" };
  106. expect(
  107. resolve([provider("personal", "same"), provider("new-account", "same")], selection),
  108. ).toEqual({ effectiveSelection: selection });
  109. });
  110. it("暂时缺模型再恢复时始终从原意图重算", () => {
  111. expect(resolve([]).effectiveSelection).toBeNull();
  112. expect(resolve([provider("new-account", "same")]).effectiveSelection?.options).toEqual(
  113. original.options,
  114. );
  115. });
  116. it("原意图为空不采用其他模型,未知账号 ID 不猜成正式账号", () => {
  117. const registry = { revision: 1, providers: [provider("new-account", "same")] };
  118. expect(resolveEffectiveModelSelection({ registry, selection: null, classifyProvider })).toEqual(
  119. { effectiveSelection: null, selectionIssue: "selection-missing" },
  120. );
  121. expect(resolve(registry.providers, { ...original, providerId: "account:not-formal" })).toEqual({
  122. effectiveSelection: null,
  123. selectionIssue: "provider-not-found",
  124. });
  125. });
  126. it("当前账号不唯一时不任选一个", () => {
  127. expect(
  128. resolveEffectiveModelSelection({
  129. registry: {
  130. revision: 1,
  131. providers: [provider("old-account", "same"), provider("new-account", "same")],
  132. },
  133. selection: original,
  134. classifyProvider,
  135. accountStates: {
  136. "old-account": { availability: "available", entitled: true, current: true },
  137. "new-account": { availability: "available", entitled: true, current: true },
  138. },
  139. }),
  140. ).toEqual({ effectiveSelection: null, selectionIssue: "account-connection-unavailable" });
  141. });
  142. it("闲时只能解析原 hidden 身份,不切到当前普通账号;普通 hidden 仍不可选", () => {
  143. const hidden = {
  144. ...provider("idle", "same"),
  145. config: createApiKeyProviderConfig({ visibility: "hidden" }),
  146. };
  147. const selection = { ...original, providerId: "idle" };
  148. expect(
  149. resolve([hidden, provider("new-account", "same")], selection).effectiveSelection,
  150. ).toEqual(selection);
  151. expect(resolve([provider("new-account", "same")], selection).effectiveSelection).toBeNull();
  152. expect(
  153. resolve([{ ...hidden, providerId: "personal" }], { ...original, providerId: "personal" })
  154. .effectiveSelection,
  155. ).toBeNull();
  156. });
  157. });
  158. describe("ProviderRegistry", () => {
  159. it("初始与替换快照保留 Provider 元数据,后续改名或清除不污染旧快照", () => {
  160. const original = { ...provider("A", "a"), providerName: "Original", templateId: "template-a" };
  161. const registry = new ProviderRegistry([original]);
  162. const oldView = registry.getView();
  163. expect(registry.getProvider("A")).toMatchObject({
  164. providerName: "Original",
  165. templateId: "template-a",
  166. });
  167. registry.replace(
  168. [{ ...original, providerName: "Renamed", templateId: "template-b" }],
  169. "rename",
  170. );
  171. expect(registry.getView().providers[0]).toMatchObject({
  172. providerName: "Renamed",
  173. templateId: "template-b",
  174. });
  175. expect(oldView.providers[0]).toMatchObject({
  176. providerName: "Original",
  177. templateId: "template-a",
  178. });
  179. expect(Object.isFrozen(oldView.providers[0])).toBe(true);
  180. registry.replace([provider("A", "a")], "clear-metadata");
  181. expect(registry.getProvider("A")?.providerName).toBeUndefined();
  182. expect(registry.getProvider("A")?.templateId).toBeUndefined();
  183. expect(
  184. registry.validateSelection({
  185. providerId: "A",
  186. modelId: "a",
  187. options: { reasoningLevel: "high" },
  188. }),
  189. ).toEqual({ ok: true });
  190. });
  191. it("旧关闭值只在意图解析中迁移,精确执行校验不能接受别名", () => {
  192. const registry = new ProviderRegistry([provider("A", "a", ["disabled", "enabled"])]);
  193. const original = { providerId: "A", modelId: "a", options: { reasoningLevel: "off" } };
  194. const resolved = resolveEffectiveModelSelection({
  195. selection: original,
  196. registry: registry.getView(),
  197. classifyProvider: () => "ordinary",
  198. resolveLegacyReasoningLevel: () => "disabled",
  199. });
  200. expect(resolved.effectiveSelection?.options?.reasoningLevel).toBe("disabled");
  201. expect(registry.validateSelection(original).ok).toBe(false);
  202. expect(registry.validateSelection(resolved.effectiveSelection!).ok).toBe(true);
  203. const unsupported = resolveEffectiveModelSelection({
  204. selection: original,
  205. registry: registry.getView(),
  206. classifyProvider: () => "ordinary",
  207. resolveLegacyReasoningLevel: () => "unsupported",
  208. });
  209. expect(unsupported.selectionIssue).toBe("reasoning-level-not-supported");
  210. });
  211. it("原子替换有序 View、索引和 revision,并让旧快照保持不变", () => {
  212. const registry = new ProviderRegistry([provider("A", "a")]);
  213. const oldView = registry.getView();
  214. const listener = vi.fn();
  215. const dispose = registry.onDidChange(listener);
  216. registry.replace([provider("B", "b"), provider("A", "a2")], "config-updated");
  217. expect(oldView.providers.map((item) => item.providerId)).toEqual(["A"]);
  218. expect(registry.getView().providers.map((item) => item.providerId)).toEqual(["B", "A"]);
  219. expect(registry.getProvider("B")?.models[0]?.modelId).toBe("b");
  220. expect(registry.getModel("A", "a2")?.modelId).toBe("a2");
  221. expect(registry.getView().revision).toBe(oldView.revision + 1);
  222. expect(listener).toHaveBeenCalledWith({
  223. revision: oldView.revision + 1,
  224. reason: "config-updated",
  225. });
  226. dispose();
  227. });
  228. it("返回稳定的 ModelSelection 校验结果", () => {
  229. const registry = new ProviderRegistry([provider("A", "a")]);
  230. expect(registry.validateSelection({ providerId: "A", modelId: "a" })).toEqual({
  231. ok: false,
  232. code: "reasoning-level-missing",
  233. providerId: "A",
  234. modelId: "a",
  235. });
  236. expect(registry.validateSelection({ providerId: "missing", modelId: "a" })).toEqual({
  237. ok: false,
  238. code: "provider-not-found",
  239. providerId: "missing",
  240. });
  241. expect(registry.validateSelection({ providerId: "A", modelId: "missing" })).toEqual({
  242. ok: false,
  243. code: "model-not-found",
  244. providerId: "A",
  245. modelId: "missing",
  246. });
  247. expect(
  248. registry.validateSelection({
  249. providerId: "A",
  250. modelId: "a",
  251. options: { reasoningLevel: "low" },
  252. }),
  253. ).toEqual({ ok: true });
  254. expect(
  255. registry.validateSelection({
  256. providerId: "A",
  257. modelId: "a",
  258. options: { reasoningLevel: "max" },
  259. }),
  260. ).toEqual({
  261. ok: false,
  262. code: "reasoning-level-not-supported",
  263. providerId: "A",
  264. modelId: "a",
  265. reasoningLevel: "max",
  266. supportedLevels: ["low", "high"],
  267. });
  268. expect(
  269. new ProviderRegistry([provider("B", "b", ["disabled"])]).validateSelection({
  270. providerId: "B",
  271. modelId: "b",
  272. options: { reasoningLevel: "high" },
  273. }),
  274. ).toEqual({
  275. ok: false,
  276. code: "reasoning-level-not-supported",
  277. providerId: "B",
  278. modelId: "b",
  279. reasoningLevel: "high",
  280. supportedLevels: ["disabled"],
  281. });
  282. });
  283. });