browser-plugin.spec.ts 12 KB

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