browser-plugin.spec.ts 16 KB

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