sessions-service.client.spec.ts 35 KB

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