sessions-service.client.spec.ts 35 KB

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