browser-plugin.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. /**
  2. * ui-skill browser half: source and keyed toolview registration +
  3. * locale dictionaries + source duplicate-name proof +
  4. * fiber-teardown removal (HMR safety) against the real SlashService, then
  5. * the source behavior contract driven directly on the captured source with
  6. * real ClientSessionContext projections — sessionId addressing, the
  7. * session-keyed catalog cache (single-flight per key, scope-birth warm
  8. * prewarm, connection/reset clear), startsWith filtering, RPC-failure
  9. * rejection, pick → plain-text outcome (decision 21), the synchronous
  10. * lexicon reads over the settled cache, and the reference codec's two
  11. * projections. Direct driving is deliberate: this spec owns only the
  12. * source's own contract.
  13. */
  14. import { Context } from 'cordis'
  15. import { describe, expect, it, vi } from 'vitest'
  16. import type { SessionId } from '@deepseek-ai/dsh-client-runtime/client'
  17. import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client'
  18. import { SlashService } from '@deepseek-ai/dsh-client-ui-slash/client'
  19. import type { ClientSessionContext, SlashSource } from '@deepseek-ai/dsh-client-ui-slash/client'
  20. import { apply, inject } from '../src/client/index.ts'
  21. import { SkillRow as SkillToolRow } from '../src/client/SkillRow.tsx'
  22. type SkillRow = { name: string; description: string; whenToUse?: string }
  23. type ListResult =
  24. | { ok: true; value: { skills: SkillRow[] } }
  25. | { ok: false; error: { code: string; message: string; details: object } }
  26. type ListFn = (payload: object, signal?: AbortSignal) => Promise<{ result: ListResult }>
  27. interface PresentationCapture {
  28. slots: SlotsService
  29. dictionaries: Array<{ namespace: string; dictionaries: unknown }>
  30. localeDisposed: boolean
  31. }
  32. /** Provide the presentation registries and capture the plugin's registrations. */
  33. function providePresentation(ctx: Context): PresentationCapture {
  34. const slots = new SlotsService(ctx)
  35. slots.register({
  36. name: 'root',
  37. children: { 'conversation.chat.toolview': { kind: 'keyed', scope: 'session' } },
  38. } as never, () => null)
  39. const capture: PresentationCapture = {
  40. slots,
  41. dictionaries: [],
  42. localeDisposed: false,
  43. }
  44. ctx.provide('locale', {
  45. register(namespace: string, dictionaries: unknown) {
  46. capture.dictionaries.push({ namespace, dictionaries })
  47. return () => { capture.localeDisposed = true }
  48. },
  49. })
  50. return capture
  51. }
  52. /** Boot the plugin over fake slash/connection faces; returns the captured source and its ctx. */
  53. async function bench(list: ListFn, addressed?: SessionId) {
  54. const ctx = new Context()
  55. let captured: SlashSource | undefined
  56. ctx.provide('slash', { registerSource: (src: SlashSource) => { captured = src; return () => {} } })
  57. ctx.provide('connection', { api: { skills: { list } } })
  58. ctx.provide('sessions', {
  59. subagentAddress: (id: SessionId) => id === addressed
  60. ? { parentSessionId: sid('parent'), childSessionId: id, mode: 'continuable' as const }
  61. : undefined,
  62. })
  63. providePresentation(ctx)
  64. await ctx.plugin({ inject: [...inject], apply }).await()
  65. return { ctx, source: captured! }
  66. }
  67. const CATALOG: SkillRow[] = [
  68. { name: 'commit-helper', description: 'commit flow' },
  69. { name: 'code-review', description: 'review flow', whenToUse: 'reviews' },
  70. { name: 'deploy', description: 'deploy flow' },
  71. ]
  72. const listOk = (skills: SkillRow[]): ListFn => () => Promise.resolve({ result: { ok: true as const, value: { skills } } })
  73. /** Counting fake: records payloads, resolves the shared catalog. */
  74. function countingList(skills: SkillRow[] = CATALOG) {
  75. const payloads: object[] = []
  76. const list: ListFn = (payload) => {
  77. payloads.push(payload)
  78. return listOk(skills)(payload)
  79. }
  80. return { list, payloads }
  81. }
  82. const sid = (id: string) => id as SessionId
  83. const proj = (id: string): ClientSessionContext => ({ sessionId: sid(id) })
  84. const req = (query: string, signal?: AbortSignal) =>
  85. ({ query, position: 'leading' as const, signal: signal ?? new AbortController().signal })
  86. describe('apply', () => {
  87. it('declares the services it binds', () => {
  88. expect(inject).toEqual(['slash', 'connection', 'sessions', 'slots', 'locale'])
  89. })
  90. it('registers the dedicated skill row and its locale dictionaries', async () => {
  91. const ctx = new Context()
  92. ctx.provide('slash', { registerSource: () => () => {} })
  93. ctx.provide('connection', { api: { skills: { list: listOk(CATALOG) } } })
  94. ctx.provide('sessions', { subagentAddress: () => undefined })
  95. const presentation = providePresentation(ctx)
  96. await ctx.plugin({ inject: [...inject], apply }).await()
  97. const entry = presentation.slots.entries('conversation.chat.toolview')[0]
  98. expect(entry?.options).toMatchObject({ key: 'skill' })
  99. expect(entry?.locale).toBe('skill')
  100. expect(entry?.component).toBe(SkillToolRow)
  101. expect(presentation.dictionaries).toEqual([{
  102. namespace: 'skill', dictionaries: {
  103. zh: {
  104. 'row.running': '正在加载 skill',
  105. 'row.failed': 'skill 加载失败',
  106. 'row.stopped': 'skill 加载已中止',
  107. 'row.instructions': '说明',
  108. },
  109. en: {
  110. 'row.running': 'Loading skill',
  111. 'row.failed': 'Skill load failed',
  112. 'row.stopped': 'Skill load stopped',
  113. 'row.instructions': 'Instructions',
  114. },
  115. },
  116. }])
  117. })
  118. it('registers the "/" skill source; disposal frees the name (HMR safety)', async () => {
  119. const ctx = new Context()
  120. // SlashService itself injects 'sessions'; the stub unblocks its fiber.
  121. ctx.provide('sessions', {})
  122. await ctx.plugin(SlashService).await()
  123. ctx.provide('connection', { api: { skills: { list: listOk(CATALOG) } } })
  124. const presentation = providePresentation(ctx)
  125. const fiber = ctx.plugin({ inject: [...inject], apply })
  126. await fiber.await()
  127. const slash = ctx.get('slash') as SlashService
  128. const rival = {
  129. trigger: '/' as const,
  130. name: 'skill',
  131. candidates: () => Promise.resolve([]),
  132. onPick: () => undefined,
  133. }
  134. // Live registration holds the (trigger, name) seat…
  135. expect(() => slash.registerSource(rival)).toThrow(/already registered/)
  136. // …and fiber teardown releases it.
  137. await fiber.dispose()
  138. expect(() => slash.registerSource(rival)).not.toThrow()
  139. expect(presentation.slots.entries('conversation.chat.toolview')).toHaveLength(0)
  140. expect(presentation.localeDisposed).toBe(true)
  141. })
  142. })
  143. describe('candidates: sessionId addressing', () => {
  144. it('lists via {sessionId} and filters by startsWith(query)', async () => {
  145. const { list, payloads } = countingList()
  146. const { source } = await bench(list)
  147. const items = await source.candidates(proj('s1'), req('co'))
  148. // Exact payload: session address only — no agent or transport vocabulary.
  149. expect(payloads).toEqual([{ sessionId: 's1' }])
  150. expect(items).toEqual([
  151. { name: 'commit-helper', description: 'commit flow' },
  152. { name: 'code-review', description: 'review flow' },
  153. ])
  154. })
  155. it('rejects on a failed result (the slash shell owns the menu-side fold)', async () => {
  156. const { source } = await bench(() => Promise.resolve({
  157. result: { ok: false, error: { code: 'internal', message: 'boom', details: {} } },
  158. }))
  159. await expect(source.candidates(proj('s1'), req('co')))
  160. .rejects.toThrow('skill.list failed: internal: boom')
  161. })
  162. it('does not fetch Agent-bound skills for an addressed child', async () => {
  163. const { list, payloads } = countingList()
  164. const { source } = await bench(list, sid('child'))
  165. await expect(source.candidates(proj('child'), req(''))).resolves.toEqual([])
  166. source.warm!(proj('child'))
  167. expect(payloads).toEqual([])
  168. })
  169. })
  170. describe('catalog cache', () => {
  171. it('re-polls on the same session filter locally: one RPC across keystrokes', async () => {
  172. const { list, payloads } = countingList()
  173. const { source } = await bench(list)
  174. await source.candidates(proj('s1'), req(''))
  175. const second = await source.candidates(proj('s1'), req('co'))
  176. expect(payloads).toHaveLength(1)
  177. expect(second).toEqual([
  178. { name: 'commit-helper', description: 'commit flow' },
  179. { name: 'code-review', description: 'review flow' },
  180. ])
  181. // A different session is its own key — one more RPC, not two.
  182. await source.candidates(proj('s2'), req(''))
  183. expect(payloads).toEqual([{ sessionId: 's1' }, { sessionId: 's2' }])
  184. })
  185. it('single-flight: concurrent candidates on one cold key share one RPC', async () => {
  186. const { list, payloads } = countingList()
  187. const { source } = await bench(list)
  188. const [a, b] = await Promise.all([
  189. source.candidates(proj('s1'), req('dep')),
  190. source.candidates(proj('s1'), req('co')),
  191. ])
  192. expect(payloads).toHaveLength(1)
  193. expect(a).toEqual([{ name: 'deploy', description: 'deploy flow' }])
  194. expect(b).toHaveLength(2)
  195. })
  196. it('an aborted caller yields empty but leaves the shared fetch warm', async () => {
  197. const { list, payloads } = countingList()
  198. const { source } = await bench(list)
  199. const aborted = new AbortController()
  200. aborted.abort()
  201. await expect(source.candidates(proj('s1'), req('co', aborted.signal))).resolves.toEqual([])
  202. // The fetch settled into the cache: the next caller pays zero RPC.
  203. await expect(source.candidates(proj('s1'), req('co'))).resolves.toHaveLength(2)
  204. expect(payloads).toHaveLength(1)
  205. })
  206. it('a failed fetch does not poison the key: the next caller retries', async () => {
  207. let fail = true
  208. const payloads: object[] = []
  209. const { source } = await bench((payload) => {
  210. payloads.push(payload)
  211. return fail
  212. ? Promise.resolve({ result: { ok: false as const, error: { code: 'internal', message: 'boom', details: {} } } })
  213. : listOk(CATALOG)(payload)
  214. })
  215. await expect(source.candidates(proj('s1'), req(''))).rejects.toThrow('boom')
  216. fail = false
  217. await expect(source.candidates(proj('s1'), req(''))).resolves.toHaveLength(3)
  218. expect(payloads).toHaveLength(2)
  219. })
  220. it('the scope-birth warm prewarms the session key fire-and-forget', async () => {
  221. const { list, payloads } = countingList()
  222. const { source } = await bench(list)
  223. source.warm!(proj('s1'))
  224. await vi.waitFor(() => { expect(payloads).toHaveLength(1) })
  225. expect(payloads[0]).toEqual({ sessionId: 's1' })
  226. // The prewarmed key serves candidates with zero further RPC; other
  227. // sessions' keys stay untouched.
  228. await expect(source.candidates(proj('s1'), req(''))).resolves.toHaveLength(3)
  229. expect(payloads).toHaveLength(1)
  230. await source.candidates(proj('s2'), req(''))
  231. expect(payloads).toHaveLength(2)
  232. })
  233. it('connection/reset clears every cached session', async () => {
  234. const { list, payloads } = countingList()
  235. const { ctx, source } = await bench(list)
  236. await source.candidates(proj('s1'), req(''))
  237. await source.candidates(proj('s2'), req(''))
  238. expect(payloads).toHaveLength(2)
  239. ctx.emit('connection/reset')
  240. await source.candidates(proj('s1'), req(''))
  241. await source.candidates(proj('s2'), req(''))
  242. expect(payloads).toHaveLength(4)
  243. })
  244. })
  245. describe('lexicon', () => {
  246. it('is undefined before the session catalog settles and serves names after', async () => {
  247. let release: (() => void) | undefined
  248. const gate = new Promise<void>((resolve) => { release = resolve })
  249. const { source } = await bench(async (payload) => {
  250. await gate
  251. return listOk(CATALOG)(payload)
  252. })
  253. // Cold: nothing cached for the session.
  254. expect(source.lexicon!(proj('s1'))).toBeUndefined()
  255. const pending = source.candidates(proj('s1'), req(''))
  256. // In flight: still no synchronous snapshot.
  257. expect(source.lexicon!(proj('s1'))).toBeUndefined()
  258. release!()
  259. await pending
  260. expect(source.lexicon!(proj('s1'))).toEqual(['commit-helper', 'code-review', 'deploy'])
  261. // Another session's key is independent — cold until its own fetch.
  262. expect(source.lexicon!(proj('s2'))).toBeUndefined()
  263. })
  264. it('subscribeLexicon notifies on catalog settle and on invalidation, per session', async () => {
  265. const { list } = countingList()
  266. const { ctx, source } = await bench(list)
  267. const s1 = vi.fn()
  268. const s2 = vi.fn()
  269. source.subscribeLexicon!(proj('s1'), s1)
  270. source.subscribeLexicon!(proj('s2'), s2)
  271. await source.candidates(proj('s1'), req(''))
  272. expect(s1).toHaveBeenCalledTimes(1)
  273. expect(s2).not.toHaveBeenCalled()
  274. // Reset invalidates every cached session: each key notifies its own listeners.
  275. await source.candidates(proj('s2'), req(''))
  276. ctx.emit('connection/reset')
  277. expect(s1).toHaveBeenCalledTimes(2)
  278. expect(s2).toHaveBeenCalledTimes(2)
  279. })
  280. it('an unsubscribed lexicon listener stops receiving notifications', async () => {
  281. const { list } = countingList()
  282. const { source } = await bench(list)
  283. const listener = vi.fn()
  284. const off = source.subscribeLexicon!(proj('s1'), listener)
  285. off()
  286. await source.candidates(proj('s1'), req(''))
  287. expect(listener).not.toHaveBeenCalled()
  288. })
  289. })
  290. describe('pick and codec', () => {
  291. it('onPick returns the literal /name text with a closing space (decision 21)', async () => {
  292. const { source } = await bench(listOk(CATALOG))
  293. const outcome = source.onPick({
  294. candidate: { name: 'commit-helper', description: 'commit flow' },
  295. session: proj('s1'),
  296. position: 'leading',
  297. via: 'menu',
  298. span: { start: 0, end: 4, draftRev: 7 },
  299. })
  300. expect(outcome).toEqual({ text: '/commit-helper ' })
  301. })
  302. it('codec projects clipboard `/name` and serializes the model form <skill>name</skill>', async () => {
  303. const { source } = await bench(listOk(CATALOG))
  304. expect(source.codec!.clipboardText('deploy')).toBe('/deploy')
  305. await expect(source.codec!.serialize('deploy', new AbortController().signal))
  306. .resolves.toBe('<skill>deploy</skill>')
  307. })
  308. })
  309. describe('adjudication', () => {
  310. it('never participates: no matchSpace/matchEnter hooks on the skill source', async () => {
  311. const { source } = await bench(listOk(CATALOG))
  312. expect(typeof source.matchSpace).toBe('undefined')
  313. expect(typeof source.matchEnter).toBe('undefined')
  314. })
  315. })