browser-plugin.client.spec.ts 16 KB

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