browser-plugin.client.spec.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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), shared fuzzy name ranking, RPC-failure
  9. * rejection, pick → plain-text outcome (the plain-text-reference decision:
  10. * .agents/notes/archived/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 ranks case-insensitive subsequence matches with prefixes first', 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. const names = async (query: string) => (await source.candidates(proj('s1'), req(query))).map(c => c.name)
  167. // 'de' prefixes deploy and is a subsequence of code-review: the prefix ranks first.
  168. await expect(names('de')).resolves.toEqual(['deploy', 'code-review'])
  169. await expect(names('REV')).resolves.toEqual(['code-review'])
  170. await expect(names('zzz')).resolves.toEqual([])
  171. })
  172. it('rejects on a failed result (the slash shell owns the menu-side fold)', async () => {
  173. const { source } = await bench(() => Promise.resolve({
  174. ok: false, error: new RemoteError('gateway/internal', 'boom', {}),
  175. }))
  176. await expect(source.candidates(proj('s1'), req('co')))
  177. .rejects.toThrow('skills/list failed: gateway/internal: boom')
  178. })
  179. it('does not fetch Agent-bound skills for an addressed child', async () => {
  180. const { list, payloads } = countingList()
  181. const { source } = await bench(list, sid('child'))
  182. await expect(source.candidates(proj('child'), req(''))).resolves.toEqual([])
  183. source.warm!(proj('child'))
  184. expect(payloads).toEqual([])
  185. })
  186. })
  187. describe('catalog cache', () => {
  188. it('re-polls on the same session filter locally: one RPC across keystrokes', async () => {
  189. const { list, payloads } = countingList()
  190. const { source } = await bench(list)
  191. await source.candidates(proj('s1'), req(''))
  192. const second = await source.candidates(proj('s1'), req('co'))
  193. expect(payloads).toHaveLength(1)
  194. expect(second).toEqual([
  195. { name: 'commit-helper', description: 'commit flow' },
  196. { name: 'code-review', description: 'review flow' },
  197. ])
  198. // A different session is its own key — one more RPC, not two.
  199. await source.candidates(proj('s2'), req(''))
  200. expect(payloads).toEqual([{ sessionId: 's1' }, { sessionId: 's2' }])
  201. })
  202. it('single-flight: concurrent candidates on one cold key share one RPC', async () => {
  203. const { list, payloads } = countingList()
  204. const { source } = await bench(list)
  205. const [a, b] = await Promise.all([
  206. source.candidates(proj('s1'), req('dep')),
  207. source.candidates(proj('s1'), req('co')),
  208. ])
  209. expect(payloads).toHaveLength(1)
  210. expect(a).toEqual([{ name: 'deploy', description: 'deploy flow' }])
  211. expect(b).toHaveLength(2)
  212. })
  213. it('an aborted caller yields empty but leaves the shared fetch warm', async () => {
  214. const { list, payloads } = countingList()
  215. const { source } = await bench(list)
  216. const aborted = new AbortController()
  217. aborted.abort()
  218. await expect(source.candidates(proj('s1'), req('co', aborted.signal))).resolves.toEqual([])
  219. // The fetch settled into the cache: the next caller pays zero RPC.
  220. await expect(source.candidates(proj('s1'), req('co'))).resolves.toHaveLength(2)
  221. expect(payloads).toHaveLength(1)
  222. })
  223. it('a failed fetch does not poison the key: the next caller retries', async () => {
  224. let fail = true
  225. const payloads: object[] = []
  226. const { source } = await bench((payload) => {
  227. payloads.push(payload)
  228. return fail
  229. ? Promise.resolve({ ok: false as const, error: new RemoteError('gateway/internal', 'boom', {}) })
  230. : listOk(CATALOG)(payload)
  231. })
  232. await expect(source.candidates(proj('s1'), req(''))).rejects.toThrow('boom')
  233. fail = false
  234. await expect(source.candidates(proj('s1'), req(''))).resolves.toHaveLength(3)
  235. expect(payloads).toHaveLength(2)
  236. })
  237. it('the scope-birth warm prewarms the session key fire-and-forget', async () => {
  238. const { list, payloads } = countingList()
  239. const { source } = await bench(list)
  240. source.warm!(proj('s1'))
  241. await vi.waitFor(() => { expect(payloads).toHaveLength(1) })
  242. expect(payloads[0]).toEqual({ sessionId: 's1' })
  243. // The prewarmed key serves candidates with zero further RPC; other
  244. // sessions' keys stay untouched.
  245. await expect(source.candidates(proj('s1'), req(''))).resolves.toHaveLength(3)
  246. expect(payloads).toHaveLength(1)
  247. await source.candidates(proj('s2'), req(''))
  248. expect(payloads).toHaveLength(2)
  249. })
  250. it('agent-preset/selected clears only the recomposed session', async () => {
  251. const { list, payloads } = countingList()
  252. const { source, remote } = await bench(list)
  253. await source.candidates(proj('s1'), req(''))
  254. await source.candidates(proj('s2'), req(''))
  255. expect(payloads).toHaveLength(2)
  256. // The catalog a preset supplies is the preset's; the other session's
  257. // composition did not change, so its cached catalog still holds.
  258. remote.emit('agent-preset/selected', [sid('s1'), 'minimal'])
  259. await source.candidates(proj('s1'), req(''))
  260. await source.candidates(proj('s2'), req(''))
  261. expect(payloads).toHaveLength(3)
  262. expect(payloads[2]).toEqual({ sessionId: 's1' })
  263. })
  264. it('connection/reset clears every cached session', async () => {
  265. const { list, payloads } = countingList()
  266. const { ctx, source } = await bench(list)
  267. await source.candidates(proj('s1'), req(''))
  268. await source.candidates(proj('s2'), req(''))
  269. expect(payloads).toHaveLength(2)
  270. ctx.emit('connection/reset')
  271. await source.candidates(proj('s1'), req(''))
  272. await source.candidates(proj('s2'), req(''))
  273. expect(payloads).toHaveLength(4)
  274. })
  275. })
  276. describe('lexicon', () => {
  277. it('is undefined before the session catalog settles and serves names after', async () => {
  278. let release: (() => void) | undefined
  279. const gate = new Promise<void>((resolve) => { release = resolve })
  280. const { source } = await bench(async (payload) => {
  281. await gate
  282. return listOk(CATALOG)(payload)
  283. })
  284. // Cold: nothing cached for the session.
  285. expect(source.lexicon!(proj('s1'))).toBeUndefined()
  286. const pending = source.candidates(proj('s1'), req(''))
  287. // In flight: still no synchronous snapshot.
  288. expect(source.lexicon!(proj('s1'))).toBeUndefined()
  289. release!()
  290. await pending
  291. expect(source.lexicon!(proj('s1'))).toEqual(['commit-helper', 'code-review', 'deploy'])
  292. // Another session's key is independent — cold until its own fetch.
  293. expect(source.lexicon!(proj('s2'))).toBeUndefined()
  294. })
  295. it('subscribeLexicon notifies on catalog settle and on invalidation, per session', async () => {
  296. const { list } = countingList()
  297. const { ctx, source } = await bench(list)
  298. const s1 = vi.fn()
  299. const s2 = vi.fn()
  300. source.subscribeLexicon!(proj('s1'), s1)
  301. source.subscribeLexicon!(proj('s2'), s2)
  302. await source.candidates(proj('s1'), req(''))
  303. expect(s1).toHaveBeenCalledTimes(1)
  304. expect(s2).not.toHaveBeenCalled()
  305. // Reset invalidates every cached session: each key notifies its own listeners.
  306. await source.candidates(proj('s2'), req(''))
  307. ctx.emit('connection/reset')
  308. expect(s1).toHaveBeenCalledTimes(2)
  309. expect(s2).toHaveBeenCalledTimes(2)
  310. })
  311. it('an unsubscribed lexicon listener stops receiving notifications', async () => {
  312. const { list } = countingList()
  313. const { source } = await bench(list)
  314. const listener = vi.fn()
  315. const off = source.subscribeLexicon!(proj('s1'), listener)
  316. off()
  317. await source.candidates(proj('s1'), req(''))
  318. expect(listener).not.toHaveBeenCalled()
  319. })
  320. })
  321. describe('pick lands plain text', () => {
  322. it('onPick returns the literal /name text with a closing space', async () => {
  323. const { source } = await bench(listOk(CATALOG))
  324. const outcome = source.onPick({
  325. candidate: { name: 'commit-helper', description: 'commit flow' },
  326. session: proj('s1'),
  327. position: 'leading',
  328. via: 'menu',
  329. action: 'pick',
  330. span: { start: 0, end: 4, draftRev: 7 },
  331. })
  332. expect(outcome).toEqual({ text: '/commit-helper ' })
  333. })
  334. it('keeps the legacy reference codec removed and stays out of adjudication', async () => {
  335. const { source } = await bench(listOk(CATALOG))
  336. // Determinism lives host-side (the pre-step gesture boundary), so the
  337. // source neither claims lines nor serializes reference markup.
  338. expect(source.codec).toBeUndefined()
  339. expect(typeof source.matchSpace).toBe('undefined')
  340. expect(typeof source.matchEnter).toBe('undefined')
  341. })
  342. })
  343. describe('user-only marking', () => {
  344. it('prefixes the description of candidates the model cannot invoke', async () => {
  345. const rows: SkillRow[] = [
  346. { name: 'shared-skill', description: 'both surfaces', modelInvocable: true },
  347. { name: 'user-only-skill', description: 'user surface only', modelInvocable: false },
  348. ]
  349. const { source } = await bench(listOk(rows))
  350. const candidates = await source.candidates(proj('s1'), req(''))
  351. expect(candidates).toEqual([
  352. { name: 'shared-skill', description: 'both surfaces' },
  353. { name: 'user-only-skill', description: '仅用户 · user surface only' },
  354. ])
  355. })
  356. })