browser-plugin.spec.ts 12 KB

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