provider-application.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. import { describe, expect, it, vi } from 'vitest';
  2. import type { McodeProviderModel, McodeProviderView } from '../../src/provider/contract.js';
  3. import { McodeProviderApplication } from '../../src/provider/application.js';
  4. function createPort() {
  5. return {
  6. discoverUserModelsCandidate: vi.fn(async (): Promise<readonly McodeProviderModel[]> => []),
  7. listProviderPresets: vi.fn(async () => []),
  8. getCodexOAuthStatus: vi.fn(async () => ({
  9. state: 'disconnected' as const,
  10. providerId: 'openai-codex' as const,
  11. })),
  12. cancelCodexOAuthLogin: vi.fn(async () => ({ state: 'disconnected' as const, providerId: 'openai-codex' as const })),
  13. startCodexOAuthLogin: vi.fn(async () => ({
  14. state: 'pending' as const,
  15. providerId: 'openai-codex' as const,
  16. authUrl: 'https://auth.openai.example/authorize',
  17. })),
  18. listUserModelProviders: vi.fn(async () => [
  19. {
  20. providerId: 'custom_provider:openai',
  21. name: 'OpenAI',
  22. kind: 'custom' as const,
  23. enabled: true,
  24. apiFormat: 'openai-completions' as const,
  25. baseUrl: 'https://api.openai.com/v1',
  26. hasApiKey: true,
  27. configRevision: 'rev-1',
  28. maskedApiKey: 'sk-****1234',
  29. rawApiKey: 'must-never-cross-the-cli-boundary',
  30. models: [{ modelId: 'gpt-4.1', displayName: 'GPT-4.1', contextLimit: 32768, maxOutputTokens: 4096 }],
  31. },
  32. ]),
  33. getMiniMaxApiKeyStatus: vi.fn(async () => ({
  34. hasApiKey: true,
  35. maskedApiKey: 'sk-****5678',
  36. rawApiKey: 'must-never-cross-the-cli-boundary',
  37. })),
  38. getMiniMaxModelSource: vi.fn(async () => 'minimax_api_key' as const),
  39. setMiniMaxModelSource: vi.fn(async (source: 'token_plan' | 'minimax_api_key') => source),
  40. upsertMiniMaxApiKey: vi.fn(async () => undefined),
  41. createUserModelProvider: vi.fn(async () => undefined),
  42. saveUserModelProviderCandidate: vi.fn(async () => ({
  43. success: true,
  44. provider: { providerId: 'custom_provider:openai' },
  45. })),
  46. updateUserModelProvider: vi.fn(async () => undefined),
  47. deleteUserModelProvider: vi.fn(async () => undefined),
  48. testUserModelProvider: vi.fn(async () => ({
  49. success: true,
  50. status: { state: 'available' },
  51. })),
  52. testUserModel: vi.fn(async () => ({
  53. success: true,
  54. status: { state: 'available' },
  55. })),
  56. };
  57. }
  58. describe('McodeProviderApplication', () => {
  59. it('exposes a disconnected Codex OAuth row when Runtime makes it visible', async () => {
  60. const application = new McodeProviderApplication(createPort());
  61. const snapshot = await application.snapshot({ includeCodexOAuth: true });
  62. expect(snapshot.providers[0]).toMatchObject({
  63. providerId: 'openai-codex',
  64. name: 'OpenAI Codex',
  65. kind: 'codex-oauth',
  66. active: false,
  67. enabled: true,
  68. readOnly: true,
  69. hasApiKey: false,
  70. status: { state: 'disconnected' },
  71. });
  72. });
  73. it('omits the Codex OAuth row when Runtime marks it hidden', async () => {
  74. const port = createPort();
  75. port.getCodexOAuthStatus.mockResolvedValueOnce({
  76. state: 'hidden',
  77. providerId: 'openai-codex',
  78. });
  79. const application = new McodeProviderApplication(port);
  80. const snapshot = await application.snapshot({ includeCodexOAuth: true });
  81. expect(snapshot.providers).not.toContainEqual(
  82. expect.objectContaining({ providerId: 'openai-codex' }),
  83. );
  84. });
  85. it('builds a CLI-owned snapshot without exposing raw API keys', async () => {
  86. const port = createPort();
  87. const application = new McodeProviderApplication(port);
  88. const snapshot = await application.snapshot();
  89. expect(snapshot.providers.map((provider) => provider.providerId)).toEqual([
  90. 'minimax_oauth',
  91. 'minimax_api',
  92. 'custom_provider:openai',
  93. ]);
  94. expect(snapshot.providers[0]).toMatchObject({
  95. providerId: 'minimax_oauth',
  96. name: 'MiniMax OAuth',
  97. kind: 'minimax-oauth',
  98. active: false,
  99. enabled: true,
  100. readOnly: true,
  101. hasApiKey: false,
  102. });
  103. expect(snapshot.providers[1]).toMatchObject({
  104. kind: 'minimax-api-key',
  105. active: true,
  106. hasApiKey: true,
  107. });
  108. expect(JSON.stringify(snapshot)).toContain('MiniMax OAuth');
  109. expect(JSON.stringify(snapshot)).not.toContain('must-never-cross-the-cli-boundary');
  110. expect(snapshot.providers[2]).not.toHaveProperty('rawApiKey');
  111. expect(snapshot.providers[2]?.models[0]).toMatchObject({
  112. contextLimit: 32768,
  113. maxOutputTokens: 4096,
  114. });
  115. expect(port.getCodexOAuthStatus).not.toHaveBeenCalled();
  116. });
  117. it('marks OAuth active when the MiniMax source is Token Plan', async () => {
  118. const port = createPort();
  119. port.getMiniMaxModelSource.mockResolvedValueOnce('token_plan');
  120. const application = new McodeProviderApplication(port);
  121. const snapshot = await application.snapshot();
  122. expect(snapshot.minimaxModelSource).toBe('token_plan');
  123. expect(snapshot.providers[0]).toMatchObject({ kind: 'minimax-oauth', active: true });
  124. expect(snapshot.providers[1]).toMatchObject({ kind: 'minimax-api-key', active: false });
  125. });
  126. it('forwards MiniMax source changes through the CLI port', async () => {
  127. const port = createPort();
  128. const application = new McodeProviderApplication(port);
  129. await expect(application.setMiniMaxSource('token_plan')).resolves.toBe('token_plan');
  130. expect(port.setMiniMaxModelSource).toHaveBeenCalledWith('token_plan');
  131. });
  132. it('forwards custom provider creation through the CLI port', async () => {
  133. const port = createPort();
  134. const application = new McodeProviderApplication(port);
  135. await application.create({
  136. name: 'OpenAI',
  137. baseUrl: 'https://api.openai.com/v1',
  138. apiKey: 'sk-live',
  139. apiFormat: 'openai-completions',
  140. models: [{ modelId: 'gpt-4.1' }],
  141. saveAndUse: true,
  142. });
  143. expect(port.createUserModelProvider).toHaveBeenCalledWith({
  144. name: 'OpenAI',
  145. baseUrl: 'https://api.openai.com/v1',
  146. apiKey: 'sk-live',
  147. apiFormat: 'openai-completions',
  148. models: [{ modelId: 'gpt-4.1' }],
  149. saveAndUse: true,
  150. });
  151. });
  152. it('saves a tested provider candidate and selects its chosen model atomically', async () => {
  153. const port = createPort();
  154. const application = new McodeProviderApplication(port);
  155. const result = await application.saveCandidate({
  156. name: 'OpenAI',
  157. baseUrl: 'https://api.openai.com/v1',
  158. apiKey: 'sk-live',
  159. apiFormat: 'openai-responses',
  160. models: [{ modelId: 'gpt-5.6' }],
  161. modelId: 'gpt-5.6',
  162. saveAndUse: true,
  163. });
  164. expect(result).toMatchObject({ success: true });
  165. expect(port.saveUserModelProviderCandidate).toHaveBeenCalledWith({
  166. name: 'OpenAI',
  167. baseUrl: 'https://api.openai.com/v1',
  168. apiKey: 'sk-live',
  169. apiFormat: 'openai-responses',
  170. models: [{ modelId: 'gpt-5.6' }],
  171. modelId: 'gpt-5.6',
  172. saveAndUse: true,
  173. });
  174. });
  175. it('preserves the Runtime-supported OpenAI Responses protocol', async () => {
  176. const port = createPort();
  177. port.listUserModelProviders.mockResolvedValueOnce([
  178. {
  179. providerId: 'custom_provider:responses',
  180. name: 'OpenAI Responses',
  181. kind: 'custom',
  182. enabled: true,
  183. apiFormat: 'openai-responses',
  184. baseUrl: 'https://api.openai.com/v1',
  185. hasApiKey: true,
  186. models: [{ modelId: 'gpt-5.6' }],
  187. },
  188. ]);
  189. const application = new McodeProviderApplication(port);
  190. const snapshot = await application.snapshot();
  191. expect(
  192. snapshot.providers.find((provider) => provider.providerId === 'custom_provider:responses'),
  193. ).toMatchObject({ apiFormat: 'openai-responses' });
  194. });
  195. it('uses provider and model-specific connectivity tests', async () => {
  196. const port = createPort();
  197. const application = new McodeProviderApplication(port);
  198. await application.test('custom_provider:openai');
  199. await application.test('custom_provider:openai', 'gpt-4.1');
  200. expect(port.testUserModelProvider).toHaveBeenCalledWith('custom_provider:openai');
  201. expect(port.testUserModel).toHaveBeenCalledWith('custom_provider:openai', 'gpt-4.1');
  202. });
  203. it('keeps a disabled provider inactive even when a model is still selected', async () => {
  204. const port = createPort();
  205. port.listUserModelProviders.mockResolvedValueOnce([
  206. {
  207. providerId: 'custom_provider:byok',
  208. name: 'BYOK Vendor',
  209. kind: 'custom' as const,
  210. enabled: false,
  211. apiFormat: 'openai-completions' as const,
  212. baseUrl: 'https://api.byok.example/v1',
  213. hasApiKey: true,
  214. maskedApiKey: 'sk-****9999',
  215. rawApiKey: 'must-never-cross-the-cli-boundary',
  216. models: [{ modelId: 'byok-large-5', selected: true }],
  217. },
  218. ]);
  219. const application = new McodeProviderApplication(port);
  220. const snapshot = await application.snapshot();
  221. // Runtime drops disabled providers from the roster, so rendering the row
  222. // as active would contradict the "Disabled" label on the same line.
  223. expect(snapshot.providers[2]).toMatchObject({
  224. providerId: 'custom_provider:byok',
  225. enabled: false,
  226. active: false,
  227. });
  228. });
  229. it('keeps an enabled provider active while a model is selected', async () => {
  230. const port = createPort();
  231. port.listUserModelProviders.mockResolvedValueOnce([
  232. {
  233. providerId: 'custom_provider:byok',
  234. name: 'BYOK Vendor',
  235. kind: 'custom' as const,
  236. enabled: true,
  237. apiFormat: 'openai-completions' as const,
  238. baseUrl: 'https://api.byok.example/v1',
  239. hasApiKey: true,
  240. models: [{ modelId: 'byok-large-5', selected: true }],
  241. },
  242. ]);
  243. const application = new McodeProviderApplication(port);
  244. const snapshot = await application.snapshot();
  245. expect(snapshot.providers[2]).toMatchObject({ enabled: true, active: true });
  246. });
  247. });
  248. describe('saved provider model refresh', () => {
  249. const provider: McodeProviderView = {
  250. providerId: 'custom_provider:work', name: 'Work', kind: 'custom',
  251. enabled: true, readOnly: false, active: true, hasApiKey: true,
  252. configRevision: 'rev-1', baseUrl: 'https://models.example/v1',
  253. models: [{ modelId: 'old-model', selected: true }],
  254. };
  255. it('discovers with saved credentials and adds only new IDs without switching models', async () => {
  256. const port = createPort();
  257. port.discoverUserModelsCandidate.mockResolvedValue([
  258. { modelId: 'old-model', displayName: 'Do not overwrite saved settings' },
  259. { modelId: 'new-model', displayName: 'New model' }, { modelId: ' new-model ' }, { modelId: ' old-model ' },
  260. ]);
  261. await expect(new McodeProviderApplication(port).refreshModels(provider)).resolves.toBe(1);
  262. const identity = { providerId: provider.providerId, expectedRevision: 'rev-1', baseUrl: provider.baseUrl };
  263. expect(port.discoverUserModelsCandidate).toHaveBeenCalledWith(identity);
  264. expect(port.saveUserModelProviderCandidate).toHaveBeenCalledWith({
  265. ...identity, models: [{ modelId: 'old-model' }, { modelId: 'new-model', displayName: 'New model', configurationSource: 'discovered' }],
  266. modelId: 'new-model', skipConnectionTest: true, saveAndUse: false,
  267. });
  268. expect(port.createUserModelProvider).not.toHaveBeenCalled();
  269. expect(port.setMiniMaxModelSource).not.toHaveBeenCalled();
  270. expect(provider.models).toEqual([{ modelId: 'old-model', selected: true }]);
  271. });
  272. it.each([{ models: [] }, { models: [{ modelId: 'old-model' }] }])('does not save an empty or unchanged discovery result', async ({ models }) => {
  273. const port = createPort();
  274. port.discoverUserModelsCandidate.mockResolvedValue(models);
  275. await expect(new McodeProviderApplication(port).refreshModels(provider)).resolves.toBe(0);
  276. expect(port.saveUserModelProviderCandidate).not.toHaveBeenCalled();
  277. });
  278. it('keeps the saved configuration when discovery fails', async () => {
  279. const port = createPort();
  280. port.discoverUserModelsCandidate.mockRejectedValue(new Error('Authentication failed'));
  281. await expect(new McodeProviderApplication(port).refreshModels(provider)).rejects.toThrow('Authentication failed');
  282. expect(port.saveUserModelProviderCandidate).not.toHaveBeenCalled();
  283. });
  284. it('surfaces a revision conflict without retrying or creating a new account', async () => {
  285. const port = createPort();
  286. port.discoverUserModelsCandidate.mockResolvedValue([{ modelId: 'new-model' }]);
  287. port.saveUserModelProviderCandidate.mockRejectedValue(new Error('Configuration changed'));
  288. await expect(new McodeProviderApplication(port).refreshModels(provider)).rejects.toThrow('Configuration changed');
  289. expect(port.saveUserModelProviderCandidate).toHaveBeenCalledOnce();
  290. expect(port.createUserModelProvider).not.toHaveBeenCalled();
  291. });
  292. it('rejects a missing revision before making any request', async () => {
  293. const port = createPort();
  294. await expect(new McodeProviderApplication(port).refreshModels({ ...provider, configRevision: undefined })).rejects.toThrow('Reopen /provider');
  295. expect(port.discoverUserModelsCandidate).not.toHaveBeenCalled();
  296. });
  297. });