browser-plugin.client.spec.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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 InputTriggerService, 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-session/types'
  19. import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
  20. import { InputTriggerService } from '@deepseek-ai/dsh-client-ui-input-trigger/client'
  21. import { TestRemote } from '@deepseek-ai/dsh-client-test-runtime'
  22. import type { ClientSessionContext, InputTriggerSource } from '@deepseek-ai/dsh-client-ui-input-trigger/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: SlotRegistry
  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 SlotRegistry(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: InputTriggerSource | undefined
  65. ctx.provide('inputTriggers', { registerSource: (src: InputTriggerSource) => { 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. const remote = new TestRemote(ctx)
  74. providePresentation(ctx)
  75. await ctx.plugin({ inject: [...inject], apply }).await()
  76. return { ctx, source: captured!, remote }
  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(['inputTriggers', '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('inputTriggers', { 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.title': 'Skill',
  117. 'row.running': '正在加载 skill',
  118. 'row.failed': 'skill 加载失败',
  119. 'row.stopped': 'skill 加载已中止',
  120. 'row.instructions': '说明',
  121. 'row.inspect': '查看',
  122. 'menu.userOnly': '仅用户',
  123. },
  124. en: {
  125. 'row.title': 'Skill',
  126. 'row.running': 'Loading skill',
  127. 'row.failed': 'Skill load failed',
  128. 'row.stopped': 'Skill load stopped',
  129. 'row.instructions': 'Instructions',
  130. 'row.inspect': 'Inspect',
  131. 'menu.userOnly': 'user-only',
  132. },
  133. },
  134. }])
  135. })
  136. it('registers the "/" skill source; disposal frees the name (HMR safety)', async () => {
  137. const ctx = new Context()
  138. // InputTriggerService itself injects 'sessions'; the stub unblocks its fiber.
  139. ctx.provide('sessions', {})
  140. await ctx.plugin(InputTriggerService).await()
  141. ctx.provide('connection', { api: { skills: { list: listOk(CATALOG) } } })
  142. new TestRemote(ctx)
  143. const presentation = providePresentation(ctx)
  144. const fiber = ctx.plugin({ inject: [...inject], apply })
  145. await fiber.await()
  146. const inputTriggers = ctx.get('inputTriggers') as InputTriggerService
  147. const rival = {
  148. trigger: '/' as const,
  149. name: 'skill',
  150. candidates: () => Promise.resolve([]),
  151. onPick: () => undefined,
  152. }
  153. // Live registration holds the (trigger, name) seat…
  154. expect(() => inputTriggers.registerSource(rival)).toThrow(/already registered/)
  155. // …and fiber teardown releases it.
  156. await fiber.dispose()
  157. expect(() => inputTriggers.registerSource(rival)).not.toThrow()
  158. expect(presentation.slots.entries('tool.call.toolview')).toHaveLength(0)
  159. expect(presentation.localeDisposed).toBe(true)
  160. })
  161. })
  162. describe('candidates: sessionId addressing', () => {
  163. it('lists via {sessionId} and filters by startsWith(query)', async () => {
  164. const { list, payloads } = countingList()
  165. const { source } = await bench(list)
  166. const items = await source.candidates(proj('s1'), req('co'))
  167. // Exact payload: session address only — no agent or transport vocabulary.
  168. expect(payloads).toEqual([{ sessionId: 's1' }])
  169. expect(items).toEqual([
  170. { name: 'commit-helper', description: 'commit flow' },
  171. { name: 'code-review', description: 'review flow' },
  172. ])
  173. })
  174. it('rejects on a failed result (the slash shell owns the menu-side fold)', async () => {
  175. const { source } = await bench(() => Promise.resolve({
  176. result: { ok: false, error: { code: 'internal', message: 'boom', details: {} } },
  177. }))
  178. await expect(source.candidates(proj('s1'), req('co')))
  179. .rejects.toThrow('skill.list failed: internal: boom')
  180. })
  181. it('does not fetch Agent-bound skills for an addressed child', async () => {
  182. const { list, payloads } = countingList()
  183. const { source } = await bench(list, sid('child'))
  184. await expect(source.candidates(proj('child'), req(''))).resolves.toEqual([])
  185. source.warm!(proj('child'))
  186. expect(payloads).toEqual([])
  187. })
  188. })
  189. describe('catalog cache', () => {
  190. it('re-polls on the same session filter locally: one RPC across keystrokes', async () => {
  191. const { list, payloads } = countingList()
  192. const { source } = await bench(list)
  193. await source.candidates(proj('s1'), req(''))
  194. const second = await source.candidates(proj('s1'), req('co'))
  195. expect(payloads).toHaveLength(1)
  196. expect(second).toEqual([
  197. { name: 'commit-helper', description: 'commit flow' },
  198. { name: 'code-review', description: 'review flow' },
  199. ])
  200. // A different session is its own key — one more RPC, not two.
  201. await source.candidates(proj('s2'), req(''))
  202. expect(payloads).toEqual([{ sessionId: 's1' }, { sessionId: 's2' }])
  203. })
  204. it('single-flight: concurrent candidates on one cold key share one RPC', async () => {
  205. const { list, payloads } = countingList()
  206. const { source } = await bench(list)
  207. const [a, b] = await Promise.all([
  208. source.candidates(proj('s1'), req('dep')),
  209. source.candidates(proj('s1'), req('co')),
  210. ])
  211. expect(payloads).toHaveLength(1)
  212. expect(a).toEqual([{ name: 'deploy', description: 'deploy flow' }])
  213. expect(b).toHaveLength(2)
  214. })
  215. it('an aborted caller yields empty but leaves the shared fetch warm', async () => {
  216. const { list, payloads } = countingList()
  217. const { source } = await bench(list)
  218. const aborted = new AbortController()
  219. aborted.abort()
  220. await expect(source.candidates(proj('s1'), req('co', aborted.signal))).resolves.toEqual([])
  221. // The fetch settled into the cache: the next caller pays zero RPC.
  222. await expect(source.candidates(proj('s1'), req('co'))).resolves.toHaveLength(2)
  223. expect(payloads).toHaveLength(1)
  224. })
  225. it('a failed fetch does not poison the key: the next caller retries', async () => {
  226. let fail = true
  227. const payloads: object[] = []
  228. const { source } = await bench((payload) => {
  229. payloads.push(payload)
  230. return fail
  231. ? Promise.resolve({ result: { ok: false as const, error: { code: 'internal', message: 'boom', details: {} } } })
  232. : listOk(CATALOG)(payload)
  233. })
  234. await expect(source.candidates(proj('s1'), req(''))).rejects.toThrow('boom')
  235. fail = false
  236. await expect(source.candidates(proj('s1'), req(''))).resolves.toHaveLength(3)
  237. expect(payloads).toHaveLength(2)
  238. })
  239. it('the scope-birth warm prewarms the session key fire-and-forget', async () => {
  240. const { list, payloads } = countingList()
  241. const { source } = await bench(list)
  242. source.warm!(proj('s1'))
  243. await vi.waitFor(() => { expect(payloads).toHaveLength(1) })
  244. expect(payloads[0]).toEqual({ sessionId: 's1' })
  245. // The prewarmed key serves candidates with zero further RPC; other
  246. // sessions' keys stay untouched.
  247. await expect(source.candidates(proj('s1'), req(''))).resolves.toHaveLength(3)
  248. expect(payloads).toHaveLength(1)
  249. await source.candidates(proj('s2'), req(''))
  250. expect(payloads).toHaveLength(2)
  251. })
  252. it('agent-preset/selected clears only the recomposed session', async () => {
  253. const { list, payloads } = countingList()
  254. const { source, remote } = await bench(list)
  255. await source.candidates(proj('s1'), req(''))
  256. await source.candidates(proj('s2'), req(''))
  257. expect(payloads).toHaveLength(2)
  258. // The catalog a preset supplies is the preset's; the other session's
  259. // composition did not change, so its cached catalog still holds.
  260. remote.emit('agent-preset/selected', [sid('s1'), 'minimal'])
  261. await source.candidates(proj('s1'), req(''))
  262. await source.candidates(proj('s2'), req(''))
  263. expect(payloads).toHaveLength(3)
  264. expect(payloads[2]).toEqual({ sessionId: 's1' })
  265. })
  266. it('connection/reset clears every cached session', async () => {
  267. const { list, payloads } = countingList()
  268. const { ctx, source } = await bench(list)
  269. await source.candidates(proj('s1'), req(''))
  270. await source.candidates(proj('s2'), req(''))
  271. expect(payloads).toHaveLength(2)
  272. ctx.emit('connection/reset')
  273. await source.candidates(proj('s1'), req(''))
  274. await source.candidates(proj('s2'), req(''))
  275. expect(payloads).toHaveLength(4)
  276. })
  277. })
  278. describe('lexicon', () => {
  279. it('is undefined before the session catalog settles and serves names after', async () => {
  280. let release: (() => void) | undefined
  281. const gate = new Promise<void>((resolve) => { release = resolve })
  282. const { source } = await bench(async (payload) => {
  283. await gate
  284. return listOk(CATALOG)(payload)
  285. })
  286. // Cold: nothing cached for the session.
  287. expect(source.lexicon!(proj('s1'))).toBeUndefined()
  288. const pending = source.candidates(proj('s1'), req(''))
  289. // In flight: still no synchronous snapshot.
  290. expect(source.lexicon!(proj('s1'))).toBeUndefined()
  291. release!()
  292. await pending
  293. expect(source.lexicon!(proj('s1'))).toEqual(['commit-helper', 'code-review', 'deploy'])
  294. // Another session's key is independent — cold until its own fetch.
  295. expect(source.lexicon!(proj('s2'))).toBeUndefined()
  296. })
  297. it('subscribeLexicon notifies on catalog settle and on invalidation, per session', async () => {
  298. const { list } = countingList()
  299. const { ctx, source } = await bench(list)
  300. const s1 = vi.fn()
  301. const s2 = vi.fn()
  302. source.subscribeLexicon!(proj('s1'), s1)
  303. source.subscribeLexicon!(proj('s2'), s2)
  304. await source.candidates(proj('s1'), req(''))
  305. expect(s1).toHaveBeenCalledTimes(1)
  306. expect(s2).not.toHaveBeenCalled()
  307. // Reset invalidates every cached session: each key notifies its own listeners.
  308. await source.candidates(proj('s2'), req(''))
  309. ctx.emit('connection/reset')
  310. expect(s1).toHaveBeenCalledTimes(2)
  311. expect(s2).toHaveBeenCalledTimes(2)
  312. })
  313. it('an unsubscribed lexicon listener stops receiving notifications', async () => {
  314. const { list } = countingList()
  315. const { source } = await bench(list)
  316. const listener = vi.fn()
  317. const off = source.subscribeLexicon!(proj('s1'), listener)
  318. off()
  319. await source.candidates(proj('s1'), req(''))
  320. expect(listener).not.toHaveBeenCalled()
  321. })
  322. })
  323. describe('pick lands plain text', () => {
  324. it('onPick returns the literal /name text with a closing space', async () => {
  325. const { source } = await bench(listOk(CATALOG))
  326. const outcome = source.onPick({
  327. candidate: { name: 'commit-helper', description: 'commit flow' },
  328. session: proj('s1'),
  329. position: 'leading',
  330. via: 'menu',
  331. span: { start: 0, end: 4, draftRev: 7 },
  332. })
  333. expect(outcome).toEqual({ text: '/commit-helper ' })
  334. })
  335. it('keeps the legacy reference codec removed and stays out of adjudication', async () => {
  336. const { source } = await bench(listOk(CATALOG))
  337. // Determinism lives host-side (the pre-step gesture boundary), so the
  338. // source neither claims lines nor serializes reference markup.
  339. expect(source.codec).toBeUndefined()
  340. expect(typeof source.matchSpace).toBe('undefined')
  341. expect(typeof source.matchEnter).toBe('undefined')
  342. })
  343. })
  344. describe('user-only marking', () => {
  345. it('prefixes the description of candidates the model cannot invoke', async () => {
  346. const rows: SkillRow[] = [
  347. { name: 'shared-skill', description: 'both surfaces', modelInvocable: true },
  348. { name: 'user-only-skill', description: 'user surface only', modelInvocable: false },
  349. ]
  350. const { source } = await bench(listOk(rows))
  351. const candidates = await source.candidates(proj('s1'), req(''))
  352. expect(candidates).toEqual([
  353. { name: 'shared-skill', description: 'both surfaces' },
  354. { name: 'user-only-skill', description: '仅用户 · user surface only' },
  355. ])
  356. })
  357. })