browser-plugin.client.spec.ts 15 KB

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