browser-plugin.spec.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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) {
  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. await ctx.plugin({ inject: [...inject], apply }).await()
  31. return { ctx, source: captured! }
  32. }
  33. const CATALOG: SkillRow[] = [
  34. { name: 'commit-helper', description: 'commit flow' },
  35. { name: 'code-review', description: 'review flow', whenToUse: 'reviews' },
  36. { name: 'deploy', description: 'deploy flow' },
  37. ]
  38. const listOk = (skills: SkillRow[]): ListFn => () => Promise.resolve({ result: { ok: true as const, value: { skills } } })
  39. /** Counting fake: records payloads, resolves the shared catalog. */
  40. function countingList(skills: SkillRow[] = CATALOG) {
  41. const payloads: object[] = []
  42. const list: ListFn = (payload) => {
  43. payloads.push(payload)
  44. return listOk(skills)(payload)
  45. }
  46. return { list, payloads }
  47. }
  48. const sid = (id: string) => id as SessionId
  49. const proj = (id: string): ClientSessionContext => ({ sessionId: sid(id) })
  50. const req = (query: string, signal?: AbortSignal) =>
  51. ({ query, position: 'leading' as const, signal: signal ?? new AbortController().signal })
  52. describe('apply', () => {
  53. it('declares the services it binds', () => {
  54. expect(inject).toEqual(['slash', 'connection'])
  55. })
  56. it('registers the "/" skill source; disposal frees the name (HMR safety)', async () => {
  57. const ctx = new Context()
  58. // SlashService itself injects 'sessions'; the stub unblocks its fiber.
  59. ctx.provide('sessions', {})
  60. await ctx.plugin(SlashService).await()
  61. ctx.provide('connection', { api: { skills: { list: listOk(CATALOG) } } })
  62. const fiber = ctx.plugin({ inject: [...inject], apply })
  63. await fiber.await()
  64. const slash = ctx.get('slash') as SlashService
  65. const rival = {
  66. trigger: '/' as const,
  67. name: 'skill',
  68. candidates: () => Promise.resolve([]),
  69. onPick: () => undefined,
  70. }
  71. // Live registration holds the (trigger, name) seat…
  72. expect(() => slash.registerSource(rival)).toThrow(/already registered/)
  73. // …and fiber teardown releases it.
  74. await fiber.dispose()
  75. expect(() => slash.registerSource(rival)).not.toThrow()
  76. })
  77. })
  78. describe('candidates: sessionId addressing', () => {
  79. it('lists via {sessionId} and filters by startsWith(query)', async () => {
  80. const { list, payloads } = countingList()
  81. const { source } = await bench(list)
  82. const items = await source.candidates(proj('s1'), req('co'))
  83. // Exact payload: session address only — no agent or transport vocabulary.
  84. expect(payloads).toEqual([{ sessionId: 's1' }])
  85. expect(items).toEqual([
  86. { name: 'commit-helper', description: 'commit flow' },
  87. { name: 'code-review', description: 'review flow' },
  88. ])
  89. })
  90. it('rejects on a failed result (the slash shell owns the menu-side fold)', async () => {
  91. const { source } = await bench(() => Promise.resolve({
  92. result: { ok: false, error: { code: 'internal', message: 'boom', details: {} } },
  93. }))
  94. await expect(source.candidates(proj('s1'), req('co')))
  95. .rejects.toThrow('skill.list failed: internal: boom')
  96. })
  97. })
  98. describe('catalog cache', () => {
  99. it('re-polls on the same session filter locally: one RPC across keystrokes', async () => {
  100. const { list, payloads } = countingList()
  101. const { source } = await bench(list)
  102. await source.candidates(proj('s1'), req(''))
  103. const second = await source.candidates(proj('s1'), req('co'))
  104. expect(payloads).toHaveLength(1)
  105. expect(second).toEqual([
  106. { name: 'commit-helper', description: 'commit flow' },
  107. { name: 'code-review', description: 'review flow' },
  108. ])
  109. // A different session is its own key — one more RPC, not two.
  110. await source.candidates(proj('s2'), req(''))
  111. expect(payloads).toEqual([{ sessionId: 's1' }, { sessionId: 's2' }])
  112. })
  113. it('single-flight: concurrent candidates on one cold key share one RPC', async () => {
  114. const { list, payloads } = countingList()
  115. const { source } = await bench(list)
  116. const [a, b] = await Promise.all([
  117. source.candidates(proj('s1'), req('dep')),
  118. source.candidates(proj('s1'), req('co')),
  119. ])
  120. expect(payloads).toHaveLength(1)
  121. expect(a).toEqual([{ name: 'deploy', description: 'deploy flow' }])
  122. expect(b).toHaveLength(2)
  123. })
  124. it('an aborted caller yields empty but leaves the shared fetch warm', async () => {
  125. const { list, payloads } = countingList()
  126. const { source } = await bench(list)
  127. const aborted = new AbortController()
  128. aborted.abort()
  129. await expect(source.candidates(proj('s1'), req('co', aborted.signal))).resolves.toEqual([])
  130. // The fetch settled into the cache: the next caller pays zero RPC.
  131. await expect(source.candidates(proj('s1'), req('co'))).resolves.toHaveLength(2)
  132. expect(payloads).toHaveLength(1)
  133. })
  134. it('a failed fetch does not poison the key: the next caller retries', async () => {
  135. let fail = true
  136. const payloads: object[] = []
  137. const { source } = await bench((payload) => {
  138. payloads.push(payload)
  139. return fail
  140. ? Promise.resolve({ result: { ok: false as const, error: { code: 'internal', message: 'boom', details: {} } } })
  141. : listOk(CATALOG)(payload)
  142. })
  143. await expect(source.candidates(proj('s1'), req(''))).rejects.toThrow('boom')
  144. fail = false
  145. await expect(source.candidates(proj('s1'), req(''))).resolves.toHaveLength(3)
  146. expect(payloads).toHaveLength(2)
  147. })
  148. it('the scope-birth warm prewarms the session key fire-and-forget', async () => {
  149. const { list, payloads } = countingList()
  150. const { source } = await bench(list)
  151. source.warm!(proj('s1'))
  152. await vi.waitFor(() => { expect(payloads).toHaveLength(1) })
  153. expect(payloads[0]).toEqual({ sessionId: 's1' })
  154. // The prewarmed key serves candidates with zero further RPC; other
  155. // sessions' keys stay untouched.
  156. await expect(source.candidates(proj('s1'), req(''))).resolves.toHaveLength(3)
  157. expect(payloads).toHaveLength(1)
  158. await source.candidates(proj('s2'), req(''))
  159. expect(payloads).toHaveLength(2)
  160. })
  161. it('connection/reset clears every cached session', async () => {
  162. const { list, payloads } = countingList()
  163. const { ctx, source } = await bench(list)
  164. await source.candidates(proj('s1'), req(''))
  165. await source.candidates(proj('s2'), req(''))
  166. expect(payloads).toHaveLength(2)
  167. ctx.emit('connection/reset')
  168. await source.candidates(proj('s1'), req(''))
  169. await source.candidates(proj('s2'), req(''))
  170. expect(payloads).toHaveLength(4)
  171. })
  172. })
  173. describe('lexicon', () => {
  174. it('is undefined before the session catalog settles and serves names after', async () => {
  175. let release: (() => void) | undefined
  176. const gate = new Promise<void>((resolve) => { release = resolve })
  177. const { source } = await bench(async (payload) => {
  178. await gate
  179. return listOk(CATALOG)(payload)
  180. })
  181. // Cold: nothing cached for the session.
  182. expect(source.lexicon!(proj('s1'))).toBeUndefined()
  183. const pending = source.candidates(proj('s1'), req(''))
  184. // In flight: still no synchronous snapshot.
  185. expect(source.lexicon!(proj('s1'))).toBeUndefined()
  186. release!()
  187. await pending
  188. expect(source.lexicon!(proj('s1'))).toEqual(['commit-helper', 'code-review', 'deploy'])
  189. // Another session's key is independent — cold until its own fetch.
  190. expect(source.lexicon!(proj('s2'))).toBeUndefined()
  191. })
  192. })
  193. describe('pick and codec', () => {
  194. it('onPick returns the literal /name text with a closing space (decision 21)', async () => {
  195. const { source } = await bench(listOk(CATALOG))
  196. const outcome = source.onPick({
  197. candidate: { name: 'commit-helper', description: 'commit flow' },
  198. session: proj('s1'),
  199. position: 'leading',
  200. via: 'menu',
  201. span: { start: 0, end: 4, draftRev: 7 },
  202. })
  203. expect(outcome).toEqual({ text: '/commit-helper ' })
  204. })
  205. it('codec projects clipboard `/name` and serializes the model form <skill>name</skill>', async () => {
  206. const { source } = await bench(listOk(CATALOG))
  207. expect(source.codec!.clipboardText('deploy')).toBe('/deploy')
  208. await expect(source.codec!.serialize('deploy', new AbortController().signal))
  209. .resolves.toBe('<skill>deploy</skill>')
  210. })
  211. })
  212. describe('adjudication', () => {
  213. it('never participates: no matchSpace/matchEnter hooks on the skill source', async () => {
  214. const { source } = await bench(listOk(CATALOG))
  215. expect(typeof source.matchSpace).toBe('undefined')
  216. expect(typeof source.matchEnter).toBe('undefined')
  217. })
  218. })