api-proxy-config.spec.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. /**
  2. * Settings/credentials/llm RPC domains and their host-stream frames over
  3. * createApiProxy: layered redacted describe, write-path rejection mapping,
  4. * value-free credential views, the directory/live-route merge, and the three
  5. * invalidation frames (settings/credentials/models changed).
  6. */
  7. import { describe, expect, it } from 'vitest'
  8. import { Context } from 'cordis'
  9. import z from 'schemastery'
  10. import AgentRegistry from '@deepseek-ai/dsh-agent'
  11. import SessionStore from '@deepseek-ai/dsh-session'
  12. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  13. import ToolRegistry from '@deepseek-ai/dsh-tools'
  14. import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
  15. import LlmService, { LlmAdapter } from '@deepseek-ai/dsh-llm'
  16. import type { GenerateOptions, LlmModelInfo, LlmProviderInfo, StreamChunk } from '@deepseek-ai/dsh-llm'
  17. import { Settings, settingsNamespace } from '@deepseek-ai/dsh-settings'
  18. import type { SettingsNamespace } from '@deepseek-ai/dsh-settings'
  19. import { Credentials } from '@deepseek-ai/dsh-credentials'
  20. import type { CredentialInfo, CredentialRef, ResolvedCredential } from '@deepseek-ai/dsh-credentials'
  21. import type { HostFrame } from '../src/api/index.ts'
  22. import type { RpcRequest, RpcResponse } from '../src/api/rpc.ts'
  23. import { RpcId } from '../src/api/rpc.ts'
  24. import { createApiProxy } from '../src/api-proxy.ts'
  25. const DEFAULTS = { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' }
  26. let nextRpc = 1
  27. function request<P>(payload: P): RpcRequest<P> {
  28. return { rpcId: RpcId(`req-${String(nextRpc++)}`), payload }
  29. }
  30. function expectOk<T>(response: RpcResponse<T>): T {
  31. expect(response.result.ok).toBe(true)
  32. if (!response.result.ok) throw new Error('unreachable')
  33. return response.result.value
  34. }
  35. function expectErr<T>(response: RpcResponse<T>): { code: string; message: string; details: unknown } {
  36. expect(response.result.ok).toBe(false)
  37. if (response.result.ok) throw new Error('unreachable')
  38. return response.result.error
  39. }
  40. /** In-memory settings provider: the seam base class owns all tested behavior. */
  41. class MemorySettings extends Settings {
  42. doc: Record<string, unknown>
  43. constructor(ctx: ConstructorParameters<typeof Settings>[0], options?: { doc?: Record<string, unknown>; readOnly?: boolean }) {
  44. super(ctx)
  45. this.doc = structuredClone(options?.doc ?? {})
  46. this.readOnly = options?.readOnly ?? false
  47. }
  48. private readonly readOnly: boolean
  49. get writable(): boolean {
  50. return !this.readOnly
  51. }
  52. protected load(): Promise<Record<string, unknown>> {
  53. return Promise.resolve(structuredClone(this.doc))
  54. }
  55. protected persist(ns: SettingsNamespace, section: Record<string, unknown>): Promise<void> {
  56. this.doc[ns] = structuredClone(section)
  57. return Promise.resolve()
  58. }
  59. }
  60. /** In-memory credential provider with an env-shadow double for the rejection path. */
  61. class MemoryCredentials extends Credentials {
  62. private readonly values = new Map<string, string>()
  63. constructor(ctx: ConstructorParameters<typeof Credentials>[0], options?: { shadowed?: string[] }) {
  64. super(ctx)
  65. this.shadowed = new Set(options?.shadowed ?? [])
  66. }
  67. private readonly shadowed: Set<string>
  68. resolve(ref: CredentialRef): Promise<ResolvedCredential | undefined> {
  69. if (this.shadowed.has(ref)) return Promise.resolve({ value: 'from-env', source: 'env' })
  70. const value = this.values.get(ref)
  71. return Promise.resolve(value === undefined ? undefined : { value, source: 'file' })
  72. }
  73. describe(ref: CredentialRef): Promise<CredentialInfo> {
  74. if (this.shadowed.has(ref)) return Promise.resolve({ configured: true, source: 'env', writable: false })
  75. const configured = this.values.has(ref)
  76. return Promise.resolve({ configured, ...configured ? { source: 'file' } : {}, writable: true })
  77. }
  78. set(ref: CredentialRef, value: string): Promise<void> {
  79. if (this.shadowed.has(ref)) {
  80. return Promise.reject(new Error(`credentials: ${ref} is shadowed by the read-only environment`))
  81. }
  82. this.values.set(ref, value)
  83. this.ctx.emit('credentials/updated', ref)
  84. return Promise.resolve()
  85. }
  86. unset(ref: CredentialRef): Promise<void> {
  87. if (this.shadowed.has(ref)) {
  88. return Promise.reject(new Error(`credentials: ${ref} is shadowed by the read-only environment`))
  89. }
  90. this.values.delete(ref)
  91. this.ctx.emit('credentials/updated', ref)
  92. return Promise.resolve()
  93. }
  94. }
  95. /** Catalog-serving adapter stub for the llm.models path. */
  96. class CatalogAdapter extends LlmAdapter {
  97. constructor(private readonly name: string, private readonly models: readonly string[]) {
  98. super()
  99. }
  100. override providerInfo(provider: string): LlmProviderInfo {
  101. return { id: provider, name: this.name }
  102. }
  103. override listModels(provider: string): Promise<readonly LlmModelInfo[]> {
  104. return Promise.resolve(this.models.map(id => ({ provider, id, name: id })))
  105. }
  106. async * stream(_options: GenerateOptions): AsyncIterable<StreamChunk> {
  107. throw new Error('not exercised')
  108. }
  109. }
  110. class BrokenCatalogAdapter extends CatalogAdapter {
  111. override listModels(): Promise<readonly LlmModelInfo[]> {
  112. return Promise.reject(new Error('catalog backend down'))
  113. }
  114. }
  115. const NS = settingsNamespace('llm-deepseek')
  116. const AdapterConfig = z.object({
  117. apiKey: z.string().role('secret'),
  118. apiKeyEnv: z.string().default('DEEPSEEK_API_KEY'),
  119. baseURL: z.string(),
  120. })
  121. async function harness(options?: {
  122. settings?: false | { doc?: Record<string, unknown>; readOnly?: boolean }
  123. credentials?: false | { shadowed?: string[] }
  124. /** Skip the directory registration to exercise a namespace the proxy does not expose. */
  125. configurableProviders?: false
  126. }): Promise<Context> {
  127. const ctx = new Context()
  128. await ctx.plugin(SessionStore)
  129. await ctx.plugin(SystemPrompt, { persona: '' })
  130. await ctx.plugin(ToolRegistry)
  131. await ctx.plugin(UserInteractionService)
  132. await ctx.plugin(AgentRegistry)
  133. await ctx.plugin(LlmService)
  134. if (options?.settings !== false) await ctx.plugin(MemorySettings, options?.settings)
  135. if (options?.credentials !== false) await ctx.plugin(MemoryCredentials, options?.credentials)
  136. // Model-provider namespaces plus the explicit Web preference and product
  137. // onboarding allowlists are the proxy's complete settings surface.
  138. if (options?.configurableProviders !== false) {
  139. ctx.llm.registerConfigurableProviders([
  140. { provider: 'deepseek-official', displayName: 'DeepSeek', settingsNs: 'llm-deepseek', settingsPath: [] },
  141. ])
  142. }
  143. // Host-stream opener reads the committed-workspace baseline; the stub
  144. // suffices — the real workspace composition is api-proxy-workspace.spec's.
  145. ctx.provide('workspace', { list: () => [] } as never)
  146. return ctx
  147. }
  148. /** Drain `count` host frames matching `types`, then abort the stream. */
  149. async function collectHost(
  150. api: ReturnType<typeof createApiProxy>,
  151. types: string[],
  152. count: number,
  153. run: () => Promise<void>,
  154. ): Promise<HostFrame[]> {
  155. const abort = new AbortController()
  156. const frames: HostFrame[] = []
  157. const stream = api.events.host(request({}), abort.signal)
  158. const consume = (async () => {
  159. for await (const frame of stream) {
  160. if (!types.includes(frame.payload.type)) continue
  161. frames.push(frame.payload)
  162. if (frames.length >= count) abort.abort()
  163. }
  164. })()
  165. await run()
  166. await consume
  167. return frames
  168. }
  169. describe('settings domain', () => {
  170. it('reports an actionable error when no settings provider is mounted', async () => {
  171. const ctx = await harness({ settings: false })
  172. const api = createApiProxy(ctx, DEFAULTS)
  173. const error = expectErr(await api.settings.describe(request({})))
  174. expect(error.code).toBe('internal')
  175. expect(error.message).toContain('dsh-settings-local')
  176. })
  177. it('describes layered redacted namespaces with their secret slots', async () => {
  178. const ctx = await harness({ settings: { doc: { 'llm-deepseek': { apiKey: 'user-secret', baseURL: 'https://user' } } } })
  179. ctx.settings.register(NS, AdapterConfig, { base: { baseURL: 'https://base' } })
  180. const api = createApiProxy(ctx, DEFAULTS)
  181. const value = expectOk(await api.settings.describe(request({})))
  182. expect(value.writable).toBe(true)
  183. expect(value.namespaces).toHaveLength(1)
  184. const view = value.namespaces[0]!
  185. expect(view.ns).toBe('llm-deepseek')
  186. expect(view.applies).toBe('live')
  187. expect((view.schema as { refs?: unknown }).refs).toBeDefined()
  188. expect(view.value).toEqual({ apiKeyEnv: 'DEEPSEEK_API_KEY', baseURL: 'https://user' })
  189. expect(view.base).toEqual({ baseURL: 'https://base' })
  190. expect(view.user).toEqual({ baseURL: 'https://user' })
  191. expect(view.secrets).toEqual([{ path: ['apiKey'], set: true }])
  192. expect(JSON.stringify(value)).not.toContain('user-secret')
  193. })
  194. it('serves model-provider and explicitly allowlisted Web namespaces only', async () => {
  195. // The settings seam is general: any plugin may register a namespace for
  196. // its own configuration. The Web configuration plane remains opt-in, so a
  197. // future internal plugin cannot become remotely configurable just by
  198. // registering; permission and the product onboarding namespace are the
  199. // non-model namespaces intentionally admitted by this surface.
  200. const ctx = await harness()
  201. ctx.settings.register(NS, AdapterConfig)
  202. ctx.settings.register(settingsNamespace('some-other-plugin'), z.object({ secretPath: z.string() }))
  203. ctx.settings.register(settingsNamespace('permission'), z.object({
  204. defaultPreset: z.union(['read-only', 'workspace-write']).required(),
  205. }), {
  206. base: { defaultPreset: 'read-only' },
  207. })
  208. const api = createApiProxy(ctx, DEFAULTS)
  209. const value = expectOk(await api.settings.describe(request({})))
  210. expect(value.namespaces.map(view => view.ns)).toEqual(['llm-deepseek', 'permission'])
  211. const permission = expectOk(await api.settings.mutate(request({
  212. ns: 'permission',
  213. ops: [{ op: 'set', path: ['defaultPreset'], value: 'workspace-write' }],
  214. })))
  215. expect(permission.value).toEqual({ defaultPreset: 'workspace-write' })
  216. for (const response of [
  217. await api.settings.update(request({ ns: 'some-other-plugin', patch: { secretPath: '/etc/shadow' } })),
  218. await api.settings.replace(request({ ns: 'some-other-plugin', section: {} })),
  219. ]) {
  220. const error = expectErr(response)
  221. expect(error.code).toBe('settings-not-exposed')
  222. expect(error.details).toEqual({ ns: 'some-other-plugin' })
  223. }
  224. // The write never reached the seam.
  225. expect(ctx.settings.describe().find(d => String(d.ns) === 'some-other-plugin')?.value).toEqual({})
  226. })
  227. it('serves the product onboarding namespace without invalidating the model catalog', async () => {
  228. const ctx = await harness()
  229. ctx.settings.register(settingsNamespace('ui-onboarding'), z.object({ welcomeNoticeVersion: z.string() }))
  230. const api = createApiProxy(ctx, DEFAULTS)
  231. expect(expectOk(await api.settings.describe(request({}))).namespaces.map(view => view.ns))
  232. .toEqual(['ui-onboarding'])
  233. const frames = await collectHost(api, ['host/settings-changed'], 1, async () => {
  234. expectOk(await api.settings.mutate(request({
  235. ns: 'ui-onboarding',
  236. ops: [{ op: 'set', path: ['welcomeNoticeVersion'], value: 'v1' }],
  237. })))
  238. })
  239. expect(frames).toEqual([{ type: 'host/settings-changed', ns: 'ui-onboarding' }])
  240. })
  241. it('refuses even a model-provider namespace once its directory entry is gone', async () => {
  242. const ctx = await harness({ configurableProviders: false })
  243. ctx.settings.register(NS, AdapterConfig)
  244. const api = createApiProxy(ctx, DEFAULTS)
  245. expect(expectOk(await api.settings.describe(request({}))).namespaces).toEqual([])
  246. expect(expectErr(await api.settings.update(request({ ns: 'llm-deepseek', patch: { baseURL: 'https://x' } }))).code)
  247. .toBe('settings-not-exposed')
  248. })
  249. it('invalidates the model catalog when a provider namespace changes, and broadcasts a raw-only change', async () => {
  250. // Editing `models` changes no route, so llm/adapters-updated never fires
  251. // and an open model picker kept serving the old catalog. And storing an
  252. // override equal to the resolved value emits nothing on settings/updated,
  253. // so another tab never learned the field became overridden.
  254. const ctx = await harness()
  255. ctx.settings.register(NS, AdapterConfig, { base: { baseURL: 'https://base' } })
  256. const api = createApiProxy(ctx, DEFAULTS)
  257. const frames = await collectHost(api, ['host/settings-changed', 'host/models-changed'], 2, async () => {
  258. await api.settings.update(request({ ns: 'llm-deepseek', patch: { baseURL: 'https://base' } }))
  259. })
  260. expect(frames).toEqual([
  261. { type: 'host/settings-changed', ns: 'llm-deepseek' },
  262. { type: 'host/models-changed' },
  263. ])
  264. // The resolved value never moved: base already said https://base.
  265. expect(expectOk(await api.settings.describe(request({}))).namespaces[0]!.value)
  266. .toEqual({ apiKeyEnv: 'DEEPSEEK_API_KEY', baseURL: 'https://base' })
  267. })
  268. it('broadcasts a permission change without invalidating the model catalog', async () => {
  269. const ctx = await harness()
  270. const permission = ctx.settings.register(settingsNamespace('permission'), z.object({
  271. defaultPreset: z.union(['read-only', 'workspace-write']).required(),
  272. }), {
  273. base: { defaultPreset: 'read-only' },
  274. })
  275. const api = createApiProxy(ctx, DEFAULTS)
  276. const frames = await collectHost(api, ['host/settings-changed', 'host/models-changed'], 1, async () => {
  277. await permission.update({ defaultPreset: 'workspace-write' })
  278. })
  279. expect(frames).toEqual([{ type: 'host/settings-changed', ns: 'permission' }])
  280. })
  281. it('maps a stale expectedRevision to settings-conflict carrying both revisions', async () => {
  282. const ctx = await harness()
  283. ctx.settings.register(NS, AdapterConfig)
  284. const api = createApiProxy(ctx, DEFAULTS)
  285. const opened = expectOk(await api.settings.describe(request({}))).namespaces[0]!.revision
  286. expect(expectOk(await api.settings.update(request({ ns: 'llm-deepseek', patch: { baseURL: 'https://first' }, expectedRevision: opened })))
  287. .revision).toBe(opened + 1)
  288. const error = expectErr(await api.settings.update(request({ ns: 'llm-deepseek', patch: { baseURL: 'https://second' }, expectedRevision: opened })))
  289. expect(error.code).toBe('settings-conflict')
  290. expect(error.details).toEqual({ ns: 'llm-deepseek', expected: opened, actual: opened + 1 })
  291. // The refused write changed nothing.
  292. expect(expectOk(await api.settings.describe(request({}))).namespaces[0]!.user).toEqual({ baseURL: 'https://first' })
  293. })
  294. it('updates the user layer, answers with the new redacted view, and broadcasts the frame', async () => {
  295. const ctx = await harness()
  296. ctx.settings.register(NS, AdapterConfig, { base: { baseURL: 'https://base' } })
  297. const api = createApiProxy(ctx, DEFAULTS)
  298. const frames = await collectHost(api, ['host/settings-changed'], 1, async () => {
  299. const view = expectOk(await api.settings.update(request({ ns: 'llm-deepseek', patch: { apiKey: 'sk-new', baseURL: 'https://next' } })))
  300. expect(view.value).toEqual({ apiKeyEnv: 'DEEPSEEK_API_KEY', baseURL: 'https://next' })
  301. expect(view.user).toEqual({ baseURL: 'https://next' })
  302. expect(view.secrets).toEqual([{ path: ['apiKey'], set: true }])
  303. expect(JSON.stringify(view)).not.toContain('sk-new')
  304. })
  305. expect(frames).toEqual([{ type: 'host/settings-changed', ns: 'llm-deepseek' }])
  306. })
  307. it('replace resets the user layer wholesale', async () => {
  308. const ctx = await harness({ settings: { doc: { 'llm-deepseek': { baseURL: 'https://user' } } } })
  309. ctx.settings.register(NS, AdapterConfig)
  310. const api = createApiProxy(ctx, DEFAULTS)
  311. const view = expectOk(await api.settings.replace(request({ ns: 'llm-deepseek', section: {} })))
  312. expect(view.value).toEqual({ apiKeyEnv: 'DEEPSEEK_API_KEY' })
  313. expect(view.user).toEqual({})
  314. })
  315. it.each([
  316. ['an invalid namespace name', 'Not A Namespace', {}],
  317. ['a schema-invalid patch', 'llm-deepseek', { baseURL: 42 }],
  318. ])('rejects %s as settings-rejected', async (_case, ns, patch) => {
  319. const ctx = await harness()
  320. ctx.settings.register(NS, AdapterConfig)
  321. const api = createApiProxy(ctx, DEFAULTS)
  322. const error = expectErr(await api.settings.update(request({ ns, patch })))
  323. expect(error.code).toBe('settings-rejected')
  324. expect(error.details).toEqual({ ns })
  325. })
  326. it('answers an unregistered namespace exactly like an unexposed one', async () => {
  327. // Deliberately indistinguishable: separating "does not exist" from
  328. // "exists but is not yours to configure" would let a caller enumerate the
  329. // registered namespaces one probe at a time.
  330. const ctx = await harness()
  331. ctx.settings.register(NS, AdapterConfig)
  332. ctx.settings.register(settingsNamespace('some-other-plugin'), z.object({ secretPath: z.string() }))
  333. const api = createApiProxy(ctx, DEFAULTS)
  334. const unknown = expectErr(await api.settings.update(request({ ns: 'unknown-ns', patch: {} })))
  335. const unexposed = expectErr(await api.settings.update(request({ ns: 'some-other-plugin', patch: {} })))
  336. expect(unknown.code).toBe('settings-not-exposed')
  337. expect(unexposed.code).toBe(unknown.code)
  338. expect(unexposed.message.replace('some-other-plugin', 'unknown-ns')).toBe(unknown.message)
  339. })
  340. it('maps a read-only provider refusal onto the same rejection', async () => {
  341. const ctx = await harness({ settings: { readOnly: true } })
  342. ctx.settings.register(NS, AdapterConfig)
  343. const api = createApiProxy(ctx, DEFAULTS)
  344. const value = expectOk(await api.settings.describe(request({})))
  345. expect(value.writable).toBe(false)
  346. const error = expectErr(await api.settings.update(request({ ns: 'llm-deepseek', patch: {} })))
  347. expect(error.code).toBe('settings-rejected')
  348. expect(error.message).toContain('read-only')
  349. })
  350. })
  351. describe('credentials domain', () => {
  352. it('reports an actionable error when no credential provider is mounted', async () => {
  353. const ctx = await harness({ credentials: false })
  354. const api = createApiProxy(ctx, DEFAULTS)
  355. const error = expectErr(await api.credentials.describe(request({ refs: ['A'] })))
  356. expect(error.code).toBe('internal')
  357. expect(error.message).toContain('dsh-credentials-local')
  358. })
  359. it('describes value-free views and flips state through set/unset with frames', async () => {
  360. const ctx = await harness()
  361. const api = createApiProxy(ctx, DEFAULTS)
  362. const before = expectOk(await api.credentials.describe(request({ refs: ['OPENAI_API_KEY'] })))
  363. expect(before.credentials).toEqual({ OPENAI_API_KEY: { configured: false, writable: true } })
  364. const frames = await collectHost(api, ['host/credentials-changed'], 2, async () => {
  365. expectOk(await api.credentials.set(request({ ref: 'OPENAI_API_KEY', value: 'sk-secret' })))
  366. const after = expectOk(await api.credentials.describe(request({ refs: ['OPENAI_API_KEY'] })))
  367. expect(after.credentials).toEqual({ OPENAI_API_KEY: { configured: true, source: 'file', writable: true } })
  368. expect(JSON.stringify(after)).not.toContain('sk-secret')
  369. expectOk(await api.credentials.unset(request({ ref: 'OPENAI_API_KEY' })))
  370. })
  371. expect(frames).toEqual([
  372. { type: 'host/credentials-changed', ref: 'OPENAI_API_KEY' },
  373. { type: 'host/credentials-changed', ref: 'OPENAI_API_KEY' },
  374. ])
  375. })
  376. it('maps a shadowed write onto credential-rejected for set and unset alike', async () => {
  377. const ctx = await harness({ credentials: { shadowed: ['DEEPSEEK_API_KEY'] } })
  378. const api = createApiProxy(ctx, DEFAULTS)
  379. const described = expectOk(await api.credentials.describe(request({ refs: ['DEEPSEEK_API_KEY'] })))
  380. expect(described.credentials['DEEPSEEK_API_KEY']).toEqual({ configured: true, source: 'env', writable: false })
  381. const setError = expectErr(await api.credentials.set(request({ ref: 'DEEPSEEK_API_KEY', value: 'x' })))
  382. expect(setError.code).toBe('credential-rejected')
  383. expect(setError.details).toEqual({ ref: 'DEEPSEEK_API_KEY' })
  384. const unsetError = expectErr(await api.credentials.unset(request({ ref: 'DEEPSEEK_API_KEY' })))
  385. expect(unsetError.code).toBe('credential-rejected')
  386. })
  387. })
  388. describe('llm domain', () => {
  389. it('merges the configurable directory with live routes and appends undeclared ones', async () => {
  390. const ctx = await harness({ configurableProviders: false })
  391. ctx.llm.registerConfigurableProviders([
  392. { provider: 'deepseek-official', displayName: 'DeepSeek', settingsNs: 'llm-deepseek', settingsPath: [] },
  393. { provider: 'openai', displayName: 'openai', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'openai'] },
  394. ])
  395. ctx.llm.registerAdapter(['deepseek-official'], new CatalogAdapter('DeepSeek', ['deepseek-v4-flash']))
  396. ctx.llm.registerAdapter(['undeclared'], new CatalogAdapter('Undeclared', ['u-1']))
  397. const api = createApiProxy(ctx, DEFAULTS)
  398. const value = expectOk(await api.llm.providers(request({})))
  399. expect(value.providers).toEqual([
  400. { provider: 'deepseek-official', displayName: 'DeepSeek', settingsNs: 'llm-deepseek', settingsPath: [], active: true },
  401. { provider: 'openai', displayName: 'openai', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'openai'], active: false },
  402. { provider: 'undeclared', displayName: 'Undeclared', settingsNs: '', settingsPath: [], active: true },
  403. ])
  404. })
  405. it('serves the host-scoped catalog with per-provider failures contained', async () => {
  406. const ctx = await harness()
  407. ctx.llm.registerAdapter(['deepseek-official'], new CatalogAdapter('DeepSeek', ['deepseek-v4-flash', 'deepseek-v4-pro']))
  408. ctx.llm.registerAdapter(['broken'], new BrokenCatalogAdapter('Broken', []))
  409. const api = createApiProxy(ctx, DEFAULTS)
  410. const value = expectOk(await api.llm.models(request({})))
  411. expect(value.groups).toEqual([{
  412. id: 'deepseek-official',
  413. name: 'DeepSeek',
  414. models: [
  415. { id: 'deepseek-v4-flash', name: 'deepseek-v4-flash' },
  416. { id: 'deepseek-v4-pro', name: 'deepseek-v4-pro' },
  417. ],
  418. }])
  419. expect(value.failures).toEqual([{ id: 'broken', name: 'Broken', message: 'catalog backend down' }])
  420. })
  421. it('broadcasts host/models-changed at every topology commit point', async () => {
  422. const ctx = await harness()
  423. const api = createApiProxy(ctx, DEFAULTS)
  424. const frames = await collectHost(api, ['host/models-changed'], 2, async () => {
  425. const dispose = ctx.llm.registerAdapter(['deepseek-official'], new CatalogAdapter('DeepSeek', []))
  426. dispose()
  427. return Promise.resolve()
  428. })
  429. expect(frames).toEqual([{ type: 'host/models-changed' }, { type: 'host/models-changed' }])
  430. })
  431. })