browser-plugin.spec.ts 12 KB

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