browser-plugin.client.spec.ts 16 KB

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