session-models.host.spec.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. /**
  2. * Session Controller 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, LlmCallConfigAdapterDefaults, LlmModelInfo,
  15. LlmModelReasoningInfo, LlmProviderInfo, 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 type { SessionPromptRequest, SessionRequestId } from '../src/types.ts'
  21. import { ApiSessionAgentController } from '../src/agent.ts'
  22. import { buildModelCatalog } from '../src/catalog.ts'
  23. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  24. import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
  25. import { createSessionTestRemote } from './test-remote.ts'
  26. function request<P>(payload: P): P {
  27. return payload
  28. }
  29. let nextRequestId = 1
  30. function promptRequest(
  31. payload: Omit<SessionPromptRequest, 'requestId'>,
  32. ): SessionPromptRequest {
  33. return {
  34. ...payload,
  35. requestId: `models-${String(nextRequestId++)}` as SessionRequestId,
  36. }
  37. }
  38. class CatalogAdapter extends LlmAdapter {
  39. constructor(
  40. private readonly name: string,
  41. private readonly models: readonly LlmModelInfo[] | Error,
  42. private readonly reasoning?: LlmModelReasoningInfo,
  43. private readonly exactError?: Error,
  44. ) {
  45. super()
  46. }
  47. override providerInfo(provider: string): LlmProviderInfo {
  48. return { id: provider, name: this.name }
  49. }
  50. override listModels(): Promise<readonly LlmModelInfo[]> {
  51. return this.models instanceof Error
  52. ? Promise.reject(this.models)
  53. : Promise.resolve(this.models)
  54. }
  55. override resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
  56. if (this.exactError !== undefined) return Promise.reject(this.exactError)
  57. return Promise.resolve({
  58. provider,
  59. id: model,
  60. name: model,
  61. ...this.reasoning === undefined ? {} : { reasoning: this.reasoning },
  62. })
  63. }
  64. override async *stream(_options: GenerateOptions): AsyncIterable<StreamChunk> {
  65. // Catalog tests never enter provider streaming.
  66. }
  67. }
  68. const REASONING: LlmModelReasoningInfo = {
  69. efforts: [
  70. { id: ReasoningEffortId('off'), name: 'Off' },
  71. { id: ReasoningEffortId('high'), name: 'High' },
  72. { id: ReasoningEffortId('max'), name: 'Max' },
  73. ],
  74. defaultEffort: ReasoningEffortId('high'),
  75. }
  76. async function harness(logged?: {
  77. provider: string
  78. model: string
  79. reasoningEffort?: ReasoningEffortId
  80. adapterDefaults?: LlmCallConfigAdapterDefaults
  81. }): Promise<{
  82. ctx: Context
  83. agent: Agent
  84. sessionId: SessionId
  85. }> {
  86. const ctx = new Context()
  87. await ctx.plugin(SessionStore)
  88. await ctx.plugin(SystemPrompt, { persona: '' })
  89. await ctx.plugin(LlmRuntime)
  90. await ctx.plugin(AgentRegistry)
  91. ctx.llm.registerAdapter(['deepseek-official'], new CatalogAdapter('DeepSeek', [
  92. { provider: 'deepseek-official', id: 'deepseek-chat', name: 'DeepSeek Chat' },
  93. { provider: 'deepseek-official', id: 'deepseek-reasoner', name: 'DeepSeek Reasoner', description: 'Reasoning model' },
  94. ], REASONING))
  95. ctx.llm.registerAdapter(['broken'], new CatalogAdapter('Broken Provider', new Error('catalog offline')))
  96. ctx.llm.registerAdapter(['metadata-broken'], new CatalogAdapter('Metadata Broken', [
  97. { provider: 'metadata-broken', id: 'listed', name: 'Listed' },
  98. ], undefined, new Error('reasoning metadata offline')))
  99. ctx.llm.registerAdapter(['remote-rejected'], new CatalogAdapter(
  100. 'Remote Rejected',
  101. [],
  102. undefined,
  103. new RemoteError('gateway/internal', 'fixture rejected the selection', {}),
  104. ))
  105. ctx.llm.registerAdapter(['empty'], new CatalogAdapter('Empty Provider', []))
  106. ctx.llm.registerAdapter(['duplicate'], new CatalogAdapter('Duplicate Provider', [
  107. { provider: 'duplicate', id: 'same', name: 'Same' },
  108. { provider: 'duplicate', id: 'same', name: 'Same Again' },
  109. ]))
  110. const session = ctx.sessions.create()
  111. if (logged !== undefined) {
  112. const { adapterDefaults, ...config } = logged
  113. session.append('request/header', {
  114. header: { config, ...adapterDefaults === undefined ? {} : { adapterDefaults } },
  115. reason: 'initial',
  116. })
  117. }
  118. const agent = {
  119. id: session.id,
  120. session,
  121. status: 'running',
  122. ctx,
  123. inbox: { nextTurn: [], nextStep: [] },
  124. } as unknown as Agent
  125. ctx.agents.register(agent)
  126. return { ctx, agent, sessionId: session.id }
  127. }
  128. function expectValue<T>(result: { ok: true; value: T } | { ok: false }): T {
  129. if (!result.ok) throw new Error('expected successful response')
  130. return result.value
  131. }
  132. function registerTextOnly(ctx: Context): void {
  133. ctx.llm.registerAdapter(['text-only'], new class extends CatalogAdapter {
  134. override resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
  135. return Promise.resolve({ provider, id: model, name: model, inputModalities: ['text'] })
  136. }
  137. }('Text Only', []))
  138. }
  139. /** Resolve the Client-visible next selection from durable state and the Host default. */
  140. function currentSelection(ctx: Context, sessionId: SessionId) {
  141. const session = ctx.sessions.get(sessionId)
  142. if (session === undefined) throw new Error('expected a live test Session')
  143. return ctx.sessionProjections.snapshot(session).values.modelSelection?.next
  144. ?? ctx.agentDefaultModel.currentSelection()
  145. }
  146. describe('Web session model selection', () => {
  147. it('validates an ordered image batch before persisting any member', async () => {
  148. const { ctx, agent, sessionId } = await harness()
  149. const validateImage = vi.fn((_input: { data: Uint8Array }) => Promise.resolve())
  150. const saveImage = vi.fn((input: { data: Uint8Array; mediaType: 'image/png'; name?: string }) => Promise.resolve({
  151. attachmentId: `att-${String(input.data[0])}`,
  152. mediaType: input.mediaType,
  153. bytes: input.data.byteLength,
  154. width: 1,
  155. height: 1,
  156. ...input.name === undefined ? {} : { name: input.name },
  157. }))
  158. const attachments = {
  159. imageLimits: {
  160. maxImageBytes: 4,
  161. maxImagesPerMessage: 2,
  162. maxMessageImageBytes: 4,
  163. maxImagePixels: 4,
  164. maxImageDimension: 2000,
  165. mediaTypes: ['image/png'],
  166. },
  167. validateImage,
  168. saveImage,
  169. }
  170. ctx.provide('attachments', Object.setPrototypeOf(attachments, AttachmentStore.prototype) as never)
  171. const followup = vi.fn()
  172. Object.assign(agent, { followup })
  173. const remote = createSessionTestRemote(ctx, {
  174. defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
  175. cwd: '/tmp',
  176. })
  177. const result = await remote.prompt(promptRequest({
  178. sessionId,
  179. mode: 'queue' as const,
  180. content: [
  181. { type: 'image' as const, mediaType: 'image/png' as const, data: 'AQ==', name: 'first.png' },
  182. { type: 'text' as const, text: 'compare' },
  183. { type: 'image' as const, mediaType: 'image/png' as const, data: 'Ag==' },
  184. ],
  185. }))
  186. expect(result.ok).toBe(true)
  187. expect(validateImage.mock.calls.map(([input]) => [...input.data])).toEqual([[1], [2]])
  188. expect(saveImage.mock.calls.map(([input]) => [...input.data])).toEqual([[1], [2]])
  189. expect((followup.mock.calls[0]?.[0] as UserMessage).content).toEqual([
  190. {
  191. type: 'image',
  192. attachment: {
  193. attachmentId: 'att-1', mediaType: 'image/png', bytes: 1, width: 1, height: 1, name: 'first.png',
  194. },
  195. },
  196. { type: 'text', text: 'compare' },
  197. { type: 'image', attachment: { attachmentId: 'att-2', mediaType: 'image/png', bytes: 1, width: 1, height: 1 } },
  198. ])
  199. const denied = await remote.prompt(promptRequest({
  200. sessionId,
  201. mode: 'queue' as const,
  202. content: Array.from({ length: 3 }, () => ({
  203. type: 'image' as const, mediaType: 'image/png' as const, data: 'AQ==',
  204. })),
  205. }))
  206. expect(denied).toMatchObject({
  207. ok: false,
  208. error: { code: 'session/attachment-invalid', details: { reason: 'TOO_MANY_IMAGES' } },
  209. })
  210. expect(saveImage).toHaveBeenCalledTimes(2)
  211. await ctx.fiber.dispose()
  212. })
  213. it('delivers an admitted image batch through steer with the same ordered content as queue', async () => {
  214. const { ctx, agent, sessionId } = await harness()
  215. const attachments = {
  216. imageLimits: {
  217. maxImageBytes: 4,
  218. maxImagesPerMessage: 2,
  219. maxMessageImageBytes: 4,
  220. maxImagePixels: 4,
  221. maxImageDimension: 2000,
  222. mediaTypes: ['image/png'],
  223. },
  224. validateImage: vi.fn(() => Promise.resolve()),
  225. saveImage: vi.fn((input: { data: Uint8Array; mediaType: 'image/png'; name?: string }) => Promise.resolve({
  226. attachmentId: `att-${String(input.data[0])}`,
  227. mediaType: input.mediaType,
  228. bytes: input.data.byteLength,
  229. width: 1,
  230. height: 1,
  231. ...input.name === undefined ? {} : { name: input.name },
  232. })),
  233. }
  234. ctx.provide('attachments', Object.setPrototypeOf(attachments, AttachmentStore.prototype) as never)
  235. const steer = vi.fn()
  236. const followup = vi.fn()
  237. Object.assign(agent, { steer, followup })
  238. const remote = createSessionTestRemote(ctx, {
  239. defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
  240. cwd: '/tmp',
  241. })
  242. const result = await remote.prompt(promptRequest({
  243. sessionId,
  244. mode: 'steer' as const,
  245. content: [
  246. { type: 'text' as const, text: 'look at this' },
  247. { type: 'image' as const, mediaType: 'image/png' as const, data: 'AQ==', name: 'mid-turn.png' },
  248. ],
  249. }))
  250. expect(result.ok).toBe(true)
  251. expect(followup).not.toHaveBeenCalled()
  252. expect((steer.mock.calls[0]?.[0] as UserMessage).content).toEqual([
  253. { type: 'text', text: 'look at this' },
  254. {
  255. type: 'image',
  256. attachment: {
  257. attachmentId: 'att-1', mediaType: 'image/png', bytes: 1, width: 1, height: 1, name: 'mid-turn.png',
  258. },
  259. },
  260. ])
  261. await ctx.fiber.dispose()
  262. })
  263. it('allows a text-only selection while durable or pending images remain available for later models', async () => {
  264. const { ctx, agent, sessionId } = await harness()
  265. registerTextOnly(ctx)
  266. const remote = createSessionTestRemote(ctx, {
  267. defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
  268. cwd: '/tmp',
  269. })
  270. const image = {
  271. type: 'image' as const,
  272. attachment: { attachmentId: 'att-history', mediaType: 'image/png' as const, bytes: 1, width: 1, height: 1 },
  273. }
  274. const imageEvent = agent.session.append('user/message', {
  275. id: 'image-message', role: 'user', source: { kind: 'user' }, content: [image],
  276. } as never, { surfaceOp: 'append' })
  277. expect(expectValue(await remote.selectModel(request({
  278. sessionId, provider: 'text-only', model: 'plain',
  279. }))).selected).toEqual({ provider: 'text-only', model: 'plain' })
  280. agent.session.append('user/message', {
  281. id: 'summary', role: 'user', source: { kind: 'plugin', plugin: 'compact' },
  282. content: [{ type: 'text', text: 'image summarized' }],
  283. } as never, {
  284. surfaceOp: { op: 'replace', start: imageEvent.seq, end: imageEvent.seq },
  285. sourceEventSeqs: [imageEvent.seq],
  286. })
  287. ;(agent.inbox.nextTurn as UserMessage[]).push({
  288. id: 'pending-image', role: 'user', source: { kind: 'user' }, content: [image],
  289. } as never)
  290. expect(expectValue(await remote.selectModel(request({
  291. sessionId, provider: 'text-only', model: 'plain',
  292. }))).selected).toEqual({ provider: 'text-only', model: 'plain' })
  293. await ctx.fiber.dispose()
  294. })
  295. it('authorizes attachment bytes only when the session event stream references the id', async () => {
  296. const { ctx, agent, sessionId } = await harness()
  297. const ref = {
  298. attachmentId: 'att-authorized', mediaType: 'image/png' as const, bytes: 2, width: 1, height: 1,
  299. }
  300. const readImage = vi.fn(() => Promise.resolve({ ref, data: Uint8Array.of(1, 2) }))
  301. ctx.provide('attachments', { readImage } as never)
  302. const remote = createSessionTestRemote(ctx, {
  303. defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
  304. cwd: '/tmp',
  305. })
  306. agent.session.append('agent/inbox/spliced', {
  307. target: 'next-turn',
  308. start: 0,
  309. inserted: [{
  310. id: 'queued-image', role: 'user', source: { kind: 'user' },
  311. content: [{ type: 'image', attachment: ref }],
  312. }],
  313. } as never)
  314. const allowed = await remote.attachment(request({
  315. sessionId, attachmentId: 'att-authorized' as never,
  316. }))
  317. expect(allowed).toMatchObject({ ok: true, value: { attachment: ref, data: 'AQI=' } })
  318. const denied = await remote.attachment(request({
  319. sessionId, attachmentId: 'att-other' as never,
  320. }))
  321. expect(denied).toMatchObject({
  322. ok: false,
  323. error: { code: 'session/attachment-invalid', details: { reason: 'ATTACHMENT_NOT_REFERENCED' } },
  324. })
  325. expect(readImage).toHaveBeenCalledOnce()
  326. await ctx.fiber.dispose()
  327. })
  328. it('groups successful providers and leaves an unlisted current selection out of the catalog', async () => {
  329. const { ctx, sessionId } = await harness({
  330. provider: 'deepseek-official',
  331. model: 'private-preview',
  332. reasoningEffort: ReasoningEffortId('max'),
  333. })
  334. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }), cwd: '/tmp' })
  335. const catalog = expectValue(await remote.modelCatalog())
  336. expect(currentSelection(ctx, sessionId)).toEqual({
  337. provider: 'deepseek-official',
  338. model: 'private-preview',
  339. reasoningEffort: 'max',
  340. })
  341. expect(catalog.groups).toEqual([{
  342. id: 'deepseek-official',
  343. name: 'DeepSeek',
  344. models: [
  345. { id: 'deepseek-chat', name: 'DeepSeek Chat', reasoning: REASONING },
  346. {
  347. id: 'deepseek-reasoner',
  348. name: 'DeepSeek Reasoner',
  349. description: 'Reasoning model',
  350. reasoning: REASONING,
  351. },
  352. ],
  353. }])
  354. expect(catalog.failures).toEqual([
  355. { id: 'broken', name: 'Broken Provider', message: 'catalog offline' },
  356. { id: 'metadata-broken', name: 'Metadata Broken', message: 'reasoning metadata offline' },
  357. {
  358. id: 'duplicate',
  359. name: 'Duplicate Provider',
  360. message: 'adapter returned invalid or duplicate model metadata for provider "duplicate"',
  361. },
  362. ])
  363. await ctx.fiber.dispose()
  364. })
  365. it('preserves optional catalog metadata and string provider failures', async () => {
  366. const { ctx } = await harness()
  367. ctx.llm.registerAdapter(['plain'], new CatalogAdapter('Plain', [
  368. { provider: 'plain', id: 'plain-model', name: 'Plain Model' },
  369. ]))
  370. ctx.llm.registerAdapter(['described-reasoning'], new CatalogAdapter('Described Reasoning', [
  371. { provider: 'described-reasoning', id: 'reasoning-model', name: 'Reasoning Model' },
  372. ], {
  373. efforts: [{ id: ReasoningEffortId('high'), name: 'High', description: 'More thinking' }],
  374. }))
  375. ctx.llm.registerAdapter(['string-failure'], new class extends CatalogAdapter {
  376. override listModels(): Promise<readonly LlmModelInfo[]> {
  377. // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- non-Error provider normalization is the scenario.
  378. return Promise.reject('string catalog failure')
  379. }
  380. }('String Failure', []))
  381. createSessionTestRemote(ctx, {
  382. defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
  383. cwd: '/tmp',
  384. })
  385. const catalog = await buildModelCatalog(ctx)
  386. expect(catalog.groups).toEqual(expect.arrayContaining([
  387. { id: 'plain', name: 'Plain', models: [{ id: 'plain-model', name: 'Plain Model' }] },
  388. {
  389. id: 'described-reasoning',
  390. name: 'Described Reasoning',
  391. models: [{
  392. id: 'reasoning-model',
  393. name: 'Reasoning Model',
  394. reasoning: {
  395. efforts: [{ id: 'high', name: 'High', description: 'More thinking' }],
  396. },
  397. }],
  398. },
  399. ]))
  400. expect(catalog.failures).toContainEqual({
  401. id: 'string-failure', name: 'String Failure', message: 'string catalog failure',
  402. })
  403. await ctx.fiber.dispose()
  404. })
  405. it('accepts an advisory-unlisted model, rejects an unavailable provider, and switches only after the next assembly', async () => {
  406. const { ctx, agent, sessionId } = await harness()
  407. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }), cwd: '/tmp' })
  408. const seed: LlmCallConfig = { provider: 'seed', model: 'seed', temperature: 0.2 }
  409. const signal = new AbortController().signal
  410. expect(currentSelection(ctx, sessionId))
  411. .toEqual({ provider: 'deepseek-official', model: 'deepseek-chat' })
  412. const selected = expectValue(await remote.selectModel(request({
  413. sessionId,
  414. provider: 'deepseek-official',
  415. model: 'private-preview',
  416. reasoningEffort: 'max',
  417. })))
  418. expect(selected.selected).toEqual({
  419. provider: 'deepseek-official',
  420. model: 'private-preview',
  421. reasoningEffort: 'max',
  422. })
  423. await expect(agentEvents(ctx, agent).waterfall(
  424. 'agent/request', { turn: 1, step: 0, signal }, () => Promise.resolve(seed),
  425. )).resolves.toEqual(seed)
  426. expect((await ctx.systemPrompt.assemble()).variables)
  427. .toMatchObject({ provider: 'deepseek-official', model: 'private-preview' })
  428. await expect(agentEvents(ctx, agent).waterfall(
  429. 'agent/request', { turn: 1, step: 1, signal }, () => Promise.resolve(seed),
  430. )).resolves.toMatchObject({
  431. provider: 'deepseek-official',
  432. model: 'private-preview',
  433. reasoningEffort: 'max',
  434. })
  435. const unsupported = await remote.selectModel(request({
  436. sessionId,
  437. provider: 'deepseek-official',
  438. model: 'private-preview',
  439. reasoningEffort: 'medium',
  440. }))
  441. expect(unsupported).toMatchObject({
  442. ok: false,
  443. error: {
  444. code: 'session/model-unavailable',
  445. message: 'provider "deepseek-official" model "private-preview" does not support reasoning effort "medium"',
  446. },
  447. })
  448. const rejected = await remote.selectModel(request({
  449. sessionId,
  450. provider: 'missing',
  451. model: 'model',
  452. }))
  453. expect(rejected).toMatchObject({
  454. ok: false,
  455. error: {
  456. code: 'session/model-unavailable',
  457. message: 'no adapter registered for provider "missing"',
  458. details: { provider: 'missing', model: 'model' },
  459. },
  460. })
  461. expect(await remote.selectModel(request({
  462. sessionId,
  463. provider: 'remote-rejected',
  464. model: 'model',
  465. }))).toMatchObject({
  466. ok: false,
  467. error: {
  468. code: 'gateway/internal',
  469. message: 'fixture rejected the selection',
  470. details: {},
  471. },
  472. })
  473. expect(currentSelection(ctx, sessionId))
  474. .toEqual({ provider: 'deepseek-official', model: 'private-preview', reasoningEffort: 'max' })
  475. await ctx.fiber.dispose()
  476. })
  477. it('reads the Agent default live for a session whose log names no selection', async () => {
  478. const { ctx, sessionId } = await harness()
  479. let stored = { provider: 'deepseek-official', model: 'deepseek-chat' }
  480. createSessionTestRemote(ctx, {
  481. defaultModelSelection: () => stored,
  482. cwd: '/tmp',
  483. })
  484. expect(currentSelection(ctx, sessionId))
  485. .toEqual({ provider: 'deepseek-official', model: 'deepseek-chat' })
  486. // The default moving after the session exists still reaches it: New
  487. // Session reuses a blank session rather than minting another, so a seed
  488. // captured at creation would show the superseded model there.
  489. stored = { provider: 'deepseek-official', model: 'deepseek-reasoner' }
  490. expect(currentSelection(ctx, sessionId))
  491. .toEqual({ provider: 'deepseek-official', model: 'deepseek-reasoner' })
  492. await ctx.fiber.dispose()
  493. })
  494. it('keeps a session on its logged selection when the Agent default differs', async () => {
  495. const { ctx, sessionId } = await harness({
  496. provider: 'deepseek-official',
  497. model: 'deepseek-chat',
  498. })
  499. let stored = { provider: 'deepseek-official', model: 'deepseek-chat' }
  500. createSessionTestRemote(ctx, {
  501. defaultModelSelection: () => stored,
  502. cwd: '/tmp',
  503. })
  504. stored = { provider: 'duplicate', model: 'same' }
  505. expect(currentSelection(ctx, sessionId))
  506. .toEqual({ provider: 'deepseek-official', model: 'deepseek-chat' })
  507. await ctx.fiber.dispose()
  508. })
  509. it('does not reinterpret an adapter-owned reasoning default as an explicit Web selection', async () => {
  510. const { ctx, agent } = await harness({
  511. provider: 'deepseek-official',
  512. model: 'deepseek-chat',
  513. reasoningEffort: ReasoningEffortId('high'),
  514. adapterDefaults: { reasoningEffort: true },
  515. })
  516. createSessionTestRemote(ctx, {
  517. defaultModelSelection: () => ({ provider: 'duplicate', model: 'same' }),
  518. cwd: '/tmp',
  519. })
  520. expect(new ApiSessionAgentController(ctx).selectionFor(agent).current)
  521. .toEqual({ provider: 'deepseek-official', model: 'deepseek-chat' })
  522. await ctx.fiber.dispose()
  523. })
  524. it('saves an accepted selection as the default and survives a storage failure', async () => {
  525. const { ctx, sessionId } = await harness()
  526. const saved: unknown[] = []
  527. let reject = false
  528. const remote = createSessionTestRemote(ctx, {
  529. defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
  530. saveDefaultModelSelection: (selection) => {
  531. saved.push(selection)
  532. return reject ? Promise.reject(new Error('read-only document')) : Promise.resolve()
  533. },
  534. cwd: '/tmp',
  535. })
  536. expectValue(await remote.selectModel(request({
  537. sessionId, provider: 'deepseek-official', model: 'deepseek-reasoner', reasoningEffort: 'max',
  538. })))
  539. expect(saved).toEqual([
  540. { provider: 'deepseek-official', model: 'deepseek-reasoner', reasoningEffort: 'max' },
  541. ])
  542. // A refused selection never becomes anyone's default.
  543. await remote.selectModel(request({ sessionId, provider: 'missing', model: 'model' }))
  544. expect(saved).toHaveLength(1)
  545. // Storage failing is not the selection failing: the switch already applies
  546. // to this session, so the call still succeeds.
  547. reject = true
  548. const stillAccepted = expectValue(await remote.selectModel(request({
  549. sessionId, provider: 'deepseek-official', model: 'deepseek-chat',
  550. })))
  551. expect(stillAccepted.selected).toEqual({ provider: 'deepseek-official', model: 'deepseek-chat', reasoningEffort: 'high' })
  552. expect(currentSelection(ctx, sessionId))
  553. .toEqual({ provider: 'deepseek-official', model: 'deepseek-chat', reasoningEffort: 'high' })
  554. await ctx.fiber.dispose()
  555. })
  556. it('refuses a prompt no adapter can route, and reports it on the directory', async () => {
  557. const { ctx, sessionId } = await harness()
  558. const remote = createSessionTestRemote(ctx, {
  559. defaultModelSelection: () => ({ provider: 'deleted-gateway', model: 'deleted-model' }),
  560. cwd: '/tmp',
  561. })
  562. // The client disabling its input is an affordance; this method stays
  563. // callable, so the refusal has to live here.
  564. const refused = await remote.prompt(promptRequest({
  565. sessionId, mode: 'queue' as const, content: [{ type: 'text' as const, text: 'hi' }],
  566. }))
  567. expect(refused).toMatchObject({
  568. ok: false,
  569. error: { code: 'session/model-unavailable', details: { provider: 'deleted-gateway', model: 'deleted-model' } },
  570. })
  571. const unavailableCatalog = await buildModelCatalog(ctx)
  572. expect(unavailableCatalog.routableProviders.includes(currentSelection(ctx, sessionId).provider)).toBe(false)
  573. // An advisory-unlisted model on a live route is NOT this: the route
  574. // serves it, so the prompt goes through and nothing blocks.
  575. expectValue(await remote.selectModel(request({
  576. sessionId, provider: 'deepseek-official', model: 'unlisted-but-served',
  577. })))
  578. const catalog = await buildModelCatalog(ctx)
  579. expect(catalog.routableProviders.includes(currentSelection(ctx, sessionId).provider)).toBe(true)
  580. expect(catalog.groups.flatMap(group => group.models.map(model => model.id)))
  581. .not.toContain('unlisted-but-served')
  582. await ctx.fiber.dispose()
  583. })
  584. it('serves a session and its catalog when the stored default names a route that is gone', async () => {
  585. const { ctx, sessionId } = await harness()
  586. createSessionTestRemote(ctx, {
  587. // What a Models-page removal leaves behind: the settings document still
  588. // names the route the user last picked, and nothing serves it.
  589. defaultModelSelection: () => ({ provider: 'deleted-gateway', model: 'deleted-model' }),
  590. cwd: '/tmp',
  591. })
  592. const catalog = await buildModelCatalog(ctx)
  593. // Passed through rather than repaired: matching no group is precisely what
  594. // makes the composer seat prompt for a selection instead of naming a model
  595. // the deployment cannot reach.
  596. expect(currentSelection(ctx, sessionId)).toEqual({ provider: 'deleted-gateway', model: 'deleted-model' })
  597. expect(catalog.groups.flatMap(group => group.models.map(model => `${group.id}/${model.id}`)))
  598. .not.toContain('deleted-gateway/deleted-model')
  599. await ctx.fiber.dispose()
  600. })
  601. it('maps image admission failures and accepts image-capable selections', async () => {
  602. const { ctx, agent, sessionId } = await harness()
  603. registerTextOnly(ctx)
  604. ctx.llm.registerAdapter(['image-capable'], new class extends CatalogAdapter {
  605. override resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
  606. return Promise.resolve({
  607. provider, id: model, name: model, inputModalities: ['text', 'image'],
  608. })
  609. }
  610. }('Image Capable', []))
  611. ctx.llm.registerAdapter(['string-error'], new class extends CatalogAdapter {
  612. override resolveModel(): Promise<LlmResolvedModelInfo> {
  613. // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- non-Error provider normalization is the scenario.
  614. return Promise.reject('string selection failure')
  615. }
  616. }('String Error', []))
  617. let saveMode: 'success' | 'error' | 'remote' = 'success'
  618. const savedRef = {
  619. attachmentId: 'saved-image', mediaType: 'image/png' as const, bytes: 1, width: 1, height: 1,
  620. }
  621. ctx.provide('attachments', Object.setPrototypeOf({
  622. saveImages: () => {
  623. if (saveMode === 'error') return Promise.reject(new Error('image store offline'))
  624. if (saveMode === 'remote') {
  625. return Promise.reject(new RemoteError('gateway/internal', 'fixture rejected', {}))
  626. }
  627. return Promise.resolve([savedRef])
  628. },
  629. }, AttachmentStore.prototype) as never)
  630. const followup = vi.fn()
  631. Object.assign(agent, { followup })
  632. const remote = createSessionTestRemote(ctx, {
  633. defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
  634. cwd: '/tmp',
  635. })
  636. const image = { type: 'image' as const, mediaType: 'image/png' as const, data: 'AQ==' }
  637. expectValue(await remote.selectModel(request({
  638. sessionId, provider: 'text-only', model: 'plain',
  639. })))
  640. expect(await remote.prompt(promptRequest({
  641. sessionId, mode: 'queue', content: [image],
  642. }))).toMatchObject({
  643. ok: false,
  644. error: { code: 'session/attachment-invalid', details: { reason: 'MODEL_DOES_NOT_SUPPORT_IMAGES' } },
  645. })
  646. expectValue(await remote.selectModel(request({
  647. sessionId, provider: 'image-capable', model: 'vision',
  648. })))
  649. expect(await remote.prompt(promptRequest({
  650. sessionId, mode: 'queue', content: [{ ...image, data: '' }],
  651. }))).toMatchObject({
  652. ok: false,
  653. error: { code: 'session/attachment-invalid', details: { reason: 'INVALID_IMAGE_BASE64' } },
  654. })
  655. saveMode = 'error'
  656. expect(await remote.prompt(promptRequest({
  657. sessionId, mode: 'queue', content: [image],
  658. }))).toMatchObject({ ok: false, error: { code: 'session/agent-busy' } })
  659. saveMode = 'remote'
  660. expect(await remote.prompt(promptRequest({
  661. sessionId, mode: 'queue', content: [image],
  662. }))).toMatchObject({ ok: false, error: { code: 'gateway/internal', message: 'fixture rejected' } })
  663. saveMode = 'success'
  664. expectValue(await remote.prompt(promptRequest({ sessionId, mode: 'queue', content: [image] })))
  665. expect(followup).toHaveBeenCalledOnce()
  666. ;(agent.inbox.nextTurn as UserMessage[]).push({
  667. id: 'pending-image', role: 'user', source: { kind: 'user' },
  668. content: [{ type: 'image', attachment: savedRef }],
  669. } as never)
  670. expectValue(await remote.selectModel(request({
  671. sessionId, provider: 'deepseek-official', model: 'deepseek-chat',
  672. })))
  673. expectValue(await remote.selectModel(request({
  674. sessionId, provider: 'image-capable', model: 'vision',
  675. })))
  676. expect(await remote.selectModel(request({
  677. sessionId, provider: 'metadata-broken', model: 'broken',
  678. }))).toMatchObject({
  679. ok: false, error: { code: 'session/model-unavailable', message: 'reasoning metadata offline' },
  680. })
  681. expect(await remote.selectModel(request({
  682. sessionId, provider: 'string-error', model: 'broken',
  683. }))).toMatchObject({
  684. ok: false,
  685. error: { code: 'session/model-unavailable', message: 'string selection failure' },
  686. })
  687. await ctx.fiber.dispose()
  688. })
  689. })