browser-plugin.client.spec.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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-client-runtime/client'
  14. import type { SessionId } from '@deepseek-ai/dsh-client-runtime/client'
  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-remotes/client'
  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. ctx.provide('connection', { api: { sessions: {
  59. models: () => {
  60. calls.models += 1
  61. return Promise.resolve({
  62. result: { ok: true as const, value: { current, routable, groups: GROUPS, failures: [] } },
  63. })
  64. },
  65. selectModel: (payload: { provider: string; model: string; reasoningEffort?: string }) => {
  66. calls.select += 1
  67. current = {
  68. provider: payload.provider,
  69. model: payload.model,
  70. ...payload.reasoningEffort === undefined
  71. ? {}
  72. : { reasoningEffort: payload.reasoningEffort },
  73. }
  74. return Promise.resolve({ result: { ok: true as const, value: { selected: current } } })
  75. },
  76. } } })
  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. new TestRemote(ctx)
  119. const fiber = ctx.plugin({ inject: [...inject], apply })
  120. await fiber.await()
  121. await ctx.plugin(function probe() {}).await()
  122. const mint = (key: string) => {
  123. const handle = createScope(ctx, sid(key))
  124. scopes.set(sid(key), handle.ctx)
  125. return handle
  126. }
  127. return {
  128. ctx, fiber, mint, calls,
  129. contribution: () => contribution!,
  130. seat: () => seats.get('conversation.input.model')!,
  131. hostCurrent: () => current,
  132. setHostCurrent: (selection: ModelSelection) => { current = selection },
  133. address: (id: SessionId) => { addressed.add(id) },
  134. setRoutable: (next: boolean) => { routable = next },
  135. blockOf: (key: string) => blocks.get(sid(key)),
  136. }
  137. }
  138. const projection = (id: string) => ({ sessionId: sid(id) })
  139. describe('ui-model-selection dual entry', () => {
  140. it('registers the /model contribution and the composer model seat', async () => {
  141. const b = await bench()
  142. expect(b.contribution().name).toBe('model')
  143. expect(b.contribution().ui.kind).toBe('popupSelect')
  144. expect(b.seat().inject).toBeTypeOf('function')
  145. // Copy rides the standard locale seat.
  146. expect(b.seat().locale).toBe('model')
  147. })
  148. it('popup options mark the host current active with the provider group in the detail', async () => {
  149. const b = await bench()
  150. b.mint('s1')
  151. const options = await b.contribution().ui.options(projection('s1'), new AbortController().signal)
  152. expect(options.map((o: SelectOption) => o.label)).toEqual(['DeepSeek-V4-Flash', 'DeepSeek-V4-Pro'])
  153. expect(options[0]).toMatchObject({ active: true, detail: 'DeepSeek' })
  154. expect(options[1]?.active).toBeUndefined()
  155. })
  156. it('a seat selection is the current the popup marks active next — one shared state', async () => {
  157. const b = await bench()
  158. b.mint('s1')
  159. const seatFace = b.seat().inject!(sid('s1'))
  160. // Switch through the SEAT entry.
  161. expect(await seatFace.select({
  162. provider: 'deepseek-official',
  163. model: 'deepseek-v4-pro',
  164. reasoningEffort: 'max',
  165. })).toBe(true)
  166. expect(b.hostCurrent()).toEqual({
  167. provider: 'deepseek-official',
  168. model: 'deepseek-v4-pro',
  169. reasoningEffort: 'max',
  170. })
  171. expect(seatFace.directory.getSnapshot().current).toEqual({
  172. provider: 'deepseek-official',
  173. model: 'deepseek-v4-pro',
  174. reasoningEffort: 'max',
  175. })
  176. // The POPUP's next options pass reflects it without a seat-side reload.
  177. const options = await b.contribution().ui.options(projection('s1'), new AbortController().signal)
  178. expect(options.find((o: SelectOption) => o.label === 'DeepSeek-V4-Pro')).toMatchObject({ active: true })
  179. })
  180. it('a popup selection lands on the seat store — the reverse direction of the same state', async () => {
  181. const b = await bench()
  182. b.mint('s1')
  183. const seatFace = b.seat().inject!(sid('s1'))
  184. const options = await b.contribution().ui.options(projection('s1'), new AbortController().signal)
  185. const pro = options.find((o: SelectOption) => o.label === 'DeepSeek-V4-Pro')!
  186. await b.contribution().ui.onSelect(pro, projection('s1'))
  187. expect(seatFace.directory.getSnapshot().current).toEqual({
  188. provider: 'deepseek-official',
  189. model: 'deepseek-v4-pro',
  190. reasoningEffort: 'high',
  191. })
  192. })
  193. it('both entries share one directory instance per session, isolated across sessions', async () => {
  194. const b = await bench()
  195. b.mint('a')
  196. b.mint('b')
  197. const faceA = b.seat().inject!(sid('a'))
  198. const faceA2 = b.seat().inject!(sid('a'))
  199. const faceB = b.seat().inject!(sid('b'))
  200. expect(faceA.directory).toBe(faceA2.directory)
  201. expect(faceA.directory).not.toBe(faceB.directory)
  202. // The service face resolves the same instance the seat inject handed out.
  203. expect(b.ctx.modelDirectories.directoryFor(sid('a')).store).toBe(faceA.directory)
  204. })
  205. it('drops an unconsumed local selection and restores the Host target after reconnect', async () => {
  206. const b = await bench()
  207. b.mint('s1')
  208. const face = b.seat().inject!(sid('s1'))
  209. await face.select({ provider: 'deepseek-official', model: 'deepseek-v4-pro' })
  210. b.setHostCurrent({ provider: 'deepseek-official', model: 'deepseek-v4-flash' })
  211. b.ctx.emit('connection/reset')
  212. expect(face.directory.getSnapshot()).toMatchObject({ current: null, status: 'loading' })
  213. await Promise.resolve()
  214. expect(face.directory.getSnapshot()).toMatchObject({
  215. current: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  216. status: 'ready',
  217. })
  218. })
  219. it('scope disposal drops the directory; a reborn scope gets a fresh one', async () => {
  220. const b = await bench()
  221. const first = b.mint('s1')
  222. const face1 = b.seat().inject!(sid('s1'))
  223. await first.fiber.dispose()
  224. b.mint('s1')
  225. const face2 = b.seat().inject!(sid('s1'))
  226. expect(face2.directory).not.toBe(face1.directory)
  227. })
  228. it('blocks the composer only once the Host reports the route unservable', async () => {
  229. const b = await bench()
  230. b.mint('s1')
  231. const face = b.seat().inject!(sid('s1'))
  232. // Before the first load nothing is known. `null` is not `false`: a slow
  233. // or unreachable Host must never lock a working composer.
  234. expect(b.blockOf('s1')).toBeUndefined()
  235. face.load()
  236. await Promise.resolve()
  237. await Promise.resolve()
  238. expect(b.blockOf('s1')).toBeUndefined()
  239. b.setRoutable(false)
  240. b.ctx.remote.$dispatch('llm/adapters-updated', [])
  241. await Promise.resolve()
  242. await Promise.resolve()
  243. expect(b.blockOf('s1')?.reason).toBe(zh['blocked.composer'])
  244. // Recovering clears it without a reload of the surface.
  245. b.setRoutable(true)
  246. b.ctx.remote.$dispatch('settings/document-updated', ['llm-deepseek', 1])
  247. await Promise.resolve()
  248. await Promise.resolve()
  249. expect(b.blockOf('s1')).toBeUndefined()
  250. })
  251. it('never blocks on catalog membership alone', async () => {
  252. const b = await bench()
  253. b.mint('s1')
  254. const face = b.seat().inject!(sid('s1'))
  255. // A model the route serves but no longer advertises: the seat prompts for
  256. // a selection, the composer stays usable. Blocking here would break a
  257. // supported configuration (a narrowed `models` list over a live route).
  258. b.setHostCurrent({ provider: 'deepseek-official', model: 'unlisted' })
  259. face.load()
  260. await Promise.resolve()
  261. await Promise.resolve()
  262. const snapshot = face.directory.getSnapshot()
  263. expect(snapshot.groups.flatMap(group => group.models.map(model => model.id))).not.toContain('unlisted')
  264. expect(b.blockOf('s1')).toBeUndefined()
  265. })
  266. it('clears its block when the session scope goes', async () => {
  267. const b = await bench()
  268. const scope = b.mint('s1')
  269. b.setRoutable(false)
  270. const face = b.seat().inject!(sid('s1'))
  271. face.load()
  272. await Promise.resolve()
  273. await Promise.resolve()
  274. expect(b.blockOf('s1')).toBeDefined()
  275. await scope.fiber.dispose()
  276. expect(b.blockOf('s1')).toBeUndefined()
  277. })
  278. it('an unknown session fails loud at the seat inject', async () => {
  279. const b = await bench()
  280. expect(() => b.seat().inject!(sid('ghost'))).toThrow(/resolved no scope/)
  281. })
  282. it('withholds both model entries from addressed subagent sessions without Agent-bound RPCs', async () => {
  283. const b = await bench()
  284. b.mint('child')
  285. b.address(sid('child'))
  286. expect(b.contribution().available(projection('child'))).toBe(false)
  287. await expect(b.contribution().ui.options(
  288. projection('child'),
  289. new AbortController().signal,
  290. )).rejects.toThrow(/unavailable for addressed subagent/)
  291. const face = b.seat().inject!(sid('child'))
  292. expect(face.available).toBe(false)
  293. face.load()
  294. await expect(face.select({ provider: 'deepseek', model: 'deepseek-v4-pro' })).resolves.toBe(false)
  295. await expect(b.ctx.modelDirectories.directoryFor(sid('child')).load())
  296. .rejects.toThrow(/unavailable for addressed subagent/)
  297. await expect(b.ctx.modelDirectories.directoryFor(sid('child')).select({
  298. provider: 'deepseek',
  299. model: 'deepseek-v4-pro',
  300. })).rejects.toThrow(/unavailable for addressed subagent/)
  301. b.ctx.emit('connection/reset')
  302. await Promise.resolve()
  303. expect(b.calls).toEqual({ models: 0, select: 0 })
  304. })
  305. })