browser-plugin.spec.ts 15 KB

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