sessions-service.spec.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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/title', sessionId: sid('s1'), title: 'Durable title', eventSeq: 2, updatedAt: 3 },
  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. expect(binding?.session).toBe(b.svc.provideInfo('s1')?.hooks['session'])
  75. expect(b.svc.binding(sid('s1'))).toBe(binding)
  76. expect(binding?.ctx).toBe(scoped)
  77. })
  78. it('tears down an off-stage removed session but defers the staged one until the stage moves', async () => {
  79. const b = bench()
  80. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  81. const ctx1 = b.svc.scope(sid('s1'))
  82. b.svc.open(sid('s1')) // s1 staged (current)
  83. b.svc.scope(sid('s2')) // s2 scoped but off stage
  84. await feedList(b, [{ id: 's1' }]) // s2 removed, off stage: torn down
  85. expect(b.svc.scope(sid('s2'))).toBeUndefined()
  86. await feedList(b, []) // s1 removed while staged (current masks): deferred, scope survives
  87. expect(b.svc.scope(sid('s1'))).toBe(ctx1)
  88. await feedList(b, [{ id: 's3' }])
  89. b.svc.open(sid('s3')) // stage moves: deferred teardown sweeps s1
  90. expect(b.svc.scope(sid('s1'))).toBeUndefined()
  91. })
  92. it('keeps the scope when the session merely stops running (frozen ≠ removed)', async () => {
  93. const b = bench()
  94. await feedList(b, [{ id: 's1', running: true }])
  95. const scoped = b.svc.scope(sid('s1'))
  96. await feedList(b, [{ id: 's1', running: false }])
  97. expect(b.svc.scope(sid('s1'))).toBe(scoped)
  98. })
  99. it('cancels a deferred teardown when the id reappears in the list', async () => {
  100. const b = bench()
  101. await feedList(b, [{ id: 's1' }])
  102. const scoped = b.svc.scope(sid('s1'))
  103. b.svc.open(sid('s1'))
  104. await feedList(b, []) // removed while staged → deferred
  105. await feedList(b, [{ id: 's1' }, { id: 's2' }]) // reappears (current resurfaces, stage unchanged)
  106. b.svc.open(sid('s2')) // stage moves; sweep must NOT tear down the re-listed s1
  107. expect(b.svc.scope(sid('s1'))).toBe(scoped)
  108. })
  109. })
  110. describe('current selection (migrated from ui-layout, arbitrated into the list snapshot)', () => {
  111. afterEach(() => { vi.unstubAllGlobals() })
  112. it('open() writes list.current; unknown ids fail loud', async () => {
  113. const b = bench()
  114. await feedList(b, [{ id: 's1' }])
  115. expect(b.svc.list.getSnapshot().current).toBeUndefined()
  116. b.svc.open(sid('s1'))
  117. expect(b.svc.list.getSnapshot().current).toBe('s1')
  118. expect(() => { b.svc.open(sid('ghost')) }).toThrow(/unknown session ghost/)
  119. expect(b.svc.list.getSnapshot().current).toBe('s1') // failed open leaves the selection alone
  120. })
  121. it('clear() blanks list.current and the persisted selection', async () => {
  122. const storage = new Map<string, string>()
  123. vi.stubGlobal('localStorage', {
  124. getItem: (k: string) => storage.get(k) ?? null,
  125. setItem: (k: string, v: string) => { storage.set(k, v) },
  126. removeItem: (k: string) => { storage.delete(k) },
  127. clear: () => { storage.clear() },
  128. })
  129. const b = bench()
  130. await feedList(b, [{ id: 's1' }])
  131. b.svc.open(sid('s1'))
  132. expect(storage.get('dsh.sessions.current')).toContain('s1')
  133. b.svc.clear()
  134. expect(b.svc.list.getSnapshot().current).toBeUndefined()
  135. // Persisted wipe: a fresh service with the same storage stays on empty.
  136. const again = bench()
  137. await feedList(again, [{ id: 's1' }])
  138. expect(again.svc.list.getSnapshot().current).toBeUndefined()
  139. })
  140. it('masks (not destroys) the selection while its session is off the list', async () => {
  141. const b = bench()
  142. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  143. b.svc.open(sid('s1'))
  144. await feedList(b, [{ id: 's2' }]) // s1 removed → current falls to the empty state
  145. expect(b.svc.list.getSnapshot().current).toBeUndefined()
  146. await feedList(b, [{ id: 's1' }, { id: 's2' }]) // s1 returns → selection resurfaces
  147. expect(b.svc.list.getSnapshot().current).toBe('s1')
  148. })
  149. it('persists the selection under dsh.sessions.current and rehydrates it into a fresh service', async () => {
  150. const storage = new Map<string, string>()
  151. vi.stubGlobal('localStorage', {
  152. getItem: (k: string) => storage.get(k) ?? null,
  153. setItem: (k: string, v: string) => { storage.set(k, v) },
  154. })
  155. const first = bench()
  156. await feedList(first, [{ id: 's1' }])
  157. first.svc.open(sid('s1'))
  158. expect(storage.get('dsh.sessions.current')).toContain('s1')
  159. // A fresh boot (same storage) recovers the selection once the list holds the session.
  160. const second = bench()
  161. await feedList(second, [{ id: 's1' }])
  162. expect(second.svc.list.getSnapshot().current).toBe('s1')
  163. })
  164. })
  165. describe('cell (render-layer session kit)', () => {
  166. it('resolves an identity-stable {sessionId, session} cell; unknown ids yield undefined', async () => {
  167. const b = bench()
  168. await feedList(b, [{ id: 's1' }])
  169. const info = b.svc.provideInfo('s1')
  170. expect(info).toBeDefined()
  171. expect(info?.sessionId).toBe('s1')
  172. // The bundle carries bare observables; hook binding happens in React.
  173. expect(info?.hooks['session']).toBe(b.svc.binding(sid('s1'))?.session)
  174. expect(b.svc.provideInfo('s1')).toBe(info)
  175. expect(b.svc.provideInfo('ghost')).toBeUndefined()
  176. })
  177. it('provideInfo()/binding() are pure resolution: no staging, no deferred sweep', async () => {
  178. const b = bench()
  179. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  180. b.svc.open(sid('s1')) // staged
  181. b.svc.provideInfo('s2') // resolution only — must NOT move the stage
  182. b.svc.binding(sid('s2'))
  183. await feedList(b, [{ id: 's2' }]) // s1 removed: still staged → deferred, scope survives
  184. expect(b.svc.scope(sid('s1'))).toBeDefined()
  185. })
  186. it('staging (current write) opens the session event window; resolution and re-staging do not re-pull', async () => {
  187. const b = bench()
  188. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  189. const historyCalls = () => b.api.calls.filter(c => c.method === 'session.history')
  190. // Resolution is addressing, not staging: no window pull.
  191. b.svc.scope(sid('s1'))
  192. b.svc.provideInfo('s1')
  193. b.svc.binding(sid('s1'))
  194. expect(historyCalls()).toHaveLength(0)
  195. b.svc.open(sid('s1'))
  196. expect(historyCalls().map(c => (c.payload as { sessionId: string }).sessionId)).toEqual(['s1'])
  197. // Same current again: no second pull.
  198. b.svc.open(sid('s1'))
  199. expect(historyCalls()).toHaveLength(1)
  200. // Stage moves: the new occupant opens.
  201. b.svc.open(sid('s2'))
  202. expect(historyCalls().map(c => (c.payload as { sessionId: string }).sessionId)).toEqual(['s1', 's2'])
  203. })
  204. it('startup restore: a persisted selection validated by the first projection opens its window unprompted', async () => {
  205. const storage = new Map<string, string>([
  206. ['dsh.sessions.current', JSON.stringify({ sessionId: 's1' })],
  207. ])
  208. vi.stubGlobal('localStorage', {
  209. getItem: (k: string) => storage.get(k) ?? null,
  210. setItem: (k: string, v: string) => { storage.set(k, v) },
  211. })
  212. try {
  213. const b = bench()
  214. expect(b.api.calls.filter(c => c.method === 'session.history')).toHaveLength(0)
  215. await feedList(b, [{ id: 's1' }]) // projection validates the persisted id → current lands → stage follows
  216. const historyCalls = b.api.calls.filter(c => c.method === 'session.history')
  217. expect(historyCalls.map(c => (c.payload as { sessionId: string }).sessionId)).toEqual(['s1'])
  218. } finally {
  219. vi.unstubAllGlobals()
  220. }
  221. })
  222. })
  223. describe('slot-store scope prune hook', () => {
  224. it('notifies ctx.slots.pruneStoreScope when a scope dies (both teardown paths)', async () => {
  225. const b = bench()
  226. const pruneStoreScope = vi.fn()
  227. b.ctx.reflect.provide('slots', { pruneStoreScope })
  228. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  229. b.svc.scope(sid('s1'))
  230. b.svc.scope(sid('s2'))
  231. b.svc.open(sid('s2')) // s2 staged
  232. await feedList(b, []) // s1 off stage → immediate drop; s2 staged → deferred
  233. expect(pruneStoreScope).toHaveBeenCalledWith('s1')
  234. expect(pruneStoreScope).not.toHaveBeenCalledWith('s2')
  235. await feedList(b, [{ id: 's3' }])
  236. b.svc.open(sid('s3')) // stage moves → deferred sweep drops s2
  237. expect(pruneStoreScope).toHaveBeenCalledWith('s2')
  238. })
  239. it('tolerates a slots-less boot (object-layer benches carry no slot service)', async () => {
  240. const b = bench()
  241. await feedList(b, [{ id: 's1' }])
  242. b.svc.scope(sid('s1'))
  243. await feedList(b, []) // teardown without ctx.slots must not throw
  244. expect(b.svc.scope(sid('s1'))).toBeUndefined()
  245. })
  246. })
  247. describe('ancestry', () => {
  248. it('walks parentId links root-first including self; broken links stop the walk', async () => {
  249. const b = bench()
  250. await feedList(b, [
  251. { id: 'root', cwd: '/w/app' },
  252. { id: 'mid', parentId: 'root' },
  253. { id: 'leaf', parentId: 'mid' },
  254. { id: 'orphan', parentId: 'ghost' },
  255. ])
  256. expect(b.svc.ancestry(sid('leaf')).map(s => s.id)).toEqual(['root', 'mid', 'leaf'])
  257. expect(b.svc.ancestry(sid('orphan')).map(s => s.id)).toEqual(['orphan'])
  258. expect(b.svc.ancestry(sid('ghost'))).toEqual([])
  259. })
  260. })
  261. describe('create', () => {
  262. it('passes a preallocated id and preserves it on ordinary failure', async () => {
  263. const b = bench()
  264. b.api.onCreate = () => Promise.resolve(ok({ sessionId: sid('fresh') }))
  265. await expect(b.svc.create({ cwd: '/w', sessionId: sid('fresh') })).resolves.toBe('fresh')
  266. expect(b.api.callsOf('session.create')).toEqual([{ cwd: '/w', sessionId: 'fresh' }])
  267. b.api.onCreate = () => Promise.resolve({
  268. rpcId: 'e' as never,
  269. result: { ok: false as const, error: { code: 'internal' as const, message: '爆了', details: {} } },
  270. } as never)
  271. const failure = await b.svc.create({ sessionId: sid('candidate') }).catch((error: unknown) => error)
  272. expect(failure).toBeInstanceOf(SessionCreateError)
  273. expect(failure).toMatchObject({
  274. requestedSessionId: 'candidate',
  275. rpcError: { code: 'internal', message: '爆了' },
  276. })
  277. })
  278. it('resolves with the session already listed and binding-resolvable (no flush wait)', async () => {
  279. const b = bench()
  280. b.api.onCreate = () => Promise.resolve(ok({ sessionId: sid('born') }))
  281. const born = await b.svc.create({ workspaceId: 'ws' as never })
  282. // Synchronously after resolution — the draft hand-off contract: the
  283. // create echo IS the entity entering the client's view (blank row +
  284. // resolvable scope/binding), no notifier flush in between.
  285. expect(b.svc.list.getSnapshot().byId[born]).toMatchObject({ id: 'born', blank: true })
  286. expect(b.svc.binding(born)).toBeDefined()
  287. expect(b.svc.scope(born)).toBeDefined()
  288. })
  289. it('lists the published id after Workspace attachment fails (publication precedes attachment)', async () => {
  290. const b = bench()
  291. b.api.onCreate = () => Promise.resolve({
  292. rpcId: 'attach' as never,
  293. result: {
  294. ok: false,
  295. error: {
  296. code: 'workspace-attach-failed', message: 'ledger unavailable',
  297. details: { sessionId: sid('published'), workspaceId: 'ws' },
  298. },
  299. },
  300. } as never)
  301. const failure = await b.svc.create({
  302. workspaceId: 'ws' as never,
  303. sessionId: sid('published'),
  304. }).catch((error: unknown) => error)
  305. await Promise.resolve()
  306. expect(failure).toBeInstanceOf(SessionCreateError)
  307. expect(failure).toMatchObject({
  308. requestedSessionId: 'published',
  309. rpcError: { code: 'workspace-attach-failed' },
  310. })
  311. expect(b.svc.list.getSnapshot().byId[sid('published')]).toMatchObject({ id: 'published', blank: true })
  312. })
  313. })
  314. describe('scope lifecycle rides the list mirror (entity parity: no client-side pre-birth)', () => {
  315. it('a session-added frame births the row (blank) and makes the scope resolvable; removal prunes it', async () => {
  316. const b = bench()
  317. await feedList(b, [])
  318. expect(b.svc.scope(sid('s-new'))).toBeUndefined() // not in view: no scope, no exceptions
  319. b.svc.handleHostEnvelope({
  320. rpcId: 'add' as never,
  321. payload: { type: 'host/session-added', sessionId: sid('s-new'), blank: true, cwd: '/w/a' } as never,
  322. })
  323. await Promise.resolve()
  324. const scoped = b.svc.scope(sid('s-new'))
  325. expect(scoped).toBeDefined()
  326. expect(scopeOf(scoped as Context)).toBe('s-new')
  327. b.svc.handleHostEnvelope({
  328. rpcId: 'rm' as never,
  329. payload: { type: 'host/session-removed', sessionId: sid('s-new') },
  330. })
  331. await Promise.resolve()
  332. expect(b.svc.scope(sid('s-new'))).toBeUndefined()
  333. })
  334. })
  335. describe('blank mirror', () => {
  336. it('flips blank=false from the running:true status frame (cross-client conversion)', async () => {
  337. const b = bench()
  338. await feedList(b, [{ id: 's1', blank: true }])
  339. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: true })
  340. b.svc.handleHostEnvelope({
  341. rpcId: 'st' as never,
  342. payload: { type: 'host/session-status', sessionId: sid('s1'), running: true },
  343. })
  344. await Promise.resolve()
  345. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: false, running: true })
  346. // The instantiated Session mirrors the same flip.
  347. expect(b.svc.binding(sid('s1'))?.session.getSnapshot().blank).toBe(false)
  348. })
  349. it('flips blank=false on prompt ACCEPTANCE, not on the attempt', async () => {
  350. const b = bench()
  351. await feedList(b, [{ id: 's1', blank: true, cwd: '/w/a' }])
  352. const session = b.svc.binding(sid('s1'))!.session
  353. expect(session.getSnapshot().blank).toBe(true)
  354. const gate = deferred<Awaited<ReturnType<FakeApiClient['onPrompt']>>>()
  355. b.api.onPrompt = () => gate.promise
  356. const send = session.prompt([{ type: 'text', text: 'hi' }], 'queue')
  357. // In flight: still blank (the flip point is the success response, which
  358. // proves the user message reached the host log).
  359. expect(session.getSnapshot().blank).toBe(true)
  360. gate.resolve(ok({ accepted: true as const }))
  361. await send
  362. expect(session.getSnapshot().blank).toBe(false)
  363. await Promise.resolve()
  364. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: false })
  365. })
  366. it('keeps a rejected first prompt blank: hidden and still reusable', async () => {
  367. const b = bench()
  368. await feedList(b, [{ id: 's1', blank: true, cwd: '/w/a' }])
  369. const session = b.svc.binding(sid('s1'))!.session
  370. b.api.onPrompt = () => Promise.resolve({
  371. rpcId: 'busy' as never,
  372. result: { ok: false as const, error: { code: 'internal' as const, message: 'agent busy', details: {} } },
  373. } as never)
  374. const result = await session.prompt([{ type: 'text', text: 'hi' }], 'queue')
  375. expect(result.ok).toBe(false)
  376. // No flip on failure: local stays aligned with the host authority
  377. // (events.length still 0), so the session stays hidden and reusable.
  378. expect(session.getSnapshot().blank).toBe(true)
  379. await Promise.resolve()
  380. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: true })
  381. })
  382. it('takes session-added blank=true as the hidden birth and list blank as reconnect authority', async () => {
  383. const b = bench()
  384. await feedList(b, [])
  385. b.svc.handleHostEnvelope({
  386. rpcId: 'add' as never,
  387. payload: { type: 'host/session-added', sessionId: sid('s-new'), blank: true, cwd: '/w/a' } as never,
  388. })
  389. await Promise.resolve()
  390. expect(b.svc.list.getSnapshot().byId[sid('s-new')]).toMatchObject({ blank: true })
  391. // Reconnect re-pull: the summary's blank=false wins (authoritative alignment).
  392. await feedList(b, [{ id: 's-new', blank: false, cwd: '/w/a' }])
  393. expect(b.svc.list.getSnapshot().byId[sid('s-new')]).toMatchObject({ blank: false })
  394. })
  395. it('never re-blanks: a stale blank=true summary cannot hide an engaged session', async () => {
  396. const b = bench()
  397. await feedList(b, [{ id: 's1', blank: true }])
  398. const session = b.svc.binding(sid('s1'))!.session
  399. await session.prompt([{ type: 'text', text: 'hi' }], 'queue')
  400. await Promise.resolve()
  401. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: false })
  402. // The next list pull still claims blank (host hasn't logged the message yet).
  403. await feedList(b, [{ id: 's1', blank: true }])
  404. expect(b.svc.binding(sid('s1'))?.session.getSnapshot().blank).toBe(false)
  405. })
  406. })
  407. describe('coverage tails (branch duals)', () => {
  408. it('displayTitleOf falls back to the id for empty and separator-only cwd', async () => {
  409. const b = bench()
  410. await feedList(b, [{ id: 'no-base', cwd: '///' }, { id: 'empty-cwd', cwd: '' }])
  411. const { byId } = b.svc.list.getSnapshot()
  412. expect(byId[sid('no-base')]?.displayTitle).toBe('no-base')
  413. expect(byId[sid('empty-cwd')]?.displayTitle).toBe('empty-cwd')
  414. expect(byId[sid('no-base')]?.title).toBeUndefined()
  415. })
  416. it('binding for an unknown session returns undefined and leaves the staged scope intact', async () => {
  417. const b = bench()
  418. await feedList(b, [{ id: 's1' }])
  419. b.svc.open(sid('s1'))
  420. expect(b.svc.binding(sid('ghost'))).toBeUndefined()
  421. // Stage unchanged: removing s1 defers (still staged), proving the ghost lookup touched nothing.
  422. await feedList(b, [])
  423. expect(b.svc.scope(sid('s1'))).toBeDefined()
  424. })
  425. it('a masked current gap holds the stage (no teardown, no re-open) until the stage moves', async () => {
  426. const b = bench()
  427. await feedList(b, [{ id: 's1' }])
  428. b.svc.open(sid('s1'))
  429. const historyCalls = () => b.api.calls.filter(c => c.method === 'session.history')
  430. expect(historyCalls()).toHaveLength(1)
  431. await feedList(b, []) // removed while staged: current masks to undefined, stage holds → deferred
  432. expect(b.svc.scope(sid('s1'))).toBeDefined()
  433. // Resurfacing re-projects current = s1: same stage occupant, no second pull.
  434. await feedList(b, [{ id: 's1' }])
  435. expect(historyCalls()).toHaveLength(1)
  436. expect(b.svc.list.getSnapshot().current).toBe('s1')
  437. })
  438. it('sweep hits both deferral edges: staged-id skip and an already-vacated scope record', async () => {
  439. const b = bench()
  440. await feedList(b, [{ id: 'a' }, { id: 'b' }])
  441. b.svc.scope(sid('a'))
  442. b.svc.open(sid('b')) // stage: b; both scoped
  443. await feedList(b, []) // a removed off stage → torn immediately; b removed staged → deferred
  444. // Move the stage to a THIRD id while b stays deferred: sweep walks a set
  445. // containing b (torn).
  446. await feedList(b, [{ id: 'c' }])
  447. b.svc.open(sid('c'))
  448. expect(b.svc.scope(sid('b'))).toBeUndefined()
  449. // Deferral for an id whose record was never minted: force the deferral
  450. // via removed list state — sweep must tolerate the missing record.
  451. await feedList(b, []) // c removed while staged → deferred (scope exists)
  452. await feedList(b, [{ id: 'd' }])
  453. b.svc.open(sid('d')) // sweep tears c
  454. expect(b.svc.scope(sid('c'))).toBeUndefined()
  455. })
  456. })