sessions-service.spec.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. /**
  2. * SessionsService: list store projection (manager → {ids, byId, current}
  3. * with derived titles), the migrated current-selection account (open
  4. * validation, persisted mask semantics, cell resolution), scope-tree
  5. * lifecycle (lazy mint / frozen survival / removed teardown with staged
  6. * deferral — the stage follows list.current), binding identity, ancestry
  7. * walk, create.
  8. */
  9. import { Context } from 'cordis'
  10. import { afterEach, describe, expect, it, vi } from 'vitest'
  11. import type { SessionId } from '@deepseek-ai/dsh-client-connection/client'
  12. import { SessionCreateError, SessionsService, scopeOf } from '../src/client/sessions/service.ts'
  13. import { FakeApiClient, deferred, ok } from './fake-api.ts'
  14. const sid = (s: string): SessionId => s as SessionId
  15. interface Bench {
  16. ctx: Context
  17. api: FakeApiClient
  18. svc: SessionsService
  19. }
  20. function bench(): Bench {
  21. const ctx = new Context()
  22. const api = new FakeApiClient()
  23. const svc = new SessionsService(ctx, api)
  24. return { ctx, api, svc }
  25. }
  26. /** Refresh the manager list from programmable rows and flush the microtask batch. */
  27. type FeedRow = { id: string; cwd?: string; parentId?: string; running?: boolean; blank?: boolean }
  28. async function feedList(b: Bench, rows: FeedRow[]): Promise<void> {
  29. b.api.onList = () => Promise.resolve(ok({
  30. items: rows.map(r => ({
  31. sessionId: sid(r.id), updatedAt: 1, running: r.running ?? false, blank: r.blank ?? false,
  32. ...(r.cwd !== undefined ? { cwd: r.cwd } : {}),
  33. ...(r.parentId !== undefined ? { parentSessionId: sid(r.parentId) } : {}),
  34. })),
  35. }) as never)
  36. await b.svc.refresh()
  37. await Promise.resolve() // manager notifier flush
  38. }
  39. describe('list store projection', () => {
  40. it('projects durable titles separately from cwd/id display fallbacks and parent links', async () => {
  41. const b = bench()
  42. b.svc.handleMuxEnvelope({
  43. rpcId: 'title' as never,
  44. payload: { type: 'session/projection', sessionId: sid('s1'), key: 'title', value: 'Durable title', seq: 2 } as never,
  45. })
  46. await feedList(b, [
  47. { id: 's1', cwd: '/home/u/proj-a/' },
  48. { id: 's2', parentId: 's1', running: true },
  49. ])
  50. const state = b.svc.list.getSnapshot()
  51. expect(state.ids).toEqual(['s1', 's2'])
  52. expect(state.byId[sid('s1')]).toMatchObject({ title: 'Durable title', displayTitle: 'Durable title', cwd: '/home/u/proj-a/' })
  53. expect(state.byId[sid('s2')]).toMatchObject({ displayTitle: 's2', parentId: 's1', running: true })
  54. expect(state.byId[sid('s2')]?.title).toBeUndefined()
  55. })
  56. it('reflects live increments (host stream via manager) into the store', async () => {
  57. const b = bench()
  58. await feedList(b, [{ id: 's1' }])
  59. b.svc.handleHostEnvelope({ rpcId: 'r1' as never, payload: { type: 'host/session-added', blank: true, sessionId: sid('s2') } as never })
  60. await Promise.resolve()
  61. expect(b.svc.list.getSnapshot().ids).toContain('s2')
  62. })
  63. })
  64. describe('scope tree', () => {
  65. it('mints lazily on first resolution, tags the ctx, and keeps binding identity stable', async () => {
  66. const b = bench()
  67. await feedList(b, [{ id: 's1' }])
  68. expect(b.svc.scope(sid('unknown'))).toBeUndefined()
  69. const scoped = b.svc.scope(sid('s1'))
  70. expect(scoped).toBeDefined()
  71. expect(scopeOf(scoped as Context)).toBe('s1')
  72. expect(scopeOf(b.ctx)).toBeUndefined()
  73. const binding = b.svc.binding(sid('s1'))
  74. b.svc.open(sid('s1'))
  75. expect(binding?.session).toBe(b.svc.currentProvideInfo.getSnapshot().hooks['session'])
  76. expect(b.svc.binding(sid('s1'))).toBe(binding)
  77. expect(binding?.ctx).toBe(scoped)
  78. })
  79. it('tears down an off-stage removed session but defers the staged one until the stage moves', async () => {
  80. const b = bench()
  81. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  82. const ctx1 = b.svc.scope(sid('s1'))
  83. b.svc.open(sid('s1')) // s1 staged (current)
  84. b.svc.scope(sid('s2')) // s2 scoped but off stage
  85. await feedList(b, [{ id: 's1' }]) // s2 removed, off stage: torn down
  86. expect(b.svc.scope(sid('s2'))).toBeUndefined()
  87. await feedList(b, []) // s1 removed while staged (current masks): deferred, scope survives
  88. expect(b.svc.scope(sid('s1'))).toBe(ctx1)
  89. await feedList(b, [{ id: 's3' }])
  90. b.svc.open(sid('s3')) // stage moves: deferred teardown sweeps s1
  91. expect(b.svc.scope(sid('s1'))).toBeUndefined()
  92. })
  93. it('keeps the scope when the session merely stops running (frozen ≠ removed)', async () => {
  94. const b = bench()
  95. await feedList(b, [{ id: 's1', running: true }])
  96. const scoped = b.svc.scope(sid('s1'))
  97. await feedList(b, [{ id: 's1', running: false }])
  98. expect(b.svc.scope(sid('s1'))).toBe(scoped)
  99. })
  100. it('cancels a deferred teardown when the id reappears in the list', async () => {
  101. const b = bench()
  102. await feedList(b, [{ id: 's1' }])
  103. const scoped = b.svc.scope(sid('s1'))
  104. b.svc.open(sid('s1'))
  105. await feedList(b, []) // removed while staged → deferred
  106. await feedList(b, [{ id: 's1' }, { id: 's2' }]) // reappears (current resurfaces, stage unchanged)
  107. b.svc.open(sid('s2')) // stage moves; sweep must NOT tear down the re-listed s1
  108. expect(b.svc.scope(sid('s1'))).toBe(scoped)
  109. })
  110. })
  111. describe('current selection (migrated from ui-layout, arbitrated into the list snapshot)', () => {
  112. afterEach(() => { vi.unstubAllGlobals() })
  113. it('open() writes list.current; unknown ids fail loud', async () => {
  114. const b = bench()
  115. await feedList(b, [{ id: 's1' }])
  116. expect(b.svc.list.getSnapshot().current).toBeUndefined()
  117. b.svc.open(sid('s1'))
  118. expect(b.svc.list.getSnapshot().current).toBe('s1')
  119. expect(() => { b.svc.open(sid('ghost')) }).toThrow(/unknown session ghost/)
  120. expect(b.svc.list.getSnapshot().current).toBe('s1') // failed open leaves the selection alone
  121. })
  122. it('clear() blanks list.current and the persisted selection', async () => {
  123. const storage = new Map<string, string>()
  124. vi.stubGlobal('localStorage', {
  125. getItem: (k: string) => storage.get(k) ?? null,
  126. setItem: (k: string, v: string) => { storage.set(k, v) },
  127. removeItem: (k: string) => { storage.delete(k) },
  128. clear: () => { storage.clear() },
  129. })
  130. const b = bench()
  131. await feedList(b, [{ id: 's1' }])
  132. b.svc.open(sid('s1'))
  133. expect(storage.get('dsh.sessions.current')).toContain('s1')
  134. b.svc.clear()
  135. expect(b.svc.list.getSnapshot().current).toBeUndefined()
  136. // Persisted wipe: a fresh service with the same storage stays on empty.
  137. const again = bench()
  138. await feedList(again, [{ id: 's1' }])
  139. expect(again.svc.list.getSnapshot().current).toBeUndefined()
  140. })
  141. it('masks (not destroys) the selection while its session is off the list', async () => {
  142. const b = bench()
  143. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  144. b.svc.open(sid('s1'))
  145. await feedList(b, [{ id: 's2' }]) // s1 removed → current falls to the empty state
  146. expect(b.svc.list.getSnapshot().current).toBeUndefined()
  147. await feedList(b, [{ id: 's1' }, { id: 's2' }]) // s1 returns → selection resurfaces
  148. expect(b.svc.list.getSnapshot().current).toBe('s1')
  149. })
  150. it('persists the selection under dsh.sessions.current and rehydrates it into a fresh service', async () => {
  151. const storage = new Map<string, string>()
  152. vi.stubGlobal('localStorage', {
  153. getItem: (k: string) => storage.get(k) ?? null,
  154. setItem: (k: string, v: string) => { storage.set(k, v) },
  155. })
  156. const first = bench()
  157. await feedList(first, [{ id: 's1' }])
  158. first.svc.open(sid('s1'))
  159. expect(storage.get('dsh.sessions.current')).toContain('s1')
  160. // A fresh boot (same storage) recovers the selection once the list holds the session.
  161. const second = bench()
  162. await feedList(second, [{ id: 's1' }])
  163. expect(second.svc.list.getSnapshot().current).toBe('s1')
  164. })
  165. })
  166. describe('cell (render-layer session kit)', () => {
  167. it('resolves an identity-stable {sessionId, session} cell through the current projection', async () => {
  168. const b = bench()
  169. await feedList(b, [{ id: 's1' }])
  170. b.svc.open(sid('s1'))
  171. const info = b.svc.currentProvideInfo.getSnapshot()
  172. expect(info.sessionId).toBe('s1')
  173. // The bundle carries bare observables; hook binding happens in React.
  174. expect(info.hooks['session']).toBe(b.svc.binding(sid('s1'))?.session)
  175. // Re-staging the same id republishes nothing: identity holds.
  176. b.svc.open(sid('s1'))
  177. expect(b.svc.currentProvideInfo.getSnapshot()).toBe(info)
  178. })
  179. it('currentProvideInfo follows selection: absent projection ↔ definite bundle, notified on each move', async () => {
  180. const b = bench()
  181. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  182. const absent = b.svc.currentProvideInfo.getSnapshot()
  183. expect(absent.sessionId).toBeUndefined()
  184. expect(Object.hasOwn(absent.hooks, 'session')).toBe(true)
  185. const notified = vi.fn()
  186. b.svc.currentProvideInfo.subscribe(notified)
  187. b.svc.open(sid('s1'))
  188. const s1Bundle = b.svc.currentProvideInfo.getSnapshot()
  189. expect(s1Bundle.sessionId).toBe('s1')
  190. expect(s1Bundle.hooks['session']).toBe(b.svc.binding(sid('s1'))?.session)
  191. expect(notified).toHaveBeenCalledTimes(1)
  192. b.svc.open(sid('s2'))
  193. const s2Bundle = b.svc.currentProvideInfo.getSnapshot()
  194. expect(s2Bundle.sessionId).toBe('s2')
  195. expect(s2Bundle).not.toBe(s1Bundle)
  196. expect(notified).toHaveBeenCalledTimes(2)
  197. b.svc.clear()
  198. await Promise.resolve() // clearSelection projects through the manager notifier
  199. expect(b.svc.currentProvideInfo.getSnapshot().sessionId).toBeUndefined()
  200. })
  201. it('a provider roster change under a stable current id republishes the bundle', async () => {
  202. const b = bench()
  203. await feedList(b, [{ id: 's1' }])
  204. b.svc.open(sid('s1'))
  205. const before = b.svc.currentProvideInfo.getSnapshot()
  206. const notified = vi.fn()
  207. b.svc.currentProvideInfo.subscribe(notified)
  208. const source = { getSnapshot: () => 'live', subscribe: () => () => {} }
  209. const dispose = b.svc.provide({
  210. hooks: ['extra'],
  211. props: ['marker'],
  212. resolve: () => ({ hooks: { extra: source }, props: { marker: 7 } }),
  213. })
  214. const added = b.svc.currentProvideInfo.getSnapshot()
  215. expect(added).not.toBe(before)
  216. expect(added).toMatchObject({ sessionId: 's1', props: { marker: 7 } })
  217. expect(added.hooks['extra']).toBe(source)
  218. expect(notified).toHaveBeenCalledTimes(1)
  219. dispose()
  220. const removed = b.svc.currentProvideInfo.getSnapshot()
  221. expect(removed).not.toBe(added)
  222. expect(Object.hasOwn(removed.hooks, 'extra')).toBe(false)
  223. expect(notified).toHaveBeenCalledTimes(2)
  224. })
  225. it('an unsubscribed currentProvideInfo listener stops receiving notifications', async () => {
  226. const b = bench()
  227. await feedList(b, [{ id: 's1' }])
  228. const notified = vi.fn()
  229. const off = b.svc.currentProvideInfo.subscribe(notified)
  230. off()
  231. b.svc.open(sid('s1'))
  232. expect(notified).not.toHaveBeenCalled()
  233. })
  234. it('binding() is pure resolution: no staging, no deferred sweep', async () => {
  235. const b = bench()
  236. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  237. b.svc.open(sid('s1')) // staged
  238. b.svc.binding(sid('s2')) // resolution only — must NOT move the stage
  239. await feedList(b, [{ id: 's2' }]) // s1 removed: still staged → deferred, scope survives
  240. expect(b.svc.scope(sid('s1'))).toBeDefined()
  241. })
  242. it('staging (current write) opens the session event window; resolution and re-staging do not re-pull', async () => {
  243. const b = bench()
  244. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  245. const historyCalls = () => b.api.calls.filter(c => c.method === 'session.history')
  246. // Resolution is addressing, not staging: no window pull.
  247. b.svc.scope(sid('s1'))
  248. b.svc.binding(sid('s1'))
  249. expect(historyCalls()).toHaveLength(0)
  250. b.svc.open(sid('s1'))
  251. expect(historyCalls().map(c => (c.payload as { sessionId: string }).sessionId)).toEqual(['s1'])
  252. // Same current again: no second pull.
  253. b.svc.open(sid('s1'))
  254. expect(historyCalls()).toHaveLength(1)
  255. // Stage moves: the new occupant opens.
  256. b.svc.open(sid('s2'))
  257. expect(historyCalls().map(c => (c.payload as { sessionId: string }).sessionId)).toEqual(['s1', 's2'])
  258. })
  259. it('startup restore: a persisted selection validated by the first projection opens its window unprompted', async () => {
  260. const storage = new Map<string, string>([
  261. ['dsh.sessions.current', JSON.stringify({ sessionId: 's1' })],
  262. ])
  263. vi.stubGlobal('localStorage', {
  264. getItem: (k: string) => storage.get(k) ?? null,
  265. setItem: (k: string, v: string) => { storage.set(k, v) },
  266. })
  267. try {
  268. const b = bench()
  269. expect(b.api.calls.filter(c => c.method === 'session.history')).toHaveLength(0)
  270. await feedList(b, [{ id: 's1' }]) // projection validates the persisted id → current lands → stage follows
  271. const historyCalls = b.api.calls.filter(c => c.method === 'session.history')
  272. expect(historyCalls.map(c => (c.payload as { sessionId: string }).sessionId)).toEqual(['s1'])
  273. } finally {
  274. vi.unstubAllGlobals()
  275. }
  276. })
  277. })
  278. describe('slot-store scope prune hook', () => {
  279. it('notifies ctx.slots.pruneStoreScope when a scope dies (both teardown paths)', async () => {
  280. const b = bench()
  281. const pruneStoreScope = vi.fn()
  282. b.ctx.reflect.provide('slots', { pruneStoreScope })
  283. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  284. b.svc.scope(sid('s1'))
  285. b.svc.scope(sid('s2'))
  286. b.svc.open(sid('s2')) // s2 staged
  287. await feedList(b, []) // s1 off stage → immediate drop; s2 staged → deferred
  288. expect(pruneStoreScope).toHaveBeenCalledWith('s1')
  289. expect(pruneStoreScope).not.toHaveBeenCalledWith('s2')
  290. await feedList(b, [{ id: 's3' }])
  291. b.svc.open(sid('s3')) // stage moves → deferred sweep drops s2
  292. expect(pruneStoreScope).toHaveBeenCalledWith('s2')
  293. })
  294. it('tolerates a slots-less boot (object-layer benches carry no slot service)', async () => {
  295. const b = bench()
  296. await feedList(b, [{ id: 's1' }])
  297. b.svc.scope(sid('s1'))
  298. await feedList(b, []) // teardown without ctx.slots must not throw
  299. expect(b.svc.scope(sid('s1'))).toBeUndefined()
  300. })
  301. })
  302. describe('ancestry', () => {
  303. it('walks parentId links root-first including self; broken links stop the walk', async () => {
  304. const b = bench()
  305. await feedList(b, [
  306. { id: 'root', cwd: '/w/app' },
  307. { id: 'mid', parentId: 'root' },
  308. { id: 'leaf', parentId: 'mid' },
  309. { id: 'orphan', parentId: 'ghost' },
  310. ])
  311. expect(b.svc.ancestry(sid('leaf')).map(s => s.id)).toEqual(['root', 'mid', 'leaf'])
  312. expect(b.svc.ancestry(sid('orphan')).map(s => s.id)).toEqual(['orphan'])
  313. expect(b.svc.ancestry(sid('ghost'))).toEqual([])
  314. })
  315. })
  316. describe('create', () => {
  317. it('passes a preallocated id and preserves it on ordinary failure', async () => {
  318. const b = bench()
  319. b.api.onCreate = () => Promise.resolve(ok({ sessionId: sid('fresh') }))
  320. await expect(b.svc.create({ cwd: '/w', sessionId: sid('fresh') })).resolves.toBe('fresh')
  321. expect(b.api.callsOf('session.create')).toEqual([{ cwd: '/w', sessionId: 'fresh' }])
  322. b.api.onCreate = () => Promise.resolve({
  323. rpcId: 'e' as never,
  324. result: { ok: false as const, error: { code: 'internal' as const, message: '爆了', details: {} } },
  325. } as never)
  326. const failure = await b.svc.create({ sessionId: sid('candidate') }).catch((error: unknown) => error)
  327. expect(failure).toBeInstanceOf(SessionCreateError)
  328. expect(failure).toMatchObject({
  329. requestedSessionId: 'candidate',
  330. rpcError: { code: 'internal', message: '爆了' },
  331. })
  332. })
  333. it('resolves with the session already listed and binding-resolvable (no flush wait)', async () => {
  334. const b = bench()
  335. b.api.onCreate = () => Promise.resolve(ok({ sessionId: sid('born') }))
  336. const born = await b.svc.create({ workspaceId: 'ws' as never })
  337. // Synchronously after resolution — the draft hand-off contract: the
  338. // create echo IS the entity entering the client's view (blank row +
  339. // resolvable scope/binding), no notifier flush in between.
  340. expect(b.svc.list.getSnapshot().byId[born]).toMatchObject({ id: 'born', blank: true })
  341. expect(b.svc.binding(born)).toBeDefined()
  342. expect(b.svc.scope(born)).toBeDefined()
  343. })
  344. it('lists the published id after Workspace attachment fails (publication precedes attachment)', async () => {
  345. const b = bench()
  346. b.api.onCreate = () => Promise.resolve({
  347. rpcId: 'attach' as never,
  348. result: {
  349. ok: false,
  350. error: {
  351. code: 'workspace-attach-failed', message: 'ledger unavailable',
  352. details: { sessionId: sid('published'), workspaceId: 'ws' },
  353. },
  354. },
  355. } as never)
  356. const failure = await b.svc.create({
  357. workspaceId: 'ws' as never,
  358. sessionId: sid('published'),
  359. }).catch((error: unknown) => error)
  360. await Promise.resolve()
  361. expect(failure).toBeInstanceOf(SessionCreateError)
  362. expect(failure).toMatchObject({
  363. requestedSessionId: 'published',
  364. rpcError: { code: 'workspace-attach-failed' },
  365. })
  366. expect(b.svc.list.getSnapshot().byId[sid('published')]).toMatchObject({ id: 'published', blank: true })
  367. })
  368. })
  369. describe('scope lifecycle rides the list mirror (entity parity: no client-side pre-birth)', () => {
  370. it('a session-added frame births the row (blank) and makes the scope resolvable; removal prunes it', async () => {
  371. const b = bench()
  372. await feedList(b, [])
  373. expect(b.svc.scope(sid('s-new'))).toBeUndefined() // not in view: no scope, no exceptions
  374. b.svc.handleHostEnvelope({
  375. rpcId: 'add' as never,
  376. payload: { type: 'host/session-added', sessionId: sid('s-new'), blank: true, cwd: '/w/a' } as never,
  377. })
  378. await Promise.resolve()
  379. const scoped = b.svc.scope(sid('s-new'))
  380. expect(scoped).toBeDefined()
  381. expect(scopeOf(scoped as Context)).toBe('s-new')
  382. b.svc.handleHostEnvelope({
  383. rpcId: 'rm' as never,
  384. payload: { type: 'host/session-removed', sessionId: sid('s-new') },
  385. })
  386. await Promise.resolve()
  387. expect(b.svc.scope(sid('s-new'))).toBeUndefined()
  388. })
  389. })
  390. describe('blank mirror', () => {
  391. it('flips blank=false from the running:true status frame (cross-client conversion)', async () => {
  392. const b = bench()
  393. await feedList(b, [{ id: 's1', blank: true }])
  394. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: true })
  395. b.svc.handleHostEnvelope({
  396. rpcId: 'st' as never,
  397. payload: { type: 'host/session-status', sessionId: sid('s1'), running: true },
  398. })
  399. await Promise.resolve()
  400. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: false, running: true })
  401. // The instantiated Session mirrors the same flip.
  402. expect(b.svc.binding(sid('s1'))?.session.getSnapshot().blank).toBe(false)
  403. })
  404. it('flips blank=false on prompt ACCEPTANCE, not on the attempt', async () => {
  405. const b = bench()
  406. await feedList(b, [{ id: 's1', blank: true, cwd: '/w/a' }])
  407. const session = b.svc.binding(sid('s1'))!.session
  408. expect(session.getSnapshot().blank).toBe(true)
  409. const gate = deferred<Awaited<ReturnType<FakeApiClient['onPrompt']>>>()
  410. b.api.onPrompt = () => gate.promise
  411. const send = session.prompt([{ type: 'text', text: 'hi' }], 'queue')
  412. // In flight: still blank (the flip point is the success response, which
  413. // proves the user message reached the host log).
  414. expect(session.getSnapshot().blank).toBe(true)
  415. gate.resolve(ok({ accepted: true as const }))
  416. await send
  417. expect(session.getSnapshot().blank).toBe(false)
  418. await Promise.resolve()
  419. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: false })
  420. })
  421. it('keeps a rejected first prompt blank: hidden and still reusable', async () => {
  422. const b = bench()
  423. await feedList(b, [{ id: 's1', blank: true, cwd: '/w/a' }])
  424. const session = b.svc.binding(sid('s1'))!.session
  425. b.api.onPrompt = () => Promise.resolve({
  426. rpcId: 'busy' as never,
  427. result: { ok: false as const, error: { code: 'internal' as const, message: 'agent busy', details: {} } },
  428. } as never)
  429. const result = await session.prompt([{ type: 'text', text: 'hi' }], 'queue')
  430. expect(result.ok).toBe(false)
  431. // No flip on failure: local stays aligned with the host authority
  432. // (events.length still 0), so the session stays hidden and reusable.
  433. expect(session.getSnapshot().blank).toBe(true)
  434. await Promise.resolve()
  435. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: true })
  436. })
  437. it('takes session-added blank=true as the hidden birth and list blank as reconnect authority', async () => {
  438. const b = bench()
  439. await feedList(b, [])
  440. b.svc.handleHostEnvelope({
  441. rpcId: 'add' as never,
  442. payload: { type: 'host/session-added', sessionId: sid('s-new'), blank: true, cwd: '/w/a' } as never,
  443. })
  444. await Promise.resolve()
  445. expect(b.svc.list.getSnapshot().byId[sid('s-new')]).toMatchObject({ blank: true })
  446. // Reconnect re-pull: the summary's blank=false wins (authoritative alignment).
  447. await feedList(b, [{ id: 's-new', blank: false, cwd: '/w/a' }])
  448. expect(b.svc.list.getSnapshot().byId[sid('s-new')]).toMatchObject({ blank: false })
  449. })
  450. it('never re-blanks: a stale blank=true summary cannot hide an engaged session', async () => {
  451. const b = bench()
  452. await feedList(b, [{ id: 's1', blank: true }])
  453. const session = b.svc.binding(sid('s1'))!.session
  454. await session.prompt([{ type: 'text', text: 'hi' }], 'queue')
  455. await Promise.resolve()
  456. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: false })
  457. // The next list pull still claims blank (host hasn't logged the message yet).
  458. await feedList(b, [{ id: 's1', blank: true }])
  459. expect(b.svc.binding(sid('s1'))?.session.getSnapshot().blank).toBe(false)
  460. })
  461. })
  462. describe('coverage tails (branch duals)', () => {
  463. it('displayTitleOf falls back to the id for empty and separator-only cwd', async () => {
  464. const b = bench()
  465. await feedList(b, [{ id: 'no-base', cwd: '///' }, { id: 'empty-cwd', cwd: '' }])
  466. const { byId } = b.svc.list.getSnapshot()
  467. expect(byId[sid('no-base')]?.displayTitle).toBe('no-base')
  468. expect(byId[sid('empty-cwd')]?.displayTitle).toBe('empty-cwd')
  469. expect(byId[sid('no-base')]?.title).toBeUndefined()
  470. })
  471. it('binding for an unknown session returns undefined and leaves the staged scope intact', async () => {
  472. const b = bench()
  473. await feedList(b, [{ id: 's1' }])
  474. b.svc.open(sid('s1'))
  475. expect(b.svc.binding(sid('ghost'))).toBeUndefined()
  476. // Stage unchanged: removing s1 defers (still staged), proving the ghost lookup touched nothing.
  477. await feedList(b, [])
  478. expect(b.svc.scope(sid('s1'))).toBeDefined()
  479. })
  480. it('a masked current gap holds the stage (no teardown, no re-open) until the stage moves', async () => {
  481. const b = bench()
  482. await feedList(b, [{ id: 's1' }])
  483. b.svc.open(sid('s1'))
  484. const historyCalls = () => b.api.calls.filter(c => c.method === 'session.history')
  485. expect(historyCalls()).toHaveLength(1)
  486. await feedList(b, []) // removed while staged: current masks to undefined, stage holds → deferred
  487. expect(b.svc.scope(sid('s1'))).toBeDefined()
  488. // Resurfacing re-projects current = s1: same stage occupant, no second pull.
  489. await feedList(b, [{ id: 's1' }])
  490. expect(historyCalls()).toHaveLength(1)
  491. expect(b.svc.list.getSnapshot().current).toBe('s1')
  492. })
  493. it('sweep hits both deferral edges: staged-id skip and an already-vacated scope record', async () => {
  494. const b = bench()
  495. await feedList(b, [{ id: 'a' }, { id: 'b' }])
  496. b.svc.scope(sid('a'))
  497. b.svc.open(sid('b')) // stage: b; both scoped
  498. await feedList(b, []) // a removed off stage → torn immediately; b removed staged → deferred
  499. // Move the stage to a THIRD id while b stays deferred: sweep walks a set
  500. // containing b (torn).
  501. await feedList(b, [{ id: 'c' }])
  502. b.svc.open(sid('c'))
  503. expect(b.svc.scope(sid('b'))).toBeUndefined()
  504. // Deferral for an id whose record was never minted: force the deferral
  505. // via removed list state — sweep must tolerate the missing record.
  506. await feedList(b, []) // c removed while staged → deferred (scope exists)
  507. await feedList(b, [{ id: 'd' }])
  508. b.svc.open(sid('d')) // sweep tears c
  509. expect(b.svc.scope(sid('c'))).toBeUndefined()
  510. })
  511. })