service.spec.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. /**
  2. * CommandService tests on a real cordis Context with fake slash/connection
  3. * faces and real session scopes (createScope): session-keyed candidate
  4. * synthesis (host catalog by sessionId + contributions by availability,
  5. * collision fail-loud), the dispatch decision table cell by cell, matchSpace
  6. * hot-key policy, matchEnter strong-wait / reject, the sessionId execute
  7. * payload, the scoped consume-token dispatch, per-session popupFor
  8. * lifecycle, and the directory invalidation event subscriptions.
  9. */
  10. import { Context } from '@deepseek-ai/cordis'
  11. import { describe, expect, it, vi } from 'vitest'
  12. import { createScope, scopeOf } from '@deepseek-ai/dsh-client-runtime/client'
  13. import { TestRemote } from '@deepseek-ai/dsh-client-test-runtime'
  14. import type { SessionId } from '@deepseek-ai/dsh-client-runtime/client'
  15. import type { ClientSessionContext, ConsumeTokenRequest, SlashPick, SlashSource } from '@deepseek-ai/dsh-client-ui-slash/client'
  16. import type { CommandContribution, CommandDecoration, CommandUiSpec, SelectOption } from '../src/client/contract.ts'
  17. import type { CommandDescriptor } from '../src/client/directory.ts'
  18. import { CommandService } from '../src/client/service.ts'
  19. const sid = (k: string): SessionId => k as SessionId
  20. /** The agent-backed session projection (single state; identity only). */
  21. const proj = (id: string): ClientSessionContext => ({ sessionId: sid(id) })
  22. const S1_CMDS: CommandDescriptor[] = [
  23. { name: 'plan', description: 'bare kind' },
  24. { name: 'goal', description: 'leadingInput kind', input: { hint: 'goal text' } },
  25. ]
  26. const S2_CMDS: CommandDescriptor[] = [
  27. ...S1_CMDS,
  28. { name: 'attach', description: 'scoped shadow', input: { hint: 'path' } },
  29. ]
  30. type ExecuteValue = { matched: boolean }
  31. interface BenchOptions {
  32. /** Scripted catalog per list payload; default serves the fixed catalogs by session. */
  33. commands?: (payload: { sessionId: SessionId }) => Promise<{ commands: CommandDescriptor[] }>
  34. execute?: (payload: { sessionId: SessionId; line: string }) => Promise<ExecuteValue>
  35. addressed?: SessionId
  36. }
  37. async function bench(opts: BenchOptions = {}) {
  38. const ctx = new Context()
  39. const registered = new Map<string, SlashSource>()
  40. const listCalls: Array<{ sessionId: SessionId }> = []
  41. const executeCalls: Array<{ sessionId: SessionId; line: string }> = []
  42. const api = {
  43. commands: {
  44. list: async (payload: { sessionId: SessionId }) => {
  45. listCalls.push(payload)
  46. const value = await (opts.commands ?? (p => Promise.resolve({
  47. commands: p.sessionId === sid('s2') ? S2_CMDS : S1_CMDS,
  48. })))(payload)
  49. return { result: { ok: true as const, value } }
  50. },
  51. execute: async (payload: { sessionId: SessionId; line: string }) => {
  52. executeCalls.push(payload)
  53. const value = await (opts.execute ?? (() => Promise.resolve({ matched: true })))(payload)
  54. return { result: { ok: true as const, value } }
  55. },
  56. },
  57. }
  58. ctx.provide('slash', {
  59. registerSource(src: SlashSource) {
  60. const key = `${src.trigger} ${src.name}`
  61. registered.set(key, src)
  62. return () => { registered.delete(key) }
  63. },
  64. })
  65. // Real scope tags behind a fake sessions face.
  66. const scopes = new Map<SessionId, { ctx: Context; fiber: { dispose(): Promise<void> } }>()
  67. ctx.provide('sessions', {
  68. scope: (id: SessionId) => scopes.get(id)?.ctx,
  69. scopeOf: (c: Context) => scopeOf(c),
  70. subagentAddress: (id: SessionId) => id === opts.addressed
  71. ? { parentSessionId: sid('parent'), childSessionId: id, mode: 'continuable' as const }
  72. : undefined,
  73. })
  74. ctx.provide('connection', { api })
  75. // CommandService injects `remote`; the directory invalidation arrives on the
  76. // same `$dispatch` handoff the connection sink makes.
  77. new TestRemote(ctx)
  78. /** Notices the fake conversation face collected (runDetached routing). */
  79. const notices: Array<{ scope: SessionId | undefined; level: 'info' | 'error'; text: string }> = []
  80. ctx.provide('conversation', {
  81. input: {
  82. for: (actx: Context) => ({
  83. notify: (level: 'info' | 'error', text: string) => {
  84. notices.push({ scope: scopeOf(actx), level, text })
  85. },
  86. }),
  87. },
  88. })
  89. const fiber = ctx.plugin(CommandService)
  90. await fiber.await()
  91. const command = ctx.get('command') as CommandService
  92. const source = registered.get('/ command')
  93. if (source === undefined) throw new Error('command source not registered')
  94. const mint = (key: string) => {
  95. const handle = createScope(ctx, sid(key))
  96. scopes.set(sid(key), handle)
  97. return handle
  98. }
  99. /** Warm one session's catalog through the source's own candidate pull. */
  100. const warm = async (session: ClientSessionContext) => {
  101. await source.candidates(session, { query: '', position: 'leading', signal: new AbortController().signal })
  102. }
  103. return { ctx, fiber, command, source, mint, warm, listCalls, executeCalls, registered, notices }
  104. }
  105. function menuPick(source: SlashSource, name: string, session: ClientSessionContext, end?: number) {
  106. const pick: SlashPick = {
  107. candidate: { name },
  108. session,
  109. position: 'leading',
  110. via: 'menu',
  111. span: { start: 0, end: end ?? name.length + 1, draftRev: 3 },
  112. }
  113. return source.onPick(pick)
  114. }
  115. const themeUi = (over: Partial<CommandUiSpec> = {}): CommandUiSpec => ({
  116. kind: 'popupSelect',
  117. options: () => Promise.resolve([{ id: 'dark', label: 'Dark' }]),
  118. onSelect: () => undefined,
  119. ...over,
  120. })
  121. const themeContribution = (over: Partial<CommandContribution> = {}): CommandContribution => ({
  122. name: 'theme',
  123. description: 'client popup kind',
  124. available: () => true,
  125. ui: themeUi(),
  126. ...over,
  127. })
  128. const req = (query: string, position: 'leading' | 'inline' = 'leading') =>
  129. ({ query, position, signal: new AbortController().signal })
  130. describe('registration', () => {
  131. it('registers the "/" source with matchSpace/matchEnter/warm hooks and removes it on fiber disposal', async () => {
  132. const { registered, source, fiber } = await bench()
  133. expect(typeof source.matchSpace).toBe('function')
  134. expect(typeof source.matchEnter).toBe('function')
  135. expect(typeof source.warm).toBe('function')
  136. expect([...registered.keys()]).toEqual(['/ command'])
  137. await fiber.dispose()
  138. expect(registered.size).toBe(0)
  139. })
  140. it('the warm hook prewarms the session key: one pull per session, no duplicate over pending', async () => {
  141. const { source, listCalls } = await bench()
  142. source.warm!(proj('s1'))
  143. expect(listCalls).toEqual([{ sessionId: sid('s1') }])
  144. source.warm!(proj('s2'))
  145. expect(listCalls).toEqual([{ sessionId: sid('s1') }, { sessionId: sid('s2') }])
  146. source.warm!(proj('s1')) // s1 already pending → no duplicate pull
  147. expect(listCalls).toHaveLength(2)
  148. })
  149. })
  150. describe('candidates', () => {
  151. it('does not fetch Agent-bound commands for an addressed child', async () => {
  152. const b = await bench({ addressed: sid('child') })
  153. await expect(b.warm(proj('child'))).resolves.toBeUndefined()
  154. expect(b.listCalls).toEqual([])
  155. })
  156. it('pulls the session catalog; fuzzy filter and hint mapping apply', async () => {
  157. const { source, listCalls } = await bench()
  158. const list = await source.candidates(proj('s1'), req('g'))
  159. expect(listCalls).toEqual([{ sessionId: sid('s1') }])
  160. expect(list).toEqual([{ name: 'goal', description: 'leadingInput kind', hint: 'goal text' }])
  161. })
  162. it('matches case-insensitive subsequences and ranks prefixes, boundaries, adjacency, gaps, then source order', async () => {
  163. const commands: CommandDescriptor[] = [
  164. { name: 'q-xylophone', description: '' },
  165. { name: 'qx-long', description: '' },
  166. { name: 'fabulous', description: '' },
  167. { name: 'foo-bar', description: '' },
  168. { name: 'zuv', description: '' },
  169. { name: 'zu1v', description: '' },
  170. { name: 'yu1v', description: '' },
  171. { name: 'zu12v', description: '' },
  172. ]
  173. const { source } = await bench({ commands: () => Promise.resolve({ commands }) })
  174. const names = async (query: string) => (await source.candidates(proj('s1'), req(query))).map(c => c.name)
  175. await expect(names('QX')).resolves.toEqual(['qx-long', 'q-xylophone'])
  176. await expect(names('fb')).resolves.toEqual(['foo-bar', 'fabulous'])
  177. await expect(names('uv')).resolves.toEqual(['zuv', 'zu1v', 'yu1v', 'zu12v'])
  178. await expect(names('zzz')).resolves.toEqual([])
  179. await expect(names('query-longer-than-every-name')).resolves.toEqual([])
  180. })
  181. it('catalogs are per session: another session pulls its own key', async () => {
  182. const { source, listCalls } = await bench()
  183. const names = (await source.candidates(proj('s2'), req(''))).map(c => c.name)
  184. expect(listCalls).toEqual([{ sessionId: sid('s2') }])
  185. expect(names).toEqual(['plan', 'goal', 'attach'])
  186. })
  187. it('hides leadingInput commands at inline position', async () => {
  188. const { source } = await bench()
  189. const names = (await source.candidates(proj('s1'), req('', 'inline'))).map(c => c.name)
  190. expect(names).toEqual(['plan'])
  191. })
  192. it('merges available contributions and filters unavailable ones with the per-call projection', async () => {
  193. const { command, source } = await bench()
  194. const available = vi.fn((session: ClientSessionContext) => session.sessionId === sid('s1'))
  195. command.register(themeContribution({ available }))
  196. const s1Names = (await source.candidates(proj('s1'), req(''))).map(c => c.name)
  197. expect(s1Names).toEqual(['plan', 'goal', 'theme'])
  198. expect(available).toHaveBeenLastCalledWith(proj('s1'))
  199. const s2Names = (await source.candidates(proj('s2'), req(''))).map(c => c.name)
  200. expect(s2Names).not.toContain('theme')
  201. })
  202. it('contribution rows ride the same fuzzy query filter', async () => {
  203. const { command, source } = await bench()
  204. command.register(themeContribution())
  205. const names = (await source.candidates(proj('s1'), req('tm'))).map(c => c.name)
  206. expect(names).toEqual(['theme'])
  207. })
  208. it('a contribution/host name collision fails loud', async () => {
  209. const { command, source } = await bench()
  210. command.register(themeContribution({ name: 'plan' }))
  211. await expect(source.candidates(proj('s1'), req(''))).rejects.toThrow('collides with a host command')
  212. })
  213. })
  214. describe('decorations (bare-invocation UI on host commands)', () => {
  215. const goalDecoration = (over: Partial<CommandDecoration> = {}): CommandDecoration => ({
  216. name: 'goal',
  217. available: () => true,
  218. ui: themeUi(),
  219. ...over,
  220. })
  221. it('adds no catalog row: the host row stands alone', async () => {
  222. const { command, source } = await bench()
  223. command.decorate(goalDecoration())
  224. const names = (await source.candidates(proj('s1'), req(''))).map(c => c.name)
  225. expect(names).toEqual(['plan', 'goal'])
  226. })
  227. it('bare enter opens the popup; an argued line never consults the decoration (host claim)', async () => {
  228. const { command, source, mint, warm } = await bench()
  229. command.decorate(goalDecoration())
  230. const scope = mint('s1')
  231. await warm(proj('s1'))
  232. expect(await source.matchEnter!(proj('s1'), '/goal', new AbortController().signal)).toBe('handled')
  233. expect(command.popupFor(scope.ctx).state.getSnapshot()).toMatchObject({ open: true, command: 'goal' })
  234. const argued = await source.matchEnter!(proj('s1'), '/goal ship it', new AbortController().signal)
  235. if (argued === undefined || argued === 'handled' || !('claim' in argued)) throw new Error('expected the host claim')
  236. expect(argued.claim.token).toBe('/goal ')
  237. })
  238. it('space never consults the decoration (host claim)', async () => {
  239. const { command, source, warm } = await bench()
  240. command.decorate(goalDecoration())
  241. await warm(proj('s1'))
  242. const outcome = source.matchSpace!(proj('s1'), '/goal')
  243. if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected the host claim')
  244. expect(outcome.claim.token).toBe('/goal ')
  245. })
  246. it('a decoration with no host row never fires (bare enter misses; menu pick misses)', async () => {
  247. const { command, source, mint, warm } = await bench()
  248. command.decorate(goalDecoration({ name: 'phantom' }))
  249. const scope = mint('s1')
  250. await warm(proj('s1'))
  251. expect(await source.matchEnter!(proj('s1'), '/phantom', new AbortController().signal)).toBeUndefined()
  252. expect(menuPick(source, 'phantom', proj('s1'))).toBeUndefined()
  253. expect(command.popupFor(scope.ctx).state.getSnapshot().open).toBe(false)
  254. })
  255. it('an unavailable decoration falls through to the host bare path (detached execute)', async () => {
  256. const { command, source, warm, executeCalls } = await bench()
  257. command.decorate(goalDecoration({ name: 'plan', available: () => false }))
  258. await warm(proj('s1'))
  259. expect(await source.matchEnter!(proj('s1'), '/plan', new AbortController().signal)).toBe('handled')
  260. expect(executeCalls).toEqual([{ sessionId: sid('s1'), line: '/plan' }])
  261. })
  262. it('duplicate decoration names fail loud', async () => {
  263. const { command } = await bench()
  264. command.decorate(goalDecoration())
  265. expect(() => { command.decorate(goalDecoration()) }).toThrow('duplicate decoration for /goal')
  266. })
  267. })
  268. describe('dispatch (menu column)', () => {
  269. it('contribution → opens the session popup with the open-time projection, no execute', async () => {
  270. const { command, source, mint, warm, executeCalls } = await bench()
  271. const options = vi.fn((_s: ClientSessionContext) => Promise.resolve([{ id: 'dark', label: 'Dark' }]))
  272. command.register(themeContribution({ ui: themeUi({ options }) }))
  273. const scope = mint('s1')
  274. await warm(proj('s1'))
  275. expect(menuPick(source, 'theme', proj('s1'))).toBe('handled')
  276. const popup = command.popupFor(scope.ctx)
  277. expect(popup.state.getSnapshot()).toMatchObject({ open: true, command: 'theme' })
  278. expect(options).toHaveBeenCalledExactlyOnceWith(proj('s1'), expect.any(AbortSignal))
  279. expect(executeCalls).toEqual([])
  280. })
  281. it('an unavailable contribution falls through to the host catalog', async () => {
  282. const { command, source, mint, warm } = await bench()
  283. command.register(themeContribution({ available: () => false }))
  284. const scope = mint('s1')
  285. await warm(proj('s1'))
  286. expect(menuPick(source, 'theme', proj('s1'))).toBeUndefined() // no host 'theme' either
  287. expect(command.popupFor(scope.ctx).state.getSnapshot().open).toBe(false)
  288. })
  289. it('host leadingInput → {claim} with token "/name " and hint; claiming never executes', async () => {
  290. const { source, warm, executeCalls } = await bench()
  291. await warm(proj('s1'))
  292. const outcome = menuPick(source, 'goal', proj('s1'))
  293. if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected claim')
  294. expect(outcome.claim.token).toBe('/goal ')
  295. expect(outcome.claim.hint).toBe('goal text')
  296. expect(executeCalls).toEqual([])
  297. })
  298. it('host bare → consume-token span guard on the session scope + detached execute', async () => {
  299. const { source, mint, warm, executeCalls } = await bench()
  300. const scope = mint('s1')
  301. const consumes: ConsumeTokenRequest[] = []
  302. scope.ctx.on('slash/input-consume-token', (r) => {
  303. consumes.push(r)
  304. return true
  305. })
  306. await warm(proj('s1'))
  307. expect(menuPick(source, 'plan', proj('s1'), 5)).toBe('handled')
  308. expect(consumes).toEqual([{ guard: { kind: 'span', span: { start: 0, end: 5, draftRev: 3 } } }])
  309. await Promise.resolve()
  310. expect(executeCalls).toEqual([{ sessionId: sid('s1'), line: '/plan' }])
  311. })
  312. it('a name the directory no longer serves → undefined (snapshot swapped between menu and pick)', async () => {
  313. const { source, warm } = await bench()
  314. await warm(proj('s1'))
  315. expect(menuPick(source, 'gone', proj('s1'))).toBeUndefined()
  316. })
  317. })
  318. describe('matchSpace (space column)', () => {
  319. it('answers undefined from a not-ready key (no waiting, no RPC)', async () => {
  320. const { source, listCalls } = await bench()
  321. expect(source.matchSpace!(proj('s1'), '/goal')).toBeUndefined()
  322. expect(listCalls).toEqual([])
  323. })
  324. it('hot leadingInput exact token → {claim}; the key axis is the session', async () => {
  325. const { source, warm } = await bench()
  326. await warm(proj('s2'))
  327. const outcome = source.matchSpace!(proj('s2'), '/attach')
  328. if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected claim')
  329. expect(outcome.claim.token).toBe('/attach ')
  330. // s1's key is still cold: the same token answers undefined there.
  331. expect(source.matchSpace!(proj('s1'), '/attach')).toBeUndefined()
  332. })
  333. it('bare kind and contribution names stay plain text', async () => {
  334. const { command, source, warm } = await bench()
  335. command.register(themeContribution())
  336. await warm(proj('s1'))
  337. expect(source.matchSpace!(proj('s1'), '/plan')).toBeUndefined()
  338. expect(source.matchSpace!(proj('s1'), '/theme')).toBeUndefined()
  339. })
  340. it('unknown token / non-slash token → undefined', async () => {
  341. const { source, warm } = await bench()
  342. await warm(proj('s1'))
  343. expect(source.matchSpace!(proj('s1'), '/nope')).toBeUndefined()
  344. expect(source.matchSpace!(proj('s1'), 'plan')).toBeUndefined()
  345. })
  346. })
  347. describe('matchEnter (enter column)', () => {
  348. const signal = () => new AbortController().signal
  349. it('strong-waits a cold key before adjudicating', async () => {
  350. let release!: (value: { commands: CommandDescriptor[] }) => void
  351. const { source } = await bench({
  352. commands: () => new Promise((resolve) => { release = resolve }),
  353. })
  354. const wait = source.matchEnter!(proj('s1'), '/goal args', signal())
  355. release({ commands: S1_CMDS })
  356. const outcome = await wait
  357. if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected claim')
  358. expect(outcome.claim.token).toBe('/goal ')
  359. })
  360. it('rejects when warmup fails (never a silent downgrade)', async () => {
  361. const { source } = await bench({
  362. commands: () => Promise.reject(new Error('warmup boom')),
  363. })
  364. await expect(source.matchEnter!(proj('s1'), '/goal', signal())).rejects.toThrow('warmup boom')
  365. })
  366. it('leadingInput claims args-tolerant (bare and with trailing text)', async () => {
  367. const { source, warm } = await bench()
  368. await warm(proj('s1'))
  369. for (const line of ['/goal', '/goal refactor the loop']) {
  370. const outcome = await source.matchEnter!(proj('s1'), line, signal())
  371. if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected claim')
  372. expect(outcome.claim.token).toBe('/goal ')
  373. }
  374. })
  375. it('bare host command executes detached with the bare-token consume guard', async () => {
  376. const { source, mint, warm, executeCalls } = await bench()
  377. const scope = mint('s1')
  378. const consumes: ConsumeTokenRequest[] = []
  379. scope.ctx.on('slash/input-consume-token', (r) => {
  380. consumes.push(r)
  381. return true
  382. })
  383. await warm(proj('s1'))
  384. await expect(source.matchEnter!(proj('s1'), '/plan', signal())).resolves.toBe('handled')
  385. expect(consumes).toEqual([{ guard: { kind: 'bare-token', token: '/plan' } }])
  386. await Promise.resolve()
  387. expect(executeCalls).toEqual([{ sessionId: sid('s1'), line: '/plan' }])
  388. })
  389. it('bare kind with trailing text → undefined and no RPC (default sink owns the line)', async () => {
  390. const { source, warm, executeCalls } = await bench()
  391. await warm(proj('s1'))
  392. await expect(source.matchEnter!(proj('s1'), '/plan now', signal())).resolves.toBeUndefined()
  393. expect(executeCalls).toEqual([])
  394. })
  395. it('contribution: bare token opens the popup without touching the directory; args → undefined', async () => {
  396. const { command, source, mint, listCalls } = await bench()
  397. command.register(themeContribution())
  398. const scope = mint('s1')
  399. await expect(source.matchEnter!(proj('s1'), '/theme', signal())).resolves.toBe('handled')
  400. expect(command.popupFor(scope.ctx).state.getSnapshot().open).toBe(true)
  401. expect(listCalls).toEqual([]) // contribution short-circuits ahead of ensureReady
  402. await expect(source.matchEnter!(proj('s1'), '/theme dark', signal())).resolves.toBeUndefined()
  403. })
  404. it('unknown name, bare "/", and non-slash lines → undefined', async () => {
  405. const { source, warm } = await bench()
  406. await warm(proj('s1'))
  407. await expect(source.matchEnter!(proj('s1'), '/nope', signal())).resolves.toBeUndefined()
  408. await expect(source.matchEnter!(proj('s1'), '/', signal())).resolves.toBeUndefined()
  409. await expect(source.matchEnter!(proj('s1'), 'plain text', signal())).resolves.toBeUndefined()
  410. })
  411. })
  412. describe('execute payload', () => {
  413. it('claim.submit addresses the session; admitted outcomes stay off the composer (flow card owns them)', async () => {
  414. const { source, warm, executeCalls } = await bench({
  415. execute: () => Promise.resolve({ matched: true }),
  416. })
  417. await warm(proj('s1'))
  418. const outcome = source.matchSpace!(proj('s1'), '/goal')
  419. if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected claim')
  420. const settled = await outcome.claim.submit('ship it', new Context())
  421. expect(executeCalls).toEqual([{ sessionId: sid('s1'), line: '/goal ship it' }])
  422. // Pure admission: no outcome text ever rides the submit result — the
  423. // durable command lifecycle events render the outcome in the flow.
  424. expect(settled).toEqual({ kind: 'success' })
  425. })
  426. it('maps matched:false to an error outcome and a matched bare result to success', async () => {
  427. const claimOf = async (opts: BenchOptions) => {
  428. const b = await bench(opts)
  429. await b.warm(proj('s1'))
  430. const outcome = b.source.matchSpace!(proj('s1'), '/goal')
  431. if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected claim')
  432. return outcome.claim
  433. }
  434. const first = await claimOf({ execute: () => Promise.resolve({ matched: false }) })
  435. const bad = await first.submit('x', new Context())
  436. expect(bad.kind).toBe('error')
  437. const second = await claimOf({ execute: () => Promise.resolve({ matched: true }) })
  438. await expect(second.submit('', new Context())).resolves.toEqual({ kind: 'success' })
  439. })
  440. })
  441. describe('detached admission notices', () => {
  442. const flush = () => new Promise(resolve => setTimeout(resolve, 0))
  443. it('admitted outcomes stay silent; admission miss and transport rejection notice as errors', async () => {
  444. let mode: 'admitted' | 'miss' | 'reject' = 'admitted'
  445. const { source, mint, warm, notices } = await bench({
  446. execute: () => {
  447. if (mode === 'reject') return Promise.reject(new Error('network down'))
  448. return Promise.resolve({ matched: mode === 'admitted' })
  449. },
  450. })
  451. mint('s1')
  452. await warm(proj('s1'))
  453. // Admitted: the durable lifecycle events own the outcome — no notice.
  454. menuPick(source, 'plan', proj('s1'))
  455. await flush()
  456. expect(notices).toEqual([])
  457. // Admission miss (matched:false): immediate composer feedback stays.
  458. mode = 'miss'
  459. await source.matchEnter!(proj('s1'), '/plan', new AbortController().signal)
  460. await flush()
  461. expect(notices).toEqual([{ scope: sid('s1'), level: 'error', text: 'unknown or malformed command: /plan' }])
  462. notices.length = 0
  463. mode = 'reject'
  464. menuPick(source, 'plan', proj('s1'))
  465. await flush()
  466. expect(notices).toEqual([{ scope: sid('s1'), level: 'error', text: 'network down' }])
  467. })
  468. it('a torn-down scope drops the failure notice', async () => {
  469. const { source, warm, notices } = await bench({
  470. execute: () => Promise.reject(new Error('orphan failure')),
  471. })
  472. await warm(proj('ghost')) // never minted: scopeFor misses
  473. menuPick(source, 'plan', proj('ghost'))
  474. await flush()
  475. expect(notices).toEqual([])
  476. })
  477. })
  478. describe('register (contribution face)', () => {
  479. it('duplicate registration throws; the disposer frees the name', async () => {
  480. const { command } = await bench()
  481. const dispose = command.register(themeContribution())
  482. expect(() => command.register(themeContribution())).toThrow('duplicate contribution')
  483. dispose()
  484. command.register(themeContribution())()
  485. })
  486. })
  487. describe('popupFor', () => {
  488. it('resolves lazily per session; a foreign session gets its own controller; unscoped ctx throws', async () => {
  489. const { ctx, command, mint } = await bench()
  490. const a = mint('s1')
  491. const first = command.popupFor(a.ctx)
  492. expect(command.popupFor(a.ctx)).toBe(first)
  493. expect(command.popupFor(mint('s2').ctx)).not.toBe(first)
  494. expect(() => command.popupFor(ctx)).toThrow('requires a session scope')
  495. })
  496. it('a successful select dispatches the scoped consume-token and fires the bound composer focus', async () => {
  497. const { command, source, mint } = await bench()
  498. const onSelect = vi.fn()
  499. command.register(themeContribution({ ui: themeUi({ onSelect }) }))
  500. const scope = mint('s1')
  501. const consumes: ConsumeTokenRequest[] = []
  502. scope.ctx.on('slash/input-consume-token', (r) => {
  503. consumes.push(r)
  504. return true
  505. })
  506. const focus = vi.fn()
  507. command.bindComposerFocus(sid('s1'), focus)
  508. expect(menuPick(source, 'theme', proj('s1'), 6)).toBe('handled')
  509. const popup = command.popupFor(scope.ctx)
  510. await Promise.resolve() // options land
  511. await popup.select(0)
  512. expect(onSelect).toHaveBeenCalledExactlyOnceWith({ id: 'dark', label: 'Dark' } satisfies SelectOption, proj('s1'))
  513. expect(consumes).toEqual([{ guard: { kind: 'span', span: { start: 0, end: 6, draftRev: 3 } } }])
  514. expect(focus).toHaveBeenCalledTimes(1)
  515. })
  516. it('the enter path opens with the bare-token guard', async () => {
  517. const { command, source, mint } = await bench()
  518. command.register(themeContribution())
  519. const scope = mint('s1')
  520. const consumes: ConsumeTokenRequest[] = []
  521. scope.ctx.on('slash/input-consume-token', (r) => {
  522. consumes.push(r)
  523. return true
  524. })
  525. await source.matchEnter!(proj('s1'), '/theme', new AbortController().signal)
  526. const popup = command.popupFor(scope.ctx)
  527. await Promise.resolve()
  528. await popup.select(0)
  529. expect(consumes).toEqual([{ guard: { kind: 'bare-token', token: '/theme' } }])
  530. })
  531. it('the scope disposer disposes the controller and a re-mint resolves fresh', async () => {
  532. const { command, source, mint } = await bench()
  533. command.register(themeContribution())
  534. const scope = mint('s1')
  535. await source.matchEnter!(proj('s1'), '/theme', new AbortController().signal)
  536. const popup = command.popupFor(scope.ctx)
  537. expect(popup.state.getSnapshot().open).toBe(true)
  538. await scope.fiber.dispose()
  539. expect(popup.state.getSnapshot().open).toBe(false)
  540. expect(command.popupFor(mint('s1').ctx)).not.toBe(popup)
  541. })
  542. })
  543. describe('directory invalidation events', () => {
  544. it('commands/change repulls in the background while the old snapshot serves', async () => {
  545. let round = 0
  546. const { ctx, source, warm } = await bench({
  547. commands: () => {
  548. round += 1
  549. return Promise.resolve({
  550. commands: round === 1
  551. ? S1_CMDS
  552. : [{ name: 'fresh', description: '', input: { hint: 'h' } }],
  553. })
  554. },
  555. })
  556. await warm(proj('s1'))
  557. ctx.remote.$dispatch('commands/change', [])
  558. await new Promise(resolve => setTimeout(resolve, 0))
  559. expect(source.matchSpace!(proj('s1'), '/fresh')).not.toBeUndefined()
  560. expect(source.matchSpace!(proj('s1'), '/goal')).toBeUndefined()
  561. })
  562. it('agent-preset/selected repulls the recomposed session and leaves the others served', async () => {
  563. const rounds = new Map<SessionId, number>()
  564. const { ctx, source, warm } = await bench({
  565. commands: (payload) => {
  566. const round = (rounds.get(payload.sessionId) ?? 0) + 1
  567. rounds.set(payload.sessionId, round)
  568. return Promise.resolve({
  569. commands: round === 1
  570. ? S1_CMDS
  571. : [{ name: 'fresh', description: '', input: { hint: 'h' } }],
  572. })
  573. },
  574. })
  575. await warm(proj('s1'))
  576. await warm(proj('s2'))
  577. // A preset switch changes which commands one session's agent resolves;
  578. // every other session keeps the catalog its own composition serves.
  579. ctx.remote.$dispatch('agent-preset/selected', [sid('s1'), 'minimal'])
  580. await new Promise(resolve => setTimeout(resolve, 0))
  581. expect(source.matchSpace!(proj('s1'), '/fresh')).not.toBeUndefined()
  582. expect(source.matchSpace!(proj('s1'), '/goal')).toBeUndefined()
  583. expect(source.matchSpace!(proj('s2'), '/goal')).not.toBeUndefined()
  584. })
  585. it('connection/reset hard-drops every session key until its rewarm lands', async () => {
  586. let block = false
  587. let release!: (value: { commands: CommandDescriptor[] }) => void
  588. const { ctx, source, warm } = await bench({
  589. commands: () => (block
  590. ? new Promise((resolve) => { release = resolve })
  591. : Promise.resolve({ commands: S2_CMDS })),
  592. })
  593. await warm(proj('s2'))
  594. expect(source.matchSpace!(proj('s2'), '/attach')).not.toBeUndefined()
  595. block = true
  596. ctx.emit('connection/reset')
  597. // Hard reset: silent until the rewarm lands.
  598. expect(source.matchSpace!(proj('s2'), '/attach')).toBeUndefined()
  599. release({ commands: S2_CMDS })
  600. await new Promise(resolve => setTimeout(resolve, 0))
  601. expect(source.matchSpace!(proj('s2'), '/attach')).not.toBeUndefined()
  602. })
  603. })