api-proxy-models.spec.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. /**
  2. * Web session model-directory and selection behavior: dynamic provider grouping,
  3. * provider-local catalog failures, logged-selection restoration without stale
  4. * catalog injection, advisory pass-through models, and the prompt-assembly
  5. * boundary for a running selection change.
  6. */
  7. import { describe, expect, it, vi } from 'vitest'
  8. import { Context } from '@deepseek-ai/cordis'
  9. import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent'
  10. import type { Agent } from '@deepseek-ai/dsh-agent'
  11. import AttachmentStore from '@deepseek-ai/dsh-attachment'
  12. import LlmService, { LlmAdapter, ReasoningEffortId } from '@deepseek-ai/dsh-llm'
  13. import type {
  14. GenerateOptions, LlmCallConfig, LlmModelInfo, LlmModelReasoningInfo, LlmProviderInfo,
  15. LlmResolvedModelInfo, StreamChunk,
  16. UserMessage,
  17. } from '@deepseek-ai/dsh-llm'
  18. import SessionStore from '@deepseek-ai/dsh-session'
  19. import type { SessionId } from '@deepseek-ai/dsh-session'
  20. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  21. import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
  22. import type { RpcRequest } from '@deepseek-ai/dsh-host-apiproxy/api/rpc'
  23. import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api/rpc'
  24. import { createApiProxy } from '../src/api-proxy.ts'
  25. let nextRpc = 1
  26. function request<P>(payload: P): RpcRequest<P> {
  27. return { rpcId: RpcId(`models-${String(nextRpc++)}`), payload }
  28. }
  29. class CatalogAdapter extends LlmAdapter {
  30. constructor(
  31. private readonly name: string,
  32. private readonly models: readonly LlmModelInfo[] | Error,
  33. private readonly reasoning?: LlmModelReasoningInfo,
  34. private readonly exactError?: Error,
  35. ) {
  36. super()
  37. }
  38. override providerInfo(provider: string): LlmProviderInfo {
  39. return { id: provider, name: this.name }
  40. }
  41. override listModels(): Promise<readonly LlmModelInfo[]> {
  42. return this.models instanceof Error
  43. ? Promise.reject(this.models)
  44. : Promise.resolve(this.models)
  45. }
  46. override resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
  47. if (this.exactError !== undefined) return Promise.reject(this.exactError)
  48. return Promise.resolve({
  49. provider,
  50. id: model,
  51. name: model,
  52. ...this.reasoning === undefined ? {} : { reasoning: this.reasoning },
  53. })
  54. }
  55. override async *stream(_options: GenerateOptions): AsyncIterable<StreamChunk> {
  56. // Catalog tests never enter provider streaming.
  57. }
  58. }
  59. const REASONING: LlmModelReasoningInfo = {
  60. efforts: [
  61. { id: ReasoningEffortId('off'), name: 'Off' },
  62. { id: ReasoningEffortId('high'), name: 'High' },
  63. { id: ReasoningEffortId('max'), name: 'Max' },
  64. ],
  65. defaultEffort: ReasoningEffortId('high'),
  66. }
  67. async function harness(logged?: {
  68. provider: string
  69. model: string
  70. reasoningEffort?: ReasoningEffortId
  71. }): Promise<{
  72. ctx: Context
  73. agent: Agent
  74. sessionId: SessionId
  75. }> {
  76. const ctx = new Context()
  77. await ctx.plugin(SessionStore)
  78. await ctx.plugin(SystemPrompt, { persona: '' })
  79. await ctx.plugin(LlmService)
  80. await ctx.plugin(UserInteractionService)
  81. await ctx.plugin(AgentRegistry)
  82. ctx.llm.registerAdapter(['deepseek-official'], new CatalogAdapter('DeepSeek', [
  83. { provider: 'deepseek-official', id: 'deepseek-chat', name: 'DeepSeek Chat' },
  84. { provider: 'deepseek-official', id: 'deepseek-reasoner', name: 'DeepSeek Reasoner', description: 'Reasoning model' },
  85. ], REASONING))
  86. ctx.llm.registerAdapter(['broken'], new CatalogAdapter('Broken Provider', new Error('catalog offline')))
  87. ctx.llm.registerAdapter(['metadata-broken'], new CatalogAdapter('Metadata Broken', [
  88. { provider: 'metadata-broken', id: 'listed', name: 'Listed' },
  89. ], undefined, new Error('reasoning metadata offline')))
  90. ctx.llm.registerAdapter(['empty'], new CatalogAdapter('Empty Provider', []))
  91. ctx.llm.registerAdapter(['duplicate'], new CatalogAdapter('Duplicate Provider', [
  92. { provider: 'duplicate', id: 'same', name: 'Same' },
  93. { provider: 'duplicate', id: 'same', name: 'Same Again' },
  94. ]))
  95. const session = ctx.sessions.create()
  96. if (logged !== undefined) {
  97. session.append('request/header', { header: { config: logged }, reason: 'initial' })
  98. }
  99. const agent = {
  100. id: session.id,
  101. session,
  102. status: 'running',
  103. ctx,
  104. inbox: { nextTurn: [], nextStep: [] },
  105. } as unknown as Agent
  106. ctx.agents.register(agent)
  107. return { ctx, agent, sessionId: session.id }
  108. }
  109. function expectValue<T>(response: { result: { ok: true; value: T } | { ok: false } }): T {
  110. if (!response.result.ok) throw new Error('expected successful response')
  111. return response.result.value
  112. }
  113. function registerTextOnly(ctx: Context): void {
  114. ctx.llm.registerAdapter(['text-only'], new class extends CatalogAdapter {
  115. override resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
  116. return Promise.resolve({ provider, id: model, name: model, inputModalities: ['text'] })
  117. }
  118. }('Text Only', []))
  119. }
  120. describe('Web session model selection', () => {
  121. it('validates an ordered image batch before persisting any member', async () => {
  122. const { ctx, agent, sessionId } = await harness()
  123. const validateImage = vi.fn((_input: { data: Uint8Array }) => Promise.resolve())
  124. const saveImage = vi.fn((input: { data: Uint8Array; mediaType: 'image/png'; name?: string }) => Promise.resolve({
  125. attachmentId: `att-${String(input.data[0])}`,
  126. mediaType: input.mediaType,
  127. bytes: input.data.byteLength,
  128. width: 1,
  129. height: 1,
  130. ...input.name === undefined ? {} : { name: input.name },
  131. }))
  132. const attachments = {
  133. imageLimits: {
  134. maxImageBytes: 4,
  135. maxImagesPerMessage: 2,
  136. maxMessageImageBytes: 4,
  137. maxImagePixels: 4,
  138. mediaTypes: ['image/png'],
  139. },
  140. validateImage,
  141. saveImage,
  142. }
  143. ctx.provide('attachments', {
  144. ...attachments,
  145. saveImages(inputs: readonly Parameters<typeof saveImage>[0][]) {
  146. return AttachmentStore.prototype.saveImages.call(attachments, inputs)
  147. },
  148. } as never)
  149. const followup = vi.fn()
  150. Object.assign(agent, { followup })
  151. const api = createApiProxy(ctx, {
  152. defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
  153. cwd: '/tmp',
  154. })
  155. const result = await api.sessions.prompt(request({
  156. sessionId,
  157. mode: 'queue' as const,
  158. content: [
  159. { type: 'image' as const, mediaType: 'image/png' as const, data: 'AQ==', name: 'first.png' },
  160. { type: 'text' as const, text: 'compare' },
  161. { type: 'image' as const, mediaType: 'image/png' as const, data: 'Ag==' },
  162. ],
  163. }))
  164. expect(result.result.ok).toBe(true)
  165. expect(validateImage.mock.calls.map(([input]) => [...input.data])).toEqual([[1], [2]])
  166. expect(saveImage.mock.calls.map(([input]) => [...input.data])).toEqual([[1], [2]])
  167. expect((followup.mock.calls[0]?.[0] as UserMessage).content).toEqual([
  168. {
  169. type: 'image',
  170. attachment: {
  171. attachmentId: 'att-1', mediaType: 'image/png', bytes: 1, width: 1, height: 1, name: 'first.png',
  172. },
  173. },
  174. { type: 'text', text: 'compare' },
  175. { type: 'image', attachment: { attachmentId: 'att-2', mediaType: 'image/png', bytes: 1, width: 1, height: 1 } },
  176. ])
  177. const denied = await api.sessions.prompt(request({
  178. sessionId,
  179. mode: 'queue' as const,
  180. content: Array.from({ length: 3 }, () => ({
  181. type: 'image' as const, mediaType: 'image/png' as const, data: 'AQ==',
  182. })),
  183. }))
  184. expect(denied.result).toMatchObject({
  185. ok: false,
  186. error: { code: 'attachment-error', details: { reason: 'TOO_MANY_IMAGES' } },
  187. })
  188. expect(saveImage).toHaveBeenCalledTimes(2)
  189. await ctx.fiber.dispose()
  190. })
  191. it('refuses a text-only selection while durable or pending image content remains visible', async () => {
  192. const { ctx, agent, sessionId } = await harness()
  193. registerTextOnly(ctx)
  194. const api = createApiProxy(ctx, {
  195. defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
  196. cwd: '/tmp',
  197. })
  198. const image = {
  199. type: 'image' as const,
  200. attachment: { attachmentId: 'att-history', mediaType: 'image/png' as const, bytes: 1, width: 1, height: 1 },
  201. }
  202. agent.session.append('user/message', {
  203. id: 'image-message', role: 'user', source: { kind: 'user' }, content: [image],
  204. } as never, { surfaceOp: 'append' })
  205. expect((await api.sessions.selectModel(request({
  206. sessionId, provider: 'text-only', model: 'plain',
  207. }))).result).toMatchObject({ ok: false, error: { code: 'model-unavailable' } })
  208. agent.session.append('user/message', {
  209. id: 'summary', role: 'user', source: { kind: 'plugin', plugin: 'compact' },
  210. content: [{ type: 'text', text: 'image summarized' }],
  211. } as never, {
  212. surfaceOp: { op: 'replace', start: 0, end: agent.session.events.length - 1 },
  213. sourceEventSeqs: agent.session.events.map(event => event.seq),
  214. })
  215. ;(agent.inbox.nextTurn as UserMessage[]).push({
  216. id: 'pending-image', role: 'user', source: { kind: 'user' }, content: [image],
  217. } as never)
  218. expect((await api.sessions.selectModel(request({
  219. sessionId, provider: 'text-only', model: 'plain',
  220. }))).result.ok).toBe(false)
  221. ;(agent.inbox.nextTurn as UserMessage[]).length = 0
  222. expect(expectValue(await api.sessions.selectModel(request({
  223. sessionId, provider: 'text-only', model: 'plain',
  224. }))).selected).toEqual({ provider: 'text-only', model: 'plain' })
  225. await ctx.fiber.dispose()
  226. })
  227. it('authorizes attachment bytes only when the session event stream references the id', async () => {
  228. const { ctx, agent, sessionId } = await harness()
  229. const ref = {
  230. attachmentId: 'att-authorized', mediaType: 'image/png' as const, bytes: 2, width: 1, height: 1,
  231. }
  232. const readImage = vi.fn(() => Promise.resolve({ ref, data: Uint8Array.of(1, 2) }))
  233. ctx.provide('attachments', { readImage } as never)
  234. const api = createApiProxy(ctx, {
  235. defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
  236. cwd: '/tmp',
  237. })
  238. agent.session.append('agent/inbox/spliced', {
  239. target: 'next-turn',
  240. start: 0,
  241. inserted: [{
  242. id: 'queued-image', role: 'user', source: { kind: 'user' },
  243. content: [{ type: 'image', attachment: ref }],
  244. }],
  245. } as never)
  246. const allowed = await api.sessions.attachment(request({
  247. sessionId, attachmentId: 'att-authorized' as never,
  248. }))
  249. expect(allowed.result).toMatchObject({ ok: true, value: { attachment: ref, data: 'AQI=' } })
  250. const denied = await api.sessions.attachment(request({
  251. sessionId, attachmentId: 'att-other' as never,
  252. }))
  253. expect(denied.result).toMatchObject({
  254. ok: false,
  255. error: { code: 'attachment-error', details: { reason: 'ATTACHMENT_NOT_REFERENCED' } },
  256. })
  257. expect(readImage).toHaveBeenCalledOnce()
  258. await ctx.fiber.dispose()
  259. })
  260. it('groups successful providers and leaves an unlisted current selection out of the catalog', async () => {
  261. const { ctx, sessionId } = await harness({
  262. provider: 'deepseek-official',
  263. model: 'private-preview',
  264. reasoningEffort: ReasoningEffortId('max'),
  265. })
  266. const api = createApiProxy(ctx, { defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }), cwd: '/tmp' })
  267. const catalog = expectValue(await api.sessions.models(request({ sessionId })))
  268. expect(catalog.current).toEqual({
  269. provider: 'deepseek-official',
  270. model: 'private-preview',
  271. reasoningEffort: 'max',
  272. })
  273. expect(catalog.groups).toEqual([{
  274. id: 'deepseek-official',
  275. name: 'DeepSeek',
  276. models: [
  277. { id: 'deepseek-chat', name: 'DeepSeek Chat', reasoning: REASONING },
  278. {
  279. id: 'deepseek-reasoner',
  280. name: 'DeepSeek Reasoner',
  281. description: 'Reasoning model',
  282. reasoning: REASONING,
  283. },
  284. ],
  285. }])
  286. expect(catalog.failures).toEqual([
  287. { id: 'broken', name: 'Broken Provider', message: 'catalog offline' },
  288. { id: 'metadata-broken', name: 'Metadata Broken', message: 'reasoning metadata offline' },
  289. {
  290. id: 'duplicate',
  291. name: 'Duplicate Provider',
  292. message: 'adapter returned invalid or duplicate model metadata for provider "duplicate"',
  293. },
  294. ])
  295. await ctx.fiber.dispose()
  296. })
  297. it('accepts an advisory-unlisted model, rejects an unavailable provider, and switches only after the next assembly', async () => {
  298. const { ctx, agent, sessionId } = await harness()
  299. const api = createApiProxy(ctx, { defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }), cwd: '/tmp' })
  300. const seed: LlmCallConfig = { provider: 'seed', model: 'seed', temperature: 0.2 }
  301. const signal = new AbortController().signal
  302. expect(expectValue(await api.sessions.models(request({ sessionId }))).current)
  303. .toEqual({ provider: 'deepseek-official', model: 'deepseek-chat' })
  304. expect((await ctx.systemPrompt.assemble()).variables)
  305. .toMatchObject({ provider: 'deepseek-official', model: 'deepseek-chat' })
  306. const selected = expectValue(await api.sessions.selectModel(request({
  307. sessionId,
  308. provider: 'deepseek-official',
  309. model: 'private-preview',
  310. reasoningEffort: 'max',
  311. })))
  312. expect(selected.selected).toEqual({
  313. provider: 'deepseek-official',
  314. model: 'private-preview',
  315. reasoningEffort: 'max',
  316. })
  317. await expect(agentEvents(ctx, agent).waterfall(
  318. 'agent/request', { turn: 1, step: 0, signal }, () => Promise.resolve(seed),
  319. )).resolves.toMatchObject({ provider: 'deepseek-official', model: 'deepseek-chat' })
  320. expect((await ctx.systemPrompt.assemble()).variables)
  321. .toMatchObject({ provider: 'deepseek-official', model: 'private-preview' })
  322. await expect(agentEvents(ctx, agent).waterfall(
  323. 'agent/request', { turn: 1, step: 1, signal }, () => Promise.resolve(seed),
  324. )).resolves.toMatchObject({
  325. provider: 'deepseek-official',
  326. model: 'private-preview',
  327. reasoningEffort: 'max',
  328. })
  329. const unsupported = await api.sessions.selectModel(request({
  330. sessionId,
  331. provider: 'deepseek-official',
  332. model: 'private-preview',
  333. reasoningEffort: 'medium',
  334. }))
  335. expect(unsupported.result).toMatchObject({
  336. ok: false,
  337. error: {
  338. code: 'model-unavailable',
  339. message: 'provider "deepseek-official" model "private-preview" does not support reasoning effort "medium"',
  340. },
  341. })
  342. const rejected = await api.sessions.selectModel(request({
  343. sessionId,
  344. provider: 'missing',
  345. model: 'model',
  346. }))
  347. expect(rejected.result).toEqual({
  348. ok: false,
  349. error: {
  350. code: 'model-unavailable',
  351. message: 'no adapter registered for provider "missing"',
  352. details: { provider: 'missing', model: 'model' },
  353. },
  354. })
  355. expect(expectValue(await api.sessions.models(request({ sessionId }))).current)
  356. .toEqual({ provider: 'deepseek-official', model: 'private-preview', reasoningEffort: 'max' })
  357. await ctx.fiber.dispose()
  358. })
  359. it('reads the Agent default live for a session whose log names no selection', async () => {
  360. const { ctx, sessionId } = await harness()
  361. let stored = { provider: 'deepseek-official', model: 'deepseek-chat' }
  362. const api = createApiProxy(ctx, {
  363. defaultModelSelection: () => stored,
  364. cwd: '/tmp',
  365. })
  366. expect(expectValue(await api.sessions.models(request({ sessionId }))).current)
  367. .toEqual({ provider: 'deepseek-official', model: 'deepseek-chat' })
  368. // The default moving after the session exists still reaches it: New
  369. // Session reuses a blank session rather than minting another, so a seed
  370. // captured at creation would show the superseded model there.
  371. stored = { provider: 'deepseek-official', model: 'deepseek-reasoner' }
  372. expect(expectValue(await api.sessions.models(request({ sessionId }))).current)
  373. .toEqual({ provider: 'deepseek-official', model: 'deepseek-reasoner' })
  374. expect(expectValue(await api.host.describe(request({}))))
  375. .toMatchObject({ provider: 'deepseek-official', model: 'deepseek-reasoner' })
  376. await ctx.fiber.dispose()
  377. })
  378. it('keeps a session on its logged selection when the Agent default differs', async () => {
  379. const { ctx, sessionId } = await harness({
  380. provider: 'deepseek-official',
  381. model: 'deepseek-chat',
  382. })
  383. let stored = { provider: 'deepseek-official', model: 'deepseek-chat' }
  384. const api = createApiProxy(ctx, {
  385. defaultModelSelection: () => stored,
  386. cwd: '/tmp',
  387. })
  388. stored = { provider: 'duplicate', model: 'same' }
  389. expect(expectValue(await api.sessions.models(request({ sessionId }))).current)
  390. .toEqual({ provider: 'deepseek-official', model: 'deepseek-chat' })
  391. await ctx.fiber.dispose()
  392. })
  393. it('saves an accepted selection as the default and survives a storage failure', async () => {
  394. const { ctx, sessionId } = await harness()
  395. const saved: unknown[] = []
  396. let reject = false
  397. const api = createApiProxy(ctx, {
  398. defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
  399. saveDefaultModelSelection: (selection) => {
  400. saved.push(selection)
  401. return reject ? Promise.reject(new Error('read-only document')) : Promise.resolve()
  402. },
  403. cwd: '/tmp',
  404. })
  405. expectValue(await api.sessions.selectModel(request({
  406. sessionId, provider: 'deepseek-official', model: 'deepseek-reasoner', reasoningEffort: 'max',
  407. })))
  408. expect(saved).toEqual([
  409. { provider: 'deepseek-official', model: 'deepseek-reasoner', reasoningEffort: 'max' },
  410. ])
  411. // A refused selection never becomes anyone's default.
  412. await api.sessions.selectModel(request({ sessionId, provider: 'missing', model: 'model' }))
  413. expect(saved).toHaveLength(1)
  414. // Storage failing is not the selection failing: the switch already applies
  415. // to this session, so the call still succeeds.
  416. reject = true
  417. const stillAccepted = expectValue(await api.sessions.selectModel(request({
  418. sessionId, provider: 'deepseek-official', model: 'deepseek-chat',
  419. })))
  420. expect(stillAccepted.selected).toEqual({ provider: 'deepseek-official', model: 'deepseek-chat', reasoningEffort: 'high' })
  421. expect(expectValue(await api.sessions.models(request({ sessionId }))).current)
  422. .toEqual({ provider: 'deepseek-official', model: 'deepseek-chat', reasoningEffort: 'high' })
  423. await ctx.fiber.dispose()
  424. })
  425. it('refuses a prompt no adapter can route, and reports it on the directory', async () => {
  426. const { ctx, sessionId } = await harness()
  427. const api = createApiProxy(ctx, {
  428. defaultModelSelection: () => ({ provider: 'deleted-gateway', model: 'deleted-model' }),
  429. cwd: '/tmp',
  430. })
  431. // The client disabling its input is an affordance; this method stays
  432. // callable, so the refusal has to live here.
  433. const refused = await api.sessions.prompt(request({
  434. sessionId, mode: 'queue' as const, content: [{ type: 'text' as const, text: 'hi' }],
  435. }))
  436. expect(refused.result).toMatchObject({
  437. ok: false,
  438. error: { code: 'model-unavailable', details: { provider: 'deleted-gateway', model: 'deleted-model' } },
  439. })
  440. expect(expectValue(await api.sessions.models(request({ sessionId }))).routable).toBe(false)
  441. // An advisory-unlisted model on a live route is NOT this: the route
  442. // serves it, so the prompt goes through and nothing blocks.
  443. expectValue(await api.sessions.selectModel(request({
  444. sessionId, provider: 'deepseek-official', model: 'unlisted-but-served',
  445. })))
  446. const catalog = expectValue(await api.sessions.models(request({ sessionId })))
  447. expect(catalog.routable).toBe(true)
  448. expect(catalog.groups.flatMap(group => group.models.map(model => model.id)))
  449. .not.toContain('unlisted-but-served')
  450. await ctx.fiber.dispose()
  451. })
  452. it('serves a session and its catalog when the stored default names a route that is gone', async () => {
  453. const { ctx, sessionId } = await harness()
  454. const api = createApiProxy(ctx, {
  455. // What a Models-page removal leaves behind: the settings document still
  456. // names the route the user last picked, and nothing serves it.
  457. defaultModelSelection: () => ({ provider: 'deleted-gateway', model: 'deleted-model' }),
  458. cwd: '/tmp',
  459. })
  460. const catalog = expectValue(await api.sessions.models(request({ sessionId })))
  461. // Passed through rather than repaired: matching no group is precisely what
  462. // makes the composer seat prompt for a selection instead of naming a model
  463. // the deployment cannot reach.
  464. expect(catalog.current).toEqual({ provider: 'deleted-gateway', model: 'deleted-model' })
  465. expect(catalog.groups.flatMap(group => group.models.map(model => `${group.id}/${model.id}`)))
  466. .not.toContain('deleted-gateway/deleted-model')
  467. await ctx.fiber.dispose()
  468. })
  469. })