service.spec.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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; prefix 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('catalogs are per session: another session pulls its own key', async () => {
  159. const { source, listCalls } = await bench()
  160. const names = (await source.candidates(proj('s2'), req(''))).map(c => c.name)
  161. expect(listCalls).toEqual([{ sessionId: sid('s2') }])
  162. expect(names).toEqual(['plan', 'goal', 'attach'])
  163. })
  164. it('hides leadingInput commands at inline position', async () => {
  165. const { source } = await bench()
  166. const names = (await source.candidates(proj('s1'), req('', 'inline'))).map(c => c.name)
  167. expect(names).toEqual(['plan'])
  168. })
  169. it('merges available contributions and filters unavailable ones with the per-call projection', async () => {
  170. const { command, source } = await bench()
  171. const available = vi.fn((session: ClientSessionContext) => session.sessionId === sid('s1'))
  172. command.register(themeContribution({ available }))
  173. const s1Names = (await source.candidates(proj('s1'), req(''))).map(c => c.name)
  174. expect(s1Names).toEqual(['plan', 'goal', 'theme'])
  175. expect(available).toHaveBeenLastCalledWith(proj('s1'))
  176. const s2Names = (await source.candidates(proj('s2'), req(''))).map(c => c.name)
  177. expect(s2Names).not.toContain('theme')
  178. })
  179. it('contribution rows ride the same query prefix filter', async () => {
  180. const { command, source } = await bench()
  181. command.register(themeContribution())
  182. const names = (await source.candidates(proj('s1'), req('th'))).map(c => c.name)
  183. expect(names).toEqual(['theme'])
  184. })
  185. it('a contribution/host name collision fails loud', async () => {
  186. const { command, source } = await bench()
  187. command.register(themeContribution({ name: 'plan' }))
  188. await expect(source.candidates(proj('s1'), req(''))).rejects.toThrow('collides with a host command')
  189. })
  190. })
  191. describe('decorations (bare-invocation UI on host commands)', () => {
  192. const goalDecoration = (over: Partial<CommandDecoration> = {}): CommandDecoration => ({
  193. name: 'goal',
  194. available: () => true,
  195. ui: themeUi(),
  196. ...over,
  197. })
  198. it('adds no catalog row: the host row stands alone', async () => {
  199. const { command, source } = await bench()
  200. command.decorate(goalDecoration())
  201. const names = (await source.candidates(proj('s1'), req(''))).map(c => c.name)
  202. expect(names).toEqual(['plan', 'goal'])
  203. })
  204. it('bare enter opens the popup; an argued line never consults the decoration (host claim)', async () => {
  205. const { command, source, mint, warm } = await bench()
  206. command.decorate(goalDecoration())
  207. const scope = mint('s1')
  208. await warm(proj('s1'))
  209. expect(await source.matchEnter!(proj('s1'), '/goal', new AbortController().signal)).toBe('handled')
  210. expect(command.popupFor(scope.ctx).state.getSnapshot()).toMatchObject({ open: true, command: 'goal' })
  211. const argued = await source.matchEnter!(proj('s1'), '/goal ship it', new AbortController().signal)
  212. if (argued === undefined || argued === 'handled' || !('claim' in argued)) throw new Error('expected the host claim')
  213. expect(argued.claim.token).toBe('/goal ')
  214. })
  215. it('space never consults the decoration (host claim)', async () => {
  216. const { command, source, warm } = await bench()
  217. command.decorate(goalDecoration())
  218. await warm(proj('s1'))
  219. const outcome = source.matchSpace!(proj('s1'), '/goal')
  220. if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected the host claim')
  221. expect(outcome.claim.token).toBe('/goal ')
  222. })
  223. it('a decoration with no host row never fires (bare enter misses; menu pick misses)', async () => {
  224. const { command, source, mint, warm } = await bench()
  225. command.decorate(goalDecoration({ name: 'phantom' }))
  226. const scope = mint('s1')
  227. await warm(proj('s1'))
  228. expect(await source.matchEnter!(proj('s1'), '/phantom', new AbortController().signal)).toBeUndefined()
  229. expect(menuPick(source, 'phantom', proj('s1'))).toBeUndefined()
  230. expect(command.popupFor(scope.ctx).state.getSnapshot().open).toBe(false)
  231. })
  232. it('an unavailable decoration falls through to the host bare path (detached execute)', async () => {
  233. const { command, source, warm, executeCalls } = await bench()
  234. command.decorate(goalDecoration({ name: 'plan', available: () => false }))
  235. await warm(proj('s1'))
  236. expect(await source.matchEnter!(proj('s1'), '/plan', new AbortController().signal)).toBe('handled')
  237. expect(executeCalls).toEqual([{ sessionId: sid('s1'), line: '/plan' }])
  238. })
  239. it('duplicate decoration names fail loud', async () => {
  240. const { command } = await bench()
  241. command.decorate(goalDecoration())
  242. expect(() => { command.decorate(goalDecoration()) }).toThrow('duplicate decoration for /goal')
  243. })
  244. })
  245. describe('dispatch (menu column)', () => {
  246. it('contribution → opens the session popup with the open-time projection, no execute', async () => {
  247. const { command, source, mint, warm, executeCalls } = await bench()
  248. const options = vi.fn((_s: ClientSessionContext) => Promise.resolve([{ id: 'dark', label: 'Dark' }]))
  249. command.register(themeContribution({ ui: themeUi({ options }) }))
  250. const scope = mint('s1')
  251. await warm(proj('s1'))
  252. expect(menuPick(source, 'theme', proj('s1'))).toBe('handled')
  253. const popup = command.popupFor(scope.ctx)
  254. expect(popup.state.getSnapshot()).toMatchObject({ open: true, command: 'theme' })
  255. expect(options).toHaveBeenCalledExactlyOnceWith(proj('s1'), expect.any(AbortSignal))
  256. expect(executeCalls).toEqual([])
  257. })
  258. it('an unavailable contribution falls through to the host catalog', async () => {
  259. const { command, source, mint, warm } = await bench()
  260. command.register(themeContribution({ available: () => false }))
  261. const scope = mint('s1')
  262. await warm(proj('s1'))
  263. expect(menuPick(source, 'theme', proj('s1'))).toBeUndefined() // no host 'theme' either
  264. expect(command.popupFor(scope.ctx).state.getSnapshot().open).toBe(false)
  265. })
  266. it('host leadingInput → {claim} with token "/name " and hint; claiming never executes', async () => {
  267. const { source, warm, executeCalls } = await bench()
  268. await warm(proj('s1'))
  269. const outcome = menuPick(source, 'goal', proj('s1'))
  270. if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected claim')
  271. expect(outcome.claim.token).toBe('/goal ')
  272. expect(outcome.claim.hint).toBe('goal text')
  273. expect(executeCalls).toEqual([])
  274. })
  275. it('host bare → consume-token span guard on the session scope + detached execute', async () => {
  276. const { source, mint, warm, executeCalls } = await bench()
  277. const scope = mint('s1')
  278. const consumes: ConsumeTokenRequest[] = []
  279. scope.ctx.on('slash/input-consume-token', (r) => {
  280. consumes.push(r)
  281. return true
  282. })
  283. await warm(proj('s1'))
  284. expect(menuPick(source, 'plan', proj('s1'), 5)).toBe('handled')
  285. expect(consumes).toEqual([{ guard: { kind: 'span', span: { start: 0, end: 5, draftRev: 3 } } }])
  286. await Promise.resolve()
  287. expect(executeCalls).toEqual([{ sessionId: sid('s1'), line: '/plan' }])
  288. })
  289. it('a name the directory no longer serves → undefined (snapshot swapped between menu and pick)', async () => {
  290. const { source, warm } = await bench()
  291. await warm(proj('s1'))
  292. expect(menuPick(source, 'gone', proj('s1'))).toBeUndefined()
  293. })
  294. })
  295. describe('matchSpace (space column)', () => {
  296. it('answers undefined from a not-ready key (no waiting, no RPC)', async () => {
  297. const { source, listCalls } = await bench()
  298. expect(source.matchSpace!(proj('s1'), '/goal')).toBeUndefined()
  299. expect(listCalls).toEqual([])
  300. })
  301. it('hot leadingInput exact token → {claim}; the key axis is the session', async () => {
  302. const { source, warm } = await bench()
  303. await warm(proj('s2'))
  304. const outcome = source.matchSpace!(proj('s2'), '/attach')
  305. if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected claim')
  306. expect(outcome.claim.token).toBe('/attach ')
  307. // s1's key is still cold: the same token answers undefined there.
  308. expect(source.matchSpace!(proj('s1'), '/attach')).toBeUndefined()
  309. })
  310. it('bare kind and contribution names stay plain text', async () => {
  311. const { command, source, warm } = await bench()
  312. command.register(themeContribution())
  313. await warm(proj('s1'))
  314. expect(source.matchSpace!(proj('s1'), '/plan')).toBeUndefined()
  315. expect(source.matchSpace!(proj('s1'), '/theme')).toBeUndefined()
  316. })
  317. it('unknown token / non-slash token → undefined', async () => {
  318. const { source, warm } = await bench()
  319. await warm(proj('s1'))
  320. expect(source.matchSpace!(proj('s1'), '/nope')).toBeUndefined()
  321. expect(source.matchSpace!(proj('s1'), 'plan')).toBeUndefined()
  322. })
  323. })
  324. describe('matchEnter (enter column)', () => {
  325. const signal = () => new AbortController().signal
  326. it('strong-waits a cold key before adjudicating', async () => {
  327. let release!: (value: { commands: CommandDescriptor[] }) => void
  328. const { source } = await bench({
  329. commands: () => new Promise((resolve) => { release = resolve }),
  330. })
  331. const wait = source.matchEnter!(proj('s1'), '/goal args', signal())
  332. release({ commands: S1_CMDS })
  333. const outcome = await wait
  334. if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected claim')
  335. expect(outcome.claim.token).toBe('/goal ')
  336. })
  337. it('rejects when warmup fails (never a silent downgrade)', async () => {
  338. const { source } = await bench({
  339. commands: () => Promise.reject(new Error('warmup boom')),
  340. })
  341. await expect(source.matchEnter!(proj('s1'), '/goal', signal())).rejects.toThrow('warmup boom')
  342. })
  343. it('leadingInput claims args-tolerant (bare and with trailing text)', async () => {
  344. const { source, warm } = await bench()
  345. await warm(proj('s1'))
  346. for (const line of ['/goal', '/goal refactor the loop']) {
  347. const outcome = await source.matchEnter!(proj('s1'), line, signal())
  348. if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected claim')
  349. expect(outcome.claim.token).toBe('/goal ')
  350. }
  351. })
  352. it('bare host command executes detached with the bare-token consume guard', async () => {
  353. const { source, mint, warm, executeCalls } = await bench()
  354. const scope = mint('s1')
  355. const consumes: ConsumeTokenRequest[] = []
  356. scope.ctx.on('slash/input-consume-token', (r) => {
  357. consumes.push(r)
  358. return true
  359. })
  360. await warm(proj('s1'))
  361. await expect(source.matchEnter!(proj('s1'), '/plan', signal())).resolves.toBe('handled')
  362. expect(consumes).toEqual([{ guard: { kind: 'bare-token', token: '/plan' } }])
  363. await Promise.resolve()
  364. expect(executeCalls).toEqual([{ sessionId: sid('s1'), line: '/plan' }])
  365. })
  366. it('bare kind with trailing text → undefined and no RPC (default sink owns the line)', async () => {
  367. const { source, warm, executeCalls } = await bench()
  368. await warm(proj('s1'))
  369. await expect(source.matchEnter!(proj('s1'), '/plan now', signal())).resolves.toBeUndefined()
  370. expect(executeCalls).toEqual([])
  371. })
  372. it('contribution: bare token opens the popup without touching the directory; args → undefined', async () => {
  373. const { command, source, mint, listCalls } = await bench()
  374. command.register(themeContribution())
  375. const scope = mint('s1')
  376. await expect(source.matchEnter!(proj('s1'), '/theme', signal())).resolves.toBe('handled')
  377. expect(command.popupFor(scope.ctx).state.getSnapshot().open).toBe(true)
  378. expect(listCalls).toEqual([]) // contribution short-circuits ahead of ensureReady
  379. await expect(source.matchEnter!(proj('s1'), '/theme dark', signal())).resolves.toBeUndefined()
  380. })
  381. it('unknown name, bare "/", and non-slash lines → undefined', async () => {
  382. const { source, warm } = await bench()
  383. await warm(proj('s1'))
  384. await expect(source.matchEnter!(proj('s1'), '/nope', signal())).resolves.toBeUndefined()
  385. await expect(source.matchEnter!(proj('s1'), '/', signal())).resolves.toBeUndefined()
  386. await expect(source.matchEnter!(proj('s1'), 'plain text', signal())).resolves.toBeUndefined()
  387. })
  388. })
  389. describe('execute payload', () => {
  390. it('claim.submit addresses the session; admitted outcomes stay off the composer (flow card owns them)', async () => {
  391. const { source, warm, executeCalls } = await bench({
  392. execute: () => Promise.resolve({ matched: true }),
  393. })
  394. await warm(proj('s1'))
  395. const outcome = source.matchSpace!(proj('s1'), '/goal')
  396. if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected claim')
  397. const settled = await outcome.claim.submit('ship it', new Context())
  398. expect(executeCalls).toEqual([{ sessionId: sid('s1'), line: '/goal ship it' }])
  399. // Pure admission: no outcome text ever rides the submit result — the
  400. // durable command lifecycle events render the outcome in the flow.
  401. expect(settled).toEqual({ kind: 'success' })
  402. })
  403. it('maps matched:false to an error outcome and a matched bare result to success', async () => {
  404. const claimOf = async (opts: BenchOptions) => {
  405. const b = await bench(opts)
  406. await b.warm(proj('s1'))
  407. const outcome = b.source.matchSpace!(proj('s1'), '/goal')
  408. if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected claim')
  409. return outcome.claim
  410. }
  411. const first = await claimOf({ execute: () => Promise.resolve({ matched: false }) })
  412. const bad = await first.submit('x', new Context())
  413. expect(bad.kind).toBe('error')
  414. const second = await claimOf({ execute: () => Promise.resolve({ matched: true }) })
  415. await expect(second.submit('', new Context())).resolves.toEqual({ kind: 'success' })
  416. })
  417. })
  418. describe('detached admission notices', () => {
  419. const flush = () => new Promise(resolve => setTimeout(resolve, 0))
  420. it('admitted outcomes stay silent; admission miss and transport rejection notice as errors', async () => {
  421. let mode: 'admitted' | 'miss' | 'reject' = 'admitted'
  422. const { source, mint, warm, notices } = await bench({
  423. execute: () => {
  424. if (mode === 'reject') return Promise.reject(new Error('network down'))
  425. return Promise.resolve({ matched: mode === 'admitted' })
  426. },
  427. })
  428. mint('s1')
  429. await warm(proj('s1'))
  430. // Admitted: the durable lifecycle events own the outcome — no notice.
  431. menuPick(source, 'plan', proj('s1'))
  432. await flush()
  433. expect(notices).toEqual([])
  434. // Admission miss (matched:false): immediate composer feedback stays.
  435. mode = 'miss'
  436. await source.matchEnter!(proj('s1'), '/plan', new AbortController().signal)
  437. await flush()
  438. expect(notices).toEqual([{ scope: sid('s1'), level: 'error', text: 'unknown or malformed command: /plan' }])
  439. notices.length = 0
  440. mode = 'reject'
  441. menuPick(source, 'plan', proj('s1'))
  442. await flush()
  443. expect(notices).toEqual([{ scope: sid('s1'), level: 'error', text: 'network down' }])
  444. })
  445. it('a torn-down scope drops the failure notice', async () => {
  446. const { source, warm, notices } = await bench({
  447. execute: () => Promise.reject(new Error('orphan failure')),
  448. })
  449. await warm(proj('ghost')) // never minted: scopeFor misses
  450. menuPick(source, 'plan', proj('ghost'))
  451. await flush()
  452. expect(notices).toEqual([])
  453. })
  454. })
  455. describe('register (contribution face)', () => {
  456. it('duplicate registration throws; the disposer frees the name', async () => {
  457. const { command } = await bench()
  458. const dispose = command.register(themeContribution())
  459. expect(() => command.register(themeContribution())).toThrow('duplicate contribution')
  460. dispose()
  461. command.register(themeContribution())()
  462. })
  463. })
  464. describe('popupFor', () => {
  465. it('resolves lazily per session; a foreign session gets its own controller; unscoped ctx throws', async () => {
  466. const { ctx, command, mint } = await bench()
  467. const a = mint('s1')
  468. const first = command.popupFor(a.ctx)
  469. expect(command.popupFor(a.ctx)).toBe(first)
  470. expect(command.popupFor(mint('s2').ctx)).not.toBe(first)
  471. expect(() => command.popupFor(ctx)).toThrow('requires a session scope')
  472. })
  473. it('a successful select dispatches the scoped consume-token and fires the bound composer focus', async () => {
  474. const { command, source, mint } = await bench()
  475. const onSelect = vi.fn()
  476. command.register(themeContribution({ ui: themeUi({ onSelect }) }))
  477. const scope = mint('s1')
  478. const consumes: ConsumeTokenRequest[] = []
  479. scope.ctx.on('slash/input-consume-token', (r) => {
  480. consumes.push(r)
  481. return true
  482. })
  483. const focus = vi.fn()
  484. command.bindComposerFocus(sid('s1'), focus)
  485. expect(menuPick(source, 'theme', proj('s1'), 6)).toBe('handled')
  486. const popup = command.popupFor(scope.ctx)
  487. await Promise.resolve() // options land
  488. await popup.select(0)
  489. expect(onSelect).toHaveBeenCalledExactlyOnceWith({ id: 'dark', label: 'Dark' } satisfies SelectOption, proj('s1'))
  490. expect(consumes).toEqual([{ guard: { kind: 'span', span: { start: 0, end: 6, draftRev: 3 } } }])
  491. expect(focus).toHaveBeenCalledTimes(1)
  492. })
  493. it('the enter path opens with the bare-token guard', async () => {
  494. const { command, source, mint } = await bench()
  495. command.register(themeContribution())
  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. await source.matchEnter!(proj('s1'), '/theme', new AbortController().signal)
  503. const popup = command.popupFor(scope.ctx)
  504. await Promise.resolve()
  505. await popup.select(0)
  506. expect(consumes).toEqual([{ guard: { kind: 'bare-token', token: '/theme' } }])
  507. })
  508. it('the scope disposer disposes the controller and a re-mint resolves fresh', async () => {
  509. const { command, source, mint } = await bench()
  510. command.register(themeContribution())
  511. const scope = mint('s1')
  512. await source.matchEnter!(proj('s1'), '/theme', new AbortController().signal)
  513. const popup = command.popupFor(scope.ctx)
  514. expect(popup.state.getSnapshot().open).toBe(true)
  515. await scope.fiber.dispose()
  516. expect(popup.state.getSnapshot().open).toBe(false)
  517. expect(command.popupFor(mint('s1').ctx)).not.toBe(popup)
  518. })
  519. })
  520. describe('directory invalidation events', () => {
  521. it('commands/changed repulls in the background while the old snapshot serves', async () => {
  522. let round = 0
  523. const { ctx, source, warm } = await bench({
  524. commands: () => {
  525. round += 1
  526. return Promise.resolve({
  527. commands: round === 1
  528. ? S1_CMDS
  529. : [{ name: 'fresh', description: '', input: { hint: 'h' } }],
  530. })
  531. },
  532. })
  533. await warm(proj('s1'))
  534. ctx.emit('commands/changed')
  535. await new Promise(resolve => setTimeout(resolve, 0))
  536. expect(source.matchSpace!(proj('s1'), '/fresh')).not.toBeUndefined()
  537. expect(source.matchSpace!(proj('s1'), '/goal')).toBeUndefined()
  538. })
  539. it('connection/reset hard-drops every session key until its rewarm lands', async () => {
  540. let block = false
  541. let release!: (value: { commands: CommandDescriptor[] }) => void
  542. const { ctx, source, warm } = await bench({
  543. commands: () => (block
  544. ? new Promise((resolve) => { release = resolve })
  545. : Promise.resolve({ commands: S2_CMDS })),
  546. })
  547. await warm(proj('s2'))
  548. expect(source.matchSpace!(proj('s2'), '/attach')).not.toBeUndefined()
  549. block = true
  550. ctx.emit('connection/reset')
  551. // Hard reset: silent until the rewarm lands.
  552. expect(source.matchSpace!(proj('s2'), '/attach')).toBeUndefined()
  553. release({ commands: S2_CMDS })
  554. await new Promise(resolve => setTimeout(resolve, 0))
  555. expect(source.matchSpace!(proj('s2'), '/attach')).not.toBeUndefined()
  556. })
  557. })