service.spec.ts 28 KB

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