service.spec.ts 26 KB

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