api-proxy-models.spec.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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 LlmRuntime, { 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 UserQuestionService from '@deepseek-ai/dsh-user-questions'
  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(LlmRuntime)
  80. await ctx.plugin(UserQuestionService)
  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. maxImageDimension: 2000,
  139. mediaTypes: ['image/png'],
  140. },
  141. validateImage,
  142. saveImage,
  143. }
  144. ctx.provide('attachments', Object.setPrototypeOf(attachments, AttachmentStore.prototype) as never)
  145. const followup = vi.fn()
  146. Object.assign(agent, { followup })
  147. const api = createApiProxy(ctx, {
  148. defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
  149. cwd: '/tmp',
  150. })
  151. const result = await api.sessions.prompt(request({
  152. sessionId,
  153. mode: 'queue' as const,
  154. content: [
  155. { type: 'image' as const, mediaType: 'image/png' as const, data: 'AQ==', name: 'first.png' },
  156. { type: 'text' as const, text: 'compare' },
  157. { type: 'image' as const, mediaType: 'image/png' as const, data: 'Ag==' },
  158. ],
  159. }))
  160. expect(result.result.ok).toBe(true)
  161. expect(validateImage.mock.calls.map(([input]) => [...input.data])).toEqual([[1], [2]])
  162. expect(saveImage.mock.calls.map(([input]) => [...input.data])).toEqual([[1], [2]])
  163. expect((followup.mock.calls[0]?.[0] as UserMessage).content).toEqual([
  164. {
  165. type: 'image',
  166. attachment: {
  167. attachmentId: 'att-1', mediaType: 'image/png', bytes: 1, width: 1, height: 1, name: 'first.png',
  168. },
  169. },
  170. { type: 'text', text: 'compare' },
  171. { type: 'image', attachment: { attachmentId: 'att-2', mediaType: 'image/png', bytes: 1, width: 1, height: 1 } },
  172. ])
  173. const denied = await api.sessions.prompt(request({
  174. sessionId,
  175. mode: 'queue' as const,
  176. content: Array.from({ length: 3 }, () => ({
  177. type: 'image' as const, mediaType: 'image/png' as const, data: 'AQ==',
  178. })),
  179. }))
  180. expect(denied.result).toMatchObject({
  181. ok: false,
  182. error: { code: 'attachment-error', details: { reason: 'TOO_MANY_IMAGES' } },
  183. })
  184. expect(saveImage).toHaveBeenCalledTimes(2)
  185. await ctx.fiber.dispose()
  186. })
  187. it('allows a text-only selection while durable or pending images remain available for later models', async () => {
  188. const { ctx, agent, sessionId } = await harness()
  189. registerTextOnly(ctx)
  190. const api = createApiProxy(ctx, {
  191. defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
  192. cwd: '/tmp',
  193. })
  194. const image = {
  195. type: 'image' as const,
  196. attachment: { attachmentId: 'att-history', mediaType: 'image/png' as const, bytes: 1, width: 1, height: 1 },
  197. }
  198. agent.session.append('user/message', {
  199. id: 'image-message', role: 'user', source: { kind: 'user' }, content: [image],
  200. } as never, { surfaceOp: 'append' })
  201. expect(expectValue(await api.sessions.selectModel(request({
  202. sessionId, provider: 'text-only', model: 'plain',
  203. }))).selected).toEqual({ provider: 'text-only', model: 'plain' })
  204. agent.session.append('user/message', {
  205. id: 'summary', role: 'user', source: { kind: 'plugin', plugin: 'compact' },
  206. content: [{ type: 'text', text: 'image summarized' }],
  207. } as never, {
  208. surfaceOp: { op: 'replace', start: 0, end: agent.session.events.length - 1 },
  209. sourceEventSeqs: agent.session.events.map(event => event.seq),
  210. })
  211. ;(agent.inbox.nextTurn as UserMessage[]).push({
  212. id: 'pending-image', role: 'user', source: { kind: 'user' }, content: [image],
  213. } as never)
  214. expect(expectValue(await api.sessions.selectModel(request({
  215. sessionId, provider: 'text-only', model: 'plain',
  216. }))).selected).toEqual({ provider: 'text-only', model: 'plain' })
  217. await ctx.fiber.dispose()
  218. })
  219. it('authorizes attachment bytes only when the session event stream references the id', async () => {
  220. const { ctx, agent, sessionId } = await harness()
  221. const ref = {
  222. attachmentId: 'att-authorized', mediaType: 'image/png' as const, bytes: 2, width: 1, height: 1,
  223. }
  224. const readImage = vi.fn(() => Promise.resolve({ ref, data: Uint8Array.of(1, 2) }))
  225. ctx.provide('attachments', { readImage } as never)
  226. const api = createApiProxy(ctx, {
  227. defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
  228. cwd: '/tmp',
  229. })
  230. agent.session.append('agent/inbox/spliced', {
  231. target: 'next-turn',
  232. start: 0,
  233. inserted: [{
  234. id: 'queued-image', role: 'user', source: { kind: 'user' },
  235. content: [{ type: 'image', attachment: ref }],
  236. }],
  237. } as never)
  238. const allowed = await api.sessions.attachment(request({
  239. sessionId, attachmentId: 'att-authorized' as never,
  240. }))
  241. expect(allowed.result).toMatchObject({ ok: true, value: { attachment: ref, data: 'AQI=' } })
  242. const denied = await api.sessions.attachment(request({
  243. sessionId, attachmentId: 'att-other' as never,
  244. }))
  245. expect(denied.result).toMatchObject({
  246. ok: false,
  247. error: { code: 'attachment-error', details: { reason: 'ATTACHMENT_NOT_REFERENCED' } },
  248. })
  249. expect(readImage).toHaveBeenCalledOnce()
  250. await ctx.fiber.dispose()
  251. })
  252. it('groups successful providers and leaves an unlisted current selection out of the catalog', async () => {
  253. const { ctx, sessionId } = await harness({
  254. provider: 'deepseek-official',
  255. model: 'private-preview',
  256. reasoningEffort: ReasoningEffortId('max'),
  257. })
  258. const api = createApiProxy(ctx, { defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }), cwd: '/tmp' })
  259. const catalog = expectValue(await api.sessions.models(request({ sessionId })))
  260. expect(catalog.current).toEqual({
  261. provider: 'deepseek-official',
  262. model: 'private-preview',
  263. reasoningEffort: 'max',
  264. })
  265. expect(catalog.groups).toEqual([{
  266. id: 'deepseek-official',
  267. name: 'DeepSeek',
  268. models: [
  269. { id: 'deepseek-chat', name: 'DeepSeek Chat', reasoning: REASONING },
  270. {
  271. id: 'deepseek-reasoner',
  272. name: 'DeepSeek Reasoner',
  273. description: 'Reasoning model',
  274. reasoning: REASONING,
  275. },
  276. ],
  277. }])
  278. expect(catalog.failures).toEqual([
  279. { id: 'broken', name: 'Broken Provider', message: 'catalog offline' },
  280. { id: 'metadata-broken', name: 'Metadata Broken', message: 'reasoning metadata offline' },
  281. {
  282. id: 'duplicate',
  283. name: 'Duplicate Provider',
  284. message: 'adapter returned invalid or duplicate model metadata for provider "duplicate"',
  285. },
  286. ])
  287. await ctx.fiber.dispose()
  288. })
  289. it('accepts an advisory-unlisted model, rejects an unavailable provider, and switches only after the next assembly', async () => {
  290. const { ctx, agent, sessionId } = await harness()
  291. const api = createApiProxy(ctx, { defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }), cwd: '/tmp' })
  292. const seed: LlmCallConfig = { provider: 'seed', model: 'seed', temperature: 0.2 }
  293. const signal = new AbortController().signal
  294. expect(expectValue(await api.sessions.models(request({ sessionId }))).current)
  295. .toEqual({ provider: 'deepseek-official', model: 'deepseek-chat' })
  296. expect((await ctx.systemPrompt.assemble()).variables)
  297. .toMatchObject({ provider: 'deepseek-official', model: 'deepseek-chat' })
  298. const selected = expectValue(await api.sessions.selectModel(request({
  299. sessionId,
  300. provider: 'deepseek-official',
  301. model: 'private-preview',
  302. reasoningEffort: 'max',
  303. })))
  304. expect(selected.selected).toEqual({
  305. provider: 'deepseek-official',
  306. model: 'private-preview',
  307. reasoningEffort: 'max',
  308. })
  309. await expect(agentEvents(ctx, agent).waterfall(
  310. 'agent/request', { turn: 1, step: 0, signal }, () => Promise.resolve(seed),
  311. )).resolves.toMatchObject({ provider: 'deepseek-official', model: 'deepseek-chat' })
  312. expect((await ctx.systemPrompt.assemble()).variables)
  313. .toMatchObject({ provider: 'deepseek-official', model: 'private-preview' })
  314. await expect(agentEvents(ctx, agent).waterfall(
  315. 'agent/request', { turn: 1, step: 1, signal }, () => Promise.resolve(seed),
  316. )).resolves.toMatchObject({
  317. provider: 'deepseek-official',
  318. model: 'private-preview',
  319. reasoningEffort: 'max',
  320. })
  321. const unsupported = await api.sessions.selectModel(request({
  322. sessionId,
  323. provider: 'deepseek-official',
  324. model: 'private-preview',
  325. reasoningEffort: 'medium',
  326. }))
  327. expect(unsupported.result).toMatchObject({
  328. ok: false,
  329. error: {
  330. code: 'model-unavailable',
  331. message: 'provider "deepseek-official" model "private-preview" does not support reasoning effort "medium"',
  332. },
  333. })
  334. const rejected = await api.sessions.selectModel(request({
  335. sessionId,
  336. provider: 'missing',
  337. model: 'model',
  338. }))
  339. expect(rejected.result).toEqual({
  340. ok: false,
  341. error: {
  342. code: 'model-unavailable',
  343. message: 'no adapter registered for provider "missing"',
  344. details: { provider: 'missing', model: 'model' },
  345. },
  346. })
  347. expect(expectValue(await api.sessions.models(request({ sessionId }))).current)
  348. .toEqual({ provider: 'deepseek-official', model: 'private-preview', reasoningEffort: 'max' })
  349. await ctx.fiber.dispose()
  350. })
  351. it('reads the Agent default live for a session whose log names no selection', async () => {
  352. const { ctx, sessionId } = await harness()
  353. let stored = { provider: 'deepseek-official', model: 'deepseek-chat' }
  354. const api = createApiProxy(ctx, {
  355. defaultModelSelection: () => stored,
  356. cwd: '/tmp',
  357. })
  358. expect(expectValue(await api.sessions.models(request({ sessionId }))).current)
  359. .toEqual({ provider: 'deepseek-official', model: 'deepseek-chat' })
  360. // The default moving after the session exists still reaches it: New
  361. // Session reuses a blank session rather than minting another, so a seed
  362. // captured at creation would show the superseded model there.
  363. stored = { provider: 'deepseek-official', model: 'deepseek-reasoner' }
  364. expect(expectValue(await api.sessions.models(request({ sessionId }))).current)
  365. .toEqual({ provider: 'deepseek-official', model: 'deepseek-reasoner' })
  366. expect(expectValue(await api.host.describe(request({}))))
  367. .toMatchObject({ provider: 'deepseek-official', model: 'deepseek-reasoner' })
  368. await ctx.fiber.dispose()
  369. })
  370. it('keeps a session on its logged selection when the Agent default differs', async () => {
  371. const { ctx, sessionId } = await harness({
  372. provider: 'deepseek-official',
  373. model: 'deepseek-chat',
  374. })
  375. let stored = { provider: 'deepseek-official', model: 'deepseek-chat' }
  376. const api = createApiProxy(ctx, {
  377. defaultModelSelection: () => stored,
  378. cwd: '/tmp',
  379. })
  380. stored = { provider: 'duplicate', model: 'same' }
  381. expect(expectValue(await api.sessions.models(request({ sessionId }))).current)
  382. .toEqual({ provider: 'deepseek-official', model: 'deepseek-chat' })
  383. await ctx.fiber.dispose()
  384. })
  385. it('saves an accepted selection as the default and survives a storage failure', async () => {
  386. const { ctx, sessionId } = await harness()
  387. const saved: unknown[] = []
  388. let reject = false
  389. const api = createApiProxy(ctx, {
  390. defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
  391. saveDefaultModelSelection: (selection) => {
  392. saved.push(selection)
  393. return reject ? Promise.reject(new Error('read-only document')) : Promise.resolve()
  394. },
  395. cwd: '/tmp',
  396. })
  397. expectValue(await api.sessions.selectModel(request({
  398. sessionId, provider: 'deepseek-official', model: 'deepseek-reasoner', reasoningEffort: 'max',
  399. })))
  400. expect(saved).toEqual([
  401. { provider: 'deepseek-official', model: 'deepseek-reasoner', reasoningEffort: 'max' },
  402. ])
  403. // A refused selection never becomes anyone's default.
  404. await api.sessions.selectModel(request({ sessionId, provider: 'missing', model: 'model' }))
  405. expect(saved).toHaveLength(1)
  406. // Storage failing is not the selection failing: the switch already applies
  407. // to this session, so the call still succeeds.
  408. reject = true
  409. const stillAccepted = expectValue(await api.sessions.selectModel(request({
  410. sessionId, provider: 'deepseek-official', model: 'deepseek-chat',
  411. })))
  412. expect(stillAccepted.selected).toEqual({ provider: 'deepseek-official', model: 'deepseek-chat', reasoningEffort: 'high' })
  413. expect(expectValue(await api.sessions.models(request({ sessionId }))).current)
  414. .toEqual({ provider: 'deepseek-official', model: 'deepseek-chat', reasoningEffort: 'high' })
  415. await ctx.fiber.dispose()
  416. })
  417. it('refuses a prompt no adapter can route, and reports it on the directory', async () => {
  418. const { ctx, sessionId } = await harness()
  419. const api = createApiProxy(ctx, {
  420. defaultModelSelection: () => ({ provider: 'deleted-gateway', model: 'deleted-model' }),
  421. cwd: '/tmp',
  422. })
  423. // The client disabling its input is an affordance; this method stays
  424. // callable, so the refusal has to live here.
  425. const refused = await api.sessions.prompt(request({
  426. sessionId, mode: 'queue' as const, content: [{ type: 'text' as const, text: 'hi' }],
  427. }))
  428. expect(refused.result).toMatchObject({
  429. ok: false,
  430. error: { code: 'model-unavailable', details: { provider: 'deleted-gateway', model: 'deleted-model' } },
  431. })
  432. expect(expectValue(await api.sessions.models(request({ sessionId }))).routable).toBe(false)
  433. // An advisory-unlisted model on a live route is NOT this: the route
  434. // serves it, so the prompt goes through and nothing blocks.
  435. expectValue(await api.sessions.selectModel(request({
  436. sessionId, provider: 'deepseek-official', model: 'unlisted-but-served',
  437. })))
  438. const catalog = expectValue(await api.sessions.models(request({ sessionId })))
  439. expect(catalog.routable).toBe(true)
  440. expect(catalog.groups.flatMap(group => group.models.map(model => model.id)))
  441. .not.toContain('unlisted-but-served')
  442. await ctx.fiber.dispose()
  443. })
  444. it('serves a session and its catalog when the stored default names a route that is gone', async () => {
  445. const { ctx, sessionId } = await harness()
  446. const api = createApiProxy(ctx, {
  447. // What a Models-page removal leaves behind: the settings document still
  448. // names the route the user last picked, and nothing serves it.
  449. defaultModelSelection: () => ({ provider: 'deleted-gateway', model: 'deleted-model' }),
  450. cwd: '/tmp',
  451. })
  452. const catalog = expectValue(await api.sessions.models(request({ sessionId })))
  453. // Passed through rather than repaired: matching no group is precisely what
  454. // makes the composer seat prompt for a selection instead of naming a model
  455. // the deployment cannot reach.
  456. expect(catalog.current).toEqual({ provider: 'deleted-gateway', model: 'deleted-model' })
  457. expect(catalog.groups.flatMap(group => group.models.map(model => `${group.id}/${model.id}`)))
  458. .not.toContain('deleted-gateway/deleted-model')
  459. await ctx.fiber.dispose()
  460. })
  461. })