sessions-service.spec.ts 27 KB

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