browser-plugin.client.spec.ts 15 KB

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