sessions-service.client.spec.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  1. /**
  2. * ClientSessions: list store projection (manager → {ids, byId, current}
  3. * with derived titles), the current-selection account (open validation and
  4. * persisted mask semantics), 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 '@deepseek-ai/cordis'
  10. import { afterEach, describe, expect, it, vi } from 'vitest'
  11. import type { SessionId } from '@deepseek-ai/dsh-api-remotes/client'
  12. import { ClientSessions, SessionCreateError } from '../src/client/sessions/service.ts'
  13. import { scopeOf } from '../src/client/scope.ts'
  14. import type { SessionFollowFrame } from '../src/types.ts'
  15. import {
  16. FakeApiClient,
  17. deferred,
  18. err,
  19. fakeRemote,
  20. ok,
  21. type RuntimeRemotes,
  22. } from './fake-api.client.ts'
  23. const sid = (s: string): SessionId => s as SessionId
  24. interface Bench {
  25. ctx: Context
  26. api: FakeApiClient
  27. svc: ClientSessions
  28. }
  29. function bench(configureRemote?: (remote: RuntimeRemotes) => RuntimeRemotes): Bench {
  30. const ctx = new Context()
  31. const api = new FakeApiClient()
  32. const remote = fakeRemote(api)
  33. const svc = new ClientSessions(ctx, api, configureRemote?.(remote) ?? remote)
  34. return { ctx, api, svc }
  35. }
  36. /** Refresh the manager list from programmable rows and flush the microtask batch. */
  37. type FeedRow = {
  38. id: string
  39. cwd?: string
  40. parentId?: string
  41. origin?: 'subagent'
  42. running?: boolean
  43. blank?: boolean
  44. projections?: Record<string, unknown>
  45. }
  46. async function feedList(b: Bench, rows: FeedRow[]): Promise<void> {
  47. b.api.onList = () => Promise.resolve(ok({
  48. items: rows.map(r => ({
  49. sessionId: sid(r.id), updatedAt: 1, running: r.running ?? false, blank: r.blank ?? false,
  50. ...(r.cwd !== undefined ? { cwd: r.cwd } : {}),
  51. ...(r.parentId !== undefined ? { parentSessionId: sid(r.parentId) } : {}),
  52. ...(r.origin !== undefined ? { origin: r.origin } : {}),
  53. ...(r.projections === undefined
  54. ? {}
  55. : { projections: { asOfSeq: 0, values: r.projections } }),
  56. })),
  57. }) as never)
  58. await b.svc.refresh()
  59. await Promise.resolve() // manager notifier flush
  60. }
  61. describe('list store projection', () => {
  62. it('projects durable titles separately from cwd/id display fallbacks and parent links', async () => {
  63. const b = bench()
  64. b.svc.handleControlFrame({
  65. type: 'projection', sessionId: sid('s1'), key: 'title', value: 'Durable title', seq: 2,
  66. })
  67. await feedList(b, [
  68. { id: 's1', cwd: '/home/u/proj-a/' },
  69. { id: 's2', parentId: 's1', origin: 'subagent', running: true },
  70. ])
  71. const state = b.svc.list.getSnapshot()
  72. expect(state.ids).toEqual(['s1', 's2'])
  73. expect(state.byId[sid('s1')]).toMatchObject({ title: 'Durable title', displayTitle: 'Durable title', cwd: '/home/u/proj-a/' })
  74. expect(state.byId[sid('s2')]).toMatchObject({
  75. displayTitle: 's2', parentId: 's1', origin: 'subagent', running: true,
  76. })
  77. expect(state.byId[sid('s2')]?.title).toBeUndefined()
  78. })
  79. it('reprojects a blank session from the generic agent-preset projection', async () => {
  80. const b = bench()
  81. await feedList(b, [{ id: 's1', blank: true, projections: { agentPreset: 'standard' } }])
  82. expect(b.svc.list.getSnapshot().byId[sid('s1')]?.projectionValues?.agentPreset).toBe('standard')
  83. b.svc.handleControlFrame({
  84. type: 'projection', sessionId: sid('s1'), key: 'agentPreset', value: 'minimal', seq: 1,
  85. })
  86. await Promise.resolve()
  87. expect(b.svc.list.getSnapshot().byId[sid('s1')]?.projectionValues?.agentPreset).toBe('minimal')
  88. })
  89. it('reflects live increments (host stream via manager) into the store', async () => {
  90. const b = bench()
  91. await feedList(b, [{ id: 's1' }])
  92. b.svc.handleSessionAdded({
  93. sessionId: sid('s2'), updatedAt: 2, running: false, blank: true,
  94. })
  95. await Promise.resolve()
  96. expect(b.svc.list.getSnapshot().ids).toContain('s2')
  97. })
  98. })
  99. describe('search', () => {
  100. it('delegates transient content search without changing the list snapshot', async () => {
  101. const b = bench()
  102. await feedList(b, [{ id: 's1' }])
  103. const before = b.svc.list.getSnapshot()
  104. b.api.onSearch = () => Promise.resolve(ok({
  105. items: [{ sessionId: sid('s1'), snippet: 'matching excerpt' }],
  106. hasMore: false,
  107. }))
  108. const signal = new AbortController().signal
  109. await expect(b.svc.search('needle', signal)).resolves.toEqual({
  110. ok: true,
  111. value: {
  112. items: [{ sessionId: 's1', snippet: 'matching excerpt' }],
  113. hasMore: false,
  114. },
  115. })
  116. expect(b.api.lastSearchSignal).toBe(signal)
  117. expect(b.svc.list.getSnapshot()).toBe(before)
  118. })
  119. })
  120. describe('scope tree', () => {
  121. it('retains a Host-addressed scope until the first Session baseline owns pruning', async () => {
  122. const b = bench()
  123. const scoped = b.svc.resolveAgentScope(sid('s-early'))
  124. expect(scopeOf(scoped)).toBe('s-early')
  125. b.svc.handleControlFrame({
  126. type: 'baseline',
  127. value: { queues: {}, jobs: {}, projections: {} },
  128. })
  129. await Promise.resolve()
  130. expect(b.svc.resolveAgentScope(sid('s-early'))).toBe(scoped)
  131. await feedList(b, [])
  132. expect(b.svc.scope(sid('s-early'))).toBeUndefined()
  133. })
  134. it('mints lazily on first resolution, tags the ctx, and keeps binding identity stable', async () => {
  135. const b = bench()
  136. await feedList(b, [{ id: 's1' }])
  137. expect(b.svc.scope(sid('unknown'))).toBeUndefined()
  138. const scoped = b.svc.scope(sid('s1'))
  139. expect(scoped).toBeDefined()
  140. expect(scopeOf(scoped as Context)).toBe('s1')
  141. expect(scopeOf(b.ctx)).toBeUndefined()
  142. const binding = b.svc.binding(sid('s1'))
  143. b.svc.open(sid('s1'))
  144. expect(b.svc.sessionOf(scoped as Context)).toBe(binding?.session)
  145. expect(b.svc.binding(sid('s1'))).toBe(binding)
  146. expect(binding?.ctx).toBe(scoped)
  147. })
  148. it('tears down an off-stage removed session but defers the staged one until the stage moves', async () => {
  149. const b = bench()
  150. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  151. const ctx1 = b.svc.scope(sid('s1'))
  152. b.svc.open(sid('s1')) // s1 staged (current)
  153. b.svc.scope(sid('s2')) // s2 scoped but off stage
  154. await feedList(b, [{ id: 's1' }]) // s2 removed, off stage: torn down
  155. expect(b.svc.scope(sid('s2'))).toBeUndefined()
  156. await feedList(b, []) // s1 removed while staged (current masks): deferred, scope survives
  157. expect(b.svc.scope(sid('s1'))).toBe(ctx1)
  158. await feedList(b, [{ id: 's3' }])
  159. b.svc.open(sid('s3')) // stage moves: deferred teardown sweeps s1
  160. expect(b.svc.scope(sid('s1'))).toBeUndefined()
  161. })
  162. it('keeps the scope when the session merely stops running (frozen ≠ removed)', async () => {
  163. const b = bench()
  164. await feedList(b, [{ id: 's1', running: true }])
  165. const scoped = b.svc.scope(sid('s1'))
  166. await feedList(b, [{ id: 's1', running: false }])
  167. expect(b.svc.scope(sid('s1'))).toBe(scoped)
  168. })
  169. it('cancels a deferred teardown when the id reappears in the list', async () => {
  170. const b = bench()
  171. await feedList(b, [{ id: 's1' }])
  172. const scoped = b.svc.scope(sid('s1'))
  173. b.svc.open(sid('s1'))
  174. await feedList(b, []) // removed while staged → deferred
  175. await feedList(b, [{ id: 's1' }, { id: 's2' }]) // reappears (current resurfaces, stage unchanged)
  176. b.svc.open(sid('s2')) // stage moves; sweep must NOT tear down the re-listed s1
  177. expect(b.svc.scope(sid('s1'))).toBe(scoped)
  178. })
  179. it('closes an opened journal when its removed scope drops', async () => {
  180. const b = bench()
  181. await feedList(b, [{ id: 's1' }])
  182. b.svc.open(sid('s1'))
  183. const session = b.svc.binding(sid('s1'))?.session
  184. if (session === undefined) throw new Error('expected the selected Session binding')
  185. await vi.waitFor(() => { expect(b.api.activeFollows(sid('s1'))).toBe(1) })
  186. const notified = vi.fn()
  187. session.subscribe(notified)
  188. await feedList(b, [])
  189. await feedList(b, [{ id: 's2' }])
  190. b.svc.open(sid('s2'))
  191. await vi.waitFor(() => { expect(b.api.activeFollows(sid('s1'))).toBe(0) })
  192. notified.mockClear()
  193. await b.api.pushFollow(sid('s1'), {
  194. type: 'event',
  195. event: { seq: 0, timestamp: 0, type: 'turn/start', data: { turn: 0 } } as never,
  196. })
  197. await Promise.resolve()
  198. expect(b.api.followStarts.filter(id => id === sid('s1'))).toHaveLength(1)
  199. expect(notified).not.toHaveBeenCalled()
  200. })
  201. })
  202. describe('Agent scope disposal lifecycle', () => {
  203. it('root disposal runs Agent scope effects', async () => {
  204. const b = bench()
  205. const readiness = b.ctx.plugin(() => undefined)
  206. await readiness
  207. b.svc.handleSessionAdded({
  208. sessionId: sid('live'), updatedAt: 1, running: false, blank: true,
  209. })
  210. await Promise.resolve()
  211. const scoped = b.svc.scope(sid('live'))
  212. if (scoped === undefined) throw new Error('fixture Agent Context was not minted')
  213. await scoped.fiber.await()
  214. const scopeDisposed = vi.fn()
  215. scoped.effect(() => scopeDisposed, 'fixture Agent scope effect')
  216. await b.ctx.fiber.dispose()
  217. expect(scopeDisposed).toHaveBeenCalledOnce()
  218. expect(b.svc.sessionOf(scoped)).toBeUndefined()
  219. })
  220. it('root disposal waits for an opened Session source to finish closing', async () => {
  221. const closeGate = deferred<undefined>()
  222. const abortObserved = vi.fn()
  223. let followSignal: AbortSignal | undefined
  224. const b = bench(remote => ({
  225. ...remote,
  226. session: {
  227. ...remote.session,
  228. follow: (request, signal) => {
  229. if (signal === undefined) throw new Error('fixture requires a signal')
  230. followSignal = signal
  231. let opened = false
  232. return {
  233. [Symbol.asyncIterator]: () => ({
  234. next: () => {
  235. if (!opened) {
  236. opened = true
  237. return Promise.resolve({
  238. done: false,
  239. value: {
  240. type: 'snapshot',
  241. header: {
  242. version: 0,
  243. id: request.address.kind === 'session'
  244. ? request.address.sessionId
  245. : request.address.childSessionId,
  246. createdAt: 0,
  247. },
  248. cursor: -1,
  249. events: [],
  250. hasMore: false,
  251. projections: { asOfSeq: -1, values: {} },
  252. } as const,
  253. })
  254. }
  255. return new Promise((_resolve, reject) => {
  256. signal.addEventListener('abort', () => {
  257. abortObserved()
  258. void closeGate.promise.then(() => {
  259. reject(signal.reason instanceof Error
  260. ? signal.reason
  261. : new Error(String(signal.reason)))
  262. })
  263. }, { once: true })
  264. })
  265. },
  266. }),
  267. }
  268. },
  269. },
  270. }))
  271. const readiness = b.ctx.plugin(() => undefined)
  272. await readiness
  273. await feedList(b, [{ id: 's1' }])
  274. b.svc.open(sid('s1'))
  275. await vi.waitFor(() => {
  276. expect(b.svc.binding(sid('s1'))?.session.getSnapshot().openState).toBe('open')
  277. })
  278. const disposal = b.ctx.fiber.dispose()
  279. const settled = vi.fn()
  280. const observed = disposal.then(settled)
  281. await vi.waitFor(() => { expect(abortObserved).toHaveBeenCalledOnce() })
  282. expect(followSignal?.aborted).toBe(true)
  283. expect(settled).not.toHaveBeenCalled()
  284. closeGate.resolve(undefined)
  285. await observed
  286. expect(settled).toHaveBeenCalledOnce()
  287. })
  288. it('root disposal joins every Session drop already started by pruning under load', async () => {
  289. const closeGates = new Map<SessionId, ReturnType<typeof deferred<undefined>>>()
  290. const aborted = new Set<SessionId>()
  291. const b = bench(remote => ({
  292. ...remote,
  293. session: {
  294. ...remote.session,
  295. follow: (request, signal) => {
  296. if (signal === undefined) throw new Error('fixture requires a signal')
  297. const sessionId = request.address.kind === 'session'
  298. ? request.address.sessionId
  299. : request.address.childSessionId
  300. const closeGate = deferred<undefined>()
  301. closeGates.set(sessionId, closeGate)
  302. let opened = false
  303. return {
  304. [Symbol.asyncIterator]: () => ({
  305. next: () => {
  306. if (!opened) {
  307. opened = true
  308. return Promise.resolve({
  309. done: false,
  310. value: {
  311. type: 'snapshot',
  312. header: { version: 0, id: sessionId, createdAt: 0 },
  313. cursor: -1,
  314. events: [],
  315. hasMore: false,
  316. projections: { asOfSeq: -1, values: {} },
  317. } as const,
  318. })
  319. }
  320. return new Promise<IteratorResult<SessionFollowFrame>>((_resolve, reject) => {
  321. signal.addEventListener('abort', () => {
  322. aborted.add(sessionId)
  323. void closeGate.promise.then(() => {
  324. reject(signal.reason instanceof Error
  325. ? signal.reason
  326. : new Error(String(signal.reason)))
  327. })
  328. }, { once: true })
  329. })
  330. },
  331. }),
  332. }
  333. },
  334. },
  335. }))
  336. const readiness = b.ctx.plugin(() => undefined)
  337. await readiness
  338. const sessionIds = Array.from({ length: 24 }, (_, index) => sid(`load-${String(index)}`))
  339. const retained = sessionIds.at(-1)
  340. const held = sessionIds[0]
  341. if (retained === undefined || held === undefined) throw new Error('fixture requires sessions')
  342. await feedList(b, sessionIds.map(id => ({ id })))
  343. for (const id of sessionIds) b.svc.open(id)
  344. await vi.waitFor(() => {
  345. for (const id of sessionIds) {
  346. expect(b.svc.binding(id)?.session.getSnapshot().openState).toBe('open')
  347. }
  348. })
  349. const pruned = sessionIds.slice(0, -1)
  350. await feedList(b, [{ id: retained }])
  351. await vi.waitFor(() => { expect(aborted.size).toBe(pruned.length) })
  352. for (const id of pruned) expect(b.svc.scope(id)).toBeUndefined()
  353. const disposal = b.ctx.fiber.dispose()
  354. const settled = vi.fn()
  355. const observed = disposal.then(settled)
  356. await vi.waitFor(() => { expect(aborted.size).toBe(sessionIds.length) })
  357. const otherClosures: Promise<void>[] = []
  358. for (const [id, gate] of closeGates) {
  359. if (id === held) continue
  360. gate.resolve(undefined)
  361. otherClosures.push(gate.promise)
  362. }
  363. await Promise.all(otherClosures)
  364. await new Promise((resolve) => { setTimeout(resolve, 0) })
  365. expect(settled).not.toHaveBeenCalled()
  366. closeGates.get(held)?.resolve(undefined)
  367. await observed
  368. expect(settled).toHaveBeenCalledOnce()
  369. })
  370. })
  371. describe('current selection (migrated from ui-layout, arbitrated into the list snapshot)', () => {
  372. afterEach(() => { vi.unstubAllGlobals() })
  373. it('open() writes list.current; unknown ids fail loud', async () => {
  374. const b = bench()
  375. await feedList(b, [{ id: 's1' }])
  376. expect(b.svc.list.getSnapshot().current).toBeUndefined()
  377. b.svc.open(sid('s1'))
  378. expect(b.svc.list.getSnapshot().current).toBe('s1')
  379. expect(() => { b.svc.open(sid('ghost')) }).toThrow(/unknown session ghost/)
  380. expect(b.svc.list.getSnapshot().current).toBe('s1') // failed open leaves the selection alone
  381. })
  382. it('clear() blanks list.current and the persisted selection', async () => {
  383. const storage = new Map<string, string>()
  384. vi.stubGlobal('localStorage', {
  385. getItem: (k: string) => storage.get(k) ?? null,
  386. setItem: (k: string, v: string) => { storage.set(k, v) },
  387. removeItem: (k: string) => { storage.delete(k) },
  388. clear: () => { storage.clear() },
  389. })
  390. const b = bench()
  391. await feedList(b, [{ id: 's1' }])
  392. b.svc.open(sid('s1'))
  393. expect(storage.get('dsh.sessions.current')).toContain('s1')
  394. b.svc.clear()
  395. expect(b.svc.list.getSnapshot().current).toBeUndefined()
  396. // Persisted wipe: a fresh service with the same storage stays on empty.
  397. const again = bench()
  398. await feedList(again, [{ id: 's1' }])
  399. expect(again.svc.list.getSnapshot().current).toBeUndefined()
  400. })
  401. it('masks (not destroys) the selection while its session is off the list', async () => {
  402. const b = bench()
  403. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  404. b.svc.open(sid('s1'))
  405. await feedList(b, [{ id: 's2' }]) // s1 removed → current falls to the empty state
  406. expect(b.svc.list.getSnapshot().current).toBeUndefined()
  407. await feedList(b, [{ id: 's1' }, { id: 's2' }]) // s1 returns → selection resurfaces
  408. expect(b.svc.list.getSnapshot().current).toBe('s1')
  409. })
  410. it('persists the selection under dsh.sessions.current and rehydrates it into a fresh service', async () => {
  411. const storage = new Map<string, string>()
  412. vi.stubGlobal('localStorage', {
  413. getItem: (k: string) => storage.get(k) ?? null,
  414. setItem: (k: string, v: string) => { storage.set(k, v) },
  415. })
  416. const first = bench()
  417. await feedList(first, [{ id: 's1' }])
  418. first.svc.open(sid('s1'))
  419. expect(storage.get('dsh.sessions.current')).toContain('s1')
  420. // A fresh boot (same storage) recovers the selection once the list holds the session.
  421. const second = bench()
  422. await feedList(second, [{ id: 's1' }])
  423. expect(second.svc.list.getSnapshot().current).toBe('s1')
  424. })
  425. })
  426. describe('binding and stage lifecycle', () => {
  427. it('binding() is pure resolution: no staging, no deferred sweep', async () => {
  428. const b = bench()
  429. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  430. b.svc.open(sid('s1')) // staged
  431. b.svc.binding(sid('s2')) // resolution only — must NOT move the stage
  432. await feedList(b, [{ id: 's2' }]) // s1 removed: still staged → deferred, scope survives
  433. expect(b.svc.scope(sid('s1'))).toBeDefined()
  434. })
  435. it('staging (current write) opens the session event window; resolution and re-staging do not re-pull', async () => {
  436. const b = bench()
  437. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  438. const followStarts = () => b.api.followStarts.map(String)
  439. // Resolution is addressing, not staging: no window pull.
  440. b.svc.scope(sid('s1'))
  441. b.svc.binding(sid('s1'))
  442. expect(followStarts()).toEqual([])
  443. b.svc.open(sid('s1'))
  444. await vi.waitFor(() => {
  445. expect(followStarts()).toEqual(['s1'])
  446. })
  447. // Same current again: no second pull.
  448. b.svc.open(sid('s1'))
  449. expect(followStarts()).toHaveLength(1)
  450. // Stage moves: the new occupant opens.
  451. b.svc.open(sid('s2'))
  452. await vi.waitFor(() => {
  453. expect(followStarts()).toEqual(['s1', 's2'])
  454. })
  455. })
  456. it('startup restore: a persisted selection validated by the first projection opens its window unprompted', async () => {
  457. const storage = new Map<string, string>([
  458. ['dsh.sessions.current', JSON.stringify({ sessionId: 's1' })],
  459. ])
  460. vi.stubGlobal('localStorage', {
  461. getItem: (k: string) => storage.get(k) ?? null,
  462. setItem: (k: string, v: string) => { storage.set(k, v) },
  463. })
  464. try {
  465. const b = bench()
  466. expect(b.api.followStarts).toEqual([])
  467. await feedList(b, [{ id: 's1' }]) // projection validates the persisted id → current lands → stage follows
  468. await vi.waitFor(() => {
  469. expect(b.api.followStarts.map(String)).toEqual(['s1'])
  470. })
  471. } finally {
  472. vi.unstubAllGlobals()
  473. }
  474. })
  475. })
  476. describe('catalog-addressed navigation', () => {
  477. it('uses catalog labels for a listed addressed route', async () => {
  478. const b = bench()
  479. b.api.onSubagentList = (payload) => {
  480. const { parentSessionId } = payload as { parentSessionId: SessionId }
  481. if (parentSessionId === sid('root')) {
  482. return Promise.resolve(ok({
  483. entries: [{
  484. kind: 'child', id: sid('child'), mode: 'continuable', label: 'Child',
  485. activity: 'inactive', hasChildren: true,
  486. }] as never[],
  487. parentAvailable: true,
  488. }))
  489. }
  490. if (parentSessionId === sid('child')) {
  491. return Promise.resolve(ok({
  492. entries: [{
  493. kind: 'child', id: sid('grandchild'), mode: 'continuable', label: 'Grandchild',
  494. activity: 'inactive', hasChildren: false,
  495. }] as never[],
  496. parentAvailable: false,
  497. }))
  498. }
  499. return Promise.resolve(ok({ entries: [], parentAvailable: false }))
  500. }
  501. await feedList(b, [
  502. { id: 'root' },
  503. { id: 'child', cwd: '/summary-child', parentId: 'root', origin: 'subagent' },
  504. { id: 'grandchild', cwd: '/summary-grandchild', parentId: 'child', origin: 'subagent' },
  505. ])
  506. await b.svc.refreshSubagents(sid('root'))
  507. await b.svc.refreshSubagents(sid('child'))
  508. b.svc.openSubagent({
  509. parentSessionId: sid('child'), childSessionId: sid('grandchild'), mode: 'continuable',
  510. })
  511. expect(b.svc.list.getSnapshot().byId[sid('child')]?.displayTitle).toBe('Child')
  512. expect(b.svc.list.getSnapshot().byId[sid('grandchild')]?.displayTitle).toBe('Grandchild')
  513. })
  514. it('projects a directly opened descendant route without retaining ancestor scopes or addresses', async () => {
  515. const b = bench()
  516. b.api.onSubagentList = (payload) => {
  517. const { parentSessionId } = payload as { parentSessionId: SessionId }
  518. if (parentSessionId === sid('root')) {
  519. return Promise.resolve(ok({
  520. entries: [{
  521. kind: 'child', id: sid('child'), mode: 'continuable', label: 'Child',
  522. activity: 'inactive', hasChildren: true,
  523. }] as never[],
  524. parentAvailable: true,
  525. }))
  526. }
  527. if (parentSessionId === sid('child')) {
  528. return Promise.resolve(ok({
  529. entries: [{
  530. kind: 'child', id: sid('grandchild'), mode: 'continuable', label: 'Grandchild',
  531. activity: 'inactive', hasChildren: false,
  532. }] as never[],
  533. parentAvailable: false,
  534. }))
  535. }
  536. return Promise.resolve(ok({ entries: [], parentAvailable: false }))
  537. }
  538. await feedList(b, [{ id: 'root' }])
  539. await b.svc.refreshSubagents(sid('root'))
  540. await b.svc.refreshSubagents(sid('child'))
  541. b.svc.openSubagent({
  542. parentSessionId: sid('child'), childSessionId: sid('grandchild'), mode: 'continuable',
  543. })
  544. const list = b.svc.list.getSnapshot()
  545. expect(list.ids).toEqual([sid('root')])
  546. expect(list.byId[sid('child')]).toMatchObject({ parentId: sid('root'), origin: 'subagent' })
  547. expect(list.byId[sid('grandchild')]).toMatchObject({ parentId: sid('child'), origin: 'subagent' })
  548. expect(b.svc.binding(sid('child'))).toBeUndefined()
  549. expect(b.svc.subagentAddress(sid('child'))).toBeUndefined()
  550. b.svc.open(sid('child'))
  551. expect(b.svc.list.getSnapshot().current).toBe(sid('child'))
  552. expect(b.svc.subagentAddress(sid('child'))).toEqual({
  553. parentSessionId: sid('root'), childSessionId: sid('child'), mode: 'continuable',
  554. })
  555. })
  556. })
  557. describe('create', () => {
  558. it('passes a preallocated id and preserves it on ordinary failure', async () => {
  559. const b = bench()
  560. b.api.onCreate = () => Promise.resolve(ok({ sessionId: sid('fresh') }))
  561. await expect(b.svc.create({ cwd: '/w', sessionId: sid('fresh') })).resolves.toBe('fresh')
  562. expect(b.api.callsOf('session.create')).toEqual([{ cwd: '/w', sessionId: 'fresh' }])
  563. b.api.onCreate = () => Promise.resolve({
  564. rpcId: 'e' as never,
  565. result: { ok: false as const, error: { code: 'internal' as const, message: '爆了', details: {} } },
  566. } as never)
  567. const failure = await b.svc.create({ sessionId: sid('candidate') }).catch((error: unknown) => error)
  568. expect(failure).toBeInstanceOf(SessionCreateError)
  569. expect(failure).toMatchObject({
  570. requestedSessionId: 'candidate',
  571. rpcError: { code: 'internal', message: '爆了' },
  572. })
  573. })
  574. it('resolves with the session already listed and binding-resolvable (no flush wait)', async () => {
  575. const b = bench()
  576. b.api.onCreate = () => Promise.resolve(ok({ sessionId: sid('born') }))
  577. const born = await b.svc.create({ workspaceId: 'ws' as never })
  578. // Synchronously after resolution — the draft hand-off contract: the
  579. // create echo IS the entity entering the client's view (blank row +
  580. // resolvable scope/binding), no notifier flush in between.
  581. expect(b.svc.list.getSnapshot().byId[born]).toMatchObject({ id: 'born', blank: true })
  582. expect(b.svc.binding(born)).toBeDefined()
  583. expect(b.svc.scope(born)).toBeDefined()
  584. })
  585. it('lists the published id after Workspace attachment fails (publication precedes attachment)', async () => {
  586. const b = bench()
  587. b.api.onCreate = () => Promise.resolve({
  588. rpcId: 'attach' as never,
  589. result: {
  590. ok: false,
  591. error: {
  592. code: 'workspace-attach-failed', message: 'ledger unavailable',
  593. details: { sessionId: sid('published'), workspaceId: 'ws' },
  594. },
  595. },
  596. } as never)
  597. const failure = await b.svc.create({
  598. workspaceId: 'ws' as never,
  599. sessionId: sid('published'),
  600. }).catch((error: unknown) => error)
  601. await Promise.resolve()
  602. expect(failure).toBeInstanceOf(SessionCreateError)
  603. expect(failure).toMatchObject({
  604. requestedSessionId: 'published',
  605. rpcError: { code: 'workspace-attach-failed' },
  606. })
  607. expect(b.svc.list.getSnapshot().byId[sid('published')]).toMatchObject({ id: 'published', blank: true })
  608. })
  609. })
  610. describe('fork', () => {
  611. it.each([
  612. ['Roadmap', 'Roadmap (1)'],
  613. ['Roadmap (1)', 'Roadmap (2)'],
  614. ['计划(1)', '计划(2)'],
  615. ['计划 (9)', '计划 (10)'],
  616. ])('increments the durable title %j after the child is published', async (sourceTitle, childTitle) => {
  617. const b = bench()
  618. b.svc.handleControlFrame({
  619. type: 'projection', sessionId: sid('source'), key: 'title', value: sourceTitle, seq: 2,
  620. })
  621. await feedList(b, [{ id: 'source', cwd: '/work' }])
  622. b.api.onFork = () => Promise.resolve(ok({ sessionId: sid('child') }))
  623. b.api.onRename = (payload) => {
  624. const { title } = payload as { title: string }
  625. return Promise.resolve(ok({ title, seq: 3 }))
  626. }
  627. await expect(b.svc.fork({
  628. sessionId: sid('source'), atSeq: 7, increaseTitle: true,
  629. })).resolves.toBe('child')
  630. expect(b.api.callsOf('session.fork')).toEqual([{ sessionId: 'source', atSeq: 7 }])
  631. expect(b.api.callsOf('session.rename')).toEqual([{ sessionId: 'child', title: childTitle }])
  632. await Promise.resolve()
  633. expect(b.svc.list.getSnapshot().byId[sid('child')]).toMatchObject({
  634. title: childTitle,
  635. displayTitle: childTitle,
  636. parentId: 'source',
  637. })
  638. })
  639. it('floors a fractional anchor to the real event seq the wire accepts', async () => {
  640. const b = bench()
  641. await feedList(b, [{ id: 'source', cwd: '/work' }])
  642. b.api.onFork = () => Promise.resolve(ok({ sessionId: sid('child') }))
  643. // The frozen node of an interrupted turn carries turnEnd.seq - 0.9.
  644. await expect(b.svc.fork({ sessionId: sid('source'), atSeq: 41.1 })).resolves.toBe('child')
  645. expect(b.api.callsOf('session.fork')).toEqual([{ sessionId: 'source', atSeq: 41 }])
  646. })
  647. it('does not rename without the title policy or a durable source title', async () => {
  648. const b = bench()
  649. await feedList(b, [{ id: 'source', cwd: '/work' }])
  650. b.api.onFork = () => Promise.resolve(ok({ sessionId: sid('child') }))
  651. await expect(b.svc.fork({ sessionId: sid('source'), increaseTitle: true })).resolves.toBe('child')
  652. expect(b.api.callsOf('session.rename')).toEqual([])
  653. b.api.onFork = () => Promise.resolve(ok({ sessionId: sid('child-2') }))
  654. await expect(b.svc.fork({ sessionId: sid('source') })).resolves.toBe('child-2')
  655. expect(b.api.callsOf('session.rename')).toEqual([])
  656. })
  657. it('rejects when child rename fails while keeping the published child addressable', async () => {
  658. const b = bench()
  659. b.svc.handleControlFrame({
  660. type: 'projection', sessionId: sid('source'), key: 'title', value: 'Roadmap', seq: 2,
  661. })
  662. await feedList(b, [{ id: 'source' }])
  663. b.api.onFork = () => Promise.resolve(ok({ sessionId: sid('child') }))
  664. b.api.onRename = () => Promise.resolve(err({
  665. code: 'title-invalid', message: 'rejected', details: { sessionId: sid('child') },
  666. } as never))
  667. await expect(b.svc.fork({ sessionId: sid('source'), increaseTitle: true }))
  668. .rejects.toThrow('fork child rename failed: title-invalid: rejected')
  669. expect(b.svc.binding(sid('child'))).toBeDefined()
  670. })
  671. })
  672. describe('scope lifecycle rides the list mirror (entity parity: no client-side pre-birth)', () => {
  673. it('a session-added frame births the row (blank) and makes the scope resolvable; removal prunes it', async () => {
  674. const b = bench()
  675. await feedList(b, [])
  676. expect(b.svc.scope(sid('s-new'))).toBeUndefined() // not in view: no scope, no exceptions
  677. b.svc.handleSessionAdded({
  678. sessionId: sid('s-new'), updatedAt: 2, running: false, blank: true, cwd: '/w/a',
  679. })
  680. await Promise.resolve()
  681. const scoped = b.svc.scope(sid('s-new'))
  682. expect(scoped).toBeDefined()
  683. expect(scopeOf(scoped as Context)).toBe('s-new')
  684. b.svc.handleSessionRemoved(sid('s-new'))
  685. await Promise.resolve()
  686. expect(b.svc.scope(sid('s-new'))).toBeUndefined()
  687. })
  688. })
  689. describe('blank mirror', () => {
  690. it('flips blank=false from the running:true status frame (cross-client conversion)', async () => {
  691. const b = bench()
  692. await feedList(b, [{ id: 's1', blank: true }])
  693. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: true })
  694. b.svc.handleSessionStatus(sid('s1'), true)
  695. await Promise.resolve()
  696. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: false, running: true })
  697. // The instantiated Session mirrors the same flip.
  698. expect(b.svc.binding(sid('s1'))?.session.getSnapshot().blank).toBe(false)
  699. })
  700. it('flips blank=false on prompt ACCEPTANCE, not on the attempt', async () => {
  701. const b = bench()
  702. await feedList(b, [{ id: 's1', blank: true, cwd: '/w/a' }])
  703. const session = b.svc.binding(sid('s1'))!.session
  704. expect(session.getSnapshot().blank).toBe(true)
  705. const gate = deferred<Awaited<ReturnType<FakeApiClient['onPrompt']>>>()
  706. b.api.onPrompt = () => gate.promise
  707. const send = session.prompt([{ type: 'text', text: 'hi' }], 'queue')
  708. // In flight: still blank (the flip point is the success response, which
  709. // proves the user message reached the host log).
  710. expect(session.getSnapshot().blank).toBe(true)
  711. gate.resolve(ok({ accepted: true as const }))
  712. await send
  713. expect(session.getSnapshot().blank).toBe(false)
  714. await Promise.resolve()
  715. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: false })
  716. })
  717. it('keeps a rejected first prompt blank: hidden and still reusable', async () => {
  718. const b = bench()
  719. await feedList(b, [{ id: 's1', blank: true, cwd: '/w/a' }])
  720. const session = b.svc.binding(sid('s1'))!.session
  721. b.api.onPrompt = () => Promise.resolve({
  722. rpcId: 'busy' as never,
  723. result: { ok: false as const, error: { code: 'internal' as const, message: 'agent busy', details: {} } },
  724. } as never)
  725. const result = await session.prompt([{ type: 'text', text: 'hi' }], 'queue')
  726. expect(result.ok).toBe(false)
  727. // No flip on failure: local stays aligned with the host authority
  728. // (events.length still 0), so the session stays hidden and reusable.
  729. expect(session.getSnapshot().blank).toBe(true)
  730. await Promise.resolve()
  731. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: true })
  732. })
  733. it('takes session-added blank=true as the hidden birth and list blank as reconnect authority', async () => {
  734. const b = bench()
  735. await feedList(b, [])
  736. b.svc.handleSessionAdded({
  737. sessionId: sid('s-new'), updatedAt: 2, running: false, blank: true, cwd: '/w/a',
  738. })
  739. await Promise.resolve()
  740. expect(b.svc.list.getSnapshot().byId[sid('s-new')]).toMatchObject({ blank: true })
  741. // Reconnect re-pull: the summary's blank=false wins (authoritative alignment).
  742. await feedList(b, [{ id: 's-new', blank: false, cwd: '/w/a' }])
  743. expect(b.svc.list.getSnapshot().byId[sid('s-new')]).toMatchObject({ blank: false })
  744. })
  745. it('never re-blanks: a stale blank=true summary cannot hide an engaged session', async () => {
  746. const b = bench()
  747. await feedList(b, [{ id: 's1', blank: true }])
  748. const session = b.svc.binding(sid('s1'))!.session
  749. await session.prompt([{ type: 'text', text: 'hi' }], 'queue')
  750. await Promise.resolve()
  751. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: false })
  752. // The next list pull still claims blank (host hasn't logged the message yet).
  753. await feedList(b, [{ id: 's1', blank: true }])
  754. expect(b.svc.binding(sid('s1'))?.session.getSnapshot().blank).toBe(false)
  755. })
  756. })
  757. describe('coverage tails (branch duals)', () => {
  758. it('displayTitleOf falls back to the id for empty and separator-only cwd', async () => {
  759. const b = bench()
  760. await feedList(b, [{ id: 'no-base', cwd: '///' }, { id: 'empty-cwd', cwd: '' }])
  761. const { byId } = b.svc.list.getSnapshot()
  762. expect(byId[sid('no-base')]?.displayTitle).toBe('no-base')
  763. expect(byId[sid('empty-cwd')]?.displayTitle).toBe('empty-cwd')
  764. expect(byId[sid('no-base')]?.title).toBeUndefined()
  765. })
  766. it('binding for an unknown session returns undefined and leaves the staged scope intact', async () => {
  767. const b = bench()
  768. await feedList(b, [{ id: 's1' }])
  769. b.svc.open(sid('s1'))
  770. expect(b.svc.binding(sid('ghost'))).toBeUndefined()
  771. // Stage unchanged: removing s1 defers (still staged), proving the ghost lookup touched nothing.
  772. await feedList(b, [])
  773. expect(b.svc.scope(sid('s1'))).toBeDefined()
  774. })
  775. it('a masked current gap holds the stage (no teardown, no re-open) until the stage moves', async () => {
  776. const b = bench()
  777. await feedList(b, [{ id: 's1' }])
  778. b.svc.open(sid('s1'))
  779. await vi.waitFor(() => { expect(b.api.followStarts).toHaveLength(1) })
  780. await feedList(b, []) // removed while staged: current masks to undefined, stage holds → deferred
  781. expect(b.svc.scope(sid('s1'))).toBeDefined()
  782. // Resurfacing re-projects current = s1: same stage occupant, no second pull.
  783. await feedList(b, [{ id: 's1' }])
  784. expect(b.api.followStarts).toHaveLength(1)
  785. expect(b.svc.list.getSnapshot().current).toBe('s1')
  786. })
  787. it('sweep hits both deferral edges: staged-id skip and an already-vacated scope record', async () => {
  788. const b = bench()
  789. await feedList(b, [{ id: 'a' }, { id: 'b' }])
  790. b.svc.scope(sid('a'))
  791. b.svc.open(sid('b')) // stage: b; both scoped
  792. await feedList(b, []) // a removed off stage → torn immediately; b removed staged → deferred
  793. // Move the stage to a THIRD id while b stays deferred: sweep walks a set
  794. // containing b (torn).
  795. await feedList(b, [{ id: 'c' }])
  796. b.svc.open(sid('c'))
  797. expect(b.svc.scope(sid('b'))).toBeUndefined()
  798. // Deferral for an id whose record was never minted: force the deferral
  799. // via removed list state — sweep must tolerate the missing record.
  800. await feedList(b, []) // c removed while staged → deferred (scope exists)
  801. await feedList(b, [{ id: 'd' }])
  802. b.svc.open(sid('d')) // sweep tears c
  803. expect(b.svc.scope(sid('c'))).toBeUndefined()
  804. })
  805. })