sessions-service.spec.ts 31 KB

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