browser-plugin.client.spec.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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 } 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 { TestRemote } from '@deepseek-ai/dsh-client-test-runtime'
  17. import type { ModelSelection } from '@deepseek-ai/dsh-api-session-controller/types'
  18. import type { CommandContribution, SelectOption } from '@deepseek-ai/dsh-client-ui-commands/client'
  19. import type { ModelSelectInjected } from '../src/client/slots.ts'
  20. import { apply, inject } from '../src/client/index.ts'
  21. import { zh } from '../src/client/locales.ts'
  22. const sid = (k: string): SessionId => k as SessionId
  23. const GROUPS = [{
  24. id: 'deepseek-official',
  25. name: 'DeepSeek',
  26. models: [
  27. {
  28. id: 'deepseek-v4-flash',
  29. name: 'DeepSeek-V4-Flash',
  30. reasoning: {
  31. efforts: [
  32. { id: 'off', name: 'Off' },
  33. { id: 'high', name: 'High' },
  34. { id: 'max', name: 'Max' },
  35. ],
  36. defaultEffort: 'high',
  37. },
  38. },
  39. {
  40. id: 'deepseek-v4-pro',
  41. name: 'DeepSeek-V4-Pro',
  42. reasoning: {
  43. efforts: [
  44. { id: 'off', name: 'Off' },
  45. { id: 'high', name: 'High' },
  46. { id: 'max', name: 'Max' },
  47. ],
  48. defaultEffort: 'high',
  49. },
  50. },
  51. ],
  52. }]
  53. /** Boot the plugin over fake faces + a stateful fake host (current moves on selectModel). */
  54. async function bench() {
  55. const ctx = new Context()
  56. let current: ModelSelection = { provider: 'deepseek-official', model: 'deepseek-v4-flash' }
  57. const calls = { models: 0, select: 0 }
  58. const sessionRemote = {
  59. models: () => {
  60. calls.models += 1
  61. return Promise.resolve({ ok: true as const, value: { current, routable, groups: GROUPS, failures: [] } })
  62. },
  63. selectModel: (payload: { provider: string; model: string; reasoningEffort?: string }) => {
  64. calls.select += 1
  65. current = {
  66. provider: payload.provider,
  67. model: payload.model,
  68. ...payload.reasoningEffort === undefined
  69. ? {}
  70. : { reasoningEffort: payload.reasoningEffort },
  71. }
  72. return Promise.resolve({ ok: true as const, value: { selected: current } })
  73. },
  74. }
  75. const remote = Object.assign(new TestRemote(ctx), { session: sessionRemote })
  76. ctx.reflect.provide('remote.session', sessionRemote)
  77. // Whether the Host reports an adapter for the current route; the composer
  78. // block follows this, never catalog membership.
  79. let routable = true
  80. const blocks = new Map<SessionId, { reason: string } | undefined>()
  81. ctx.provide('conversation', {
  82. blocks: {
  83. set: (id: SessionId, block: { reason: string } | undefined) => { blocks.set(id, block) },
  84. },
  85. })
  86. let contribution: CommandContribution | undefined
  87. ctx.provide('commandUi', {
  88. register(c: CommandContribution) {
  89. contribution = c
  90. return () => { contribution = undefined }
  91. },
  92. })
  93. const seats = new Map<string, {
  94. inject: ((sessionId: SessionId) => ModelSelectInjected) | undefined
  95. locale: string | undefined
  96. }>()
  97. ctx.provide('slots', {
  98. inject(_name: string, callback: () => () => void) { return callback() },
  99. register(options: { name: string; locale?: string; inject?: (sessionId: SessionId) => ModelSelectInjected }) {
  100. seats.set(options.name, { inject: options.inject, locale: options.locale })
  101. return () => { seats.delete(options.name) }
  102. },
  103. })
  104. const localeRuntime = new LocaleRuntime(ctx)
  105. // This spec asserts the shipped Chinese copy. There is no jsdom `window` in
  106. // this lane, so browser-language detection never runs and the locale comes
  107. // from FALLBACK_LOCALE (en): state the asserted locale explicitly.
  108. localeRuntime.setLocale('zh')
  109. ctx.provide('locale', localeRuntime)
  110. const scopes = new Map<SessionId, Context>()
  111. const addressed = new Set<SessionId>()
  112. ctx.provide('sessions', {
  113. scope: (id: SessionId) => scopes.get(id),
  114. subagentAddress: (id: SessionId) => addressed.has(id)
  115. ? { parentSessionId: sid('parent'), childSessionId: id, mode: 'continuable' as const }
  116. : undefined,
  117. })
  118. const fiber = ctx.plugin({ inject: [...inject], apply })
  119. await fiber.await()
  120. await ctx.plugin(function probe() {}).await()
  121. const mint = (key: string) => {
  122. const handle = createScope(ctx, sid(key))
  123. scopes.set(sid(key), handle.ctx)
  124. return handle
  125. }
  126. return {
  127. ctx, fiber, mint, calls, remote,
  128. contribution: () => contribution!,
  129. seat: () => seats.get('conversation.input.model')!,
  130. hostCurrent: () => current,
  131. setHostCurrent: (selection: ModelSelection) => { current = selection },
  132. address: (id: SessionId) => { addressed.add(id) },
  133. setRoutable: (next: boolean) => { routable = next },
  134. blockOf: (key: string) => blocks.get(sid(key)),
  135. }
  136. }
  137. const projection = (id: string) => ({ sessionId: sid(id) })
  138. describe('ui-model-selection dual entry', () => {
  139. it('registers the /model contribution and the composer model seat', async () => {
  140. const b = await bench()
  141. expect(b.contribution().name).toBe('model')
  142. expect(b.contribution().ui.kind).toBe('popupSelect')
  143. expect(b.seat().inject).toBeTypeOf('function')
  144. // Copy rides the standard locale seat.
  145. expect(b.seat().locale).toBe('model')
  146. })
  147. it('popup options mark the host current active with the provider group in the detail', async () => {
  148. const b = await bench()
  149. b.mint('s1')
  150. const options = await b.contribution().ui.options(projection('s1'), new AbortController().signal)
  151. expect(options.map((o: SelectOption) => o.label)).toEqual(['DeepSeek-V4-Flash', 'DeepSeek-V4-Pro'])
  152. expect(options[0]).toMatchObject({ active: true, detail: 'DeepSeek' })
  153. expect(options[1]?.active).toBeUndefined()
  154. })
  155. it('a seat selection is the current the popup marks active next — one shared state', async () => {
  156. const b = await bench()
  157. b.mint('s1')
  158. const seatFace = b.seat().inject!(sid('s1'))
  159. // Switch through the SEAT entry.
  160. expect(await seatFace.select({
  161. provider: 'deepseek-official',
  162. model: 'deepseek-v4-pro',
  163. reasoningEffort: 'max',
  164. })).toBe(true)
  165. expect(b.hostCurrent()).toEqual({
  166. provider: 'deepseek-official',
  167. model: 'deepseek-v4-pro',
  168. reasoningEffort: 'max',
  169. })
  170. expect(seatFace.directory.getSnapshot().current).toEqual({
  171. provider: 'deepseek-official',
  172. model: 'deepseek-v4-pro',
  173. reasoningEffort: 'max',
  174. })
  175. // The POPUP's next options pass reflects it without a seat-side reload.
  176. const options = await b.contribution().ui.options(projection('s1'), new AbortController().signal)
  177. expect(options.find((o: SelectOption) => o.label === 'DeepSeek-V4-Pro')).toMatchObject({ active: true })
  178. })
  179. it('a popup selection lands on the seat store — the reverse direction of the same state', async () => {
  180. const b = await bench()
  181. b.mint('s1')
  182. const seatFace = b.seat().inject!(sid('s1'))
  183. const options = await b.contribution().ui.options(projection('s1'), new AbortController().signal)
  184. const pro = options.find((o: SelectOption) => o.label === 'DeepSeek-V4-Pro')!
  185. await b.contribution().ui.onSelect(pro, projection('s1'))
  186. expect(seatFace.directory.getSnapshot().current).toEqual({
  187. provider: 'deepseek-official',
  188. model: 'deepseek-v4-pro',
  189. reasoningEffort: 'high',
  190. })
  191. })
  192. it('both entries share one directory instance per session, isolated across sessions', async () => {
  193. const b = await bench()
  194. b.mint('a')
  195. b.mint('b')
  196. const faceA = b.seat().inject!(sid('a'))
  197. const faceA2 = b.seat().inject!(sid('a'))
  198. const faceB = b.seat().inject!(sid('b'))
  199. expect(faceA.directory).toBe(faceA2.directory)
  200. expect(faceA.directory).not.toBe(faceB.directory)
  201. // The service face resolves the same instance the seat inject handed out.
  202. expect(b.ctx.modelDirectories.directoryFor(sid('a')).store).toBe(faceA.directory)
  203. })
  204. it('drops an unconsumed local selection and restores the Host target after reconnect', async () => {
  205. const b = await bench()
  206. b.mint('s1')
  207. const face = b.seat().inject!(sid('s1'))
  208. await face.select({ provider: 'deepseek-official', model: 'deepseek-v4-pro' })
  209. b.setHostCurrent({ provider: 'deepseek-official', model: 'deepseek-v4-flash' })
  210. b.ctx.emit('connection/reset')
  211. expect(face.directory.getSnapshot()).toMatchObject({ current: null, status: 'loading' })
  212. await Promise.resolve()
  213. expect(face.directory.getSnapshot()).toMatchObject({
  214. current: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  215. status: 'ready',
  216. })
  217. })
  218. it('scope disposal drops the directory; a reborn scope gets a fresh one', async () => {
  219. const b = await bench()
  220. const first = b.mint('s1')
  221. const face1 = b.seat().inject!(sid('s1'))
  222. await first.fiber.dispose()
  223. b.mint('s1')
  224. const face2 = b.seat().inject!(sid('s1'))
  225. expect(face2.directory).not.toBe(face1.directory)
  226. })
  227. it('blocks the composer only once the Host reports the route unservable', async () => {
  228. const b = await bench()
  229. b.mint('s1')
  230. const face = b.seat().inject!(sid('s1'))
  231. // Before the first load nothing is known. `null` is not `false`: a slow
  232. // or unreachable Host must never lock a working composer.
  233. expect(b.blockOf('s1')).toBeUndefined()
  234. face.load()
  235. await Promise.resolve()
  236. await Promise.resolve()
  237. expect(b.blockOf('s1')).toBeUndefined()
  238. b.setRoutable(false)
  239. b.remote.emit('llm/adapters-updated', [])
  240. await Promise.resolve()
  241. await Promise.resolve()
  242. expect(b.blockOf('s1')?.reason).toBe(zh['blocked.composer'])
  243. // Recovering clears it without a reload of the surface.
  244. b.setRoutable(true)
  245. b.remote.emit('settings/document-updated', ['llm-deepseek', 1])
  246. await Promise.resolve()
  247. await Promise.resolve()
  248. expect(b.blockOf('s1')).toBeUndefined()
  249. })
  250. it('never blocks on catalog membership alone', async () => {
  251. const b = await bench()
  252. b.mint('s1')
  253. const face = b.seat().inject!(sid('s1'))
  254. // A model the route serves but no longer advertises: the seat prompts for
  255. // a selection, the composer stays usable. Blocking here would break a
  256. // supported configuration (a narrowed `models` list over a live route).
  257. b.setHostCurrent({ provider: 'deepseek-official', model: 'unlisted' })
  258. face.load()
  259. await Promise.resolve()
  260. await Promise.resolve()
  261. const snapshot = face.directory.getSnapshot()
  262. expect(snapshot.groups.flatMap(group => group.models.map(model => model.id))).not.toContain('unlisted')
  263. expect(b.blockOf('s1')).toBeUndefined()
  264. })
  265. it('clears its block when the session scope goes', async () => {
  266. const b = await bench()
  267. const scope = b.mint('s1')
  268. b.setRoutable(false)
  269. const face = b.seat().inject!(sid('s1'))
  270. face.load()
  271. await Promise.resolve()
  272. await Promise.resolve()
  273. expect(b.blockOf('s1')).toBeDefined()
  274. await scope.fiber.dispose()
  275. expect(b.blockOf('s1')).toBeUndefined()
  276. })
  277. it('an unknown session fails loud at the seat inject', async () => {
  278. const b = await bench()
  279. expect(() => b.seat().inject!(sid('ghost'))).toThrow(/resolved no scope/)
  280. })
  281. it('withholds both model entries from addressed subagent sessions without Agent-bound RPCs', async () => {
  282. const b = await bench()
  283. b.mint('child')
  284. b.address(sid('child'))
  285. expect(b.contribution().available(projection('child'))).toBe(false)
  286. await expect(b.contribution().ui.options(
  287. projection('child'),
  288. new AbortController().signal,
  289. )).rejects.toThrow(/unavailable for addressed subagent/)
  290. const face = b.seat().inject!(sid('child'))
  291. expect(face.available).toBe(false)
  292. face.load()
  293. await expect(face.select({ provider: 'deepseek', model: 'deepseek-v4-pro' })).resolves.toBe(false)
  294. await expect(b.ctx.modelDirectories.directoryFor(sid('child')).load())
  295. .rejects.toThrow(/unavailable for addressed subagent/)
  296. await expect(b.ctx.modelDirectories.directoryFor(sid('child')).select({
  297. provider: 'deepseek',
  298. model: 'deepseek-v4-pro',
  299. })).rejects.toThrow(/unavailable for addressed subagent/)
  300. b.ctx.emit('connection/reset')
  301. await Promise.resolve()
  302. expect(b.calls).toEqual({ models: 0, select: 0 })
  303. })
  304. })