browser-plugin.spec.ts 16 KB

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