browser-plugin.spec.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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: { 'conversation.chat.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. getSnapshot: () => ({ active: 'zh', locales: ['zh', 'en'], revision: 0 }),
  54. })
  55. return capture
  56. }
  57. /** Boot the plugin over fake slash/connection faces; returns the captured source and its ctx. */
  58. async function bench(list: ListFn, addressed?: SessionId, invoke?: InvokeFn) {
  59. const ctx = new Context()
  60. let captured: SlashSource | undefined
  61. ctx.provide('slash', { registerSource: (src: SlashSource) => { captured = src; return () => {} } })
  62. const defaultInvoke: InvokeFn = () => Promise.resolve({ result: { ok: true as const, value: { accepted: true as const } } })
  63. ctx.provide('connection', { api: { skills: { list, invoke: invoke ?? defaultInvoke } } })
  64. ctx.provide('sessions', {
  65. subagentAddress: (id: SessionId) => id === addressed
  66. ? { parentSessionId: sid('parent'), childSessionId: id, mode: 'continuable' as const }
  67. : undefined,
  68. })
  69. providePresentation(ctx)
  70. await ctx.plugin({ inject: [...inject], apply }).await()
  71. return { ctx, source: captured! }
  72. }
  73. const CATALOG: SkillRow[] = [
  74. { name: 'commit-helper', description: 'commit flow', modelInvocable: true },
  75. { name: 'code-review', description: 'review flow', whenToUse: 'reviews', modelInvocable: true },
  76. { name: 'deploy', description: 'deploy flow', modelInvocable: true },
  77. ]
  78. const listOk = (skills: SkillRow[]): ListFn => () => Promise.resolve({ result: { ok: true as const, value: { skills } } })
  79. /** Counting fake: records payloads, resolves the shared catalog. */
  80. function countingList(skills: SkillRow[] = CATALOG) {
  81. const payloads: object[] = []
  82. const list: ListFn = (payload) => {
  83. payloads.push(payload)
  84. return listOk(skills)(payload)
  85. }
  86. return { list, payloads }
  87. }
  88. const sid = (id: string) => id as SessionId
  89. const proj = (id: string): ClientSessionContext => ({ sessionId: sid(id) })
  90. const req = (query: string, signal?: AbortSignal) =>
  91. ({ query, position: 'leading' as const, signal: signal ?? new AbortController().signal })
  92. describe('apply', () => {
  93. it('declares the services it binds', () => {
  94. expect(inject).toEqual(['slash', 'connection', 'sessions', 'slots', 'locale'])
  95. })
  96. it('registers the dedicated skill row and its locale dictionaries', async () => {
  97. const ctx = new Context()
  98. ctx.provide('slash', { registerSource: () => () => {} })
  99. ctx.provide('connection', { api: { skills: { list: listOk(CATALOG) } } })
  100. ctx.provide('sessions', { subagentAddress: () => undefined })
  101. const presentation = providePresentation(ctx)
  102. await ctx.plugin({ inject: [...inject], apply }).await()
  103. const entry = presentation.slots.entries('conversation.chat.toolview')[0]
  104. expect(entry?.options).toMatchObject({ key: 'skill' })
  105. expect(entry?.locale).toBe('skill')
  106. expect(entry?.component).toBe(SkillToolRow)
  107. expect(presentation.dictionaries).toEqual([{
  108. namespace: 'skill', dictionaries: {
  109. zh: {
  110. 'row.running': '正在加载 skill',
  111. 'row.failed': 'skill 加载失败',
  112. 'row.stopped': 'skill 加载已中止',
  113. 'row.instructions': '说明',
  114. 'menu.userOnly': '仅用户',
  115. },
  116. en: {
  117. 'row.running': 'Loading skill',
  118. 'row.failed': 'Skill load failed',
  119. 'row.stopped': 'Skill load stopped',
  120. 'row.instructions': 'Instructions',
  121. 'menu.userOnly': 'user-only',
  122. },
  123. },
  124. }])
  125. })
  126. it('registers the "/" skill source; disposal frees the name (HMR safety)', async () => {
  127. const ctx = new Context()
  128. // SlashService itself injects 'sessions'; the stub unblocks its fiber.
  129. ctx.provide('sessions', {})
  130. await ctx.plugin(SlashService).await()
  131. ctx.provide('connection', { api: { skills: { list: listOk(CATALOG) } } })
  132. const presentation = providePresentation(ctx)
  133. const fiber = ctx.plugin({ inject: [...inject], apply })
  134. await fiber.await()
  135. const slash = ctx.get('slash') as SlashService
  136. const rival = {
  137. trigger: '/' as const,
  138. name: 'skill',
  139. candidates: () => Promise.resolve([]),
  140. onPick: () => undefined,
  141. }
  142. // Live registration holds the (trigger, name) seat…
  143. expect(() => slash.registerSource(rival)).toThrow(/already registered/)
  144. // …and fiber teardown releases it.
  145. await fiber.dispose()
  146. expect(() => slash.registerSource(rival)).not.toThrow()
  147. expect(presentation.slots.entries('conversation.chat.toolview')).toHaveLength(0)
  148. expect(presentation.localeDisposed).toBe(true)
  149. })
  150. })
  151. describe('candidates: sessionId addressing', () => {
  152. it('lists via {sessionId} and filters by startsWith(query)', async () => {
  153. const { list, payloads } = countingList()
  154. const { source } = await bench(list)
  155. const items = await source.candidates(proj('s1'), req('co'))
  156. // Exact payload: session address only — no agent or transport vocabulary.
  157. expect(payloads).toEqual([{ sessionId: 's1' }])
  158. expect(items).toEqual([
  159. { name: 'commit-helper', description: 'commit flow' },
  160. { name: 'code-review', description: 'review flow' },
  161. ])
  162. })
  163. it('rejects on a failed result (the slash shell owns the menu-side fold)', async () => {
  164. const { source } = await bench(() => Promise.resolve({
  165. result: { ok: false, error: { code: 'internal', message: 'boom', details: {} } },
  166. }))
  167. await expect(source.candidates(proj('s1'), req('co')))
  168. .rejects.toThrow('skill.list failed: internal: boom')
  169. })
  170. it('does not fetch Agent-bound skills for an addressed child', async () => {
  171. const { list, payloads } = countingList()
  172. const { source } = await bench(list, sid('child'))
  173. await expect(source.candidates(proj('child'), req(''))).resolves.toEqual([])
  174. source.warm!(proj('child'))
  175. expect(payloads).toEqual([])
  176. })
  177. })
  178. describe('catalog cache', () => {
  179. it('re-polls on the same session filter locally: one RPC across keystrokes', async () => {
  180. const { list, payloads } = countingList()
  181. const { source } = await bench(list)
  182. await source.candidates(proj('s1'), req(''))
  183. const second = await source.candidates(proj('s1'), req('co'))
  184. expect(payloads).toHaveLength(1)
  185. expect(second).toEqual([
  186. { name: 'commit-helper', description: 'commit flow' },
  187. { name: 'code-review', description: 'review flow' },
  188. ])
  189. // A different session is its own key — one more RPC, not two.
  190. await source.candidates(proj('s2'), req(''))
  191. expect(payloads).toEqual([{ sessionId: 's1' }, { sessionId: 's2' }])
  192. })
  193. it('single-flight: concurrent candidates on one cold key share one RPC', async () => {
  194. const { list, payloads } = countingList()
  195. const { source } = await bench(list)
  196. const [a, b] = await Promise.all([
  197. source.candidates(proj('s1'), req('dep')),
  198. source.candidates(proj('s1'), req('co')),
  199. ])
  200. expect(payloads).toHaveLength(1)
  201. expect(a).toEqual([{ name: 'deploy', description: 'deploy flow' }])
  202. expect(b).toHaveLength(2)
  203. })
  204. it('an aborted caller yields empty but leaves the shared fetch warm', async () => {
  205. const { list, payloads } = countingList()
  206. const { source } = await bench(list)
  207. const aborted = new AbortController()
  208. aborted.abort()
  209. await expect(source.candidates(proj('s1'), req('co', aborted.signal))).resolves.toEqual([])
  210. // The fetch settled into the cache: the next caller pays zero RPC.
  211. await expect(source.candidates(proj('s1'), req('co'))).resolves.toHaveLength(2)
  212. expect(payloads).toHaveLength(1)
  213. })
  214. it('a failed fetch does not poison the key: the next caller retries', async () => {
  215. let fail = true
  216. const payloads: object[] = []
  217. const { source } = await bench((payload) => {
  218. payloads.push(payload)
  219. return fail
  220. ? Promise.resolve({ result: { ok: false as const, error: { code: 'internal', message: 'boom', details: {} } } })
  221. : listOk(CATALOG)(payload)
  222. })
  223. await expect(source.candidates(proj('s1'), req(''))).rejects.toThrow('boom')
  224. fail = false
  225. await expect(source.candidates(proj('s1'), req(''))).resolves.toHaveLength(3)
  226. expect(payloads).toHaveLength(2)
  227. })
  228. it('the scope-birth warm prewarms the session key fire-and-forget', async () => {
  229. const { list, payloads } = countingList()
  230. const { source } = await bench(list)
  231. source.warm!(proj('s1'))
  232. await vi.waitFor(() => { expect(payloads).toHaveLength(1) })
  233. expect(payloads[0]).toEqual({ sessionId: 's1' })
  234. // The prewarmed key serves candidates with zero further RPC; other
  235. // sessions' keys stay untouched.
  236. await expect(source.candidates(proj('s1'), req(''))).resolves.toHaveLength(3)
  237. expect(payloads).toHaveLength(1)
  238. await source.candidates(proj('s2'), req(''))
  239. expect(payloads).toHaveLength(2)
  240. })
  241. it('connection/reset clears every cached session', async () => {
  242. const { list, payloads } = countingList()
  243. const { ctx, source } = await bench(list)
  244. await source.candidates(proj('s1'), req(''))
  245. await source.candidates(proj('s2'), req(''))
  246. expect(payloads).toHaveLength(2)
  247. ctx.emit('connection/reset')
  248. await source.candidates(proj('s1'), req(''))
  249. await source.candidates(proj('s2'), req(''))
  250. expect(payloads).toHaveLength(4)
  251. })
  252. })
  253. describe('lexicon', () => {
  254. it('is undefined before the session catalog settles and serves names after', async () => {
  255. let release: (() => void) | undefined
  256. const gate = new Promise<void>((resolve) => { release = resolve })
  257. const { source } = await bench(async (payload) => {
  258. await gate
  259. return listOk(CATALOG)(payload)
  260. })
  261. // Cold: nothing cached for the session.
  262. expect(source.lexicon!(proj('s1'))).toBeUndefined()
  263. const pending = source.candidates(proj('s1'), req(''))
  264. // In flight: still no synchronous snapshot.
  265. expect(source.lexicon!(proj('s1'))).toBeUndefined()
  266. release!()
  267. await pending
  268. expect(source.lexicon!(proj('s1'))).toEqual(['commit-helper', 'code-review', 'deploy'])
  269. // Another session's key is independent — cold until its own fetch.
  270. expect(source.lexicon!(proj('s2'))).toBeUndefined()
  271. })
  272. it('subscribeLexicon notifies on catalog settle and on invalidation, per session', async () => {
  273. const { list } = countingList()
  274. const { ctx, source } = await bench(list)
  275. const s1 = vi.fn()
  276. const s2 = vi.fn()
  277. source.subscribeLexicon!(proj('s1'), s1)
  278. source.subscribeLexicon!(proj('s2'), s2)
  279. await source.candidates(proj('s1'), req(''))
  280. expect(s1).toHaveBeenCalledTimes(1)
  281. expect(s2).not.toHaveBeenCalled()
  282. // Reset invalidates every cached session: each key notifies its own listeners.
  283. await source.candidates(proj('s2'), req(''))
  284. ctx.emit('connection/reset')
  285. expect(s1).toHaveBeenCalledTimes(2)
  286. expect(s2).toHaveBeenCalledTimes(2)
  287. })
  288. it('an unsubscribed lexicon listener stops receiving notifications', async () => {
  289. const { list } = countingList()
  290. const { source } = await bench(list)
  291. const listener = vi.fn()
  292. const off = source.subscribeLexicon!(proj('s1'), listener)
  293. off()
  294. await source.candidates(proj('s1'), req(''))
  295. expect(listener).not.toHaveBeenCalled()
  296. })
  297. })
  298. describe('pick claims into skill.invoke', () => {
  299. it('onPick returns an args-tolerant claim whose submit invokes the skill', async () => {
  300. const invoke = vi.fn(() => Promise.resolve({ result: { ok: true as const, value: { accepted: true as const } } }))
  301. const { source } = await bench(listOk(CATALOG), undefined, invoke)
  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. if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected a claim outcome')
  310. expect(outcome.claim.token).toBe('/commit-helper ')
  311. await expect(outcome.claim.submit('check the fixture', {} as never)).resolves.toEqual({ kind: 'success' })
  312. expect(invoke).toHaveBeenCalledWith({ sessionId: sid('s1'), name: 'commit-helper', text: 'check the fixture' })
  313. })
  314. it('submit omits blank args and folds an RPC refusal into an error outcome', async () => {
  315. const invoke = vi.fn(() => Promise.resolve({
  316. result: { ok: false as const, error: { code: 'skill-not-invocable', message: 'nope', details: { name: 'deploy' } } },
  317. }))
  318. const { source } = await bench(listOk(CATALOG), undefined, invoke)
  319. const outcome = source.onPick({
  320. candidate: { name: 'deploy', description: 'deploy flow' },
  321. session: proj('s1'),
  322. position: 'leading',
  323. via: 'menu',
  324. span: { start: 0, end: 4, draftRev: 7 },
  325. })
  326. if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected a claim outcome')
  327. await expect(outcome.claim.submit(' ', {} as never))
  328. .resolves.toEqual({ kind: 'error', text: 'skill-not-invocable: nope' })
  329. expect(invoke).toHaveBeenCalledWith({ sessionId: sid('s1'), name: 'deploy' })
  330. })
  331. it('drops the legacy reference codec (decision 21 removal cut)', async () => {
  332. const { source } = await bench(listOk(CATALOG))
  333. expect(source.codec).toBeUndefined()
  334. })
  335. })
  336. describe('adjudication', () => {
  337. it('claims an entered /name line, args-tolerant, once the catalog knows the name', async () => {
  338. const invoke = vi.fn(() => Promise.resolve({ result: { ok: true as const, value: { accepted: true as const } } }))
  339. const { source } = await bench(listOk(CATALOG), undefined, invoke)
  340. const outcome = await source.matchEnter!(proj('s1'), '/deploy run the smoke suite', new AbortController().signal)
  341. if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected a claim outcome')
  342. expect(outcome.claim.token).toBe('/deploy ')
  343. await outcome.claim.submit('run the smoke suite', {} as never)
  344. expect(invoke).toHaveBeenCalledWith({ sessionId: sid('s1'), name: 'deploy', text: 'run the smoke suite' })
  345. })
  346. it('answers undefined for unknown names, non-slash lines, and bare "/"', async () => {
  347. const { source } = await bench(listOk(CATALOG))
  348. const signal = new AbortController().signal
  349. await expect(source.matchEnter!(proj('s1'), '/unlisted do it', signal)).resolves.toBeUndefined()
  350. await expect(source.matchEnter!(proj('s1'), 'plain prose', signal)).resolves.toBeUndefined()
  351. await expect(source.matchEnter!(proj('s1'), '/', signal)).resolves.toBeUndefined()
  352. })
  353. it('never claims on space (menu and enter own the skill flows)', async () => {
  354. const { source } = await bench(listOk(CATALOG))
  355. expect(typeof source.matchSpace).toBe('undefined')
  356. })
  357. })
  358. describe('user-only marking', () => {
  359. it('prefixes the description of candidates the model cannot invoke', async () => {
  360. const rows: SkillRow[] = [
  361. { name: 'shared-skill', description: 'both surfaces', modelInvocable: true },
  362. { name: 'user-only-skill', description: 'user surface only', modelInvocable: false },
  363. ]
  364. const { source } = await bench(listOk(rows))
  365. const candidates = await source.candidates(proj('s1'), req(''))
  366. expect(candidates).toEqual([
  367. { name: 'shared-skill', description: 'both surfaces' },
  368. { name: 'user-only-skill', description: '仅用户 · user surface only' },
  369. ])
  370. })
  371. })