provider-application.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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' }],
  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(port.getCodexOAuthStatus).not.toHaveBeenCalled();
  112. });
  113. it('marks OAuth active when the MiniMax source is Token Plan', async () => {
  114. const port = createPort();
  115. port.getMiniMaxModelSource.mockResolvedValueOnce('token_plan');
  116. const application = new McodeProviderApplication(port);
  117. const snapshot = await application.snapshot();
  118. expect(snapshot.minimaxModelSource).toBe('token_plan');
  119. expect(snapshot.providers[0]).toMatchObject({ kind: 'minimax-oauth', active: true });
  120. expect(snapshot.providers[1]).toMatchObject({ kind: 'minimax-api-key', active: false });
  121. });
  122. it('forwards MiniMax source changes through the CLI port', async () => {
  123. const port = createPort();
  124. const application = new McodeProviderApplication(port);
  125. await expect(application.setMiniMaxSource('token_plan')).resolves.toBe('token_plan');
  126. expect(port.setMiniMaxModelSource).toHaveBeenCalledWith('token_plan');
  127. });
  128. it('forwards custom provider creation through the CLI port', async () => {
  129. const port = createPort();
  130. const application = new McodeProviderApplication(port);
  131. await application.create({
  132. name: 'OpenAI',
  133. baseUrl: 'https://api.openai.com/v1',
  134. apiKey: 'sk-live',
  135. apiFormat: 'openai-completions',
  136. models: [{ modelId: 'gpt-4.1' }],
  137. saveAndUse: true,
  138. });
  139. expect(port.createUserModelProvider).toHaveBeenCalledWith({
  140. name: 'OpenAI',
  141. baseUrl: 'https://api.openai.com/v1',
  142. apiKey: 'sk-live',
  143. apiFormat: 'openai-completions',
  144. models: [{ modelId: 'gpt-4.1' }],
  145. saveAndUse: true,
  146. });
  147. });
  148. it('saves a tested provider candidate and selects its chosen model atomically', async () => {
  149. const port = createPort();
  150. const application = new McodeProviderApplication(port);
  151. const result = await application.saveCandidate({
  152. name: 'OpenAI',
  153. baseUrl: 'https://api.openai.com/v1',
  154. apiKey: 'sk-live',
  155. apiFormat: 'openai-responses',
  156. models: [{ modelId: 'gpt-5.6' }],
  157. modelId: 'gpt-5.6',
  158. saveAndUse: true,
  159. });
  160. expect(result).toMatchObject({ success: true });
  161. expect(port.saveUserModelProviderCandidate).toHaveBeenCalledWith({
  162. name: 'OpenAI',
  163. baseUrl: 'https://api.openai.com/v1',
  164. apiKey: 'sk-live',
  165. apiFormat: 'openai-responses',
  166. models: [{ modelId: 'gpt-5.6' }],
  167. modelId: 'gpt-5.6',
  168. saveAndUse: true,
  169. });
  170. });
  171. it('preserves the Runtime-supported OpenAI Responses protocol', async () => {
  172. const port = createPort();
  173. port.listUserModelProviders.mockResolvedValueOnce([
  174. {
  175. providerId: 'custom_provider:responses',
  176. name: 'OpenAI Responses',
  177. kind: 'custom',
  178. enabled: true,
  179. apiFormat: 'openai-responses',
  180. baseUrl: 'https://api.openai.com/v1',
  181. hasApiKey: true,
  182. models: [{ modelId: 'gpt-5.6' }],
  183. },
  184. ]);
  185. const application = new McodeProviderApplication(port);
  186. const snapshot = await application.snapshot();
  187. expect(
  188. snapshot.providers.find((provider) => provider.providerId === 'custom_provider:responses'),
  189. ).toMatchObject({ apiFormat: 'openai-responses' });
  190. });
  191. it('uses provider and model-specific connectivity tests', async () => {
  192. const port = createPort();
  193. const application = new McodeProviderApplication(port);
  194. await application.test('custom_provider:openai');
  195. await application.test('custom_provider:openai', 'gpt-4.1');
  196. expect(port.testUserModelProvider).toHaveBeenCalledWith('custom_provider:openai');
  197. expect(port.testUserModel).toHaveBeenCalledWith('custom_provider:openai', 'gpt-4.1');
  198. });
  199. it('keeps a disabled provider inactive even when a model is still selected', async () => {
  200. const port = createPort();
  201. port.listUserModelProviders.mockResolvedValueOnce([
  202. {
  203. providerId: 'custom_provider:byok',
  204. name: 'BYOK Vendor',
  205. kind: 'custom' as const,
  206. enabled: false,
  207. apiFormat: 'openai-completions' as const,
  208. baseUrl: 'https://api.byok.example/v1',
  209. hasApiKey: true,
  210. maskedApiKey: 'sk-****9999',
  211. rawApiKey: 'must-never-cross-the-cli-boundary',
  212. models: [{ modelId: 'byok-large-5', selected: true }],
  213. },
  214. ]);
  215. const application = new McodeProviderApplication(port);
  216. const snapshot = await application.snapshot();
  217. // Runtime drops disabled providers from the roster, so rendering the row
  218. // as active would contradict the "Disabled" label on the same line.
  219. expect(snapshot.providers[2]).toMatchObject({
  220. providerId: 'custom_provider:byok',
  221. enabled: false,
  222. active: false,
  223. });
  224. });
  225. it('keeps an enabled provider active while a model is selected', async () => {
  226. const port = createPort();
  227. port.listUserModelProviders.mockResolvedValueOnce([
  228. {
  229. providerId: 'custom_provider:byok',
  230. name: 'BYOK Vendor',
  231. kind: 'custom' as const,
  232. enabled: true,
  233. apiFormat: 'openai-completions' as const,
  234. baseUrl: 'https://api.byok.example/v1',
  235. hasApiKey: true,
  236. models: [{ modelId: 'byok-large-5', selected: true }],
  237. },
  238. ]);
  239. const application = new McodeProviderApplication(port);
  240. const snapshot = await application.snapshot();
  241. expect(snapshot.providers[2]).toMatchObject({ enabled: true, active: true });
  242. });
  243. });
  244. describe('saved provider model refresh', () => {
  245. const provider: McodeProviderView = {
  246. providerId: 'custom_provider:work', name: 'Work', kind: 'custom',
  247. enabled: true, readOnly: false, active: true, hasApiKey: true,
  248. configRevision: 'rev-1', baseUrl: 'https://models.example/v1',
  249. models: [{ modelId: 'old-model', selected: true }],
  250. };
  251. it('discovers with saved credentials and adds only new IDs without switching models', async () => {
  252. const port = createPort();
  253. port.discoverUserModelsCandidate.mockResolvedValue([
  254. { modelId: 'old-model', displayName: 'Do not overwrite saved settings' },
  255. { modelId: 'new-model', displayName: 'New model' }, { modelId: ' new-model ' }, { modelId: ' old-model ' },
  256. ]);
  257. await expect(new McodeProviderApplication(port).refreshModels(provider)).resolves.toBe(1);
  258. const identity = { providerId: provider.providerId, expectedRevision: 'rev-1', baseUrl: provider.baseUrl };
  259. expect(port.discoverUserModelsCandidate).toHaveBeenCalledWith(identity);
  260. expect(port.saveUserModelProviderCandidate).toHaveBeenCalledWith({
  261. ...identity, models: [{ modelId: 'old-model' }, { modelId: 'new-model', displayName: 'New model', configurationSource: 'discovered' }],
  262. modelId: 'new-model', skipConnectionTest: true, saveAndUse: false,
  263. });
  264. expect(port.createUserModelProvider).not.toHaveBeenCalled();
  265. expect(port.setMiniMaxModelSource).not.toHaveBeenCalled();
  266. expect(provider.models).toEqual([{ modelId: 'old-model', selected: true }]);
  267. });
  268. it.each([{ models: [] }, { models: [{ modelId: 'old-model' }] }])('does not save an empty or unchanged discovery result', async ({ models }) => {
  269. const port = createPort();
  270. port.discoverUserModelsCandidate.mockResolvedValue(models);
  271. await expect(new McodeProviderApplication(port).refreshModels(provider)).resolves.toBe(0);
  272. expect(port.saveUserModelProviderCandidate).not.toHaveBeenCalled();
  273. });
  274. it('keeps the saved configuration when discovery fails', async () => {
  275. const port = createPort();
  276. port.discoverUserModelsCandidate.mockRejectedValue(new Error('Authentication failed'));
  277. await expect(new McodeProviderApplication(port).refreshModels(provider)).rejects.toThrow('Authentication failed');
  278. expect(port.saveUserModelProviderCandidate).not.toHaveBeenCalled();
  279. });
  280. it('surfaces a revision conflict without retrying or creating a new account', async () => {
  281. const port = createPort();
  282. port.discoverUserModelsCandidate.mockResolvedValue([{ modelId: 'new-model' }]);
  283. port.saveUserModelProviderCandidate.mockRejectedValue(new Error('Configuration changed'));
  284. await expect(new McodeProviderApplication(port).refreshModels(provider)).rejects.toThrow('Configuration changed');
  285. expect(port.saveUserModelProviderCandidate).toHaveBeenCalledOnce();
  286. expect(port.createUserModelProvider).not.toHaveBeenCalled();
  287. });
  288. it('rejects a missing revision before making any request', async () => {
  289. const port = createPort();
  290. await expect(new McodeProviderApplication(port).refreshModels({ ...provider, configRevision: undefined })).rejects.toThrow('Reopen /provider');
  291. expect(port.discoverUserModelsCandidate).not.toHaveBeenCalled();
  292. });
  293. });