service.test.ts 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612
  1. import { mkdtemp, rm } from 'node:fs/promises';
  2. import { tmpdir } from 'node:os';
  3. import { join } from 'node:path';
  4. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
  5. import type {
  6. LocalByokConfigDraft,
  7. LocalRuntimeConfig,
  8. ModelConnectionTestResult,
  9. ModelConnectionTestTarget,
  10. ModelDiscoveryResult,
  11. ModelDiscoveryTarget,
  12. } from '../contracts.js';
  13. import { planCustomProviderResolution } from '../resolution/model-resolver-byok.js';
  14. import { LocalModelCache } from '../catalog/model-cache.js';
  15. import { MINIMAX_API_DEFAULT_BASE_URL, minimaxApiModels } from '../catalog/minimax-api.js';
  16. import { listLocalRuntimeModels } from '../catalog/catalog.js';
  17. import { LocalModelProviderError, LocalModelProviderService } from './service.js';
  18. const RAW_KEY = 'sk-user-minimax-key-12345678';
  19. const CUSTOM_KEY = 'sk-custom-key-abcdefgh';
  20. let dataDir: string;
  21. interface Harness {
  22. service: LocalModelProviderService;
  23. config: LocalRuntimeConfig;
  24. cache: LocalModelCache;
  25. selectModel: ReturnType<typeof vi.fn>;
  26. testCalls: Array<{ key: string; target: ModelConnectionTestTarget }>;
  27. discoverCalls: ModelDiscoveryTarget[];
  28. setTestResult(result: ModelConnectionTestResult): void;
  29. setTestHandler(
  30. handler: (key: string, target: ModelConnectionTestTarget) => Promise<ModelConnectionTestResult>,
  31. ): void;
  32. setDiscoverResult(result: ModelDiscoveryResult): void;
  33. failNextConfigWrite(error: Error): void;
  34. setNextRawCustomProviders(raw: Record<string, unknown> | undefined): void;
  35. }
  36. function makeHarness(
  37. initial?: Partial<LocalRuntimeConfig>,
  38. options: { implicitCustomProviderThinking?: boolean } = {},
  39. ): Harness {
  40. const config: LocalRuntimeConfig = {
  41. dataDir,
  42. provider: {
  43. minimax: {
  44. options: { authMode: 'managed-login', baseURL: 'https://managed.example/v1' },
  45. models: {
  46. 'MiniMax-M3': {
  47. name: 'MiniMax M3',
  48. limit: { context: 200_000, output: 32_000 },
  49. contextWindowOptions: [512_000, 1_000_000],
  50. },
  51. 'MiniMax-M2.5': { name: 'MiniMax M2.5' },
  52. },
  53. },
  54. },
  55. defaultModel: 'minimax/MiniMax-M3',
  56. ...initial,
  57. };
  58. let testResult: ModelConnectionTestResult = { ok: true };
  59. let testHandler:
  60. | ((key: string, target: ModelConnectionTestTarget) => Promise<ModelConnectionTestResult>)
  61. | undefined;
  62. let configWriteError: Error | undefined;
  63. let discoverResult: ModelDiscoveryResult = { ok: true, models: [] };
  64. let nextRawCustomProviders: Record<string, unknown> | undefined;
  65. const testCalls: Array<{ key: string; target: ModelConnectionTestTarget }> = [];
  66. const discoverCalls: ModelDiscoveryTarget[] = [];
  67. let configUpdateTail = Promise.resolve();
  68. const selectModel = vi.fn(async (modelKey: string) => {
  69. config.defaultModel = modelKey;
  70. });
  71. const cache = new LocalModelCache(() => dataDir);
  72. const service = new LocalModelProviderService({
  73. configGetter: () => config,
  74. updateByokConfig: (mutate) => {
  75. const update = configUpdateTail.then(async () => {
  76. const draft: LocalByokConfigDraft = {
  77. minimax_api: config.minimax_api ? { ...config.minimax_api } : undefined,
  78. custom_provider: nextRawCustomProviders
  79. ? (JSON.parse(JSON.stringify(nextRawCustomProviders)) as Record<string, unknown>)
  80. : config.custom_provider
  81. ? (JSON.parse(JSON.stringify(config.custom_provider)) as Record<string, unknown>)
  82. : undefined,
  83. minimaxModelSource: config.minimaxModelSource,
  84. defaultModel: config.defaultModel,
  85. defaultModelVariant: config.defaultModelVariant,
  86. };
  87. await mutate(draft, config);
  88. nextRawCustomProviders = undefined;
  89. if (configWriteError) {
  90. const error = configWriteError;
  91. configWriteError = undefined;
  92. throw error;
  93. }
  94. config.minimax_api = draft.minimax_api as LocalRuntimeConfig['minimax_api'];
  95. config.custom_provider = draft.custom_provider as LocalRuntimeConfig['custom_provider'];
  96. config.minimaxModelSource = draft.minimaxModelSource;
  97. config.defaultModel = draft.defaultModel;
  98. config.defaultModelVariant = draft.defaultModelVariant;
  99. return { config };
  100. });
  101. configUpdateTail = update.then(
  102. () => undefined,
  103. () => undefined,
  104. );
  105. return update;
  106. },
  107. cache,
  108. tester: {
  109. test: async (key, target) => {
  110. testCalls.push({ key, target });
  111. if (testHandler) return testHandler(key, target);
  112. return testResult;
  113. },
  114. },
  115. discoverer: {
  116. discover: async (target) => {
  117. discoverCalls.push(target);
  118. return discoverResult;
  119. },
  120. },
  121. compareAndSetModelContext: (input, beforeCommit) => {
  122. const update = configUpdateTail.then(async () => {
  123. const model =
  124. input.providerId === 'minimax_api'
  125. ? minimaxApiModels(config)[input.modelId]
  126. : config.provider?.[input.providerId]?.models?.[input.modelId];
  127. if (model?.limit?.context !== input.expectedContextLimit) return false;
  128. if (!(await beforeCommit(config))) return false;
  129. if (configWriteError) {
  130. const error = configWriteError;
  131. configWriteError = undefined;
  132. throw error;
  133. }
  134. if (input.providerId === 'minimax_api') {
  135. config.minimax_api = {
  136. ...(config.minimax_api ?? {}),
  137. modelContextLimits: {
  138. ...(config.minimax_api?.modelContextLimits ?? {}),
  139. [input.modelId]: input.contextLimit,
  140. },
  141. };
  142. } else {
  143. model.limit = { ...model.limit, context: input.contextLimit };
  144. }
  145. return true;
  146. });
  147. configUpdateTail = update.then(
  148. () => undefined,
  149. () => undefined,
  150. );
  151. return update;
  152. },
  153. selectModel,
  154. ...options,
  155. now: () => 1_750_000_000_000,
  156. randomHex: () => 'a1b2c3',
  157. });
  158. return {
  159. service,
  160. config,
  161. cache,
  162. selectModel,
  163. testCalls,
  164. discoverCalls,
  165. setTestResult: (result) => {
  166. testResult = result;
  167. },
  168. setTestHandler: (handler) => {
  169. testHandler = handler;
  170. },
  171. setDiscoverResult: (result) => {
  172. discoverResult = result;
  173. },
  174. failNextConfigWrite: (error) => {
  175. configWriteError = error;
  176. },
  177. setNextRawCustomProviders: (raw) => {
  178. nextRawCustomProviders = raw;
  179. },
  180. };
  181. }
  182. beforeEach(async () => {
  183. dataDir = await mkdtemp(join(tmpdir(), 'model-provider-service-'));
  184. });
  185. afterEach(async () => {
  186. await rm(dataDir, { recursive: true, force: true });
  187. });
  188. describe('MiniMax api key', () => {
  189. it('reports no key before upsert and a masked key after', async () => {
  190. const h = makeHarness();
  191. expect(h.service.getMinimaxApiKeyStatus()).toEqual({ hasApiKey: false });
  192. await h.service.upsertMinimaxApiKey({ apiKey: RAW_KEY });
  193. const status = h.service.getMinimaxApiKeyStatus();
  194. expect(status.hasApiKey).toBe(true);
  195. expect(status.maskedApiKey).toBe(`${RAW_KEY.slice(0, 4)}****${RAW_KEY.slice(-4)}`);
  196. expect(status.maskedApiKey).not.toBe(RAW_KEY);
  197. expect(h.config.minimax_api?.apiKey).toBe(RAW_KEY);
  198. });
  199. it('keeps the BYOK catalog independent when the managed snapshot only has other models', async () => {
  200. const h = makeHarness({
  201. provider: {
  202. minimax: {
  203. models: {
  204. 'Remote-B': { name: 'Remote B' },
  205. 'Remote-C': { name: 'Remote C' },
  206. },
  207. },
  208. },
  209. });
  210. const provider = await h.service.upsertMinimaxApiKey({ apiKey: RAW_KEY });
  211. expect(provider.models.map((model) => model.modelId)).toContain('MiniMax-M3');
  212. expect(provider.models.map((model) => model.modelId)).not.toContain('Remote-B');
  213. });
  214. it('rejects empty, whitespace-only, and masked placeholder keys', async () => {
  215. const h = makeHarness();
  216. for (const bad of ['', ' ', 'sk-u****5678', '****']) {
  217. await expect(h.service.upsertMinimaxApiKey({ apiKey: bad })).rejects.toBeInstanceOf(
  218. LocalModelProviderError,
  219. );
  220. }
  221. expect(h.config.minimax_api).toBeUndefined();
  222. });
  223. it('upsert preserves an existing baseURL override and never writes one', async () => {
  224. const h = makeHarness({ minimax_api: { apiKey: 'sk-old', baseURL: 'https://custom.example' } });
  225. await h.service.upsertMinimaxApiKey({ apiKey: RAW_KEY });
  226. expect(h.config.minimax_api).toEqual({ apiKey: RAW_KEY, baseURL: 'https://custom.example' });
  227. const h2 = makeHarness();
  228. await h2.service.upsertMinimaxApiKey({ apiKey: RAW_KEY });
  229. expect(h2.config.minimax_api).toEqual({ apiKey: RAW_KEY });
  230. });
  231. it('save_and_use sets minimaxModelSource without calling selectModel', async () => {
  232. const h = makeHarness();
  233. await h.service.upsertMinimaxApiKey({ apiKey: RAW_KEY, saveAndUse: true });
  234. expect(h.selectModel).not.toHaveBeenCalled();
  235. expect(h.testCalls).toEqual([]);
  236. expect(h.config.minimax_api?.apiKey).toBe(RAW_KEY);
  237. expect(h.config.minimaxModelSource).toBe('minimax_api_key');
  238. });
  239. it('save_and_use sets minimaxModelSource when default model is unknown', async () => {
  240. const h = makeHarness({ defaultModel: 'other/unknown-model' });
  241. await h.service.upsertMinimaxApiKey({ apiKey: RAW_KEY, saveAndUse: true });
  242. expect(h.selectModel).not.toHaveBeenCalled();
  243. expect(h.config.minimaxModelSource).toBe('minimax_api_key');
  244. });
  245. it('switches to the MiniMax API source without a prior connection test', async () => {
  246. const h = makeHarness();
  247. await h.service.upsertMinimaxApiKey({ apiKey: RAW_KEY });
  248. await expect(h.service.setMinimaxModelSource('minimax_api_key')).resolves.toBe(
  249. 'minimax_api_key',
  250. );
  251. expect(h.testCalls).toEqual([]);
  252. expect(h.config.minimaxModelSource).toBe('minimax_api_key');
  253. expect(() => h.service.assertModelSelectable('minimax', 'MiniMax-M3')).not.toThrow();
  254. const m3 = h.config.provider?.minimax?.models?.['MiniMax-M3'];
  255. if (!m3?.limit) throw new Error('invalid MiniMax-M3 test fixture');
  256. m3.limit.context = 1_000_000;
  257. expect(() => h.service.assertModelSelectable('minimax', 'MiniMax-M3')).not.toThrow();
  258. });
  259. it('switches to the MiniMax API source after a failed connection test', async () => {
  260. const h = makeHarness();
  261. h.setTestResult({
  262. ok: false,
  263. errorCode: 'UPSTREAM_REJECTED',
  264. errorMessage: 'provider rejected the test request',
  265. });
  266. await h.service.upsertMinimaxApiKey({ apiKey: RAW_KEY });
  267. await h.service.testProvider('minimax_api');
  268. await expect(h.service.setMinimaxModelSource('minimax_api_key')).resolves.toBe(
  269. 'minimax_api_key',
  270. );
  271. expect(h.config.minimaxModelSource).toBe('minimax_api_key');
  272. });
  273. it('still requires a saved key before switching to the MiniMax API source', async () => {
  274. const h = makeHarness();
  275. await expect(h.service.setMinimaxModelSource('minimax_api_key')).rejects.toMatchObject({
  276. code: 'NO_API_KEY',
  277. });
  278. expect(h.config.minimaxModelSource).toBeUndefined();
  279. });
  280. it('allows selecting a configured custom model without a prior connectivity test', () => {
  281. const h = makeHarness({
  282. custom_provider: {
  283. work: {
  284. enabled: true,
  285. api: 'openai-completions',
  286. options: { apiKey: CUSTOM_KEY, baseURL: 'https://saved.example/v1' },
  287. models: {
  288. 'm-1': { limit: { context: 128_000, output: 16_000 } },
  289. },
  290. },
  291. },
  292. });
  293. expect(h.cache.load().model_status).toEqual({});
  294. expect(h.testCalls).toEqual([]);
  295. expect(() => h.service.assertModelSelectable('custom_provider:work', 'm-1')).not.toThrow();
  296. });
  297. it('allows selecting a login-backed custom model without an API key', () => {
  298. const h = makeHarness({
  299. custom_provider: {
  300. login: {
  301. kind: 'oauth',
  302. enabled: true,
  303. models: {
  304. 'm-1': { limit: { context: 128_000, output: 16_000 } },
  305. },
  306. },
  307. },
  308. });
  309. expect(() => h.service.assertModelSelectable('custom_provider:login', 'm-1')).not.toThrow();
  310. expect(h.testCalls).toEqual([]);
  311. });
  312. it('allows selecting a configured custom model with a failed cached connectivity status', async () => {
  313. const h = makeHarness({
  314. custom_provider: {
  315. work: {
  316. enabled: true,
  317. api: 'openai-completions',
  318. options: { apiKey: CUSTOM_KEY, baseURL: 'https://saved.example/v1' },
  319. models: {
  320. 'm-1': { limit: { context: 128_000, output: 16_000 } },
  321. },
  322. },
  323. },
  324. });
  325. h.setTestResult({
  326. ok: false,
  327. errorCode: 'UPSTREAM_REJECTED',
  328. errorMessage: 'provider rejected the test request',
  329. });
  330. await expect(h.service.testModel('custom_provider:work', 'm-1')).resolves.toMatchObject({
  331. ok: false,
  332. status: { state: 'failed' },
  333. });
  334. expect(h.cache.load().model_status['custom_provider:work/m-1']).toMatchObject({
  335. state: 'failed',
  336. });
  337. expect(() => h.service.assertModelSelectable('custom_provider:work', 'm-1')).not.toThrow();
  338. });
  339. it('still rejects selecting a custom model with incomplete or unavailable configuration', () => {
  340. const missingKey = makeHarness({
  341. custom_provider: {
  342. work: {
  343. enabled: true,
  344. api: 'openai-completions',
  345. options: { baseURL: 'https://saved.example/v1' },
  346. models: {
  347. 'm-1': { limit: { context: 128_000, output: 16_000 } },
  348. },
  349. },
  350. },
  351. });
  352. expect(() =>
  353. missingKey.service.assertModelSelectable('custom_provider:work', 'm-1'),
  354. ).toThrowError(expect.objectContaining({ code: 'NO_API_KEY' }));
  355. const missingBaseUrl = makeHarness({
  356. custom_provider: {
  357. work: {
  358. enabled: true,
  359. api: 'openai-completions',
  360. options: { apiKey: CUSTOM_KEY },
  361. models: {
  362. 'm-1': { limit: { context: 128_000, output: 16_000 } },
  363. },
  364. },
  365. },
  366. });
  367. expect(() =>
  368. missingBaseUrl.service.assertModelSelectable('custom_provider:work', 'm-1'),
  369. ).toThrowError(expect.objectContaining({ code: 'NO_BASE_URL' }));
  370. const missingModel = makeHarness({
  371. custom_provider: {
  372. work: {
  373. enabled: true,
  374. api: 'openai-completions',
  375. options: { apiKey: CUSTOM_KEY, baseURL: 'https://saved.example/v1' },
  376. models: {
  377. 'other-model': { limit: { context: 128_000, output: 16_000 } },
  378. },
  379. },
  380. },
  381. });
  382. expect(() =>
  383. missingModel.service.assertModelSelectable('custom_provider:work', 'm-1'),
  384. ).toThrowError(expect.objectContaining({ code: 'MODEL_NOT_FOUND' }));
  385. });
  386. });
  387. describe('MiniMax model context', () => {
  388. it('updates a managed model using its current dynamic context options', async () => {
  389. const h = makeHarness({
  390. minimaxModelSource: 'token_plan',
  391. provider: {
  392. minimax: {
  393. models: {
  394. 'MiniMax-M4': {
  395. name: 'MiniMax M4',
  396. limit: { context: 256_000, output: 64_000 },
  397. contextWindowOptions: [256_000, 768_000],
  398. },
  399. },
  400. },
  401. },
  402. });
  403. await expect(
  404. h.service.updateMinimaxModelContext({
  405. modelId: 'MiniMax-M4',
  406. contextLimit: 768_000,
  407. expectedContextLimit: 256_000,
  408. }),
  409. ).resolves.toEqual({ ok: true });
  410. expect(h.config.provider.minimax?.models?.['MiniMax-M4']?.limit?.context).toBe(768_000);
  411. });
  412. it('tests a Paygo M3 context candidate before committing config and cache together', async () => {
  413. const h = makeHarness({
  414. minimax_api: { apiKey: RAW_KEY },
  415. minimaxModelSource: 'minimax_api_key',
  416. });
  417. const m3 = h.config.provider.minimax?.models?.['MiniMax-M3'];
  418. if (!m3) throw new Error('missing MiniMax-M3 fixture');
  419. m3.limit = { ...m3.limit, context: 512_000 };
  420. const outcome = await h.service.updateMinimaxModelContext({
  421. modelId: 'MiniMax-M3',
  422. contextLimit: 1_000_000,
  423. expectedContextLimit: 512_000,
  424. });
  425. expect(outcome).toMatchObject({ ok: true, status: { state: 'available' } });
  426. expect(h.testCalls).toHaveLength(1);
  427. expect(h.testCalls[0]?.target).toMatchObject({
  428. api: 'anthropic-messages',
  429. apiKey: RAW_KEY,
  430. modelId: 'MiniMax-M3',
  431. });
  432. expect(m3.limit?.context).toBe(512_000);
  433. expect(h.config.minimax_api?.modelContextLimits).toEqual({ 'MiniMax-M3': 1_000_000 });
  434. expect(minimaxApiModels(h.config)['MiniMax-M3']?.limit?.context).toBe(1_000_000);
  435. h.config.provider.minimax = {
  436. models: { 'Remote-Only-M4': { limit: { context: 256_000 } } },
  437. };
  438. expect(minimaxApiModels(h.config)['MiniMax-M3']?.limit?.context).toBe(1_000_000);
  439. expect(() => h.service.assertModelSelectable('minimax', 'MiniMax-M3')).not.toThrow();
  440. });
  441. it('keeps the current Paygo M3 context and cache when its candidate test fails', async () => {
  442. const h = makeHarness({
  443. minimax_api: { apiKey: RAW_KEY },
  444. minimaxModelSource: 'minimax_api_key',
  445. });
  446. const m3 = h.config.provider.minimax?.models?.['MiniMax-M3'];
  447. if (!m3) throw new Error('missing MiniMax-M3 fixture');
  448. m3.limit = { ...m3.limit, context: 512_000 };
  449. h.setTestResult({ ok: false, errorCode: 'rejected', errorMessage: 'Rejected' });
  450. await expect(
  451. h.service.updateMinimaxModelContext({
  452. modelId: 'MiniMax-M3',
  453. contextLimit: 1_000_000,
  454. expectedContextLimit: 512_000,
  455. }),
  456. ).resolves.toMatchObject({ ok: false, status: { state: 'failed' } });
  457. expect(m3.limit?.context).toBe(512_000);
  458. expect(h.cache.load().model_status['minimax_api/MiniMax-M3']).toBeUndefined();
  459. });
  460. it('ignores an unsupported stored BYOK context and rejects selecting it', async () => {
  461. const h = makeHarness({
  462. minimax_api: {
  463. apiKey: RAW_KEY,
  464. modelContextLimits: { 'MiniMax-M3': 768_000 },
  465. },
  466. minimaxModelSource: 'minimax_api_key',
  467. });
  468. expect(minimaxApiModels(h.config)['MiniMax-M3']?.limit?.context).toBe(512_000);
  469. await expect(
  470. h.service.updateMinimaxModelContext({
  471. modelId: 'MiniMax-M3',
  472. contextLimit: 768_000,
  473. expectedContextLimit: 512_000,
  474. }),
  475. ).rejects.toMatchObject({ code: 'INVALID_CONTEXT_LIMIT', status: 400 });
  476. expect(h.testCalls).toHaveLength(0);
  477. });
  478. });
  479. describe('MiniMax model context transactions', () => {
  480. it.each([
  481. [
  482. 'source',
  483. (h: Harness) => {
  484. h.config.minimaxModelSource = 'token_plan';
  485. },
  486. ],
  487. [
  488. 'api key',
  489. (h: Harness) => {
  490. h.config.minimax_api = { apiKey: 'sk-changed-key' };
  491. },
  492. ],
  493. ])('rejects the M3 commit when the MiniMax %s changes during testing', async (_name, change) => {
  494. const h = makeHarness({
  495. minimax_api: { apiKey: RAW_KEY },
  496. minimaxModelSource: 'minimax_api_key',
  497. });
  498. const m3 = h.config.provider.minimax?.models?.['MiniMax-M3'];
  499. if (!m3) throw new Error('missing MiniMax-M3 fixture');
  500. m3.limit = { ...m3.limit, context: 512_000 };
  501. h.setTestHandler(async () => {
  502. change(h);
  503. return { ok: true };
  504. });
  505. await expect(
  506. h.service.updateMinimaxModelContext({
  507. modelId: 'MiniMax-M3',
  508. contextLimit: 1_000_000,
  509. expectedContextLimit: 512_000,
  510. }),
  511. ).rejects.toMatchObject({ code: 'CONFIG_CHANGED', status: 409 });
  512. expect(m3.limit?.context).toBe(512_000);
  513. expect(h.cache.load().model_status['minimax_api/MiniMax-M3']).toBeUndefined();
  514. });
  515. it('serializes an older MiniMax test ahead of an M3 context transaction', async () => {
  516. const h = makeHarness({
  517. minimax_api: { apiKey: RAW_KEY },
  518. minimaxModelSource: 'minimax_api_key',
  519. });
  520. const m3 = h.config.provider.minimax?.models?.['MiniMax-M3'];
  521. if (!m3) throw new Error('missing MiniMax-M3 fixture');
  522. m3.limit = { ...m3.limit, context: 512_000 };
  523. let releaseFirst: (() => void) | undefined;
  524. const firstBlocked = new Promise<void>((resolve) => {
  525. releaseFirst = resolve;
  526. });
  527. let firstStarted: (() => void) | undefined;
  528. const started = new Promise<void>((resolve) => {
  529. firstStarted = resolve;
  530. });
  531. let calls = 0;
  532. h.setTestHandler(async () => {
  533. calls += 1;
  534. if (calls === 1) {
  535. firstStarted?.();
  536. await firstBlocked;
  537. }
  538. return { ok: true };
  539. });
  540. const olderTest = h.service.testModel('minimax_api', 'MiniMax-M3');
  541. await started;
  542. const contextUpdate = h.service.updateMinimaxModelContext({
  543. modelId: 'MiniMax-M3',
  544. contextLimit: 1_000_000,
  545. expectedContextLimit: 512_000,
  546. });
  547. await Promise.resolve();
  548. expect(calls).toBe(1);
  549. releaseFirst?.();
  550. await expect(Promise.all([olderTest, contextUpdate])).resolves.toMatchObject([
  551. { ok: true },
  552. { ok: true },
  553. ]);
  554. expect(calls).toBe(3);
  555. expect(m3.limit?.context).toBe(512_000);
  556. expect(h.config.minimax_api?.modelContextLimits).toEqual({ 'MiniMax-M3': 1_000_000 });
  557. expect(minimaxApiModels(h.config)['MiniMax-M3']?.limit?.context).toBe(1_000_000);
  558. expect(() => h.service.assertModelSelectable('minimax', 'MiniMax-M3')).not.toThrow();
  559. });
  560. it('updates token-plan M3 context directly without a connection test', async () => {
  561. const h = makeHarness({ minimaxModelSource: 'token_plan' });
  562. const m3 = h.config.provider.minimax?.models?.['MiniMax-M3'];
  563. if (!m3) throw new Error('missing MiniMax-M3 fixture');
  564. m3.limit = { ...m3.limit, context: 512_000 };
  565. await expect(
  566. h.service.updateMinimaxModelContext({
  567. modelId: 'MiniMax-M3',
  568. contextLimit: 1_000_000,
  569. expectedContextLimit: 512_000,
  570. }),
  571. ).resolves.toEqual({ ok: true });
  572. expect(h.testCalls).toHaveLength(0);
  573. expect(m3.limit?.context).toBe(1_000_000);
  574. });
  575. it('restores the cache state observed inside the M3 config transaction', async () => {
  576. const h = makeHarness({
  577. minimax_api: { apiKey: RAW_KEY },
  578. minimaxModelSource: 'minimax_api_key',
  579. });
  580. const m3 = h.config.provider.minimax?.models?.['MiniMax-M3'];
  581. if (!m3) throw new Error('missing MiniMax-M3 fixture');
  582. m3.limit = { ...m3.limit, context: 512_000 };
  583. await h.cache.setModelStatus('minimax_api/MiniMax-M3', {
  584. state: 'available',
  585. config_fingerprint: 'sha256:old',
  586. });
  587. h.setTestHandler(async () => {
  588. await h.cache.setModelStatus('minimax_api/MiniMax-M3', {
  589. state: 'failed',
  590. last_error_code: 'intervening',
  591. config_fingerprint: 'sha256:intervening',
  592. });
  593. return { ok: true };
  594. });
  595. h.failNextConfigWrite(new Error('config disk full'));
  596. await expect(
  597. h.service.updateMinimaxModelContext({
  598. modelId: 'MiniMax-M3',
  599. contextLimit: 1_000_000,
  600. expectedContextLimit: 512_000,
  601. }),
  602. ).rejects.toThrow('config disk full');
  603. expect(m3.limit?.context).toBe(512_000);
  604. expect(h.cache.load().model_status['minimax_api/MiniMax-M3']).toMatchObject({
  605. state: 'failed',
  606. last_error_code: 'intervening',
  607. config_fingerprint: 'sha256:intervening',
  608. });
  609. });
  610. });
  611. describe('MiniMax api key response', () => {
  612. it('upsert response contains only the masked key', async () => {
  613. const h = makeHarness();
  614. const provider = await h.service.upsertMinimaxApiKey({ apiKey: RAW_KEY });
  615. expect(provider.hasApiKey).toBe(true);
  616. expect(provider.maskedApiKey).toContain('****');
  617. expect(provider.maskedApiKey).not.toBe(RAW_KEY);
  618. expect(provider).not.toHaveProperty('rawApiKey');
  619. expect(JSON.stringify(provider)).not.toContain(RAW_KEY);
  620. expect(provider.providerId).toBe('minimax_api');
  621. expect(provider.kind).toBe('minimax-api-key');
  622. expect(provider.source).toBe('minimax_api');
  623. });
  624. it('accepts OpenAI Responses and passes custom headers to the connection test', async () => {
  625. const h = makeHarness();
  626. const provider = await h.service.createUserProvider({
  627. name: 'Responses',
  628. baseUrl: 'https://api.openai.com/v1',
  629. apiKey: CUSTOM_KEY,
  630. apiFormat: 'openai-responses',
  631. headers: { 'OpenAI-Organization': 'org-test' },
  632. models: [{ modelId: 'gpt-5.2', effortOptions: ['max'] }],
  633. });
  634. await h.service.testModel(provider.providerId, 'gpt-5.2');
  635. expect(h.testCalls[0]?.target).toEqual({
  636. api: 'openai-responses',
  637. baseUrl: 'https://api.openai.com/v1',
  638. apiKey: CUSTOM_KEY,
  639. modelId: 'gpt-5.2',
  640. headers: { 'OpenAI-Organization': 'org-test' },
  641. effort: 'max',
  642. outputLimit: 16_384,
  643. });
  644. expect(h.testCalls[0]?.key).toMatch(/^custom_provider:responses\/gpt-5\.2@sha256:/u);
  645. expect(
  646. h.cache.load().model_status['custom_provider:responses/gpt-5.2']?.config_fingerprint,
  647. ).toMatch(/^sha256:/u);
  648. });
  649. });
  650. describe('custom provider API key reveal', () => {
  651. function makeRevealHarness() {
  652. return makeHarness({
  653. custom_provider: {
  654. work: {
  655. api: 'openai-responses',
  656. options: { apiKey: CUSTOM_KEY, baseURL: 'https://example.invalid/v1' },
  657. models: {},
  658. },
  659. },
  660. });
  661. }
  662. it('reveals only the current custom key without persisting or changing list redaction', () => {
  663. const harness = makeRevealHarness();
  664. const provider = harness.service.listUserProviders()[0]!;
  665. const before = structuredClone(harness.config);
  666. expect(harness.service.revealModelProviderApiKey({ providerId: provider.providerId })).toBe(
  667. CUSTOM_KEY,
  668. );
  669. expect(harness.config).toEqual(before);
  670. expect(JSON.stringify(harness.service.listUserProviders())).not.toContain(CUSTOM_KEY);
  671. });
  672. it('reads the latest saved key without a revision and rejects missing providers', () => {
  673. const { service, config } = makeRevealHarness();
  674. config.custom_provider!.work!.options!.apiKey = 'replacement-fictional-key';
  675. expect(service.revealModelProviderApiKey({ providerId: 'custom_provider:work' })).toBe(
  676. 'replacement-fictional-key',
  677. );
  678. expect(() =>
  679. service.revealModelProviderApiKey({ providerId: 'custom_provider:missing' }),
  680. ).toThrow('Model provider not found');
  681. expect(() => service.revealModelProviderApiKey({ providerId: 'builtin:minimax' })).toThrow(
  682. 'Model provider not found',
  683. );
  684. });
  685. it('reads only the user MiniMax API key and never falls back to the managed provider key', () => {
  686. const { service, config } = makeHarness();
  687. expect(() => service.revealModelProviderApiKey({ providerId: 'minimax_api' })).toThrow(
  688. 'MiniMax API key is not configured',
  689. );
  690. config.minimax_api = { apiKey: CUSTOM_KEY };
  691. expect(service.revealModelProviderApiKey({ providerId: 'minimax_api' })).toBe(CUSTOM_KEY);
  692. expect(JSON.stringify(service.getMinimaxApiKeyStatus())).not.toContain(CUSTOM_KEY);
  693. });
  694. it.each([
  695. { kind: 'oauth' },
  696. { api: 'openai-codex-responses' },
  697. { options: { authMode: 'oauth', apiKey: 'fictional-oauth-secret' } },
  698. ])('rejects OAuth credentials: %j', (overrides) => {
  699. const { config, service } = makeRevealHarness();
  700. Object.assign(config.custom_provider!.work!, overrides);
  701. const provider = service.listUserProviders()[0]!;
  702. expect(() => service.revealModelProviderApiKey({ providerId: provider.providerId })).toThrow(
  703. 'OAuth credentials cannot be revealed',
  704. );
  705. });
  706. it('rejects a provider without an API key', () => {
  707. const { config, service } = makeRevealHarness();
  708. delete config.custom_provider!.work!.options!.apiKey;
  709. const provider = service.listUserProviders()[0]!;
  710. expect(() => service.revealModelProviderApiKey({ providerId: provider.providerId })).toThrow(
  711. 'Provider API key is not configured',
  712. );
  713. });
  714. });
  715. describe('custom providers', () => {
  716. it('tests and discovers an edit candidate without mutating config or cache', async () => {
  717. const h = makeHarness({
  718. custom_provider: {
  719. work: {
  720. name: 'Work',
  721. api: 'openai-completions',
  722. options: {
  723. apiKey: CUSTOM_KEY,
  724. baseURL: 'https://saved.example/v1',
  725. headers: { 'X-Saved': 'one' },
  726. },
  727. models: { 'm-1': { name: 'Saved model' } },
  728. },
  729. },
  730. });
  731. h.setDiscoverResult({
  732. ok: true,
  733. models: [{ modelId: 'm-discovered', displayName: 'Discovered' }],
  734. });
  735. const revision = h.service.listUserProviders()[0]?.configRevision;
  736. if (!revision) throw new Error('missing provider revision');
  737. const savedConfig = JSON.stringify(h.config.custom_provider);
  738. const candidate = {
  739. providerId: 'custom_provider:work',
  740. expectedRevision: revision,
  741. name: 'Candidate',
  742. baseUrl: 'https://candidate.example/v1',
  743. apiKey: 'sk-candidate-key-12345678',
  744. apiFormat: 'openai-responses',
  745. headers: { 'X-Candidate': 'two' },
  746. removeHeaders: ['x-saved'],
  747. models: [{ modelId: 'm-1', displayName: 'Candidate model', effortOptions: ['xhigh'] }],
  748. };
  749. await expect(h.service.testUserModelCandidate(candidate, 'm-1')).resolves.toMatchObject({
  750. ok: true,
  751. status: { state: 'available' },
  752. });
  753. await expect(h.service.discoverUserModelsCandidate(candidate)).resolves.toEqual([
  754. { modelId: 'm-discovered', displayName: 'Discovered' },
  755. ]);
  756. expect(h.testCalls[0]?.target).toEqual({
  757. api: 'openai-responses',
  758. baseUrl: 'https://candidate.example/v1',
  759. apiKey: 'sk-candidate-key-12345678',
  760. modelId: 'm-1',
  761. headers: { 'X-Candidate': 'two' },
  762. effort: 'xhigh',
  763. outputLimit: 16_384,
  764. });
  765. expect(h.discoverCalls).toEqual([
  766. {
  767. api: 'openai-responses',
  768. baseUrl: 'https://candidate.example/v1',
  769. apiKey: 'sk-candidate-key-12345678',
  770. headers: { 'X-Candidate': 'two' },
  771. },
  772. ]);
  773. expect(JSON.stringify(h.config.custom_provider)).toBe(savedConfig);
  774. expect(h.cache.load().model_status).toEqual({});
  775. expect(h.cache.load().provider_status).toEqual({});
  776. });
  777. it('tests every configured Think Effort option for a draft model', async () => {
  778. const h = makeHarness();
  779. await expect(
  780. h.service.testUserModelCandidate(
  781. {
  782. name: 'Thinking Provider',
  783. baseUrl: 'https://api.example.com/v1',
  784. apiKey: CUSTOM_KEY,
  785. apiFormat: 'openai-responses',
  786. models: [
  787. {
  788. modelId: 'thinking-model',
  789. effortOptions: ['low', 'high', 'max'],
  790. },
  791. ],
  792. },
  793. 'thinking-model',
  794. ),
  795. ).resolves.toMatchObject({ ok: true, status: { state: 'available' } });
  796. expect(h.testCalls.map((call) => call.target.effort)).toEqual(['low', 'high', 'max']);
  797. expect(new Set(h.testCalls.map((call) => call.key)).size).toBe(3);
  798. });
  799. it('tests every configured MiniMax-M3 Think Effort and reports the failing level', async () => {
  800. const h = makeHarness();
  801. h.setTestHandler(async (_key, target) =>
  802. target.effort === 'off'
  803. ? { ok: false, errorCode: 'http_400', errorMessage: 'disabled rejected' }
  804. : { ok: true },
  805. );
  806. const outcome = await h.service.testUserModelCandidate(
  807. {
  808. name: 'MiniMax Work',
  809. baseUrl: 'https://api.minimax.io/v1',
  810. apiKey: CUSTOM_KEY,
  811. apiFormat: 'openai-completions',
  812. models: [{ modelId: 'MiniMax-M3', effortOptions: ['on', 'off'] }],
  813. },
  814. 'MiniMax-M3',
  815. );
  816. expect(outcome).toMatchObject({
  817. ok: false,
  818. status: {
  819. state: 'failed',
  820. lastErrorCode: 'http_400',
  821. lastErrorMessage: 'Think Effort "off": disabled rejected',
  822. },
  823. });
  824. expect(h.testCalls.map((call) => call.target.effort)).toEqual(['on', 'off']);
  825. });
  826. it('probes a custom MiniMax-M3 with the default output limit when none is configured', async () => {
  827. const h = makeHarness();
  828. await h.service.testUserModelCandidate(
  829. {
  830. name: 'MiniMax Work',
  831. baseUrl: 'https://api.minimax.io/v1',
  832. apiKey: CUSTOM_KEY,
  833. apiFormat: 'openai-completions',
  834. models: [{ modelId: 'MiniMax-M3', effortOptions: ['on', 'off'] }],
  835. },
  836. 'MiniMax-M3',
  837. );
  838. // A real turn sends 16_384 here. A smaller probe budget fails the thinking
  839. // output floor upstream and reports a working model as unavailable.
  840. expect(h.testCalls.map((call) => call.target.outputLimit)).toEqual([16_384, 16_384]);
  841. });
  842. it('tests every Think Effort option and reports the failing level before saving', async () => {
  843. const h = makeHarness();
  844. h.setTestHandler(async (_key, target) =>
  845. target.effort === 'high'
  846. ? { ok: false, errorCode: 'http_400', errorMessage: 'HTTP 400' }
  847. : { ok: true },
  848. );
  849. const outcome = await h.service.saveUserModelProviderCandidate({
  850. candidate: {
  851. name: 'Thinking Provider',
  852. baseUrl: 'https://api.example.com/v1',
  853. apiKey: CUSTOM_KEY,
  854. apiFormat: 'openai-completions',
  855. models: [
  856. {
  857. modelId: 'thinking-model',
  858. effortOptions: ['low', 'high', 'max', 'xhigh'],
  859. },
  860. ],
  861. },
  862. modelId: 'thinking-model',
  863. saveAndUse: true,
  864. });
  865. expect(outcome).toMatchObject({
  866. ok: false,
  867. status: {
  868. state: 'failed',
  869. lastErrorCode: 'http_400',
  870. lastErrorMessage: 'Think Effort "high": HTTP 400',
  871. },
  872. });
  873. expect(h.testCalls.map((call) => call.target.effort)).toEqual(['low', 'high', 'max', 'xhigh']);
  874. expect(h.config.custom_provider).toBeUndefined();
  875. expect(h.cache.load().model_status).toEqual({});
  876. });
  877. it('tests every saved Think Effort option from the model refresh action', async () => {
  878. const h = makeHarness({
  879. custom_provider: {
  880. work: {
  881. api: 'anthropic-messages',
  882. options: { apiKey: CUSTOM_KEY, baseURL: 'https://api.example.com' },
  883. models: {
  884. 'thinking-model': {
  885. thinking: { effortOptions: ['low', 'high', 'max'] },
  886. },
  887. },
  888. },
  889. },
  890. });
  891. await expect(
  892. h.service.testModel('custom_provider:work', 'thinking-model'),
  893. ).resolves.toMatchObject({ ok: true, status: { state: 'available' } });
  894. expect(h.testCalls.map((call) => call.target.effort)).toEqual(['low', 'high', 'max']);
  895. expect(h.cache.load().model_status['custom_provider:work/thinking-model']).toMatchObject({
  896. state: 'available',
  897. });
  898. });
  899. });
  900. describe('custom provider candidate persistence implicit thinking default', () => {
  901. it('defaults only newly added models through the public candidate save path', async () => {
  902. const h = makeHarness(
  903. {
  904. custom_provider: {
  905. work: {
  906. name: 'Work',
  907. api: 'openai-responses',
  908. options: { apiKey: CUSTOM_KEY, baseURL: 'https://api.example.com/v1' },
  909. models: { old: {} },
  910. },
  911. },
  912. },
  913. { implicitCustomProviderThinking: true },
  914. );
  915. const revision = h.service.listUserProviders()[0]?.configRevision;
  916. if (!revision) throw new Error('missing provider revision');
  917. await h.service.saveUserModelProviderCandidate({
  918. candidate: {
  919. providerId: 'custom_provider:work',
  920. expectedRevision: revision,
  921. name: 'Work',
  922. baseUrl: 'https://api.example.com/v1',
  923. apiKey: CUSTOM_KEY,
  924. apiFormat: 'openai-responses',
  925. models: [{ modelId: 'old' }, { modelId: 'added' }],
  926. },
  927. saveAndUse: false,
  928. skipConnectionTest: true,
  929. });
  930. expect(h.config.custom_provider?.work?.models?.old).toEqual({});
  931. expect(h.config.custom_provider?.work?.models?.added).toEqual({
  932. reasoning: true,
  933. thinking_config: { mode: 'switchable', default_value: 'true' },
  934. });
  935. });
  936. });
  937. describe('custom provider candidate persistence', () => {
  938. it.each(['https://api.z.ai', 'https://open.bigmodel.cn'])(
  939. 'persists and resolves only the explicitly retried Coding Plan endpoint on %s',
  940. async (origin) => {
  941. const h = makeHarness();
  942. const generalUrl = `${origin}/api/paas/v4`;
  943. const codingUrl = `${origin}/api/coding/paas/v4`;
  944. const candidate = {
  945. name: 'GLM plan',
  946. apiKey: CUSTOM_KEY,
  947. baseUrl: generalUrl,
  948. apiFormat: 'openai-completions',
  949. models: [{ modelId: 'glm-5.3', toolCall: true }],
  950. };
  951. h.setTestResult({
  952. ok: false,
  953. errorCode: 'http_429',
  954. errorMessage: 'Insufficient balance',
  955. });
  956. const failed = await h.service.saveUserModelProviderCandidate({
  957. candidate,
  958. modelId: 'glm-5.3',
  959. saveAndUse: true,
  960. });
  961. expect(failed.ok).toBe(false);
  962. expect(h.config.custom_provider).toBeUndefined();
  963. expect(h.config.defaultModel).toBe('minimax/MiniMax-M3');
  964. expect(h.testCalls.map(({ target }) => target.baseUrl)).toEqual([generalUrl]);
  965. h.setTestResult({ ok: true });
  966. const saved = await h.service.saveUserModelProviderCandidate({
  967. candidate: { ...candidate, baseUrl: codingUrl },
  968. modelId: 'glm-5.3',
  969. saveAndUse: true,
  970. });
  971. expect(saved.ok).toBe(true);
  972. const provider = saved.provider!.providerId;
  973. const providerKey = provider.replace('custom_provider:', '');
  974. expect(h.config.custom_provider?.[providerKey]?.options?.baseURL).toBe(codingUrl);
  975. expect(h.config.defaultModel).toBe(`${provider}/glm-5.3`);
  976. expect(h.testCalls.map(({ target }) => target.baseUrl)).toEqual([generalUrl, codingUrl]);
  977. // Custom provider resolution must use the persisted URL, not a similarly
  978. // named provider in the bundled inference registry.
  979. expect(
  980. planCustomProviderResolution({
  981. byok: h.config,
  982. provider,
  983. providerKey,
  984. modelId: 'glm-5.3',
  985. }),
  986. ).toMatchObject({
  987. baseUrl: codingUrl,
  988. api: 'openai-completions',
  989. apiKey: CUSTOM_KEY,
  990. });
  991. },
  992. );
  993. it('saves every preset model without testing or switching the active model', async () => {
  994. const h = makeHarness();
  995. const outcome = await h.service.saveUserModelProviderCandidate({
  996. candidate: {
  997. name: 'Preset Provider',
  998. baseUrl: 'https://api.example.com/v1',
  999. apiKey: CUSTOM_KEY,
  1000. apiFormat: 'openai-completions',
  1001. models: [
  1002. { modelId: 'preset-model-a', displayName: 'Preset Model A' },
  1003. { modelId: 'preset-model-b', displayName: 'Preset Model B' },
  1004. ],
  1005. },
  1006. saveAndUse: false,
  1007. skipConnectionTest: true,
  1008. });
  1009. expect(outcome).toMatchObject({ ok: true, skippedTest: true });
  1010. expect(outcome.provider?.models).toEqual(
  1011. expect.arrayContaining([
  1012. expect.objectContaining({ modelId: 'preset-model-a' }),
  1013. expect.objectContaining({ modelId: 'preset-model-b' }),
  1014. ]),
  1015. );
  1016. expect(h.testCalls).toEqual([]);
  1017. expect(h.selectModel).not.toHaveBeenCalled();
  1018. expect(h.config.defaultModel).toBe('minimax/MiniMax-M3');
  1019. });
  1020. it('saves an untested candidate without selecting it when skipConnectionTest is true', async () => {
  1021. const h = makeHarness();
  1022. const outcome = await h.service.saveUserModelProviderCandidate({
  1023. candidate: {
  1024. name: 'Untested Provider',
  1025. baseUrl: 'https://api.example.com/v1',
  1026. apiKey: CUSTOM_KEY,
  1027. apiFormat: 'openai-responses',
  1028. models: [
  1029. {
  1030. modelId: 'untested-model',
  1031. configurationSource: 'discovered',
  1032. effortOptions: ['low', 'high'],
  1033. },
  1034. ],
  1035. },
  1036. modelId: 'untested-model',
  1037. saveAndUse: true,
  1038. skipConnectionTest: true,
  1039. });
  1040. expect(outcome).toMatchObject({ ok: true, skippedTest: true });
  1041. expect(outcome.status).toBeUndefined();
  1042. expect(h.testCalls).toEqual([]);
  1043. expect(h.config.defaultModel).toBe('minimax/MiniMax-M3');
  1044. const savedProviderKey = outcome.provider?.providerId.replace('custom_provider:', '');
  1045. expect(savedProviderKey).toBeTruthy();
  1046. expect(
  1047. savedProviderKey
  1048. ? h.config.custom_provider?.[savedProviderKey]?.models?.['untested-model']
  1049. : undefined,
  1050. ).toMatchObject({ configuration_source: 'discovered' });
  1051. expect(outcome.provider?.models[0]).toMatchObject({
  1052. modelId: 'untested-model',
  1053. configurationSource: 'discovered',
  1054. });
  1055. expect(h.cache.load().model_status).toEqual({});
  1056. });
  1057. it('saves an edited provider with no models when the connection test is skipped', async () => {
  1058. const h = makeHarness({
  1059. defaultModel: 'custom_provider:work/removed-model',
  1060. defaultModelVariant: 'max',
  1061. custom_provider: {
  1062. work: {
  1063. name: 'Work',
  1064. api: 'openai-responses',
  1065. options: { apiKey: CUSTOM_KEY, baseURL: 'https://api.example.com/v1' },
  1066. models: { 'removed-model': {} },
  1067. },
  1068. },
  1069. });
  1070. const revision = h.service.listUserProviders()[0]?.configRevision;
  1071. if (!revision) throw new Error('missing provider revision');
  1072. const outcome = await h.service.saveUserModelProviderCandidate({
  1073. candidate: {
  1074. providerId: 'custom_provider:work',
  1075. expectedRevision: revision,
  1076. name: 'Work',
  1077. baseUrl: 'https://api.example.com/v1',
  1078. apiFormat: 'openai-responses',
  1079. models: [],
  1080. },
  1081. skipConnectionTest: true,
  1082. });
  1083. expect(outcome).toMatchObject({ ok: true, skippedTest: true });
  1084. expect(outcome.provider?.models).toEqual([]);
  1085. expect(h.config.custom_provider?.work?.models).toEqual({});
  1086. expect(h.testCalls).toEqual([]);
  1087. expect(h.config.defaultModel).toBe('minimax/MiniMax-M3');
  1088. expect(h.config.defaultModelVariant).toBeUndefined();
  1089. });
  1090. it('atomically saves a tested edit candidate and preserves retained model fields', async () => {
  1091. const h = makeHarness({
  1092. custom_provider: {
  1093. work: {
  1094. name: 'Work',
  1095. kind: 'custom',
  1096. api: 'openai-responses',
  1097. npm: '@sdk/custom',
  1098. enabled: true,
  1099. options: {
  1100. apiKey: CUSTOM_KEY,
  1101. baseURL: 'https://saved.example/v1',
  1102. headers: { 'X-Saved': 'one', 'X-Remove': 'old' },
  1103. requestTimeout: 1234,
  1104. },
  1105. models: {
  1106. 'm-1': {
  1107. name: 'Primary',
  1108. attachment: true,
  1109. headers: { 'X-Model': 'primary' },
  1110. capabilities: { support_files_api: true },
  1111. variants: { thinking: { thinking: { type: 'adaptive' } } },
  1112. limit: { context: 100_000, output: 8_000 },
  1113. thinking: { effortOptions: ['low', 'medium', 'high'] },
  1114. },
  1115. 'm-2': { name: 'Removed' },
  1116. },
  1117. },
  1118. },
  1119. });
  1120. const revision = h.service.listUserProviders()[0]?.configRevision;
  1121. if (!revision) throw new Error('missing provider revision');
  1122. const outcome = await h.service.saveUserModelProviderCandidate({
  1123. candidate: {
  1124. providerId: 'custom_provider:work',
  1125. expectedRevision: revision,
  1126. name: 'Renamed',
  1127. baseUrl: 'https://candidate.example/v1',
  1128. apiFormat: 'openai-responses',
  1129. headers: { 'X-New': 'two' },
  1130. removeHeaders: ['x-remove'],
  1131. models: [
  1132. {
  1133. modelId: 'm-1',
  1134. displayName: 'Primary v2',
  1135. enabled: true,
  1136. limit: { context: 120_000, output: 16_000 },
  1137. effortOptions: ['low', 'medium', 'high'],
  1138. },
  1139. { modelId: 'm-3', displayName: 'Added', enabled: false },
  1140. ],
  1141. },
  1142. modelId: 'm-1',
  1143. saveAndUse: true,
  1144. });
  1145. expect(outcome).toMatchObject({ ok: true, status: { state: 'available' } });
  1146. expect(h.testCalls[0]?.target).toMatchObject({
  1147. api: 'openai-responses',
  1148. modelId: 'm-1',
  1149. });
  1150. expect(outcome.provider?.configRevision).toMatch(/^sha256:/u);
  1151. expect(outcome.provider?.configRevision).not.toBe(revision);
  1152. expect(h.config.defaultModel).toBe('custom_provider:work/m-1');
  1153. expect(h.selectModel).not.toHaveBeenCalled();
  1154. expect(h.config.custom_provider?.work).toMatchObject({
  1155. name: 'Renamed',
  1156. options: {
  1157. apiKey: CUSTOM_KEY,
  1158. baseURL: 'https://candidate.example/v1',
  1159. headers: { 'X-Saved': 'one', 'X-New': 'two' },
  1160. requestTimeout: 1234,
  1161. },
  1162. });
  1163. expect(h.config.custom_provider?.work).not.toHaveProperty('npm');
  1164. expect(h.config.custom_provider?.work?.models?.['m-1']).toMatchObject({
  1165. name: 'Primary v2',
  1166. enabled: true,
  1167. attachment: true,
  1168. headers: { 'X-Model': 'primary' },
  1169. capabilities: { support_files_api: true },
  1170. variants: { thinking: { thinking: { type: 'adaptive' } } },
  1171. limit: { context: 120_000, output: 16_000 },
  1172. thinking: { effortOptions: ['low', 'medium', 'high'] },
  1173. });
  1174. expect(h.config.custom_provider?.work?.models?.['m-2']).toBeUndefined();
  1175. expect(h.config.custom_provider?.work?.models?.['m-3']).toEqual({
  1176. name: 'Added',
  1177. enabled: false,
  1178. });
  1179. expect(Object.keys(h.config.custom_provider?.work?.models ?? {})).toEqual(['m-1', 'm-3']);
  1180. expect(() => h.service.assertModelSelectable('custom_provider:work', 'm-1')).not.toThrow();
  1181. });
  1182. });
  1183. describe('custom provider legacy candidates', () => {
  1184. it('saves an edit candidate when raw YAML has a normalized legacy Think Effort', async () => {
  1185. const h = makeHarness({
  1186. custom_provider: {
  1187. work: {
  1188. name: 'Work',
  1189. api: 'openai-responses',
  1190. options: { apiKey: CUSTOM_KEY, baseURL: 'https://saved.example' },
  1191. models: {
  1192. 'm-1': {
  1193. name: 'Saved model',
  1194. thinking: { effortOptions: ['high'] },
  1195. },
  1196. },
  1197. },
  1198. },
  1199. });
  1200. const revision = h.service.listUserProviders()[0]?.configRevision;
  1201. if (!revision) throw new Error('missing provider revision');
  1202. // The config reader upgrades legacy `thinking.effort` to `effortOptions`.
  1203. // A candidate revision must be compared with that normalized config, or a
  1204. // normal save is incorrectly rejected as CONFIG_CHANGED.
  1205. h.setNextRawCustomProviders({
  1206. work: {
  1207. name: 'Work',
  1208. api: 'openai-responses',
  1209. options: { apiKey: CUSTOM_KEY, baseURL: 'https://saved.example' },
  1210. models: { 'm-1': { name: 'Saved model', thinking: { effort: 'high' } } },
  1211. },
  1212. });
  1213. await expect(
  1214. h.service.saveUserModelProviderCandidate({
  1215. candidate: {
  1216. providerId: 'custom_provider:work',
  1217. expectedRevision: revision,
  1218. name: 'Work',
  1219. baseUrl: 'https://saved.example',
  1220. apiFormat: 'openai-responses',
  1221. models: [
  1222. {
  1223. modelId: 'm-1',
  1224. displayName: 'Saved model',
  1225. effortOptions: ['high'],
  1226. },
  1227. ],
  1228. },
  1229. modelId: 'm-1',
  1230. saveAndUse: true,
  1231. }),
  1232. ).resolves.toMatchObject({ ok: true, status: { state: 'available' } });
  1233. expect(h.config.custom_provider?.work?.models?.['m-1']?.thinking).toEqual({
  1234. effortOptions: ['high'],
  1235. });
  1236. });
  1237. it('leaves provider, default model, and cache unchanged when candidate persistence fails', async () => {
  1238. const h = makeHarness({
  1239. custom_provider: {
  1240. work: {
  1241. name: 'Work',
  1242. options: { apiKey: CUSTOM_KEY, baseURL: 'https://saved.example' },
  1243. models: { 'm-1': {} },
  1244. },
  1245. },
  1246. });
  1247. const revision = h.service.listUserProviders()[0]?.configRevision;
  1248. if (!revision) throw new Error('missing provider revision');
  1249. const before = JSON.stringify(h.config);
  1250. h.failNextConfigWrite(new Error('config disk full'));
  1251. await expect(
  1252. h.service.saveUserModelProviderCandidate({
  1253. candidate: {
  1254. providerId: 'custom_provider:work',
  1255. expectedRevision: revision,
  1256. name: 'Candidate',
  1257. baseUrl: 'https://candidate.example',
  1258. models: [{ modelId: 'm-1' }],
  1259. },
  1260. modelId: 'm-1',
  1261. saveAndUse: true,
  1262. }),
  1263. ).rejects.toThrow('config disk full');
  1264. expect(JSON.stringify(h.config)).toBe(before);
  1265. expect(h.cache.load().model_status).toEqual({});
  1266. });
  1267. it('rejects an edit candidate when its opaque revision is stale', async () => {
  1268. const h = makeHarness({
  1269. custom_provider: {
  1270. work: {
  1271. options: { apiKey: CUSTOM_KEY, baseURL: 'https://saved.example' },
  1272. models: { 'm-1': {} },
  1273. },
  1274. },
  1275. });
  1276. await expect(
  1277. h.service.testUserModelCandidate(
  1278. {
  1279. providerId: 'custom_provider:work',
  1280. expectedRevision: 'sha256:stale',
  1281. baseUrl: 'https://candidate.example',
  1282. models: [{ modelId: 'm-1' }],
  1283. },
  1284. 'm-1',
  1285. ),
  1286. ).rejects.toMatchObject({ code: 'CONFIG_CHANGED', status: 409 });
  1287. expect(h.testCalls).toHaveLength(0);
  1288. });
  1289. it('tests a parameter patch before saving it and preserves the full model config', async () => {
  1290. const h = makeHarness({
  1291. custom_provider: {
  1292. work: {
  1293. name: 'Work',
  1294. kind: 'custom',
  1295. api: 'openai-responses',
  1296. npm: '@ai-sdk/anthropic',
  1297. enabled: true,
  1298. options: {
  1299. apiKey: CUSTOM_KEY,
  1300. baseURL: 'https://api.example.com/v1',
  1301. headers: { 'X-Tenant': 'one' },
  1302. },
  1303. models: {
  1304. 'm-1': {
  1305. name: 'Primary',
  1306. attachment: true,
  1307. reasoning: true,
  1308. tool_call: true,
  1309. temperature: false,
  1310. modalities: { input: ['text', 'image'], output: ['text'] },
  1311. headers: { 'X-Model': 'primary' },
  1312. limit: { context: 100_000, output: 8_000 },
  1313. thinking: { effortOptions: ['low', 'medium', 'high'] },
  1314. },
  1315. 'm-2': { name: 'Secondary', limit: { context: 64_000, output: 4_000 } },
  1316. },
  1317. },
  1318. },
  1319. });
  1320. const outcome = await h.service.updateUserModelParameters({
  1321. providerId: 'custom_provider:work',
  1322. modelId: 'm-1',
  1323. contextLimit: 120_000,
  1324. maxOutputTokens: 16_000,
  1325. expectedContextLimit: 100_000,
  1326. expectedMaxOutputTokens: 8_000,
  1327. });
  1328. expect(outcome.ok).toBe(true);
  1329. expect(h.testCalls).toHaveLength(1);
  1330. expect(h.testCalls[0]?.target).toMatchObject({
  1331. api: 'openai-responses',
  1332. baseUrl: 'https://api.example.com/v1',
  1333. modelId: 'm-1',
  1334. headers: { 'X-Tenant': 'one', 'X-Model': 'primary' },
  1335. });
  1336. expect(h.config.custom_provider?.work?.models?.['m-1']).toEqual({
  1337. name: 'Primary',
  1338. attachment: true,
  1339. reasoning: true,
  1340. tool_call: true,
  1341. temperature: false,
  1342. modalities: { input: ['text', 'image'], output: ['text'] },
  1343. headers: { 'X-Model': 'primary' },
  1344. limit: { context: 120_000, output: 16_000 },
  1345. thinking: { effortOptions: ['low', 'medium', 'high'] },
  1346. });
  1347. expect(h.config.custom_provider?.work?.models?.['m-2']).toEqual({
  1348. name: 'Secondary',
  1349. limit: { context: 64_000, output: 4_000 },
  1350. });
  1351. expect(h.config.custom_provider?.work).not.toHaveProperty('npm');
  1352. expect(h.cache.load().model_status['custom_provider:work/m-1']).toMatchObject({
  1353. state: 'available',
  1354. config_fingerprint: expect.stringMatching(/^sha256:/u),
  1355. });
  1356. expect(() => h.service.assertModelSelectable('custom_provider:work', 'm-1')).not.toThrow();
  1357. expect(h.service.listUserProviders()[0]?.models[0]?.status).toMatchObject({
  1358. state: 'available',
  1359. });
  1360. const activeModel = h.config.custom_provider?.work?.models?.['m-1'];
  1361. if (!activeModel?.headers) throw new Error('invalid custom model test fixture');
  1362. activeModel.headers['X-Model'] = 'changed';
  1363. expect(h.service.listUserProviders()[0]?.models[0]?.status).toBeUndefined();
  1364. });
  1365. });
  1366. describe('custom provider model parameters', () => {
  1367. it('updates model limits without changing configured effort options', async () => {
  1368. const h = makeHarness({
  1369. custom_provider: {
  1370. work: {
  1371. enabled: true,
  1372. options: { apiKey: CUSTOM_KEY, baseURL: 'https://api.example.com' },
  1373. models: {
  1374. 'm-1': {
  1375. limit: { context: 100_000, output: 8_000 },
  1376. thinking: { effortOptions: ['low', 'high'] },
  1377. },
  1378. },
  1379. },
  1380. },
  1381. });
  1382. await expect(
  1383. h.service.updateUserModelParameters({
  1384. providerId: 'custom_provider:work',
  1385. modelId: 'm-1',
  1386. contextLimit: 120_000,
  1387. maxOutputTokens: 16_000,
  1388. expectedContextLimit: 100_000,
  1389. expectedMaxOutputTokens: 8_000,
  1390. }),
  1391. ).resolves.toMatchObject({ ok: true });
  1392. expect(h.config.custom_provider?.work?.models?.['m-1']?.thinking).toEqual({
  1393. effortOptions: ['low', 'high'],
  1394. });
  1395. });
  1396. it('keeps the active model config unchanged when the candidate test fails', async () => {
  1397. const h = makeHarness({
  1398. custom_provider: {
  1399. work: {
  1400. enabled: true,
  1401. options: { apiKey: CUSTOM_KEY, baseURL: 'https://api.example.com' },
  1402. models: {
  1403. 'm-1': {
  1404. name: 'Primary',
  1405. limit: { context: 100_000, output: 8_000 },
  1406. thinking: { effortOptions: ['high'] },
  1407. },
  1408. },
  1409. },
  1410. },
  1411. });
  1412. h.setTestResult({
  1413. ok: false,
  1414. errorCode: 'model_not_found',
  1415. errorMessage: 'Model rejected',
  1416. });
  1417. const outcome = await h.service.updateUserModelParameters({
  1418. providerId: 'custom_provider:work',
  1419. modelId: 'm-1',
  1420. contextLimit: 120_000,
  1421. maxOutputTokens: 16_000,
  1422. expectedContextLimit: 100_000,
  1423. expectedMaxOutputTokens: 8_000,
  1424. });
  1425. expect(outcome).toMatchObject({
  1426. ok: false,
  1427. status: { state: 'failed', lastErrorCode: 'model_not_found' },
  1428. });
  1429. expect(h.config.custom_provider?.work?.models?.['m-1']).toEqual({
  1430. name: 'Primary',
  1431. limit: { context: 100_000, output: 8_000 },
  1432. thinking: { effortOptions: ['high'] },
  1433. });
  1434. expect(h.cache.load().model_status['custom_provider:work/m-1']).toBeUndefined();
  1435. });
  1436. it('rejects stale model parameters before testing the candidate', async () => {
  1437. const h = makeHarness({
  1438. custom_provider: {
  1439. work: {
  1440. enabled: true,
  1441. options: { apiKey: CUSTOM_KEY, baseURL: 'https://api.example.com' },
  1442. models: {
  1443. 'm-1': {
  1444. limit: { context: 100_000, output: 8_000 },
  1445. thinking: { effortOptions: ['high'] },
  1446. },
  1447. },
  1448. },
  1449. },
  1450. });
  1451. await expect(
  1452. h.service.updateUserModelParameters({
  1453. providerId: 'custom_provider:work',
  1454. modelId: 'm-1',
  1455. contextLimit: 120_000,
  1456. maxOutputTokens: 16_000,
  1457. expectedContextLimit: 90_000,
  1458. expectedMaxOutputTokens: 8_000,
  1459. }),
  1460. ).rejects.toMatchObject({ code: 'CONFIG_CHANGED', status: 409 });
  1461. expect(h.testCalls).toHaveLength(0);
  1462. expect(h.config.custom_provider?.work?.models?.['m-1']).toMatchObject({
  1463. limit: { context: 100_000, output: 8_000 },
  1464. thinking: { effortOptions: ['high'] },
  1465. });
  1466. });
  1467. it('allows the first parameter update when a historical model has no limits or effort', async () => {
  1468. const h = makeHarness({
  1469. custom_provider: {
  1470. work: {
  1471. enabled: true,
  1472. options: { apiKey: CUSTOM_KEY, baseURL: 'https://api.example.com' },
  1473. models: { 'm-1': { name: 'Historical' } },
  1474. },
  1475. },
  1476. });
  1477. await expect(
  1478. h.service.updateUserModelParameters({
  1479. providerId: 'custom_provider:work',
  1480. modelId: 'm-1',
  1481. contextLimit: 120_000,
  1482. maxOutputTokens: 16_000,
  1483. expectedContextLimit: 0,
  1484. expectedMaxOutputTokens: 0,
  1485. }),
  1486. ).resolves.toMatchObject({ ok: true, status: { state: 'available' } });
  1487. expect(h.config.custom_provider?.work?.models?.['m-1']).toMatchObject({
  1488. name: 'Historical',
  1489. limit: { context: 120_000, output: 16_000 },
  1490. });
  1491. });
  1492. it('commits only one of two concurrent patches based on the same model snapshot', async () => {
  1493. const h = makeHarness({
  1494. custom_provider: {
  1495. work: {
  1496. enabled: true,
  1497. options: { apiKey: CUSTOM_KEY, baseURL: 'https://api.example.com' },
  1498. models: {
  1499. 'm-1': {
  1500. limit: { context: 100_000, output: 8_000 },
  1501. thinking: { effortOptions: ['high'] },
  1502. },
  1503. },
  1504. },
  1505. },
  1506. });
  1507. const expected = {
  1508. providerId: 'custom_provider:work',
  1509. modelId: 'm-1',
  1510. expectedContextLimit: 100_000,
  1511. expectedMaxOutputTokens: 8_000,
  1512. } as const;
  1513. const [first, second] = await Promise.allSettled([
  1514. h.service.updateUserModelParameters({
  1515. ...expected,
  1516. contextLimit: 120_000,
  1517. maxOutputTokens: 16_000,
  1518. }),
  1519. h.service.updateUserModelParameters({
  1520. ...expected,
  1521. contextLimit: 140_000,
  1522. maxOutputTokens: 20_000,
  1523. }),
  1524. ]);
  1525. expect(first).toMatchObject({ status: 'fulfilled', value: { ok: true } });
  1526. expect(second).toMatchObject({
  1527. status: 'rejected',
  1528. reason: { code: 'CONFIG_CHANGED', status: 409 },
  1529. });
  1530. expect(h.config.custom_provider?.work?.models?.['m-1']).toMatchObject({
  1531. limit: { context: 120_000, output: 16_000 },
  1532. thinking: { effortOptions: ['high'] },
  1533. });
  1534. });
  1535. });
  1536. describe('custom provider candidate rollback', () => {
  1537. it('keeps the active model config unchanged when cache persistence fails', async () => {
  1538. const h = makeHarness({
  1539. custom_provider: {
  1540. work: {
  1541. enabled: true,
  1542. options: { apiKey: CUSTOM_KEY, baseURL: 'https://api.example.com' },
  1543. models: {
  1544. 'm-1': {
  1545. limit: { context: 100_000, output: 8_000 },
  1546. thinking: { effortOptions: ['high'] },
  1547. },
  1548. },
  1549. },
  1550. },
  1551. });
  1552. vi.spyOn(h.cache, 'replaceModelStatus').mockRejectedValueOnce(new Error('cache disk full'));
  1553. await expect(
  1554. h.service.updateUserModelParameters({
  1555. providerId: 'custom_provider:work',
  1556. modelId: 'm-1',
  1557. contextLimit: 120_000,
  1558. maxOutputTokens: 16_000,
  1559. expectedContextLimit: 100_000,
  1560. expectedMaxOutputTokens: 8_000,
  1561. }),
  1562. ).rejects.toMatchObject({ code: 'CACHE_WRITE_FAILED', status: 500 });
  1563. expect(h.testCalls).toHaveLength(1);
  1564. expect(h.config.custom_provider?.work?.models?.['m-1']).toMatchObject({
  1565. limit: { context: 100_000, output: 8_000 },
  1566. thinking: { effortOptions: ['high'] },
  1567. });
  1568. expect(h.cache.load().model_status['custom_provider:work/m-1']).toBeUndefined();
  1569. });
  1570. it('restores the previous model status when the config write fails', async () => {
  1571. const h = makeHarness({
  1572. custom_provider: {
  1573. work: {
  1574. enabled: true,
  1575. options: { apiKey: CUSTOM_KEY, baseURL: 'https://api.example.com' },
  1576. models: {
  1577. 'm-1': {
  1578. limit: { context: 100_000, output: 8_000 },
  1579. thinking: { effortOptions: ['high'] },
  1580. },
  1581. },
  1582. },
  1583. },
  1584. });
  1585. await h.service.testModel('custom_provider:work', 'm-1');
  1586. const previousStatus = h.cache.load().model_status['custom_provider:work/m-1'];
  1587. h.failNextConfigWrite(new Error('config disk full'));
  1588. await expect(
  1589. h.service.updateUserModelParameters({
  1590. providerId: 'custom_provider:work',
  1591. modelId: 'm-1',
  1592. contextLimit: 120_000,
  1593. maxOutputTokens: 16_000,
  1594. expectedContextLimit: 100_000,
  1595. expectedMaxOutputTokens: 8_000,
  1596. }),
  1597. ).rejects.toThrow('config disk full');
  1598. expect(h.config.custom_provider?.work?.models?.['m-1']).toMatchObject({
  1599. limit: { context: 100_000, output: 8_000 },
  1600. thinking: { effortOptions: ['high'] },
  1601. });
  1602. expect(h.cache.load().model_status['custom_provider:work/m-1']).toEqual(previousStatus);
  1603. expect(() => h.service.assertModelSelectable('custom_provider:work', 'm-1')).not.toThrow();
  1604. });
  1605. it('removes the candidate model status after a first config write fails', async () => {
  1606. const h = makeHarness({
  1607. custom_provider: {
  1608. work: {
  1609. enabled: true,
  1610. options: { apiKey: CUSTOM_KEY, baseURL: 'https://api.example.com' },
  1611. models: { 'm-1': {} },
  1612. },
  1613. },
  1614. });
  1615. h.failNextConfigWrite(new Error('config disk full'));
  1616. await expect(
  1617. h.service.updateUserModelParameters({
  1618. providerId: 'custom_provider:work',
  1619. modelId: 'm-1',
  1620. contextLimit: 120_000,
  1621. maxOutputTokens: 16_000,
  1622. expectedContextLimit: 0,
  1623. expectedMaxOutputTokens: 0,
  1624. }),
  1625. ).rejects.toThrow('config disk full');
  1626. expect(h.config.custom_provider?.work?.models?.['m-1']).toEqual({});
  1627. expect(h.cache.load().model_status['custom_provider:work/m-1']).toBeUndefined();
  1628. });
  1629. it('rejects a tested patch when the provider changes during the request', async () => {
  1630. const h = makeHarness({
  1631. custom_provider: {
  1632. work: {
  1633. enabled: true,
  1634. options: { apiKey: CUSTOM_KEY, baseURL: 'https://api.example.com' },
  1635. models: { 'm-1': { limit: { context: 100_000, output: 8_000 } } },
  1636. },
  1637. },
  1638. });
  1639. h.setTestHandler(async () => {
  1640. const provider = h.config.custom_provider?.work;
  1641. if (!provider?.options) throw new Error('invalid custom provider test fixture');
  1642. provider.options.baseURL = 'https://changed.example.com';
  1643. return { ok: true };
  1644. });
  1645. await expect(
  1646. h.service.updateUserModelParameters({
  1647. providerId: 'custom_provider:work',
  1648. modelId: 'm-1',
  1649. contextLimit: 120_000,
  1650. maxOutputTokens: 16_000,
  1651. expectedContextLimit: 100_000,
  1652. expectedMaxOutputTokens: 8_000,
  1653. }),
  1654. ).rejects.toMatchObject({ code: 'CONFIG_CHANGED', status: 409 });
  1655. expect(h.config.custom_provider?.work?.options?.baseURL).toBe('https://changed.example.com');
  1656. expect(h.config.custom_provider?.work?.models?.['m-1']?.limit).toEqual({
  1657. context: 100_000,
  1658. output: 8_000,
  1659. });
  1660. expect(h.cache.load().model_status['custom_provider:work/m-1']).toBeUndefined();
  1661. });
  1662. it('validates model parameter patches before running connectivity tests', async () => {
  1663. const h = makeHarness({
  1664. custom_provider: {
  1665. work: {
  1666. options: { apiKey: CUSTOM_KEY, baseURL: 'https://api.example.com' },
  1667. models: { 'm-1': {} },
  1668. },
  1669. },
  1670. });
  1671. await expect(
  1672. h.service.updateUserModelParameters({
  1673. providerId: 'custom_provider:work',
  1674. modelId: 'm-1',
  1675. contextLimit: 0,
  1676. maxOutputTokens: 16_000,
  1677. expectedContextLimit: 0,
  1678. expectedMaxOutputTokens: 0,
  1679. }),
  1680. ).rejects.toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });
  1681. expect(h.testCalls).toHaveLength(0);
  1682. });
  1683. });
  1684. describe('custom provider creation and duplication', () => {
  1685. it('create generates a provider key from the display name', async () => {
  1686. const h = makeHarness(undefined, { implicitCustomProviderThinking: true });
  1687. const provider = await h.service.createUserProvider({
  1688. name: 'OpenAI Work',
  1689. baseUrl: 'https://api.openai.com/v1',
  1690. apiKey: CUSTOM_KEY,
  1691. apiFormat: 'openai-completions',
  1692. models: [
  1693. { modelId: 'gpt-4.1', displayName: 'GPT-4.1', limit: { context: 128_000, output: 16_000 } },
  1694. ],
  1695. });
  1696. expect(provider.providerId).toBe('custom_provider:openai-work');
  1697. expect(provider.kind).toBe('custom');
  1698. expect(provider.enabled).toBe(true);
  1699. expect(provider.apiFormat).toBe('openai-completions');
  1700. expect(provider.hasApiKey).toBe(true);
  1701. expect(provider.maskedApiKey).toContain('****');
  1702. expect(provider.maskedApiKey).not.toBe(CUSTOM_KEY);
  1703. expect(provider).not.toHaveProperty('rawApiKey');
  1704. expect(JSON.stringify(provider)).not.toContain(CUSTOM_KEY);
  1705. expect(h.config.custom_provider?.['openai-work']?.options?.apiKey).toBe(CUSTOM_KEY);
  1706. expect(h.config.custom_provider?.['openai-work']?.models?.['gpt-4.1']?.limit).toEqual({
  1707. context: 128_000,
  1708. output: 16_000,
  1709. });
  1710. expect(h.config.custom_provider?.['openai-work']?.models?.['gpt-4.1']).toMatchObject({
  1711. reasoning: true,
  1712. thinking_config: { mode: 'switchable', default_value: 'true' },
  1713. });
  1714. expect(h.config.custom_provider?.['openai-work']?.models?.['gpt-4.1']).not.toHaveProperty(
  1715. 'thinking',
  1716. );
  1717. });
  1718. it('duplicates the complete provider config under a new identity without copying runtime state', async () => {
  1719. const h = makeHarness();
  1720. const source = await h.service.createUserProvider({
  1721. name: 'OpenAI Work',
  1722. baseUrl: 'https://api.openai.com/v1',
  1723. apiKey: CUSTOM_KEY,
  1724. apiFormat: 'openai-responses',
  1725. headers: { 'X-Tenant': 'tenant-a', Authorization: 'Bearer custom' },
  1726. models: [
  1727. {
  1728. modelId: 'gpt-5.6',
  1729. displayName: 'GPT-5.6',
  1730. limit: { context: 256_000, output: 128_000 },
  1731. effortOptions: ['low', 'xhigh', 'max'],
  1732. },
  1733. ],
  1734. });
  1735. const sourceConfig = h.config.custom_provider?.['openai-work'];
  1736. if (!sourceConfig) throw new Error('missing source provider fixture');
  1737. sourceConfig.npm = '@ai-sdk/openai';
  1738. h.config.defaultModel = `${source.providerId}/gpt-5.6`;
  1739. await h.cache.setModelStatus(`${source.providerId}/gpt-5.6`, {
  1740. state: 'available',
  1741. config_fingerprint: 'source-fingerprint',
  1742. });
  1743. const duplicate = await h.service.duplicateUserProvider({
  1744. providerId: source.providerId,
  1745. name: 'OpenAI Work Copy',
  1746. });
  1747. expect(duplicate).toMatchObject({
  1748. providerId: 'custom_provider:openai-work-copy',
  1749. name: 'OpenAI Work Copy',
  1750. apiFormat: 'openai-responses',
  1751. hasApiKey: true,
  1752. headerNames: ['Authorization', 'X-Tenant'],
  1753. models: [
  1754. {
  1755. modelId: 'gpt-5.6',
  1756. contextLimit: 256_000,
  1757. maxOutputTokens: 128_000,
  1758. effortOptions: ['low', 'xhigh', 'max'],
  1759. },
  1760. ],
  1761. });
  1762. expect(duplicate.models[0]?.status).toBeUndefined();
  1763. expect(h.config.defaultModel).toBe('custom_provider:openai-work/gpt-5.6');
  1764. const originalConfig = h.config.custom_provider?.['openai-work'];
  1765. const duplicateConfig = h.config.custom_provider?.['openai-work-copy'];
  1766. if (!originalConfig) throw new Error('missing original provider fixture');
  1767. const expectedDuplicateConfig = { ...originalConfig, name: 'OpenAI Work Copy' };
  1768. delete expectedDuplicateConfig.npm;
  1769. expect(duplicateConfig).toEqual(expectedDuplicateConfig);
  1770. expect(duplicateConfig).not.toHaveProperty('npm');
  1771. expect(duplicateConfig).not.toBe(originalConfig);
  1772. expect(duplicateConfig?.options).not.toBe(originalConfig?.options);
  1773. expect(duplicateConfig?.models).not.toBe(originalConfig?.models);
  1774. expect(duplicateConfig?.options?.apiKey).toBe(CUSTOM_KEY);
  1775. expect(h.cache.load().model_status['custom_provider:openai-work-copy/gpt-5.6']).toBeUndefined();
  1776. const secondDuplicate = await h.service.duplicateUserProvider({
  1777. providerId: source.providerId,
  1778. name: 'OpenAI Work Copy',
  1779. });
  1780. expect(secondDuplicate).toMatchObject({
  1781. providerId: 'custom_provider:openai-work-copy-2',
  1782. name: 'OpenAI Work Copy 2',
  1783. });
  1784. });
  1785. it('duplicates a provider when a retired sibling survives as a null config entry', async () => {
  1786. const h = makeHarness();
  1787. const source = await h.service.createUserProvider({
  1788. name: 'appintheloop',
  1789. baseUrl: 'https://api.example.com/v1',
  1790. apiKey: CUSTOM_KEY,
  1791. apiFormat: 'openai-completions',
  1792. models: [{ modelId: 'demo-model-1', displayName: 'demo-model-1' }],
  1793. });
  1794. // A retired provider can survive in a real config as `oaii-oauth: null`.
  1795. // Walking the tree must not dereference it.
  1796. (h.config.custom_provider as Record<string, unknown>)['oaii-oauth'] = null;
  1797. const duplicate = await h.service.duplicateUserProvider({
  1798. providerId: source.providerId,
  1799. name: 'appintheloop 副本',
  1800. });
  1801. expect(duplicate.name).toBe('appintheloop 副本');
  1802. expect(duplicate.providerId).not.toBe(source.providerId);
  1803. });
  1804. it('rejects duplicating an unknown provider', async () => {
  1805. const h = makeHarness();
  1806. await expect(
  1807. h.service.duplicateUserProvider({
  1808. providerId: 'custom_provider:missing',
  1809. name: 'Missing Copy',
  1810. }),
  1811. ).rejects.toMatchObject({ status: 404, code: 'PROVIDER_NOT_FOUND' });
  1812. });
  1813. it('create rejects invalid api keys and empty base url', async () => {
  1814. const h = makeHarness();
  1815. await expect(
  1816. h.service.createUserProvider({ name: 'X', baseUrl: 'https://x', apiKey: 'a****b' }),
  1817. ).rejects.toBeInstanceOf(LocalModelProviderError);
  1818. await expect(
  1819. h.service.createUserProvider({ name: 'X', baseUrl: ' ', apiKey: CUSTOM_KEY }),
  1820. ).rejects.toBeInstanceOf(LocalModelProviderError);
  1821. });
  1822. it('rejects an unsupported model configuration source', async () => {
  1823. const h = makeHarness();
  1824. await expect(
  1825. h.service.createUserProvider({
  1826. name: 'X',
  1827. baseUrl: 'https://x.example.com',
  1828. apiKey: CUSTOM_KEY,
  1829. models: [{ modelId: 'm-1', configurationSource: 'catalog' }],
  1830. }),
  1831. ).rejects.toMatchObject({ status: 400, code: 'VALIDATION_ERROR' });
  1832. });
  1833. });
  1834. describe('custom provider thinking configuration', () => {
  1835. it('stores user-defined effort choices without enum validation', async () => {
  1836. const h = makeHarness();
  1837. await h.service.createUserProvider({
  1838. name: 'X',
  1839. baseUrl: 'https://x.example.com',
  1840. apiKey: CUSTOM_KEY,
  1841. models: [
  1842. {
  1843. modelId: 'm-1',
  1844. effortOptions: [' low ', 'light', 'low', 'turbo'],
  1845. },
  1846. ],
  1847. });
  1848. expect(h.config.custom_provider?.x?.models?.['m-1']?.thinking).toEqual({
  1849. effortOptions: ['low', 'light', 'turbo'],
  1850. });
  1851. expect(h.service.listUserProviders()[0]?.models[0]).toMatchObject({
  1852. effortOptions: ['low', 'light', 'turbo'],
  1853. });
  1854. });
  1855. it('stores and returns only the configured Think Effort choices', async () => {
  1856. const h = makeHarness();
  1857. const provider = await h.service.createUserProvider({
  1858. name: 'Configured effort',
  1859. baseUrl: 'https://configured-effort.example.com',
  1860. apiKey: CUSTOM_KEY,
  1861. models: [
  1862. {
  1863. modelId: 'm-1',
  1864. effortOptions: ['low', 'xhigh', 'max'],
  1865. },
  1866. ],
  1867. });
  1868. const providerKey = provider.providerId.replace('custom_provider:', '');
  1869. expect(h.config.custom_provider?.[providerKey]?.models?.['m-1']?.thinking).toEqual({
  1870. effortOptions: ['low', 'xhigh', 'max'],
  1871. });
  1872. expect(h.service.listUserProviders()[0]?.models[0]).toMatchObject({
  1873. effortOptions: ['low', 'xhigh', 'max'],
  1874. });
  1875. });
  1876. it('clears a historical configuration default when the effort list is saved', async () => {
  1877. const h = makeHarness();
  1878. await h.service.createUserProvider({
  1879. name: 'Historical default',
  1880. baseUrl: 'https://historical-default.example.com',
  1881. apiKey: CUSTOM_KEY,
  1882. models: [{ modelId: 'm-1', effortOptions: ['low', 'high'] }],
  1883. });
  1884. const thinking = h.config.custom_provider?.['historical-default']?.models?.['m-1']?.thinking;
  1885. if (!thinking) throw new Error('Expected a saved thinking configuration');
  1886. (thinking as Record<string, unknown>).defaultEffort = 'high';
  1887. await h.service.updateUserProvider({
  1888. providerId: 'custom_provider:historical-default',
  1889. models: [{ modelId: 'm-1', effortOptions: ['low', 'high', 'max'] }],
  1890. });
  1891. expect(h.config.custom_provider?.['historical-default']?.models?.['m-1']?.thinking).toEqual({
  1892. effortOptions: ['low', 'high', 'max'],
  1893. });
  1894. });
  1895. it('stores MiniMax-M3 Think Effort choices like every other custom model', async () => {
  1896. const h = makeHarness();
  1897. await h.service.createUserProvider({
  1898. name: 'MiniMax Work',
  1899. baseUrl: 'https://api.minimax.example.com/messages',
  1900. apiKey: CUSTOM_KEY,
  1901. apiFormat: 'anthropic-messages',
  1902. models: [
  1903. {
  1904. modelId: 'MiniMax-M3',
  1905. effortOptions: ['off', 'on'],
  1906. },
  1907. ],
  1908. });
  1909. expect(h.config.custom_provider?.['minimax-work']?.models?.['MiniMax-M3']).toMatchObject({
  1910. reasoning: true,
  1911. thinking: { effortOptions: ['off', 'on'] },
  1912. });
  1913. expect(h.config.custom_provider?.['minimax-work']?.models?.['MiniMax-M3']).not.toHaveProperty(
  1914. 'thinking_config',
  1915. );
  1916. expect(h.config.custom_provider?.['minimax-work']?.models?.['MiniMax-M3']).not.toHaveProperty(
  1917. 'variants',
  1918. );
  1919. expect(h.service.listUserProviders()[0]?.models[0]).toMatchObject({
  1920. modelId: 'MiniMax-M3',
  1921. effortOptions: ['off', 'on'],
  1922. });
  1923. });
  1924. it('rejects non-positive model limits before writing the provider', async () => {
  1925. const h = makeHarness();
  1926. await expect(
  1927. h.service.createUserProvider({
  1928. name: 'X',
  1929. baseUrl: 'https://x.example.com',
  1930. apiKey: CUSTOM_KEY,
  1931. models: [{ modelId: 'm-1', limit: { context: 0, output: -1 } }],
  1932. }),
  1933. ).rejects.toMatchObject({ code: 'VALIDATION_ERROR' });
  1934. expect(h.config.custom_provider).toBeUndefined();
  1935. });
  1936. it('create with chinese name generates provider-<hex> key', async () => {
  1937. const h = makeHarness();
  1938. const provider = await h.service.createUserProvider({
  1939. name: '我的服务',
  1940. baseUrl: 'https://api.example.com',
  1941. apiKey: CUSTOM_KEY,
  1942. });
  1943. expect(provider.providerId).toBe('custom_provider:provider-a1b2c3');
  1944. expect(provider.name).toBe('我的服务');
  1945. });
  1946. it('activates the first configured model after its current fingerprint passes', async () => {
  1947. const h = makeHarness();
  1948. const provider = await h.service.createUserProvider({
  1949. name: 'Work',
  1950. baseUrl: 'https://api.example.com',
  1951. apiKey: CUSTOM_KEY,
  1952. models: [{ modelId: 'm-1' }, { modelId: 'm-2' }],
  1953. });
  1954. await h.service.testModel(provider.providerId, 'm-1');
  1955. await h.service.updateUserProvider({
  1956. providerId: provider.providerId,
  1957. saveAndUse: true,
  1958. });
  1959. expect(h.selectModel).toHaveBeenCalledWith('custom_provider:work/m-1');
  1960. });
  1961. it('update keeps the provider key immutable when name changes', async () => {
  1962. const h = makeHarness();
  1963. await h.service.createUserProvider({
  1964. name: 'Work',
  1965. baseUrl: 'https://api.example.com',
  1966. apiKey: CUSTOM_KEY,
  1967. });
  1968. const updated = await h.service.updateUserProvider({
  1969. providerId: 'custom_provider:work',
  1970. name: 'Renamed Provider',
  1971. });
  1972. expect(updated.providerId).toBe('custom_provider:work');
  1973. expect(updated.name).toBe('Renamed Provider');
  1974. expect(h.config.custom_provider?.work).toBeDefined();
  1975. expect(h.config.custom_provider?.['renamed-provider']).toBeUndefined();
  1976. });
  1977. it('update preserves capabilities for retained models and defaults newly added models', async () => {
  1978. const h = makeHarness(undefined, { implicitCustomProviderThinking: true });
  1979. await h.service.createUserProvider({
  1980. name: 'Work',
  1981. baseUrl: 'https://api.example.com',
  1982. apiKey: CUSTOM_KEY,
  1983. models: [{ modelId: 'kept' }, { modelId: 'removed' }],
  1984. });
  1985. const kept = h.config.custom_provider?.work?.models?.kept;
  1986. if (!kept) throw new Error('expected retained model fixture');
  1987. kept.thinking_config = { mode: 'switchable', default_value: 'false' };
  1988. kept.limit = { context: 96_000, output: 12_000 };
  1989. kept.variants = {
  1990. thinking: { thinking: { type: 'adaptive' } },
  1991. 'none-thinking': { thinking: { type: 'disabled' } },
  1992. };
  1993. await h.service.updateUserProvider({
  1994. providerId: 'custom_provider:work',
  1995. models: [{ modelId: 'kept' }, { modelId: 'added' }],
  1996. });
  1997. expect(h.config.custom_provider?.work?.models?.kept).toMatchObject({
  1998. reasoning: true,
  1999. thinking_config: { mode: 'switchable', default_value: 'false' },
  2000. limit: { context: 96_000, output: 12_000 },
  2001. variants: {
  2002. thinking: { thinking: { type: 'adaptive' } },
  2003. 'none-thinking': { thinking: { type: 'disabled' } },
  2004. },
  2005. });
  2006. expect(h.config.custom_provider?.work?.models?.added).toMatchObject({
  2007. reasoning: true,
  2008. thinking_config: { mode: 'switchable', default_value: 'true' },
  2009. });
  2010. expect(h.config.custom_provider?.work?.models?.removed).toBeUndefined();
  2011. });
  2012. it('update honors an explicit reasoning opt-out for an existing model', async () => {
  2013. const h = makeHarness(undefined, { implicitCustomProviderThinking: true });
  2014. await h.service.createUserProvider({
  2015. name: 'Work',
  2016. baseUrl: 'https://api.example.com',
  2017. apiKey: CUSTOM_KEY,
  2018. models: [{ modelId: 'plain' }],
  2019. });
  2020. await h.service.updateUserProvider({
  2021. providerId: 'custom_provider:work',
  2022. models: [{ modelId: 'plain', reasoning: false }],
  2023. });
  2024. expect(h.config.custom_provider?.work?.models?.plain).toMatchObject({ reasoning: false });
  2025. expect(h.config.custom_provider?.work?.models?.plain).not.toHaveProperty('thinking_config');
  2026. });
  2027. });
  2028. describe('custom provider default model recovery', () => {
  2029. it('resets the global default when an update removes its model', async () => {
  2030. const h = makeHarness({
  2031. defaultModel: 'custom_provider:work/removed',
  2032. defaultModelVariant: 'max',
  2033. custom_provider: {
  2034. work: {
  2035. name: 'Work',
  2036. options: { apiKey: CUSTOM_KEY, baseURL: 'https://api.example.com/v1' },
  2037. models: { kept: {}, removed: {} },
  2038. },
  2039. },
  2040. });
  2041. await h.service.updateUserProvider({
  2042. providerId: 'custom_provider:work',
  2043. models: [{ modelId: 'kept' }],
  2044. });
  2045. expect(h.config.defaultModel).toBe('minimax/MiniMax-M3');
  2046. expect(h.config.defaultModelVariant).toBeUndefined();
  2047. });
  2048. });
  2049. describe('custom provider updates', () => {
  2050. it('keeps legacy provider persistence unchanged without the TUI policy', async () => {
  2051. const h = makeHarness();
  2052. await h.service.createUserProvider({
  2053. name: 'Legacy',
  2054. baseUrl: 'https://api.example.com',
  2055. apiKey: CUSTOM_KEY,
  2056. models: [{ modelId: 'plain' }],
  2057. });
  2058. expect(h.config.custom_provider?.legacy?.models?.plain).toEqual({});
  2059. });
  2060. it('persists model reorder requests and preserves retained model fields', async () => {
  2061. const h = makeHarness({
  2062. custom_provider: {
  2063. work: {
  2064. name: 'Work',
  2065. api: 'openai-responses',
  2066. options: { apiKey: CUSTOM_KEY, baseURL: 'https://api.example.com/v1' },
  2067. models: {
  2068. 'm-a': {
  2069. name: 'Model A',
  2070. enabled: false,
  2071. attachment: true,
  2072. limit: { context: 128_000, output: 16_000 },
  2073. thinking: { effortOptions: ['low', 'high'] },
  2074. },
  2075. 'm-b': { name: 'Model B' },
  2076. 'm-c': { name: 'Model C', enabled: true },
  2077. },
  2078. },
  2079. },
  2080. });
  2081. const updated = await h.service.updateUserProvider({
  2082. providerId: 'custom_provider:work',
  2083. models: [{ modelId: 'm-c' }, { modelId: 'm-a' }, { modelId: 'm-b' }],
  2084. });
  2085. expect(Object.keys(h.config.custom_provider?.work?.models ?? {})).toEqual([
  2086. 'm-c',
  2087. 'm-a',
  2088. 'm-b',
  2089. ]);
  2090. expect(updated.models.map((model) => model.modelId)).toEqual(['m-c', 'm-a', 'm-b']);
  2091. expect(h.config.custom_provider?.work?.models?.['m-a']).toEqual({
  2092. name: 'Model A',
  2093. enabled: false,
  2094. attachment: true,
  2095. limit: { context: 128_000, output: 16_000 },
  2096. thinking: { effortOptions: ['low', 'high'] },
  2097. });
  2098. });
  2099. it('removes legacy npm metadata when a custom provider is edited', async () => {
  2100. const h = makeHarness({
  2101. custom_provider: {
  2102. work: {
  2103. name: 'Work',
  2104. npm: '@ai-sdk/anthropic',
  2105. api: 'anthropic-messages',
  2106. options: { apiKey: CUSTOM_KEY, baseURL: 'https://api.example.com/v1' },
  2107. models: { 'm-1': { limit: { context: 128_000, output: 16_000 } } },
  2108. },
  2109. },
  2110. });
  2111. await h.service.updateUserProvider({ providerId: 'custom_provider:work', name: 'Renamed' });
  2112. expect(h.config.custom_provider?.work).toMatchObject({ name: 'Renamed' });
  2113. expect(h.config.custom_provider?.work).not.toHaveProperty('npm');
  2114. });
  2115. it('update api_key tri-state: absent keeps, empty clears, masked rejects', async () => {
  2116. const h = makeHarness();
  2117. await h.service.createUserProvider({
  2118. name: 'Work',
  2119. baseUrl: 'https://api.example.com',
  2120. apiKey: CUSTOM_KEY,
  2121. });
  2122. await h.service.updateUserProvider({ providerId: 'work', name: 'Still Work' });
  2123. expect(h.config.custom_provider?.work?.options?.apiKey).toBe(CUSTOM_KEY);
  2124. await expect(
  2125. h.service.updateUserProvider({ providerId: 'work', apiKey: 'sk-c****efgh' }),
  2126. ).rejects.toBeInstanceOf(LocalModelProviderError);
  2127. expect(h.config.custom_provider?.work?.options?.apiKey).toBe(CUSTOM_KEY);
  2128. const cleared = await h.service.updateUserProvider({ providerId: 'work', apiKey: '' });
  2129. expect(h.config.custom_provider?.work?.options?.apiKey).toBeUndefined();
  2130. expect(cleared.hasApiKey).toBe(false);
  2131. await h.service.updateUserProvider({ providerId: 'work', apiKey: 'sk-new-key-987654321' });
  2132. expect(h.config.custom_provider?.work?.options?.apiKey).toBe('sk-new-key-987654321');
  2133. });
  2134. it('patches and removes write-only headers case-insensitively', async () => {
  2135. const h = makeHarness();
  2136. await h.service.createUserProvider({
  2137. name: 'Work',
  2138. baseUrl: 'https://api.example.com',
  2139. apiKey: CUSTOM_KEY,
  2140. headers: { 'X-Tenant': 'one', 'X-Trace': 'keep' },
  2141. models: [{ modelId: 'm-1' }],
  2142. });
  2143. const provider = await h.service.updateUserProvider({
  2144. providerId: 'work',
  2145. headers: { 'x-tenant': 'two', 'X-New': 'new' },
  2146. removeHeaders: ['x-trace'],
  2147. });
  2148. expect(h.config.custom_provider?.work?.options?.headers).toEqual({
  2149. 'x-tenant': 'two',
  2150. 'X-New': 'new',
  2151. });
  2152. expect(provider.headerNames).toEqual(['X-New', 'x-tenant']);
  2153. expect(JSON.stringify(provider)).not.toContain('two');
  2154. });
  2155. it('allows activation after a tested model configuration changes', async () => {
  2156. const h = makeHarness();
  2157. const provider = await h.service.createUserProvider({
  2158. name: 'Work',
  2159. baseUrl: 'https://api.example.com',
  2160. apiKey: CUSTOM_KEY,
  2161. models: [{ modelId: 'm-1', limit: { context: 128_000 } }],
  2162. });
  2163. await h.service.testModel(provider.providerId, 'm-1');
  2164. await h.service.updateUserProvider({
  2165. providerId: provider.providerId,
  2166. models: [{ modelId: 'm-1', limit: { context: 256_000 } }],
  2167. });
  2168. await expect(
  2169. h.service.updateUserProvider({ providerId: provider.providerId, saveAndUse: true }),
  2170. ).resolves.toMatchObject({ providerId: provider.providerId });
  2171. expect(h.selectModel).toHaveBeenCalledWith('custom_provider:work/m-1');
  2172. });
  2173. });
  2174. describe('custom provider deletion', () => {
  2175. it('update unknown provider yields 404', async () => {
  2176. const h = makeHarness();
  2177. await expect(
  2178. h.service.updateUserProvider({ providerId: 'custom_provider:nope', name: 'x' }),
  2179. ).rejects.toMatchObject({ status: 404 });
  2180. });
  2181. it('delete removes the provider and prunes cache even when default model points at it', async () => {
  2182. const h = makeHarness();
  2183. await h.service.createUserProvider({
  2184. name: 'Work',
  2185. baseUrl: 'https://api.example.com',
  2186. apiKey: CUSTOM_KEY,
  2187. models: [{ modelId: 'm-1' }],
  2188. });
  2189. h.config.defaultModel = 'custom_provider:work/m-1';
  2190. h.config.defaultModelVariant = 'max';
  2191. expect(h.config.defaultModel).toBe('custom_provider:work/m-1');
  2192. await h.cache.setProviderStatus('custom_provider:work', { state: 'available' });
  2193. await h.service.deleteUserProvider({ providerId: 'custom_provider:work' });
  2194. expect(h.config.custom_provider?.work).toBeUndefined();
  2195. expect(h.cache.load().provider_status['custom_provider:work']).toBeUndefined();
  2196. expect(h.config.defaultModel).toBe('minimax/MiniMax-M3');
  2197. expect(h.config.defaultModelVariant).toBeUndefined();
  2198. });
  2199. it('delete unknown provider yields 404', async () => {
  2200. const h = makeHarness();
  2201. await expect(
  2202. h.service.deleteUserProvider({ providerId: 'custom_provider:nope' }),
  2203. ).rejects.toMatchObject({ status: 404 });
  2204. });
  2205. });
  2206. describe('provider listings', () => {
  2207. it('uses the active API catalog and context overrides in both model lists', () => {
  2208. const h = makeHarness({
  2209. minimaxModelSource: 'minimax_api_key',
  2210. minimax_api: { apiKey: RAW_KEY, modelContextLimits: { 'MiniMax-M3': 1_000_000 } },
  2211. provider: {
  2212. minimax: {
  2213. options: { authMode: 'managed-login' },
  2214. models: {
  2215. 'remote-only': { name: 'Remote Only' },
  2216. 'MiniMax-M3': { limit: { context: 512_000, output: 128_000 } },
  2217. },
  2218. },
  2219. },
  2220. });
  2221. const provider = h.service
  2222. .listEffectiveProviders()
  2223. .find((item) => item.providerId === 'minimax');
  2224. const listed = listLocalRuntimeModels(h.config).filter((item) => item.providerId === 'minimax');
  2225. expect(provider?.models.map((model) => model.modelId)).toEqual(
  2226. listed.map((model) => model.modelId),
  2227. );
  2228. expect(provider?.models.some((model) => model.modelId === 'remote-only')).toBe(false);
  2229. expect(provider?.models.find((model) => model.modelId === 'MiniMax-M3')).toMatchObject({
  2230. contextLimit: 1_000_000,
  2231. contextWindowOptions: [512_000, 1_000_000],
  2232. });
  2233. });
  2234. it('lists builtin and custom providers, excludes disabled custom providers', async () => {
  2235. const h = makeHarness();
  2236. await h.service.upsertMinimaxApiKey({ apiKey: RAW_KEY });
  2237. await h.service.createUserProvider({
  2238. name: 'On',
  2239. baseUrl: 'https://on.example.com',
  2240. apiKey: CUSTOM_KEY,
  2241. models: [{ modelId: 'm-on' }],
  2242. });
  2243. await h.service.createUserProvider({
  2244. name: 'Off',
  2245. baseUrl: 'https://off.example.com',
  2246. apiKey: CUSTOM_KEY,
  2247. models: [{ modelId: 'm-off' }],
  2248. });
  2249. await h.service.updateUserProvider({ providerId: 'off', enabled: false });
  2250. const effective = h.service.listEffectiveProviders();
  2251. const ids = effective.map((p) => p.providerId);
  2252. expect(ids).toContain('minimax');
  2253. expect(ids).toContain('custom_provider:on');
  2254. expect(ids).not.toContain('custom_provider:off');
  2255. // minimax_api is no longer listed as a separate provider — source routing
  2256. // is handled by the resolver at inference time.
  2257. expect(ids).not.toContain('minimax_api');
  2258. const minimax = effective.find((p) => p.providerId === 'minimax');
  2259. expect(minimax?.source).toBe('provider');
  2260. expect(minimax?.kind).toBe('minimax-managed');
  2261. // user list still shows disabled providers with their config retained
  2262. const user = h.service.listUserProviders();
  2263. expect(user.map((p) => p.providerId).sort()).toEqual([
  2264. 'custom_provider:off',
  2265. 'custom_provider:on',
  2266. ]);
  2267. expect(user.find((p) => p.providerId === 'custom_provider:off')?.enabled).toBe(false);
  2268. });
  2269. it('hides minimax_api when no key is saved', () => {
  2270. const h = makeHarness();
  2271. const ids = h.service.listEffectiveProviders().map((p) => p.providerId);
  2272. expect(ids).not.toContain('minimax_api');
  2273. });
  2274. it('returns only masked keys in listings', async () => {
  2275. const h = makeHarness();
  2276. await h.service.upsertMinimaxApiKey({ apiKey: RAW_KEY });
  2277. await h.service.createUserProvider({
  2278. name: 'Work',
  2279. baseUrl: 'https://api.example.com',
  2280. apiKey: CUSTOM_KEY,
  2281. });
  2282. const effective = h.service.listEffectiveProviders();
  2283. const user = h.service.listUserProviders();
  2284. const status = h.service.getMinimaxApiKeyStatus();
  2285. for (const provider of [...effective, ...user]) {
  2286. if (provider.hasApiKey) {
  2287. expect(provider.maskedApiKey).toContain('****');
  2288. expect(provider).not.toHaveProperty('rawApiKey');
  2289. }
  2290. }
  2291. const customProvider = user.find((p) => p.providerId === 'custom_provider:work');
  2292. expect(customProvider?.maskedApiKey).not.toBe(CUSTOM_KEY);
  2293. expect(customProvider).not.toHaveProperty('rawApiKey');
  2294. expect(status).not.toHaveProperty('rawApiKey');
  2295. expect(status.maskedApiKey).not.toBe(RAW_KEY);
  2296. });
  2297. it('surfaces cache status on listed providers', async () => {
  2298. const h = makeHarness();
  2299. await h.service.createUserProvider({
  2300. name: 'Work',
  2301. baseUrl: 'https://api.example.com',
  2302. apiKey: CUSTOM_KEY,
  2303. models: [{ modelId: 'm-1' }],
  2304. });
  2305. h.setTestResult({
  2306. ok: false,
  2307. errorCode: 'unauthorized',
  2308. errorMessage: 'Authentication failed (HTTP 401)',
  2309. });
  2310. await h.service.testProvider('custom_provider:work');
  2311. const provider = h.service
  2312. .listUserProviders()
  2313. .find((p) => p.providerId === 'custom_provider:work');
  2314. expect(provider?.status).toMatchObject({ state: 'failed', lastErrorCode: 'unauthorized' });
  2315. });
  2316. it('drops a listed provider status after the tested configuration changes', async () => {
  2317. const h = makeHarness();
  2318. await h.service.createUserProvider({
  2319. name: 'Work',
  2320. baseUrl: 'https://api.example.com',
  2321. apiKey: CUSTOM_KEY,
  2322. models: [{ modelId: 'm-1' }],
  2323. });
  2324. await h.service.testProvider('custom_provider:work');
  2325. expect(
  2326. h.service.listUserProviders().find((p) => p.providerId === 'custom_provider:work')?.status,
  2327. ).toMatchObject({ state: 'available' });
  2328. await h.service.updateUserProvider({
  2329. providerId: 'custom_provider:work',
  2330. baseUrl: 'https://rotated.example.com',
  2331. });
  2332. // The cached verdict belongs to the previous base_url; keeping it would
  2333. // report the new endpoint as verified without ever contacting it.
  2334. expect(
  2335. h.service.listUserProviders().find((p) => p.providerId === 'custom_provider:work')?.status,
  2336. ).toBeUndefined();
  2337. });
  2338. });
  2339. describe('connection tests', () => {
  2340. it('tests a custom provider with its first model and records success in cache', async () => {
  2341. const h = makeHarness();
  2342. await h.service.createUserProvider({
  2343. name: 'Work',
  2344. baseUrl: 'https://api.example.com/v1',
  2345. apiKey: CUSTOM_KEY,
  2346. apiFormat: 'openai-completions',
  2347. models: [{ modelId: 'm-1', effortOptions: ['low'] }, { modelId: 'm-2' }],
  2348. });
  2349. const result = await h.service.testProvider('custom_provider:work');
  2350. expect(result.ok).toBe(true);
  2351. expect(h.testCalls[0]?.key).toMatch(/^custom_provider:work@sha256:/u);
  2352. expect(h.testCalls[0]?.target).toMatchObject({
  2353. api: 'openai-completions',
  2354. baseUrl: 'https://api.example.com/v1',
  2355. apiKey: CUSTOM_KEY,
  2356. modelId: 'm-1',
  2357. });
  2358. expect(h.cache.load().provider_status['custom_provider:work']).toMatchObject({
  2359. state: 'available',
  2360. last_tested_at: 1_750_000_000_000,
  2361. });
  2362. });
  2363. it('records failures with normalized error codes in the model cache', async () => {
  2364. const h = makeHarness();
  2365. await h.service.createUserProvider({
  2366. name: 'Work',
  2367. baseUrl: 'https://api.example.com',
  2368. apiKey: CUSTOM_KEY,
  2369. models: [{ modelId: 'm-1' }],
  2370. });
  2371. h.setTestResult({
  2372. ok: false,
  2373. errorCode: 'unauthorized',
  2374. errorMessage: 'Authentication failed (HTTP 401)',
  2375. });
  2376. const result = await h.service.testModel('custom_provider:work', 'm-1');
  2377. expect(result.ok).toBe(false);
  2378. expect(result.status).toMatchObject({ state: 'failed', lastErrorCode: 'unauthorized' });
  2379. expect(h.cache.load().model_status['custom_provider:work/m-1']).toMatchObject({
  2380. state: 'failed',
  2381. last_error_code: 'unauthorized',
  2382. });
  2383. });
  2384. it('tests the minimax_api provider against the derived base url and models', async () => {
  2385. const h = makeHarness();
  2386. await h.service.upsertMinimaxApiKey({ apiKey: RAW_KEY });
  2387. await h.service.testProvider('minimax_api');
  2388. expect(h.testCalls[0]?.target).toMatchObject({
  2389. api: 'anthropic-messages',
  2390. baseUrl: MINIMAX_API_DEFAULT_BASE_URL,
  2391. apiKey: RAW_KEY,
  2392. modelId: 'MiniMax-M3',
  2393. });
  2394. expect(h.testCalls.map((call) => call.target.minimaxM3ThinkingMode)).toEqual(['on', 'off']);
  2395. });
  2396. it('rejects testing providers without a key or unknown providers', async () => {
  2397. const h = makeHarness();
  2398. await expect(h.service.testProvider('minimax_api')).rejects.toMatchObject({ status: 400 });
  2399. await expect(h.service.testProvider('custom_provider:nope')).rejects.toMatchObject({
  2400. status: 404,
  2401. });
  2402. });
  2403. });