manager.spec.ts 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. /**
  2. * SessionManager orchestration: lazy resident instances, list lifecycle, host
  3. * frame routing, and the pending-frame buffer for uninstantiated sessions.
  4. */
  5. import { describe, expect, it, vi } from 'vitest'
  6. import type { SessionId } from '@deepseek-ai/dsh-client-connection/client'
  7. import { SessionManager } from '../src/client/sessions/manager.ts'
  8. import { FakeApiClient, deferred, err, ok } from './fake-api.ts'
  9. import { entries, plainTurn } from './event-script.ts'
  10. const S1 = 'fk-m1' as SessionId
  11. const S2 = 'fk-m2' as SessionId
  12. type SummaryOver = Partial<{
  13. updatedAt: number
  14. running: boolean
  15. blank: boolean
  16. parentSessionId: SessionId
  17. origin: 'subagent'
  18. }>
  19. function summary(sessionId: SessionId, over: SummaryOver = {}) {
  20. return { sessionId, updatedAt: 100, running: false, blank: false, ...over }
  21. }
  22. describe('instances', () => {
  23. it('lazily builds one resident instance per id and syncs the running bit from the list', async () => {
  24. const api = new FakeApiClient()
  25. api.onList = () => Promise.resolve(ok({ items: [summary(S1, { running: true })] as never[] }))
  26. const manager = new SessionManager(api)
  27. await manager.refreshList()
  28. const session = manager.get(S1)
  29. expect(manager.get(S1)).toBe(session) // resident: same instance forever
  30. expect(session.getSnapshot().running).toBe(true) // list preceded instantiation
  31. })
  32. it('replays buffered approval frames on instantiation and drops ordinary frames for uninstantiated sessions', () => {
  33. const api = new FakeApiClient()
  34. const manager = new SessionManager(api)
  35. // Uninstantiated: approval buffers, plain session/event drops.
  36. manager.handleMuxEnvelope({ rpcId: 'ra' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'ap1' as never, toolName: 'rm' } })
  37. manager.handleMuxEnvelope({ rpcId: 're' as never, payload: { type: 'session/event', sessionId: S1, event: plainTurn(0, 0, 'x', 'y')[0] as never } })
  38. const session = manager.get(S1)
  39. expect(session.getSnapshot().pending).toMatchObject([{ kind: 'approval', payload: { approvalId: 'ap1' } }])
  40. // Buffer cleared: a second instantiation of another id gets nothing.
  41. expect(manager.get(S2).getSnapshot().pending).toEqual([])
  42. })
  43. it('caps the pending buffer at 32 keeping the newest, and drops it on session-removed', () => {
  44. const api = new FakeApiClient()
  45. const manager = new SessionManager(api)
  46. // 40 distinct question frames for an uninstantiated session: only the newest 32 survive.
  47. for (let i = 0; i < 40; i++) {
  48. manager.handleMuxEnvelope({ rpcId: `q${i}` as never, payload: { type: 'question/requested', sessionId: S1, questions: [] } })
  49. }
  50. const pending = manager.get(S1).getSnapshot().pending
  51. expect(pending).toHaveLength(32)
  52. expect(pending.map(p => p.key)).toEqual(Array.from({ length: 32 }, (_, i) => `q:q${i + 8}`)) // oldest 8 dropped
  53. // Removed session: buffered frames must not replay on a future instantiation.
  54. manager.handleMuxEnvelope({ rpcId: 'qz' as never, payload: { type: 'question/requested', sessionId: S2, questions: [] } })
  55. manager.handleHostEnvelope({ rpcId: 'hz' as never, payload: { type: 'host/session-removed', sessionId: S2 } })
  56. expect(manager.get(S2).getSnapshot().pending).toEqual([])
  57. })
  58. })
  59. describe('list lifecycle', () => {
  60. it('single-flights refreshList and preserves the Host baseline order', async () => {
  61. const api = new FakeApiClient()
  62. const gate = deferred<Awaited<ReturnType<FakeApiClient['onList']>>>()
  63. api.onList = () => gate.promise
  64. const manager = new SessionManager(api)
  65. const first = manager.refreshList()
  66. const second = manager.refreshList()
  67. expect(manager.getListSnapshot().state).toBe('loading')
  68. gate.resolve(ok({ items: [summary(S2, { updatedAt: 200 }), summary(S1)] as never[] }))
  69. await Promise.all([first, second])
  70. expect(api.callsOf('session.list')).toHaveLength(1)
  71. const snapshot = manager.getListSnapshot()
  72. expect(snapshot.state).toBe('idle')
  73. expect(snapshot.items.map(i => i.sessionId)).toEqual([S2, S1])
  74. })
  75. it('replays incremental frames over hydration and never batch-reorders established ids', async () => {
  76. const api = new FakeApiClient()
  77. const first = deferred<Awaited<ReturnType<FakeApiClient['onList']>>>()
  78. api.onList = () => first.promise
  79. const manager = new SessionManager(api)
  80. const hydration = manager.refreshList()
  81. manager.handleHostEnvelope({
  82. rpcId: 'during-first' as never,
  83. payload: { type: 'host/session-added', blank: true, sessionId: S2 },
  84. })
  85. first.resolve(ok({ items: [summary(S1)] as never[] }))
  86. await hydration
  87. expect(manager.getListSnapshot().items.map(item => item.sessionId)).toEqual([S2, S1])
  88. api.onList = () => Promise.resolve(ok({
  89. items: [summary(S1, { updatedAt: 900 }), summary(S2, { updatedAt: 800 })] as never[],
  90. }))
  91. await manager.refreshList()
  92. expect(manager.getListSnapshot().items.map(item => item.sessionId)).toEqual([S2, S1])
  93. })
  94. it('keeps the error in the list snapshot on failure', async () => {
  95. const api = new FakeApiClient()
  96. api.onList = () => Promise.resolve(err({ code: 'internal', message: 'boom', details: {} }))
  97. const manager = new SessionManager(api)
  98. await manager.refreshList()
  99. expect(manager.getListSnapshot()).toMatchObject({ state: 'error', error: { code: 'internal' } })
  100. // A failed pull does not step the arrival phase: still pending.
  101. expect(manager.getListSnapshot().phase).toBe('pending')
  102. })
  103. it('phase steps pending → ready on the first successful pull and never returns', async () => {
  104. const api = new FakeApiClient()
  105. const manager = new SessionManager(api)
  106. expect(manager.getListSnapshot().phase).toBe('pending')
  107. await manager.refreshList()
  108. expect(manager.getListSnapshot().phase).toBe('ready')
  109. // Sticky across later failures: the pull-activity axis reports the error,
  110. // the arrival phase holds.
  111. api.onList = () => Promise.resolve(err({ code: 'internal', message: 'down', details: {} }))
  112. await manager.refreshList()
  113. expect(manager.getListSnapshot()).toMatchObject({ state: 'error', phase: 'ready' })
  114. // And across an empty re-pull (empty-with-ready = truly no sessions).
  115. api.onList = () => Promise.resolve(ok({ items: [] as never[] }))
  116. await manager.refreshList()
  117. expect(manager.getListSnapshot()).toMatchObject({ state: 'idle', phase: 'ready' })
  118. expect(manager.getListSnapshot().items).toEqual([])
  119. })
  120. it('merges create into the list immediately without waiting for a refresh', async () => {
  121. const api = new FakeApiClient()
  122. api.onCreate = () => Promise.resolve(ok({ sessionId: S2 }))
  123. const manager = new SessionManager(api)
  124. const result = await manager.create()
  125. expect(result).toMatchObject({ ok: true, value: { sessionId: S2 } })
  126. expect(manager.getListSnapshot().items.map(i => i.sessionId)).toEqual([S2])
  127. })
  128. it('retains title projections before list arrival, keeps last-wins by seq, and clears them on removal', async () => {
  129. const api = new FakeApiClient()
  130. const manager = new SessionManager(api)
  131. const titleFrame = (rpcId: string, title: string, seq: number) => {
  132. manager.handleMuxEnvelope({
  133. rpcId: rpcId as never,
  134. payload: { type: 'session/projection', sessionId: S1, key: 'title', value: title, seq } as never,
  135. })
  136. }
  137. titleFrame('title-new', 'Newest', 4)
  138. titleFrame('title-stale', 'Stale', 3)
  139. titleFrame('title-equal', 'Equal', 4)
  140. api.onList = () => Promise.resolve(ok({
  141. items: [summary(S1), summary(S2, { updatedAt: 200 })] as never[],
  142. }))
  143. await manager.refreshList()
  144. const titled = manager.getListSnapshot()
  145. expect(titled.items.map(item => item.sessionId)).toEqual([S1, S2])
  146. expect(titled.items[0]?.title).toBe('Newest')
  147. expect(titled.items[1]?.title).toBeUndefined()
  148. manager.handleHostEnvelope({ rpcId: 'removed' as never, payload: { type: 'host/session-removed', sessionId: S1 } })
  149. manager.handleHostEnvelope({ rpcId: 'readded' as never, payload: { type: 'host/session-added', blank: true, sessionId: S1 } })
  150. expect(manager.getListSnapshot().items.find(item => item.sessionId === S1)?.title).toBeUndefined()
  151. })
  152. it('seeds cold titles from the list rows\' projections block under higher-seq-wins', async () => {
  153. const api = new FakeApiClient()
  154. const manager = new SessionManager(api)
  155. // A push frame landed before the list (S2's title is newer than the block's cut).
  156. manager.handleMuxEnvelope({
  157. rpcId: 'push-newer' as never,
  158. payload: { type: 'session/projection', sessionId: S2, key: 'title', value: 'Pushed', seq: 9 } as never,
  159. })
  160. api.onList = () => Promise.resolve(ok({
  161. items: [
  162. { ...summary(S1), projections: { asOfSeq: 4, values: { title: 'Cold cached' } } },
  163. { ...summary(S2, { updatedAt: 200 }), projections: { asOfSeq: 5, values: { title: 'List stale' } } },
  164. ] as never[],
  165. }))
  166. await manager.refreshList()
  167. const items = manager.getListSnapshot().items
  168. // Cold row: title surfaces straight from the list block — no open, no history.
  169. expect(items.find(item => item.sessionId === S1)?.title).toBe('Cold cached')
  170. // The stale list block (seq 5) cannot overwrite the newer push frame (seq 9).
  171. expect(items.find(item => item.sessionId === S2)?.title).toBe('Pushed')
  172. })
  173. it('drops a projection row beyond the subscription baseline before accepting its durable replay', async () => {
  174. const api = new FakeApiClient()
  175. api.onList = () => Promise.resolve(ok({ items: [summary(S1)] as never[] }))
  176. const manager = new SessionManager(api)
  177. await manager.refreshList()
  178. const frame = (rpcId: string, payload: object) => {
  179. manager.handleMuxEnvelope({ rpcId: rpcId as never, payload: payload as never })
  180. }
  181. frame('title-unflushed', { type: 'session/projection', sessionId: S1, key: 'title', value: 'Unflushed', seq: 4 })
  182. // The durable baseline says the host only knows up to seq 2: the phantom
  183. // row rode lost state and must drop, or last-wins pins it forever.
  184. frame('subscribed-recovered', { type: 'session/subscribed', sessionId: S1, lastSeq: 2 })
  185. expect(manager.getListSnapshot().items[0]?.title).toBeUndefined()
  186. frame('title-durable', { type: 'session/projection', sessionId: S1, key: 'title', value: 'Durable', seq: 2 })
  187. expect(manager.getListSnapshot().items[0]?.title).toBe('Durable')
  188. // A baseline at or past the row's seq keeps it (nothing phantom to drop).
  189. frame('subscribed-current', { type: 'session/subscribed', sessionId: S1, lastSeq: 2 })
  190. expect(manager.getListSnapshot().items[0]?.title).toBe('Durable')
  191. })
  192. })
  193. describe('search', () => {
  194. it('returns bounded Host results and forwards the caller signal', async () => {
  195. const api = new FakeApiClient()
  196. api.onSearch = () => Promise.resolve(ok({
  197. items: [{ sessionId: S1, snippet: 'matching excerpt' }],
  198. hasMore: true,
  199. }))
  200. const manager = new SessionManager(api)
  201. const signal = new AbortController().signal
  202. await expect(manager.search('exact phrase', signal)).resolves.toEqual({
  203. ok: true,
  204. value: {
  205. items: [{ sessionId: S1, snippet: 'matching excerpt' }],
  206. hasMore: true,
  207. },
  208. })
  209. expect(api.callsOf('session.search')).toEqual([{ query: 'exact phrase' }])
  210. expect(api.lastSearchSignal).toBe(signal)
  211. })
  212. it('preserves business errors and folds transport failures', async () => {
  213. const api = new FakeApiClient()
  214. const manager = new SessionManager(api)
  215. api.onSearch = () => Promise.resolve(err({
  216. code: 'internal',
  217. message: 'index unavailable',
  218. details: {},
  219. }))
  220. const signal = new AbortController().signal
  221. await expect(manager.search('first', signal)).resolves.toMatchObject({
  222. ok: false,
  223. error: { code: 'internal', message: 'index unavailable' },
  224. })
  225. api.onSearch = () => Promise.reject(new Error('wire down'))
  226. await expect(manager.search('second', signal)).resolves.toMatchObject({
  227. ok: false,
  228. error: { code: 'internal', message: 'wire down' },
  229. })
  230. })
  231. })
  232. describe('host frame routing', () => {
  233. it('adds/removes/flips sessions from host frames and keeps removed instances resident', async () => {
  234. const api = new FakeApiClient()
  235. const manager = new SessionManager(api)
  236. manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', blank: true, sessionId: S1 } })
  237. manager.handleHostEnvelope({ rpcId: 'h2' as never, payload: { type: 'host/session-added', blank: true, sessionId: S1 } }) // dup: ignored
  238. expect(manager.getListSnapshot().items).toHaveLength(1)
  239. const session = manager.get(S1)
  240. manager.handleHostEnvelope({ rpcId: 'h3' as never, payload: { type: 'host/session-status', sessionId: S1, running: true } })
  241. expect(session.getSnapshot().running).toBe(true)
  242. expect(manager.getListSnapshot().items[0]?.running).toBe(true)
  243. manager.handleHostEnvelope({ rpcId: 'h4' as never, payload: { type: 'host/agent-error', sessionId: S1, message: '炸了' } })
  244. expect(session.getSnapshot().lastAgentError).toBe('炸了')
  245. manager.handleHostEnvelope({ rpcId: 'h5' as never, payload: { type: 'host/session-removed', sessionId: S1 } })
  246. expect(manager.getListSnapshot().items).toHaveLength(0)
  247. expect(session.getSnapshot().removed).toBe(true)
  248. expect(manager.get(S1)).toBe(session) // resident-instance rule survives removal
  249. })
  250. })
  251. describe('subagent catalogs', () => {
  252. it('keeps a catalog-discovered child address across ordinary selection and status frames', async () => {
  253. const api = new FakeApiClient()
  254. api.onList = () => Promise.resolve(ok({ items: [
  255. summary(S1),
  256. summary(S2, { parentSessionId: S1, origin: 'subagent' }),
  257. ] as never[] }))
  258. api.onSubagentList = () => Promise.resolve(ok({
  259. entries: [{
  260. kind: 'child', id: S2, mode: 'continuable', label: 'worker',
  261. activity: 'running', hasChildren: false,
  262. }] as never[],
  263. parentAvailable: true,
  264. }))
  265. const manager = new SessionManager(api)
  266. await manager.refreshList()
  267. await manager.refreshSubagents(S1)
  268. manager.selectSubagent({ parentSessionId: S1, childSessionId: S2, mode: 'continuable' })
  269. expect(manager.getListSnapshot().currentAddress).toEqual({
  270. parentSessionId: S1, childSessionId: S2, mode: 'continuable',
  271. })
  272. expect(manager.get(S2).getSnapshot().subagent).toEqual({
  273. address: { parentSessionId: S1, childSessionId: S2, mode: 'continuable' },
  274. parentAvailable: true,
  275. })
  276. // Clicking the same child through an ordinary list-selection path must not
  277. // erase the catalog-derived address and fall back to session.* transport.
  278. manager.select(S2)
  279. expect(manager.getListSnapshot().currentAddress).toEqual({
  280. parentSessionId: S1, childSessionId: S2, mode: 'continuable',
  281. })
  282. expect(manager.get(S2).getSnapshot().subagent).toEqual({
  283. address: { parentSessionId: S1, childSessionId: S2, mode: 'continuable' },
  284. parentAvailable: true,
  285. })
  286. await manager.get(S2).open()
  287. await manager.get(S2).prompt([{ type: 'text', text: 'continue' }], 'queue')
  288. expect(api.callsOf('subagent.history')).toEqual([
  289. { parentSessionId: S1, childSessionId: S2, mode: 'continuable', maxMessages: 50 },
  290. ])
  291. expect(api.callsOf('subagent.prompt')).toEqual([
  292. {
  293. parentSessionId: S1, childSessionId: S2, mode: 'continuable',
  294. content: [{ type: 'text', text: 'continue' }],
  295. },
  296. ])
  297. expect(api.callsOf('session.history')).toEqual([])
  298. expect(api.callsOf('session.prompt')).toEqual([])
  299. const listCalls = api.callsOf('subagent.list').length
  300. manager.handleHostEnvelope({
  301. rpcId: 'child-complete' as never,
  302. payload: { type: 'host/session-status', sessionId: S2, running: false },
  303. })
  304. expect(manager.getListSnapshot().subagentsByParent[S1]?.entries[0]).toMatchObject({
  305. kind: 'child', id: S2, activity: 'inactive',
  306. })
  307. expect(api.callsOf('subagent.list')).toHaveLength(listCalls)
  308. manager.handleHostEnvelope({
  309. rpcId: 'child-detached' as never,
  310. payload: { type: 'host/session-removed', sessionId: S2 },
  311. })
  312. expect(manager.getListSnapshot().items.find(item => item.sessionId === S2)).toMatchObject({
  313. origin: 'subagent', parentSessionId: S1, running: false,
  314. })
  315. expect(manager.get(S2).getSnapshot()).toMatchObject({
  316. removed: false,
  317. subagent: {
  318. address: { parentSessionId: S1, childSessionId: S2, mode: 'continuable' },
  319. },
  320. })
  321. })
  322. it('refetches debounced membership only while the parent catalog is open', async () => {
  323. vi.useFakeTimers()
  324. try {
  325. const api = new FakeApiClient()
  326. const manager = new SessionManager(api)
  327. await manager.refreshSubagents(S1)
  328. manager.setSubagentCatalogOpen(S1, true)
  329. await Promise.resolve()
  330. const baseline = api.callsOf('subagent.list').length
  331. manager.handleHostEnvelope({
  332. rpcId: 'child-added' as never,
  333. payload: {
  334. type: 'host/session-added', sessionId: S2, parentSessionId: S1, blank: false,
  335. },
  336. })
  337. manager.handleHostEnvelope({
  338. rpcId: 'child-added-again' as never,
  339. payload: {
  340. type: 'host/session-added', sessionId: 'fk-m3' as SessionId, parentSessionId: S1, blank: false,
  341. },
  342. })
  343. await vi.advanceTimersByTimeAsync(50)
  344. expect(api.callsOf('subagent.list')).toHaveLength(baseline + 1)
  345. manager.setSubagentCatalogOpen(S1, false)
  346. manager.handleHostEnvelope({
  347. rpcId: 'child-added-closed' as never,
  348. payload: {
  349. type: 'host/session-added', sessionId: 'fk-m4' as SessionId, parentSessionId: S1, blank: false,
  350. },
  351. })
  352. await vi.advanceTimersByTimeAsync(50)
  353. expect(api.callsOf('subagent.list')).toHaveLength(baseline + 1)
  354. } finally {
  355. vi.useRealTimers()
  356. }
  357. })
  358. it('marks a loaded parent row expandable only for a direct subagent publication', async () => {
  359. const api = new FakeApiClient()
  360. const root = 'fk-root' as SessionId
  361. api.onSubagentList = () => Promise.resolve(ok({
  362. entries: [
  363. {
  364. kind: 'child', id: S1, mode: 'continuable', label: 'parent',
  365. activity: 'inactive', hasChildren: false,
  366. },
  367. {
  368. kind: 'child', id: S2, mode: 'continuable', label: 'ordinary parent',
  369. activity: 'inactive', hasChildren: false,
  370. },
  371. ] as never[],
  372. parentAvailable: true,
  373. }))
  374. const manager = new SessionManager(api)
  375. await manager.refreshSubagents(root)
  376. manager.handleHostEnvelope({
  377. rpcId: 'nested-subagent' as never,
  378. payload: {
  379. type: 'host/session-added', sessionId: 'fk-grandchild' as SessionId,
  380. parentSessionId: S1, origin: 'subagent', blank: false,
  381. },
  382. })
  383. manager.handleHostEnvelope({
  384. rpcId: 'ordinary-fork' as never,
  385. payload: {
  386. type: 'host/session-added', sessionId: 'fk-fork' as SessionId,
  387. parentSessionId: S2, blank: false,
  388. },
  389. })
  390. expect(manager.getListSnapshot().subagentsByParent[root]?.entries).toMatchObject([
  391. { kind: 'child', id: S1, hasChildren: true },
  392. { kind: 'child', id: S2, hasChildren: false },
  393. ])
  394. })
  395. it('preserves a live expandability hint across only the older in-flight catalog response', async () => {
  396. const api = new FakeApiClient()
  397. const root = 'fk-root' as SessionId
  398. const response = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  399. api.onSubagentList = () => response.promise
  400. const manager = new SessionManager(api)
  401. const refresh = manager.refreshSubagents(root)
  402. manager.handleHostEnvelope({
  403. rpcId: 'nested-subagent' as never,
  404. payload: {
  405. type: 'host/session-added', sessionId: 'fk-grandchild' as SessionId,
  406. parentSessionId: S1, origin: 'subagent', blank: false,
  407. },
  408. })
  409. response.resolve(ok({
  410. entries: [{
  411. kind: 'child', id: S1, mode: 'continuable', label: 'parent',
  412. activity: 'inactive', hasChildren: false,
  413. }] as never[],
  414. parentAvailable: true,
  415. }))
  416. await refresh
  417. expect(manager.getListSnapshot().subagentsByParent[root]?.entries).toMatchObject([
  418. { kind: 'child', id: S1, hasChildren: true },
  419. ])
  420. api.onSubagentList = () => Promise.resolve(ok({
  421. entries: [{
  422. kind: 'child', id: S1, mode: 'continuable', label: 'parent',
  423. activity: 'inactive', hasChildren: false,
  424. }] as never[],
  425. parentAvailable: true,
  426. }))
  427. await manager.refreshSubagents(root)
  428. expect(manager.getListSnapshot().subagentsByParent[root]?.entries).toMatchObject([
  429. { kind: 'child', id: S1, hasChildren: false },
  430. ])
  431. })
  432. it('replays status frames over an older in-flight catalog response', async () => {
  433. const api = new FakeApiClient()
  434. const root = 'fk-root' as SessionId
  435. const response = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  436. api.onSubagentList = () => response.promise
  437. const manager = new SessionManager(api)
  438. const refresh = manager.refreshSubagents(root)
  439. manager.handleHostEnvelope({
  440. rpcId: 'child-stopped' as never,
  441. payload: { type: 'host/session-status', sessionId: S1, running: false },
  442. })
  443. manager.handleHostEnvelope({
  444. rpcId: 'child-started' as never,
  445. payload: { type: 'host/session-status', sessionId: S2, running: true },
  446. })
  447. response.resolve(ok({
  448. entries: [
  449. {
  450. kind: 'child', id: S1, mode: 'continuable', label: 'stopped',
  451. activity: 'running', hasChildren: false,
  452. },
  453. {
  454. kind: 'child', id: S2, mode: 'continuable', label: 'started',
  455. activity: 'inactive', hasChildren: false,
  456. },
  457. ] as never[],
  458. parentAvailable: true,
  459. }))
  460. await refresh
  461. expect(manager.getListSnapshot().subagentsByParent[root]?.entries).toMatchObject([
  462. { kind: 'child', id: S1, activity: 'inactive' },
  463. { kind: 'child', id: S2, activity: 'running' },
  464. ])
  465. })
  466. it('marks a detached catalog child inactive without requiring a selected address', async () => {
  467. const api = new FakeApiClient()
  468. api.onSubagentList = () => Promise.resolve(ok({
  469. entries: [{
  470. kind: 'child', id: S2, mode: 'continuable', label: 'worker',
  471. activity: 'running', hasChildren: false,
  472. }] as never[],
  473. parentAvailable: true,
  474. }))
  475. const manager = new SessionManager(api)
  476. await manager.refreshSubagents(S1)
  477. manager.handleHostEnvelope({
  478. rpcId: 'child-detached' as never,
  479. payload: { type: 'host/session-removed', sessionId: S2 },
  480. })
  481. expect(manager.getListSnapshot().subagentsByParent[S1]?.entries).toMatchObject([
  482. { kind: 'child', id: S2, activity: 'inactive' },
  483. ])
  484. })
  485. it('coalesces overlapping catalog reads without scheduling a trailing pull', async () => {
  486. const api = new FakeApiClient()
  487. const root = 'fk-root' as SessionId
  488. const first = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  489. api.onSubagentList = () => first.promise
  490. const manager = new SessionManager(api)
  491. const refresh = manager.refreshSubagents(root)
  492. expect(manager.refreshSubagents(root)).toBe(refresh)
  493. api.onSubagentList = () => Promise.resolve(ok({ entries: [], parentAvailable: true }))
  494. first.resolve(ok({ entries: [], parentAvailable: true }))
  495. await refresh
  496. expect(api.callsOf('subagent.list')).toHaveLength(1)
  497. })
  498. it('runs one trailing catalog refresh for a membership change coalesced into an in-flight pull', async () => {
  499. vi.useFakeTimers()
  500. try {
  501. const api = new FakeApiClient()
  502. const root = 'fk-root' as SessionId
  503. const first = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  504. const second = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  505. api.onSubagentList = () => first.promise
  506. const manager = new SessionManager(api, root)
  507. const refresh = manager.refreshSubagents(root)
  508. // A membership frame arrives while the pull is in flight; the debounced
  509. // refresh it schedules fires 50ms later and is coalesced into the pull —
  510. // which was requested before the new child existed. The stale mark must
  511. // queue one trailing pull carrying the change.
  512. manager.handleHostEnvelope({
  513. rpcId: 'child-added' as never,
  514. payload: {
  515. type: 'host/session-added', sessionId: S2, parentSessionId: root, blank: false,
  516. },
  517. })
  518. await vi.advanceTimersByTimeAsync(50)
  519. api.onSubagentList = () => second.promise
  520. first.resolve(ok({
  521. entries: [{
  522. kind: 'child', id: S1, mode: 'continuable', label: 'older',
  523. activity: 'inactive', hasChildren: false,
  524. }] as never[],
  525. parentAvailable: true,
  526. }))
  527. await refresh
  528. // The trailing pull is already in flight (kicked synchronously in finally).
  529. second.resolve(ok({
  530. entries: [
  531. {
  532. kind: 'child', id: S1, mode: 'continuable', label: 'older',
  533. activity: 'inactive', hasChildren: false,
  534. },
  535. {
  536. kind: 'child', id: S2, mode: 'continuable', label: 'new child',
  537. activity: 'inactive', hasChildren: false,
  538. },
  539. ] as never[],
  540. parentAvailable: true,
  541. }))
  542. await second.promise
  543. expect(api.callsOf('subagent.list')).toHaveLength(2)
  544. expect(manager.getListSnapshot().subagentsByParent[root]?.entries).toMatchObject([
  545. { kind: 'child', id: S1, label: 'older' },
  546. { kind: 'child', id: S2, label: 'new child' },
  547. ])
  548. } finally {
  549. vi.useRealTimers()
  550. }
  551. })
  552. it('keeps removal invalidation across a stale success and failed trailing pull', async () => {
  553. const api = new FakeApiClient()
  554. const root = 'fk-root' as SessionId
  555. const child = () => ({
  556. kind: 'child' as const, id: S2, mode: 'continuable' as const, label: 'worker',
  557. activity: 'inactive' as const, hasChildren: false,
  558. })
  559. const first = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  560. api.onSubagentList = () => first.promise
  561. const manager = new SessionManager(api)
  562. const refresh = manager.refreshSubagents(root)
  563. first.resolve(ok({ entries: [child()] as never[], parentAvailable: true }))
  564. await refresh
  565. manager.selectSubagent({ parentSessionId: root, childSessionId: S2, mode: 'continuable' })
  566. // The removal lands while a second pull is in flight: the invalidation
  567. // must survive the pre-removal ok response, so one trailing pull runs.
  568. const mid = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  569. api.onSubagentList = () => mid.promise
  570. const midRefresh = manager.refreshSubagents(root)
  571. manager.handleHostEnvelope({
  572. rpcId: 'parent-removed-mid-pull' as never,
  573. payload: { type: 'host/session-removed', sessionId: root },
  574. })
  575. const trailing = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  576. api.onSubagentList = () => trailing.promise
  577. mid.resolve(ok({ entries: [child()] as never[], parentAvailable: true }))
  578. await midRefresh
  579. expect(manager.getListSnapshot().subagentsByParent[root]?.parentAvailable).toBe(false)
  580. expect(manager.get(S2).getSnapshot().subagent).toMatchObject({ parentAvailable: false })
  581. trailing.resolve(err({ code: 'internal', message: 'trailing pull failed', details: {} }))
  582. await vi.waitFor(() => {
  583. expect(manager.getListSnapshot().subagentsByParent[root]).toMatchObject({
  584. state: 'error',
  585. parentAvailable: false,
  586. })
  587. })
  588. const rootCalls = api.callsOf('subagent.list')
  589. .filter(call => (call as { parentSessionId: SessionId }).parentSessionId === root)
  590. expect(rootCalls).toHaveLength(3)
  591. expect(manager.getListSnapshot().subagentsByParent[root]?.parentAvailable).toBe(false)
  592. expect(manager.get(S2).getSnapshot().subagent).toMatchObject({ parentAvailable: false })
  593. })
  594. it('invalidates catalog availability when the owning parent is removed', async () => {
  595. const api = new FakeApiClient()
  596. const root = 'fk-root' as SessionId
  597. api.onSubagentList = () => Promise.resolve(ok({
  598. entries: [{
  599. kind: 'child', id: S2, mode: 'continuable', label: 'worker',
  600. activity: 'inactive', hasChildren: false,
  601. }] as never[],
  602. parentAvailable: true,
  603. }))
  604. const manager = new SessionManager(api)
  605. await manager.refreshSubagents(root)
  606. manager.selectSubagent({ parentSessionId: root, childSessionId: S2, mode: 'continuable' })
  607. expect(manager.get(S2).getSnapshot().subagent).toMatchObject({ parentAvailable: true })
  608. manager.handleHostEnvelope({
  609. rpcId: 'parent-removed' as never,
  610. payload: { type: 'host/session-removed', sessionId: root },
  611. })
  612. expect(manager.getListSnapshot().subagentsByParent[root]?.parentAvailable).toBe(false)
  613. expect(manager.get(S2).getSnapshot().subagent).toMatchObject({ parentAvailable: false })
  614. })
  615. })
  616. describe('remaining branches', () => {
  617. it('refreshList folds a transport throw into the error state', async () => {
  618. const api = new FakeApiClient()
  619. api.onList = () => Promise.reject(new Error('list wire down'))
  620. const manager = new SessionManager(api)
  621. await manager.refreshList()
  622. expect(manager.getListSnapshot()).toMatchObject({ state: 'error', error: { code: 'internal', message: 'list wire down' } })
  623. })
  624. it('refreshList pushes running bits down to already-instantiated sessions', async () => {
  625. const api = new FakeApiClient()
  626. const manager = new SessionManager(api)
  627. const session = manager.get(S1)
  628. api.onList = () => Promise.resolve(ok({ items: [summary(S1, { running: true })] as never[] }))
  629. await manager.refreshList()
  630. expect(session.getSnapshot().running).toBe(true)
  631. })
  632. it('create passes cwd and a preallocated id, folds transport throws, and deduplicates the echo', async () => {
  633. const api = new FakeApiClient()
  634. api.onCreate = () => Promise.resolve(ok({ sessionId: S1 }))
  635. const manager = new SessionManager(api)
  636. await manager.create({ cwd: '/tmp/w', sessionId: S1 })
  637. expect(api.callsOf('session.create')).toEqual([{ cwd: '/tmp/w', sessionId: S1 }])
  638. expect(manager.getListSnapshot().items[0]).toMatchObject({ sessionId: S1, cwd: '/tmp/w' })
  639. await manager.create({ cwd: '/tmp/w' }) // same id returned: no duplicate row
  640. expect(manager.getListSnapshot().items).toHaveLength(1)
  641. api.onCreate = () => Promise.reject(new Error('create wire down'))
  642. expect(await manager.create()).toMatchObject({ ok: false, error: { code: 'internal' } })
  643. // Business error passes through untouched.
  644. api.onCreate = () => Promise.resolve(err({ code: 'internal', message: 'no', details: {} }))
  645. expect(await manager.create()).toMatchObject({ ok: false })
  646. })
  647. it('publishes a real Ungrouped summary from workspace-attach-failed', async () => {
  648. const api = new FakeApiClient()
  649. api.onCreate = () => Promise.resolve(err({
  650. code: 'workspace-attach-failed',
  651. message: 'published but unattached',
  652. details: { sessionId: S1, workspaceId: 'w1' },
  653. } as never))
  654. const manager = new SessionManager(api)
  655. const result = await manager.create({ workspaceId: 'w1' as never, sessionId: S1 })
  656. expect(result).toMatchObject({ ok: false, error: { code: 'workspace-attach-failed' } })
  657. expect(manager.getListSnapshot().items).toEqual([expect.objectContaining({ sessionId: S1 })])
  658. expect(manager.getListSnapshot().items[0]).not.toHaveProperty('cwd')
  659. })
  660. it('reconciles a fork child published before workspace attachment fails', async () => {
  661. const api = new FakeApiClient()
  662. api.onFork = () => Promise.resolve(err({
  663. code: 'workspace-attach-failed',
  664. message: 'forked but unattached',
  665. details: { sessionId: S2, workspaceId: 'w1' },
  666. } as never))
  667. const manager = new SessionManager(api)
  668. const result = await manager.fork({ sessionId: S1 })
  669. expect(result).toMatchObject({ ok: false, error: { code: 'workspace-attach-failed' } })
  670. expect(manager.getListSnapshot().items).toEqual([expect.objectContaining({
  671. sessionId: S2,
  672. parentSessionId: S1,
  673. blank: false,
  674. })])
  675. })
  676. it('reconciles a preallocated id after an ordinary transport failure', async () => {
  677. const api = new FakeApiClient()
  678. api.onCreate = () => Promise.reject(new Error('response lost'))
  679. const manager = new SessionManager(api)
  680. const failed = await manager.create({ workspaceId: 'w1' as never, sessionId: S1 })
  681. expect(failed).toMatchObject({ ok: false, error: { message: 'response lost' } })
  682. expect(manager.getListSnapshot().items).toEqual([])
  683. manager.handleHostEnvelope({
  684. rpcId: 'published-later' as never,
  685. payload: { type: 'host/session-added', blank: true, sessionId: S1, cwd: '/w/one' },
  686. })
  687. expect(manager.getListSnapshot().items).toEqual([
  688. expect.objectContaining({ sessionId: S1, cwd: '/w/one' }),
  689. ])
  690. manager.handleHostEnvelope({
  691. rpcId: 'duplicate-frame' as never,
  692. payload: { type: 'host/session-added', blank: true, sessionId: S1, cwd: '/w/one' },
  693. })
  694. expect(manager.getListSnapshot().items).toHaveLength(1)
  695. })
  696. it('subscribe notifies on list changes and stops after unsubscribe', async () => {
  697. const api = new FakeApiClient()
  698. const manager = new SessionManager(api)
  699. let notified = 0
  700. const unsubscribe = manager.subscribe(() => { notified++ })
  701. await manager.refreshList()
  702. await new Promise(resolve => setTimeout(resolve, 0))
  703. expect(notified).toBeGreaterThan(0)
  704. const seen = notified
  705. unsubscribe()
  706. manager.handleHostEnvelope({ rpcId: 'h' as never, payload: { type: 'host/session-added', blank: true, sessionId: S1 } })
  707. await new Promise(resolve => setTimeout(resolve, 0))
  708. expect(notified).toBe(seen)
  709. })
  710. it('routes stream/error and unknown frames to the documented drops, and dispatches to instantiated sessions', () => {
  711. const api = new FakeApiClient()
  712. const manager = new SessionManager(api)
  713. manager.handleMuxEnvelope({ rpcId: 'e' as never, payload: { type: 'stream/error', error: { code: 'internal', message: 'x', details: {} } } })
  714. manager.handleHostEnvelope({ rpcId: 'e2' as never, payload: { type: 'stream/error', error: { code: 'internal', message: 'x', details: {} } } })
  715. manager.handleHostEnvelope({ rpcId: 'e3' as never, payload: { type: 'future/host-frame' } as never })
  716. const session = manager.get(S1)
  717. manager.handleMuxEnvelope({ rpcId: 'q1' as never, payload: { type: 'question/requested', sessionId: S1, questions: [] } })
  718. expect(session.getSnapshot().pending).toMatchObject([{ kind: 'question' }])
  719. // status flip for an unknown session only touches summaries (no crash).
  720. manager.handleHostEnvelope({ rpcId: 'h9' as never, payload: { type: 'host/session-status', sessionId: S2, running: true } })
  721. manager.handleHostEnvelope({ rpcId: 'ha' as never, payload: { type: 'host/agent-error', sessionId: S2, message: '无实例' } })
  722. })
  723. it('keeps list-entry identity for unchanged rows across an unrelated list change', async () => {
  724. const api = new FakeApiClient()
  725. api.onList = () => Promise.resolve(ok({ items: [summary(S1), summary(S2, { updatedAt: 200 })] as never[] }))
  726. const manager = new SessionManager(api)
  727. await manager.refreshList()
  728. const before = manager.getListSnapshot()
  729. manager.handleHostEnvelope({ rpcId: 'h' as never, payload: { type: 'host/session-status', sessionId: S2, running: true } })
  730. const after = manager.getListSnapshot()
  731. expect(after.items).not.toBe(before.items)
  732. const beforeS1 = before.items.find(e => e.sessionId === S1)
  733. const afterS1 = after.items.find(e => e.sessionId === S1)
  734. expect(afterS1).toBe(beforeS1) // untouched entry keeps identity (entryCache)
  735. // Same-order same-entries snapshot reuses the items array.
  736. manager.handleHostEnvelope({ rpcId: 'h2' as never, payload: { type: 'host/agent-error', sessionId: S1, message: 'x' } })
  737. expect(manager.getListSnapshot().items).toBe(after.items)
  738. })
  739. it('carries parentSessionId from host/session-added into the lineage row', () => {
  740. const api = new FakeApiClient()
  741. const manager = new SessionManager(api)
  742. manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', blank: true, sessionId: S1 } })
  743. manager.handleHostEnvelope({
  744. rpcId: 'h2' as never,
  745. payload: {
  746. type: 'host/session-added', blank: true, sessionId: S2,
  747. parentSessionId: S1, origin: 'subagent',
  748. },
  749. })
  750. const items = manager.getListSnapshot().items
  751. expect(items.find(e => e.sessionId === S2)).toMatchObject({
  752. parentSessionId: S1, origin: 'subagent', depth: 1,
  753. })
  754. })
  755. })
  756. describe('connected generation', () => {
  757. it('refreshes the list and resyncs only opened instances', async () => {
  758. const api = new FakeApiClient()
  759. api.onHistory = () => Promise.resolve(ok({
  760. events: entries(plainTurn(0, 0, 'a', 'b')) as never[],
  761. hasMore: false,
  762. modelTarget: { provider: 'deepseek-official', model: 'deepseek-chat' },
  763. }))
  764. const manager = new SessionManager(api)
  765. const openedSession = manager.get(S1)
  766. await openedSession.open()
  767. manager.get(S2) // instantiated but never opened
  768. const historyCallsBefore = api.callsOf('session.history').length
  769. manager.handleConnected()
  770. await vi.waitFor(() => {
  771. expect(api.callsOf('session.list').length).toBe(1)
  772. // Only the opened instance repulls history; the cold one stays silent.
  773. expect(api.callsOf('session.history').length).toBe(historyCallsBefore + 1)
  774. })
  775. })
  776. it('reloads the durable parent address for a restored child selection', async () => {
  777. const api = new FakeApiClient()
  778. const address = {
  779. parentSessionId: S1, childSessionId: S2, mode: 'continuable' as const,
  780. }
  781. const manager = new SessionManager(api, S2, address)
  782. manager.handleConnected()
  783. await vi.waitFor(() => {
  784. expect(api.callsOf('subagent.list')).toContainEqual({ parentSessionId: S1 })
  785. })
  786. expect(manager.getListSnapshot().currentAddress).toEqual(address)
  787. })
  788. })
  789. describe('waiting-approval list bit', () => {
  790. it('lights on requested, survives replay duplicates, and clears on resolved — without instantiation', () => {
  791. const manager = new SessionManager(new FakeApiClient())
  792. manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', sessionId: S1, blank: false } })
  793. expect(manager.getListSnapshot().items[0]?.waitingApproval).toBe(false)
  794. manager.handleMuxEnvelope({ rpcId: 'ra' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'ap1' as never, toolName: 'rm' } })
  795. expect(manager.getListSnapshot().items[0]?.waitingApproval).toBe(true)
  796. // Mux-open replay of the same question (same approvalId) is idempotent.
  797. manager.handleMuxEnvelope({ rpcId: 'ra' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'ap1' as never, toolName: 'rm' } })
  798. expect(manager.getListSnapshot().items[0]?.waitingApproval).toBe(true)
  799. manager.handleMuxEnvelope({ rpcId: 'rx' as never, payload: { type: 'approval/resolved', sessionId: S1, approvalId: 'ap1' as never, outcome: 'allowed-once' as never } })
  800. expect(manager.getListSnapshot().items[0]?.waitingApproval).toBe(false)
  801. })
  802. it('clears only when the last outstanding question resolves; session-removed drops the bit', () => {
  803. const manager = new SessionManager(new FakeApiClient())
  804. manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', sessionId: S1, blank: false } })
  805. manager.handleMuxEnvelope({ rpcId: 'r1' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'a1' as never, toolName: 'rm' } })
  806. manager.handleMuxEnvelope({ rpcId: 'r2' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'a2' as never, toolName: 'rm' } })
  807. manager.handleMuxEnvelope({ rpcId: 'rx' as never, payload: { type: 'approval/resolved', sessionId: S1, approvalId: 'a1' as never, outcome: 'rejected' as never } })
  808. expect(manager.getListSnapshot().items[0]?.waitingApproval).toBe(true)
  809. manager.handleMuxEnvelope({ rpcId: 'ry' as never, payload: { type: 'approval/resolved', sessionId: S1, approvalId: 'a2' as never, outcome: 'rejected' as never } })
  810. expect(manager.getListSnapshot().items[0]?.waitingApproval).toBe(false)
  811. // Removed sessions drop their bit outright.
  812. manager.handleMuxEnvelope({ rpcId: 'r3' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'a3' as never, toolName: 'rm' } })
  813. manager.handleHostEnvelope({ rpcId: 'h2' as never, payload: { type: 'host/session-removed', sessionId: S1 } })
  814. expect(manager.getListSnapshot().items).toHaveLength(0)
  815. })
  816. it('drops stale bits at generation death — BEFORE the reopen replay re-adds still-pending questions', () => {
  817. const manager = new SessionManager(new FakeApiClient())
  818. manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', sessionId: S1, blank: false } })
  819. manager.handleMuxEnvelope({ rpcId: 'ra' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'ap1' as never, toolName: 'rm' } })
  820. expect(manager.getListSnapshot().items[0]?.waitingApproval).toBe(true)
  821. // Generation death clears (resolved-while-disconnected questions send no frame)…
  822. manager.handleDisconnected()
  823. expect(manager.getListSnapshot().items[0]?.waitingApproval).toBe(false)
  824. // …and a replayed frame arriving before onConnected (stream open precedes
  825. // the readiness handshake) survives the later handleConnected untouched.
  826. manager.handleMuxEnvelope({ rpcId: 'ra' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'ap1' as never, toolName: 'rm' } })
  827. manager.handleConnected()
  828. expect(manager.getListSnapshot().items[0]?.waitingApproval).toBe(true)
  829. })
  830. it('generation death drops buffered answerable frames (a dead generation cannot be answered)', () => {
  831. const manager = new SessionManager(new FakeApiClient())
  832. manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', sessionId: S1, blank: false } })
  833. // Buffered pre-instantiation: an approval pair and a queued row.
  834. manager.handleMuxEnvelope({ rpcId: 'ra' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'ap1' as never, toolName: 'rm' } })
  835. manager.handleMuxEnvelope({ rpcId: 'q1' as never, payload: { type: 'question/requested', sessionId: S1, questions: [] } })
  836. manager.handleDisconnected()
  837. // Instantiate after the death sweep: no zombie interaction replays (the
  838. // pendingBuffers held only dead-generation rpcIds), so the session mints
  839. // no pending waits.
  840. const session = manager.get(S1)
  841. expect(session.getSnapshot().pending).toEqual([])
  842. })
  843. })