browser-plugin.client.spec.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. /**
  2. * ui-model-selection browser half on a real cordis Context with fake command/slots/
  3. * connection faces and real session scopes: the plugin mounts ModelDirectoryResolver
  4. * as `models`, the /model contribution and the conversation.input.model
  5. * seat both register, and BOTH entries resolve the SAME per-session
  6. * directory through the service — a selection submitted through the seat's
  7. * inject face is the current the popup's next options pass marks active
  8. * (and the reverse), the one-shared-state contract of the dual entry.
  9. * Scope disposal drops the directory (HMR safety).
  10. */
  11. import { Context } from '@deepseek-ai/cordis'
  12. import { describe, expect, it, vi } from 'vitest'
  13. import { createScope } from '@deepseek-ai/dsh-api-session-controller/client'
  14. import type { SessionId } from '@deepseek-ai/dsh-session/types'
  15. import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
  16. import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store'
  17. import { RemoteError, TestRemote } from '@deepseek-ai/dsh-client-test-runtime'
  18. import type { ModelSelection, ModelSelectionProjection } from '@deepseek-ai/dsh-api-session-controller/types'
  19. import type { CommandContribution, PopupSelectSpec, SelectOption } from '@deepseek-ai/dsh-client-ui-commands/client'
  20. import type { ModelSelectInjected } from '../src/client/slots.ts'
  21. import { apply, inject } from '../src/client/index.ts'
  22. import { zh } from '../src/client/locales.ts'
  23. const sid = (k: string): SessionId => k as SessionId
  24. const GROUPS = [{
  25. id: 'deepseek-official',
  26. name: 'DeepSeek',
  27. models: [
  28. {
  29. id: 'deepseek-v4-flash',
  30. name: 'DeepSeek-V4-Flash',
  31. description: 'Fast, efficient, and economical; suited to focused, routine, or parallel tasks.',
  32. reasoning: {
  33. efforts: [
  34. { id: 'off', name: 'Off' },
  35. { id: 'high', name: 'High' },
  36. { id: 'max', name: 'Max' },
  37. ],
  38. defaultEffort: 'high',
  39. },
  40. },
  41. {
  42. id: 'deepseek-v4-pro',
  43. name: 'DeepSeek-V4-Pro',
  44. description: 'Stronger agentic coding, knowledge, and difficult reasoning; suited to complex or quality-critical tasks at higher cost.',
  45. reasoning: {
  46. efforts: [
  47. { id: 'off', name: 'Off' },
  48. { id: 'high', name: 'High' },
  49. { id: 'max', name: 'Max' },
  50. ],
  51. defaultEffort: 'high',
  52. },
  53. },
  54. ],
  55. }, {
  56. id: 'external',
  57. name: 'External Provider',
  58. models: [{
  59. id: 'deepseek-v4-flash',
  60. name: 'External Flash',
  61. description: 'Provider-authored description.',
  62. }],
  63. }]
  64. /** Boot the plugin over fake faces + a stateful fake host (current moves on selectModel). */
  65. async function bench(locale: 'zh' | 'en' = 'zh') {
  66. const ctx = new Context()
  67. let defaultSelection: ModelSelection = { provider: 'deepseek-official', model: 'deepseek-v4-flash' }
  68. let selected = defaultSelection
  69. const calls = { models: 0, select: 0 }
  70. const projections = new Map<SessionId, SnapshotStore<ModelSelectionProjection | undefined>>()
  71. // Whether the Host reports an adapter for the current route; the composer
  72. // block follows this, never catalog membership.
  73. let routable = true
  74. let selectionFailure: RemoteError<'session/writer-held'> | undefined
  75. const sessionRemote = {
  76. modelCatalog: () => {
  77. calls.models += 1
  78. return Promise.resolve({
  79. ok: true as const,
  80. value: {
  81. default: defaultSelection,
  82. routableProviders: routable ? ['deepseek-official'] : [],
  83. groups: GROUPS,
  84. failures: [],
  85. },
  86. })
  87. },
  88. selectModel: (payload: { sessionId: SessionId; provider: string; model: string; reasoningEffort?: string }) => {
  89. calls.select += 1
  90. if (selectionFailure !== undefined) return Promise.resolve({ ok: false as const, error: selectionFailure })
  91. selected = {
  92. provider: payload.provider,
  93. model: payload.model,
  94. ...payload.reasoningEffort === undefined
  95. ? {}
  96. : { reasoningEffort: payload.reasoningEffort },
  97. }
  98. projections.get(payload.sessionId)?.set({ lastUsed: null, next: selected })
  99. return Promise.resolve({ ok: true as const, value: { selected } })
  100. },
  101. }
  102. const remote = Object.assign(new TestRemote(ctx), { session: sessionRemote })
  103. ctx.reflect.provide('remote.session', sessionRemote)
  104. const blocks = new Map<SessionId, { reason: string } | undefined>()
  105. ctx.provide('conversation', {
  106. blocks: {
  107. set: (id: SessionId, block: { reason: string } | undefined) => { blocks.set(id, block) },
  108. },
  109. })
  110. let contribution: CommandContribution | undefined
  111. ctx.provide('commandUi', {
  112. register(c: CommandContribution) {
  113. contribution = c
  114. return () => { contribution = undefined }
  115. },
  116. })
  117. const seats = new Map<string, {
  118. inject: ((sessionId: SessionId) => ModelSelectInjected) | undefined
  119. locale: string | undefined
  120. }>()
  121. ctx.provide('slots', {
  122. inject(_name: string, callback: () => () => void) { return callback() },
  123. register(options: { name: string; locale?: string; inject?: (sessionId: SessionId) => ModelSelectInjected }) {
  124. seats.set(options.name, { inject: options.inject, locale: options.locale })
  125. return () => { seats.delete(options.name) }
  126. },
  127. })
  128. const localeRuntime = new LocaleRuntime(ctx)
  129. // There is no jsdom `window` in this lane, so browser-language detection
  130. // never runs. Each bench states the locale its assertions require.
  131. localeRuntime.setLocale(locale)
  132. ctx.provide('locale', localeRuntime)
  133. const scopes = new Map<SessionId, Context>()
  134. const bindings = new Map<SessionId, {
  135. sessionId: SessionId
  136. session: { sessionId: SessionId; projections: { faceOf: () => SnapshotStore<ModelSelectionProjection | undefined> } }
  137. ctx: Context
  138. }>()
  139. const addressed = new Set<SessionId>()
  140. ctx.provide('sessions', {
  141. scope: (id: SessionId) => scopes.get(id),
  142. binding: (id: SessionId) => bindings.get(id),
  143. subagentAddress: (id: SessionId) => addressed.has(id)
  144. ? { parentSessionId: sid('parent'), childSessionId: id, mode: 'continuable' as const }
  145. : undefined,
  146. })
  147. const fiber = ctx.plugin({ inject: [...inject], apply })
  148. await fiber.await()
  149. await ctx.plugin(function probe() {}).await()
  150. const mint = (key: string) => {
  151. const id = sid(key)
  152. const handle = createScope(ctx, id)
  153. scopes.set(id, handle.ctx)
  154. const projection = createSnapshotStore<ModelSelectionProjection | undefined>({
  155. lastUsed: null,
  156. next: null,
  157. })
  158. projections.set(id, projection)
  159. const binding = {
  160. sessionId: id,
  161. session: { sessionId: id, projections: { faceOf: () => projection } },
  162. ctx: handle.ctx,
  163. }
  164. bindings.set(id, binding)
  165. handle.ctx.effect(() => () => {
  166. if (bindings.get(id) === binding) bindings.delete(id)
  167. })
  168. return handle
  169. }
  170. return {
  171. ctx, fiber, mint, calls, remote,
  172. contribution: () => contribution!,
  173. popup: (): PopupSelectSpec => {
  174. const ui = contribution!.ui
  175. if (ui.kind !== 'popupSelect') throw new Error('expected the popupSelect kind')
  176. return ui
  177. },
  178. seat: () => seats.get('conversation.input.model')!,
  179. hostCurrent: () => selected,
  180. rejectSelection: () => {
  181. selectionFailure = new RemoteError('session/writer-held', 'writer held', { sessionId: sid('owned') })
  182. },
  183. setHostCurrent: (selection: ModelSelection) => { defaultSelection = selection },
  184. setProjected: (id: SessionId, value: ModelSelectionProjection) => { projections.get(id)?.set(value) },
  185. address: (id: SessionId) => { addressed.add(id) },
  186. setRoutable: (next: boolean) => { routable = next },
  187. blockOf: (key: string) => blocks.get(sid(key)),
  188. }
  189. }
  190. const projection = (id: string) => ({ sessionId: sid(id) })
  191. describe('ui-model-selection dual entry', () => {
  192. it('carries writer contention to the model seat and localizes the command failure', async () => {
  193. const b = await bench()
  194. b.mint('owned')
  195. const input = projection('owned')
  196. const options = await b.popup().options(input, new AbortController().signal)
  197. b.rejectSelection()
  198. await expect(b.popup().onSelect(options[0]!, input)).rejects.toThrow(zh['error.sessionInUse'])
  199. expect(b.ctx.modelDirectories.directoryFor(sid('owned')).store.getSnapshot()).toMatchObject({
  200. status: 'error', error: 'session/writer-held: writer held',
  201. })
  202. })
  203. it('registers the /model contribution and the composer model seat', async () => {
  204. const b = await bench()
  205. expect(b.contribution().name).toBe('model')
  206. expect(b.contribution().ui.kind).toBe('popupSelect')
  207. expect(b.seat().inject).toBeTypeOf('function')
  208. // Copy rides the standard locale seat.
  209. expect(b.seat().locale).toBe('model')
  210. })
  211. it('localizes built-in descriptions and preserves external provider descriptions', async () => {
  212. const b = await bench()
  213. b.mint('s1')
  214. const options = await b.popup().options(projection('s1'), new AbortController().signal)
  215. expect(options.map((o: SelectOption) => o.label)).toEqual([
  216. 'DeepSeek-V4-Flash', 'DeepSeek-V4-Pro', 'External Flash',
  217. ])
  218. expect(options[0]).toMatchObject({
  219. active: true,
  220. detail: 'DeepSeek · 快速、高效且经济;适合目标明确、常规或并行任务。',
  221. })
  222. expect(options[1]?.detail)
  223. .toBe('DeepSeek · 更强的自主编码、知识与复杂推理能力;适合复杂或质量优先的任务,但成本更高。')
  224. expect(options[2]?.detail).toBe('External Provider · Provider-authored description.')
  225. expect(options[1]?.active).toBeUndefined()
  226. })
  227. it('keeps built-in descriptions unchanged in English', async () => {
  228. const b = await bench('en')
  229. b.mint('s1')
  230. const options = await b.popup().options(projection('s1'), new AbortController().signal)
  231. expect(options[0]?.detail)
  232. .toBe('DeepSeek · Fast, efficient, and economical; suited to focused, routine, or parallel tasks.')
  233. expect(options[1]?.detail)
  234. .toBe('DeepSeek · Stronger agentic coding, knowledge, and difficult reasoning; suited to complex or quality-critical tasks at higher cost.')
  235. })
  236. it('a seat selection is the current the popup marks active next — one shared state', async () => {
  237. const b = await bench()
  238. b.mint('s1')
  239. const seatFace = b.seat().inject!(sid('s1'))
  240. // Switch through the SEAT entry.
  241. expect(await seatFace.select({
  242. provider: 'deepseek-official',
  243. model: 'deepseek-v4-pro',
  244. reasoningEffort: 'max',
  245. })).toEqual({ ok: true, value: undefined })
  246. expect(b.hostCurrent()).toEqual({
  247. provider: 'deepseek-official',
  248. model: 'deepseek-v4-pro',
  249. reasoningEffort: 'max',
  250. })
  251. expect(seatFace.directory.getSnapshot().current).toEqual({
  252. provider: 'deepseek-official',
  253. model: 'deepseek-v4-pro',
  254. reasoningEffort: 'max',
  255. })
  256. // The POPUP's next options pass reflects it without a seat-side reload.
  257. const options = await b.popup().options(projection('s1'), new AbortController().signal)
  258. expect(options.find((o: SelectOption) => o.label === 'DeepSeek-V4-Pro')).toMatchObject({ active: true })
  259. })
  260. it('a popup selection lands on the seat store — the reverse direction of the same state', async () => {
  261. const b = await bench()
  262. b.mint('s1')
  263. const seatFace = b.seat().inject!(sid('s1'))
  264. const options = await b.popup().options(projection('s1'), new AbortController().signal)
  265. const pro = options.find((o: SelectOption) => o.label === 'DeepSeek-V4-Pro')!
  266. await b.popup().onSelect(pro, projection('s1'))
  267. expect(seatFace.directory.getSnapshot().current).toEqual({
  268. provider: 'deepseek-official',
  269. model: 'deepseek-v4-pro',
  270. reasoningEffort: 'high',
  271. })
  272. })
  273. it('both entries share one directory instance per session, isolated across sessions', async () => {
  274. const b = await bench()
  275. b.mint('a')
  276. b.mint('b')
  277. const faceA = b.seat().inject!(sid('a'))
  278. const faceA2 = b.seat().inject!(sid('a'))
  279. const faceB = b.seat().inject!(sid('b'))
  280. expect(faceA.directory).toBe(faceA2.directory)
  281. expect(faceA.directory).not.toBe(faceB.directory)
  282. // The service face resolves the same instance the seat inject handed out.
  283. expect(b.ctx.modelDirectories.directoryFor(sid('a')).store).toBe(faceA.directory)
  284. await Promise.all([
  285. b.popup().options(projection('a'), new AbortController().signal),
  286. b.popup().options(projection('b'), new AbortController().signal),
  287. ])
  288. expect(b.calls.models).toBe(1)
  289. })
  290. it('keeps the durable projected selection while the eager catalog reconnects', async () => {
  291. const b = await bench()
  292. b.mint('s1')
  293. const face = b.seat().inject!(sid('s1'))
  294. await face.select({ provider: 'deepseek-official', model: 'deepseek-v4-pro' })
  295. b.setHostCurrent({ provider: 'deepseek-official', model: 'deepseek-v4-flash' })
  296. b.ctx.emit('connection/reset')
  297. expect(face.directory.getSnapshot()).toMatchObject({
  298. current: { provider: 'deepseek-official', model: 'deepseek-v4-pro' },
  299. status: 'ready',
  300. })
  301. face.load()
  302. expect(face.directory.getSnapshot()).toMatchObject({
  303. current: { provider: 'deepseek-official', model: 'deepseek-v4-pro' },
  304. status: 'ready',
  305. })
  306. })
  307. it('keeps the last complete view while a refreshed catalog catches up with projection', async () => {
  308. const b = await bench()
  309. b.mint('s1')
  310. const face = b.seat().inject!(sid('s1'))
  311. face.load()
  312. expect(face.directory.getSnapshot().current?.model).toBe('deepseek-v4-flash')
  313. b.remote.emit('settings/document-updated', ['llm-deepseek', 1])
  314. b.setProjected(sid('s1'), {
  315. lastUsed: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  316. next: { provider: 'deepseek-official', model: 'deepseek-v4-pro' },
  317. })
  318. expect(face.directory.getSnapshot()).toMatchObject({
  319. current: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  320. status: 'ready',
  321. })
  322. await vi.waitFor(() => {
  323. expect(face.directory.getSnapshot()).toMatchObject({
  324. current: { provider: 'deepseek-official', model: 'deepseek-v4-pro' },
  325. status: 'ready',
  326. })
  327. })
  328. })
  329. it('scope disposal drops the directory; a reborn scope gets a fresh one', async () => {
  330. const b = await bench()
  331. const first = b.mint('s1')
  332. const face1 = b.seat().inject!(sid('s1'))
  333. await first.fiber.dispose()
  334. b.mint('s1')
  335. const face2 = b.seat().inject!(sid('s1'))
  336. expect(face2.directory).not.toBe(face1.directory)
  337. })
  338. it('blocks the composer only once the Host reports the route unservable', async () => {
  339. const b = await bench()
  340. b.mint('s1')
  341. const face = b.seat().inject!(sid('s1'))
  342. // Before the first load nothing is known. `null` is not `false`: a slow
  343. // or unreachable Host must never lock a working composer.
  344. expect(b.blockOf('s1')).toBeUndefined()
  345. face.load()
  346. await Promise.resolve()
  347. await Promise.resolve()
  348. expect(b.blockOf('s1')).toBeUndefined()
  349. expect(b.calls.models).toBe(1)
  350. b.setRoutable(false)
  351. b.remote.emit('settings/document-updated', ['llm-deepseek', 1])
  352. await Promise.resolve()
  353. await Promise.resolve()
  354. expect(b.blockOf('s1')?.reason).toBe(zh['blocked.composer'])
  355. expect(b.calls.models).toBe(2)
  356. // Recovering clears it without a reload of the surface.
  357. b.setRoutable(true)
  358. b.remote.emit('llm/adapters-updated', [])
  359. await Promise.resolve()
  360. await Promise.resolve()
  361. expect(b.blockOf('s1')).toBeUndefined()
  362. expect(b.calls.models).toBe(3)
  363. })
  364. it('never blocks on catalog membership alone', async () => {
  365. const b = await bench()
  366. b.mint('s1')
  367. const face = b.seat().inject!(sid('s1'))
  368. // A model the route serves but no longer advertises: the seat prompts for
  369. // a selection, the composer stays usable. Blocking here would break a
  370. // supported configuration (a narrowed `models` list over a live route).
  371. b.setHostCurrent({ provider: 'deepseek-official', model: 'unlisted' })
  372. face.load()
  373. await Promise.resolve()
  374. await Promise.resolve()
  375. const snapshot = face.directory.getSnapshot()
  376. expect(snapshot.groups.flatMap(group => group.models.map(model => model.id))).not.toContain('unlisted')
  377. expect(b.blockOf('s1')).toBeUndefined()
  378. })
  379. it('clears its block when the session scope goes', async () => {
  380. const b = await bench()
  381. const scope = b.mint('s1')
  382. b.setRoutable(false)
  383. const face = b.seat().inject!(sid('s1'))
  384. face.load()
  385. b.remote.emit('llm/adapters-updated', [])
  386. await vi.waitFor(() => { expect(b.blockOf('s1')).toBeDefined() })
  387. await scope.fiber.dispose()
  388. expect(b.blockOf('s1')).toBeUndefined()
  389. })
  390. it('an unknown session fails loud at the seat inject', async () => {
  391. const b = await bench()
  392. expect(() => b.seat().inject!(sid('ghost'))).toThrow(/resolved no scope/)
  393. })
  394. it('withholds both model entries from addressed subagent sessions without Agent-bound RPCs', async () => {
  395. const b = await bench()
  396. b.mint('child')
  397. b.address(sid('child'))
  398. expect(b.contribution().available(projection('child'))).toBe(false)
  399. await expect(b.popup().options(
  400. projection('child'),
  401. new AbortController().signal,
  402. )).rejects.toThrow(/unavailable for addressed subagent/)
  403. const face = b.seat().inject!(sid('child'))
  404. expect(face.available).toBe(false)
  405. face.load()
  406. await expect(face.select({ provider: 'deepseek', model: 'deepseek-v4-pro' })).resolves.toBeUndefined()
  407. await expect(b.ctx.modelDirectories.directoryFor(sid('child')).load())
  408. .rejects.toThrow(/unavailable for addressed subagent/)
  409. await expect(b.ctx.modelDirectories.directoryFor(sid('child')).select({
  410. provider: 'deepseek',
  411. model: 'deepseek-v4-pro',
  412. })).rejects.toThrow(/unavailable for addressed subagent/)
  413. b.ctx.emit('connection/reset')
  414. await Promise.resolve()
  415. expect(b.calls).toEqual({ models: 2, select: 0 })
  416. })
  417. })