manager.spec.ts 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  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: 'ra' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'ap1' as never, toolName: 'rm' } })
  38. manager.handleMuxEnvelope({ rpcId: 're' as never, payload: { type: 'session/event', sessionId: S1, event: plainTurn(0, 0, 'x', 'y')[0] as never } })
  39. const session = manager.get(S1)
  40. expect(session.getSnapshot().pending).toMatchObject([{ kind: 'approval', payload: { approvalId: 'ap1' } }])
  41. // Buffer cleared: a second instantiation of another id gets nothing.
  42. expect(manager.get(S2).getSnapshot().pending).toEqual([])
  43. })
  44. it('retains every live answerable request and compacts resolutions before instantiation', () => {
  45. const api = new FakeApiClient()
  46. const manager = new SessionManager(api)
  47. manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', sessionId: S1, blank: false } })
  48. for (let i = 0; i < 40; i++) {
  49. manager.handleMuxEnvelope({ rpcId: `q${i}` as never, payload: { type: 'question/requested', sessionId: S1, questions: [] } })
  50. }
  51. expect(manager.getListSnapshot().items[0]?.pendingInteraction).toBe('question')
  52. for (let i = 0; i < 40; i++) {
  53. manager.handleMuxEnvelope({
  54. rpcId: `r${i}` as never,
  55. payload: { type: 'question/resolved', sessionId: S1, questionRpcId: `q${i}` as never, outcome: 'answered' },
  56. })
  57. }
  58. expect(manager.getListSnapshot().items[0]?.pendingInteraction).toBeUndefined()
  59. expect(manager.get(S1).getSnapshot().pending).toEqual([])
  60. })
  61. it('drops buffered answerable requests on session removal', () => {
  62. const manager = new SessionManager(new FakeApiClient())
  63. // Removed session: buffered frames must not replay on a future instantiation.
  64. manager.handleMuxEnvelope({ rpcId: 'qz' as never, payload: { type: 'question/requested', sessionId: S2, questions: [] } })
  65. manager.handleHostEnvelope({ rpcId: 'hz' as never, payload: { type: 'host/session-removed', sessionId: S2 } })
  66. expect(manager.get(S2).getSnapshot().pending).toEqual([])
  67. })
  68. })
  69. describe('list lifecycle', () => {
  70. it('single-flights refreshList and preserves the Host baseline order', async () => {
  71. const api = new FakeApiClient()
  72. const gate = deferred<Awaited<ReturnType<FakeApiClient['onList']>>>()
  73. api.onList = () => gate.promise
  74. const manager = new SessionManager(api)
  75. const first = manager.refreshList()
  76. const second = manager.refreshList()
  77. expect(manager.getListSnapshot().state).toBe('loading')
  78. gate.resolve(ok({ items: [summary(S2, { updatedAt: 200 }), summary(S1)] as never[] }))
  79. await Promise.all([first, second])
  80. expect(api.callsOf('session.list')).toHaveLength(1)
  81. const snapshot = manager.getListSnapshot()
  82. expect(snapshot.state).toBe('idle')
  83. expect(snapshot.items.map(i => i.sessionId)).toEqual([S2, S1])
  84. })
  85. it('replays incremental frames over hydration and never batch-reorders established ids', async () => {
  86. const api = new FakeApiClient()
  87. const first = deferred<Awaited<ReturnType<FakeApiClient['onList']>>>()
  88. api.onList = () => first.promise
  89. const manager = new SessionManager(api)
  90. const hydration = manager.refreshList()
  91. manager.handleHostEnvelope({
  92. rpcId: 'during-first' as never,
  93. payload: { type: 'host/session-added', blank: true, sessionId: S2 },
  94. })
  95. first.resolve(ok({ items: [summary(S1)] as never[] }))
  96. await hydration
  97. expect(manager.getListSnapshot().items.map(item => item.sessionId)).toEqual([S2, S1])
  98. api.onList = () => Promise.resolve(ok({
  99. items: [summary(S1, { updatedAt: 900 }), summary(S2, { updatedAt: 800 })] as never[],
  100. }))
  101. await manager.refreshList()
  102. expect(manager.getListSnapshot().items.map(item => item.sessionId)).toEqual([S2, S1])
  103. })
  104. it('keeps the error in the list snapshot on failure', async () => {
  105. const api = new FakeApiClient()
  106. api.onList = () => Promise.resolve(err({ code: 'internal', message: 'boom', details: {} }))
  107. const manager = new SessionManager(api)
  108. await manager.refreshList()
  109. expect(manager.getListSnapshot()).toMatchObject({ state: 'error', error: { code: 'internal' } })
  110. // A failed pull does not step the arrival phase: still pending.
  111. expect(manager.getListSnapshot().phase).toBe('pending')
  112. })
  113. it('phase steps pending → ready on the first successful pull and never returns', async () => {
  114. const api = new FakeApiClient()
  115. const manager = new SessionManager(api)
  116. expect(manager.getListSnapshot().phase).toBe('pending')
  117. await manager.refreshList()
  118. expect(manager.getListSnapshot().phase).toBe('ready')
  119. // Sticky across later failures: the pull-activity axis reports the error,
  120. // the arrival phase holds.
  121. api.onList = () => Promise.resolve(err({ code: 'internal', message: 'down', details: {} }))
  122. await manager.refreshList()
  123. expect(manager.getListSnapshot()).toMatchObject({ state: 'error', phase: 'ready' })
  124. // And across an empty re-pull (empty-with-ready = truly no sessions).
  125. api.onList = () => Promise.resolve(ok({ items: [] as never[] }))
  126. await manager.refreshList()
  127. expect(manager.getListSnapshot()).toMatchObject({ state: 'idle', phase: 'ready' })
  128. expect(manager.getListSnapshot().items).toEqual([])
  129. })
  130. it('merges create into the list immediately without waiting for a refresh', async () => {
  131. const api = new FakeApiClient()
  132. api.onCreate = () => Promise.resolve(ok({ sessionId: S2 }))
  133. const manager = new SessionManager(api)
  134. const result = await manager.create()
  135. expect(result).toMatchObject({ ok: true, value: { sessionId: S2 } })
  136. expect(manager.getListSnapshot().items.map(i => i.sessionId)).toEqual([S2])
  137. })
  138. it('retains title projections before list arrival, keeps last-wins by seq, and clears them on removal', async () => {
  139. const api = new FakeApiClient()
  140. const manager = new SessionManager(api)
  141. const titleFrame = (rpcId: string, title: string, seq: number) => {
  142. manager.handleMuxEnvelope({
  143. rpcId: rpcId as never,
  144. payload: { type: 'session/projection', sessionId: S1, key: 'title', value: title, seq } as never,
  145. })
  146. }
  147. titleFrame('title-new', 'Newest', 4)
  148. titleFrame('title-stale', 'Stale', 3)
  149. titleFrame('title-equal', 'Equal', 4)
  150. api.onList = () => Promise.resolve(ok({
  151. items: [summary(S1), summary(S2, { updatedAt: 200 })] as never[],
  152. }))
  153. await manager.refreshList()
  154. const titled = manager.getListSnapshot()
  155. expect(titled.items.map(item => item.sessionId)).toEqual([S1, S2])
  156. expect(titled.items[0]?.title).toBe('Newest')
  157. expect(titled.items[1]?.title).toBeUndefined()
  158. manager.handleHostEnvelope({ rpcId: 'removed' as never, payload: { type: 'host/session-removed', sessionId: S1 } })
  159. manager.handleHostEnvelope({ rpcId: 'readded' as never, payload: { type: 'host/session-added', blank: true, sessionId: S1 } })
  160. expect(manager.getListSnapshot().items.find(item => item.sessionId === S1)?.title).toBeUndefined()
  161. })
  162. it('seeds cold titles from the list rows\' projections block under higher-seq-wins', async () => {
  163. const api = new FakeApiClient()
  164. const manager = new SessionManager(api)
  165. // A push frame landed before the list (S2's title is newer than the block's cut).
  166. manager.handleMuxEnvelope({
  167. rpcId: 'push-newer' as never,
  168. payload: { type: 'session/projection', sessionId: S2, key: 'title', value: 'Pushed', seq: 9 } as never,
  169. })
  170. api.onList = () => Promise.resolve(ok({
  171. items: [
  172. { ...summary(S1), projections: { asOfSeq: 4, values: { title: 'Cold cached' } } },
  173. { ...summary(S2, { updatedAt: 200 }), projections: { asOfSeq: 5, values: { title: 'List stale' } } },
  174. ] as never[],
  175. }))
  176. await manager.refreshList()
  177. const items = manager.getListSnapshot().items
  178. // Cold row: title surfaces straight from the list block — no open, no history.
  179. expect(items.find(item => item.sessionId === S1)?.title).toBe('Cold cached')
  180. // The stale list block (seq 5) cannot overwrite the newer push frame (seq 9).
  181. expect(items.find(item => item.sessionId === S2)?.title).toBe('Pushed')
  182. })
  183. it('drops a projection row beyond the subscription baseline before accepting its durable replay', async () => {
  184. const api = new FakeApiClient()
  185. api.onList = () => Promise.resolve(ok({ items: [summary(S1)] as never[] }))
  186. const manager = new SessionManager(api)
  187. await manager.refreshList()
  188. const frame = (rpcId: string, payload: object) => {
  189. manager.handleMuxEnvelope({ rpcId: rpcId as never, payload: payload as never })
  190. }
  191. frame('title-unflushed', { type: 'session/projection', sessionId: S1, key: 'title', value: 'Unflushed', seq: 4 })
  192. // The durable baseline says the host only knows up to seq 2: the phantom
  193. // row rode lost state and must drop, or last-wins pins it forever.
  194. frame('subscribed-recovered', { type: 'session/subscribed', sessionId: S1, lastSeq: 2 })
  195. expect(manager.getListSnapshot().items[0]?.title).toBeUndefined()
  196. frame('title-durable', { type: 'session/projection', sessionId: S1, key: 'title', value: 'Durable', seq: 2 })
  197. expect(manager.getListSnapshot().items[0]?.title).toBe('Durable')
  198. // A baseline at or past the row's seq keeps it (nothing phantom to drop).
  199. frame('subscribed-current', { type: 'session/subscribed', sessionId: S1, lastSeq: 2 })
  200. expect(manager.getListSnapshot().items[0]?.title).toBe('Durable')
  201. })
  202. })
  203. describe('search', () => {
  204. it('returns bounded Host results and forwards the caller signal', async () => {
  205. const api = new FakeApiClient()
  206. api.onSearch = () => Promise.resolve(ok({
  207. items: [{ sessionId: S1, snippet: 'matching excerpt' }],
  208. hasMore: true,
  209. }))
  210. const manager = new SessionManager(api)
  211. const signal = new AbortController().signal
  212. await expect(manager.search('exact phrase', signal)).resolves.toEqual({
  213. ok: true,
  214. value: {
  215. items: [{ sessionId: S1, snippet: 'matching excerpt' }],
  216. hasMore: true,
  217. },
  218. })
  219. expect(api.callsOf('session.search')).toEqual([{ query: 'exact phrase' }])
  220. expect(api.lastSearchSignal).toBe(signal)
  221. })
  222. it('preserves business errors and folds transport failures', async () => {
  223. const api = new FakeApiClient()
  224. const manager = new SessionManager(api)
  225. api.onSearch = () => Promise.resolve(err({
  226. code: 'internal',
  227. message: 'index unavailable',
  228. details: {},
  229. }))
  230. const signal = new AbortController().signal
  231. await expect(manager.search('first', signal)).resolves.toMatchObject({
  232. ok: false,
  233. error: { code: 'internal', message: 'index unavailable' },
  234. })
  235. api.onSearch = () => Promise.reject(new Error('wire down'))
  236. await expect(manager.search('second', signal)).resolves.toMatchObject({
  237. ok: false,
  238. error: { code: 'internal', message: 'wire down' },
  239. })
  240. })
  241. })
  242. describe('host frame routing', () => {
  243. it('adds/removes/flips sessions from host frames and keeps removed instances resident', async () => {
  244. const api = new FakeApiClient()
  245. const manager = new SessionManager(api)
  246. manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', blank: true, sessionId: S1 } })
  247. manager.handleHostEnvelope({ rpcId: 'h2' as never, payload: { type: 'host/session-added', blank: true, sessionId: S1 } }) // dup: ignored
  248. expect(manager.getListSnapshot().items).toHaveLength(1)
  249. const session = manager.get(S1)
  250. manager.handleHostEnvelope({ rpcId: 'h3' as never, payload: { type: 'host/session-status', sessionId: S1, running: true } })
  251. expect(session.getSnapshot().running).toBe(true)
  252. expect(manager.getListSnapshot().items[0]?.running).toBe(true)
  253. manager.handleHostEnvelope({ rpcId: 'h4' as never, payload: { type: 'host/agent-error', sessionId: S1, message: '炸了' } })
  254. expect(session.getSnapshot().lastAgentError).toBe('炸了')
  255. manager.handleHostEnvelope({ rpcId: 'h5' as never, payload: { type: 'host/session-removed', sessionId: S1 } })
  256. expect(manager.getListSnapshot().items).toHaveLength(0)
  257. expect(session.getSnapshot().removed).toBe(true)
  258. expect(manager.get(S1)).toBe(session) // resident-instance rule survives removal
  259. })
  260. })
  261. describe('subagent catalogs', () => {
  262. it('keeps a catalog-discovered child address across ordinary selection and status frames', async () => {
  263. const api = new FakeApiClient()
  264. api.onList = () => Promise.resolve(ok({ items: [
  265. summary(S1),
  266. summary(S2, { parentSessionId: S1, origin: 'subagent' }),
  267. ] as never[] }))
  268. api.onSubagentList = () => Promise.resolve(ok({
  269. entries: [{
  270. kind: 'child', id: S2, mode: 'continuable', label: 'worker',
  271. activity: 'running', hasChildren: false,
  272. }] as never[],
  273. parentAvailable: true,
  274. }))
  275. const manager = new SessionManager(api)
  276. await manager.refreshList()
  277. await manager.refreshSubagents(S1)
  278. manager.selectSubagent({ parentSessionId: S1, childSessionId: S2, mode: 'continuable' })
  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. // Clicking the same child through an ordinary list-selection path must not
  287. // erase the catalog-derived address and fall back to session.* transport.
  288. manager.select(S2)
  289. expect(manager.getListSnapshot().currentAddress).toEqual({
  290. parentSessionId: S1, childSessionId: S2, mode: 'continuable',
  291. })
  292. expect(manager.get(S2).getSnapshot().subagent).toEqual({
  293. address: { parentSessionId: S1, childSessionId: S2, mode: 'continuable' },
  294. parentAvailable: true,
  295. })
  296. await manager.get(S2).open()
  297. await manager.get(S2).prompt([{ type: 'text', text: 'continue' }], 'queue')
  298. expect(api.callsOf('subagent.history')).toEqual([
  299. { parentSessionId: S1, childSessionId: S2, mode: 'continuable', maxMessages: 50 },
  300. ])
  301. expect(api.callsOf('subagent.prompt')).toEqual([
  302. {
  303. parentSessionId: S1, childSessionId: S2, mode: 'continuable',
  304. content: [{ type: 'text', text: 'continue' }],
  305. clientTimeZone: new Intl.DateTimeFormat().resolvedOptions().timeZone,
  306. },
  307. ])
  308. expect(api.callsOf('session.history')).toEqual([])
  309. expect(api.callsOf('session.prompt')).toEqual([])
  310. const listCalls = api.callsOf('subagent.list').length
  311. manager.handleHostEnvelope({
  312. rpcId: 'child-complete' as never,
  313. payload: { type: 'host/session-status', sessionId: S2, running: false },
  314. })
  315. expect(manager.getListSnapshot().subagentsByParent[S1]?.entries[0]).toMatchObject({
  316. kind: 'child', id: S2, activity: 'inactive',
  317. })
  318. expect(api.callsOf('subagent.list')).toHaveLength(listCalls)
  319. manager.handleHostEnvelope({
  320. rpcId: 'child-detached' as never,
  321. payload: { type: 'host/session-removed', sessionId: S2 },
  322. })
  323. expect(manager.getListSnapshot().items.find(item => item.sessionId === S2)).toMatchObject({
  324. origin: 'subagent', parentSessionId: S1, running: false,
  325. })
  326. expect(manager.get(S2).getSnapshot()).toMatchObject({
  327. removed: false,
  328. subagent: {
  329. address: { parentSessionId: S1, childSessionId: S2, mode: 'continuable' },
  330. },
  331. })
  332. })
  333. it('refetches debounced membership only while the parent catalog is open', async () => {
  334. vi.useFakeTimers()
  335. try {
  336. const api = new FakeApiClient()
  337. const manager = new SessionManager(api)
  338. await manager.refreshSubagents(S1)
  339. manager.setSubagentCatalogOpen(S1, true)
  340. await Promise.resolve()
  341. const baseline = api.callsOf('subagent.list').length
  342. manager.handleHostEnvelope({
  343. rpcId: 'child-added' as never,
  344. payload: {
  345. type: 'host/session-added', sessionId: S2, parentSessionId: S1, blank: false,
  346. },
  347. })
  348. manager.handleHostEnvelope({
  349. rpcId: 'child-added-again' as never,
  350. payload: {
  351. type: 'host/session-added', sessionId: 'fk-m3' as SessionId, parentSessionId: S1, blank: false,
  352. },
  353. })
  354. await vi.advanceTimersByTimeAsync(50)
  355. expect(api.callsOf('subagent.list')).toHaveLength(baseline + 1)
  356. manager.setSubagentCatalogOpen(S1, false)
  357. manager.handleHostEnvelope({
  358. rpcId: 'child-added-closed' as never,
  359. payload: {
  360. type: 'host/session-added', sessionId: 'fk-m4' as SessionId, parentSessionId: S1, blank: false,
  361. },
  362. })
  363. await vi.advanceTimersByTimeAsync(50)
  364. expect(api.callsOf('subagent.list')).toHaveLength(baseline + 1)
  365. } finally {
  366. vi.useRealTimers()
  367. }
  368. })
  369. it('marks a loaded parent row expandable only for a direct subagent publication', async () => {
  370. const api = new FakeApiClient()
  371. const root = 'fk-root' as SessionId
  372. api.onSubagentList = () => Promise.resolve(ok({
  373. entries: [
  374. {
  375. kind: 'child', id: S1, mode: 'continuable', label: 'parent',
  376. activity: 'inactive', hasChildren: false,
  377. },
  378. {
  379. kind: 'child', id: S2, mode: 'continuable', label: 'ordinary parent',
  380. activity: 'inactive', hasChildren: false,
  381. },
  382. ] as never[],
  383. parentAvailable: true,
  384. }))
  385. const manager = new SessionManager(api)
  386. await manager.refreshSubagents(root)
  387. manager.handleHostEnvelope({
  388. rpcId: 'nested-subagent' as never,
  389. payload: {
  390. type: 'host/session-added', sessionId: 'fk-grandchild' as SessionId,
  391. parentSessionId: S1, origin: 'subagent', blank: false,
  392. },
  393. })
  394. manager.handleHostEnvelope({
  395. rpcId: 'ordinary-fork' as never,
  396. payload: {
  397. type: 'host/session-added', sessionId: 'fk-fork' as SessionId,
  398. parentSessionId: S2, blank: false,
  399. },
  400. })
  401. expect(manager.getListSnapshot().subagentsByParent[root]?.entries).toMatchObject([
  402. { kind: 'child', id: S1, hasChildren: true },
  403. { kind: 'child', id: S2, hasChildren: false },
  404. ])
  405. })
  406. it('preserves a live expandability hint across only the older in-flight catalog response', async () => {
  407. const api = new FakeApiClient()
  408. const root = 'fk-root' as SessionId
  409. const response = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  410. api.onSubagentList = () => response.promise
  411. const manager = new SessionManager(api)
  412. const refresh = manager.refreshSubagents(root)
  413. manager.handleHostEnvelope({
  414. rpcId: 'nested-subagent' as never,
  415. payload: {
  416. type: 'host/session-added', sessionId: 'fk-grandchild' as SessionId,
  417. parentSessionId: S1, origin: 'subagent', blank: false,
  418. },
  419. })
  420. response.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 refresh
  428. expect(manager.getListSnapshot().subagentsByParent[root]?.entries).toMatchObject([
  429. { kind: 'child', id: S1, hasChildren: true },
  430. ])
  431. api.onSubagentList = () => Promise.resolve(ok({
  432. entries: [{
  433. kind: 'child', id: S1, mode: 'continuable', label: 'parent',
  434. activity: 'inactive', hasChildren: false,
  435. }] as never[],
  436. parentAvailable: true,
  437. }))
  438. await manager.refreshSubagents(root)
  439. expect(manager.getListSnapshot().subagentsByParent[root]?.entries).toMatchObject([
  440. { kind: 'child', id: S1, hasChildren: false },
  441. ])
  442. })
  443. it('replays status frames over an older in-flight catalog response', async () => {
  444. const api = new FakeApiClient()
  445. const root = 'fk-root' as SessionId
  446. const response = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  447. api.onSubagentList = () => response.promise
  448. const manager = new SessionManager(api)
  449. const refresh = manager.refreshSubagents(root)
  450. manager.handleHostEnvelope({
  451. rpcId: 'child-stopped' as never,
  452. payload: { type: 'host/session-status', sessionId: S1, running: false },
  453. })
  454. manager.handleHostEnvelope({
  455. rpcId: 'child-started' as never,
  456. payload: { type: 'host/session-status', sessionId: S2, running: true },
  457. })
  458. response.resolve(ok({
  459. entries: [
  460. {
  461. kind: 'child', id: S1, mode: 'continuable', label: 'stopped',
  462. activity: 'running', hasChildren: false,
  463. },
  464. {
  465. kind: 'child', id: S2, mode: 'continuable', label: 'started',
  466. activity: 'inactive', hasChildren: false,
  467. },
  468. ] as never[],
  469. parentAvailable: true,
  470. }))
  471. await refresh
  472. expect(manager.getListSnapshot().subagentsByParent[root]?.entries).toMatchObject([
  473. { kind: 'child', id: S1, activity: 'inactive' },
  474. { kind: 'child', id: S2, activity: 'running' },
  475. ])
  476. })
  477. it('marks a detached catalog child inactive without requiring a selected address', async () => {
  478. const api = new FakeApiClient()
  479. api.onSubagentList = () => Promise.resolve(ok({
  480. entries: [{
  481. kind: 'child', id: S2, mode: 'continuable', label: 'worker',
  482. activity: 'running', hasChildren: false,
  483. }] as never[],
  484. parentAvailable: true,
  485. }))
  486. const manager = new SessionManager(api)
  487. await manager.refreshSubagents(S1)
  488. manager.handleHostEnvelope({
  489. rpcId: 'child-detached' as never,
  490. payload: { type: 'host/session-removed', sessionId: S2 },
  491. })
  492. expect(manager.getListSnapshot().subagentsByParent[S1]?.entries).toMatchObject([
  493. { kind: 'child', id: S2, activity: 'inactive' },
  494. ])
  495. })
  496. it('coalesces overlapping catalog reads without scheduling a trailing pull', async () => {
  497. const api = new FakeApiClient()
  498. const root = 'fk-root' as SessionId
  499. const first = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  500. api.onSubagentList = () => first.promise
  501. const manager = new SessionManager(api)
  502. const refresh = manager.refreshSubagents(root)
  503. expect(manager.refreshSubagents(root)).toBe(refresh)
  504. api.onSubagentList = () => Promise.resolve(ok({ entries: [], parentAvailable: true }))
  505. first.resolve(ok({ entries: [], parentAvailable: true }))
  506. await refresh
  507. expect(api.callsOf('subagent.list')).toHaveLength(1)
  508. })
  509. it('runs one trailing catalog refresh for a membership change coalesced into an in-flight pull', async () => {
  510. vi.useFakeTimers()
  511. try {
  512. const api = new FakeApiClient()
  513. const root = 'fk-root' as SessionId
  514. const first = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  515. const second = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  516. api.onSubagentList = () => first.promise
  517. const manager = new SessionManager(api, root)
  518. const refresh = manager.refreshSubagents(root)
  519. // A membership frame arrives while the pull is in flight; the debounced
  520. // refresh it schedules fires 50ms later and is coalesced into the pull —
  521. // which was requested before the new child existed. The stale mark must
  522. // queue one trailing pull carrying the change.
  523. manager.handleHostEnvelope({
  524. rpcId: 'child-added' as never,
  525. payload: {
  526. type: 'host/session-added', sessionId: S2, parentSessionId: root, blank: false,
  527. },
  528. })
  529. await vi.advanceTimersByTimeAsync(50)
  530. api.onSubagentList = () => second.promise
  531. first.resolve(ok({
  532. entries: [{
  533. kind: 'child', id: S1, mode: 'continuable', label: 'older',
  534. activity: 'inactive', hasChildren: false,
  535. }] as never[],
  536. parentAvailable: true,
  537. }))
  538. await refresh
  539. // The trailing pull is already in flight (kicked synchronously in finally).
  540. second.resolve(ok({
  541. entries: [
  542. {
  543. kind: 'child', id: S1, mode: 'continuable', label: 'older',
  544. activity: 'inactive', hasChildren: false,
  545. },
  546. {
  547. kind: 'child', id: S2, mode: 'continuable', label: 'new child',
  548. activity: 'inactive', hasChildren: false,
  549. },
  550. ] as never[],
  551. parentAvailable: true,
  552. }))
  553. await second.promise
  554. expect(api.callsOf('subagent.list')).toHaveLength(2)
  555. expect(manager.getListSnapshot().subagentsByParent[root]?.entries).toMatchObject([
  556. { kind: 'child', id: S1, label: 'older' },
  557. { kind: 'child', id: S2, label: 'new child' },
  558. ])
  559. } finally {
  560. vi.useRealTimers()
  561. }
  562. })
  563. it('keeps removal invalidation across a stale success and failed trailing pull', async () => {
  564. const api = new FakeApiClient()
  565. const root = 'fk-root' as SessionId
  566. const child = () => ({
  567. kind: 'child' as const, id: S2, mode: 'continuable' as const, label: 'worker',
  568. activity: 'inactive' as const, hasChildren: false,
  569. })
  570. const first = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  571. api.onSubagentList = () => first.promise
  572. const manager = new SessionManager(api)
  573. const refresh = manager.refreshSubagents(root)
  574. first.resolve(ok({ entries: [child()] as never[], parentAvailable: true }))
  575. await refresh
  576. manager.selectSubagent({ parentSessionId: root, childSessionId: S2, mode: 'continuable' })
  577. // The removal lands while a second pull is in flight: the invalidation
  578. // must survive the pre-removal ok response, so one trailing pull runs.
  579. const mid = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  580. api.onSubagentList = () => mid.promise
  581. const midRefresh = manager.refreshSubagents(root)
  582. manager.handleHostEnvelope({
  583. rpcId: 'parent-removed-mid-pull' as never,
  584. payload: { type: 'host/session-removed', sessionId: root },
  585. })
  586. const trailing = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  587. api.onSubagentList = () => trailing.promise
  588. mid.resolve(ok({ entries: [child()] as never[], parentAvailable: true }))
  589. await midRefresh
  590. expect(manager.getListSnapshot().subagentsByParent[root]?.parentAvailable).toBe(false)
  591. expect(manager.get(S2).getSnapshot().subagent).toMatchObject({ parentAvailable: false })
  592. trailing.resolve(err({ code: 'internal', message: 'trailing pull failed', details: {} }))
  593. await vi.waitFor(() => {
  594. expect(manager.getListSnapshot().subagentsByParent[root]).toMatchObject({
  595. state: 'error',
  596. parentAvailable: false,
  597. })
  598. })
  599. const rootCalls = api.callsOf('subagent.list')
  600. .filter(call => (call as { parentSessionId: SessionId }).parentSessionId === root)
  601. expect(rootCalls).toHaveLength(3)
  602. expect(manager.getListSnapshot().subagentsByParent[root]?.parentAvailable).toBe(false)
  603. expect(manager.get(S2).getSnapshot().subagent).toMatchObject({ parentAvailable: false })
  604. })
  605. it('invalidates catalog availability when the owning parent is removed', async () => {
  606. const api = new FakeApiClient()
  607. const root = 'fk-root' as SessionId
  608. api.onSubagentList = () => Promise.resolve(ok({
  609. entries: [{
  610. kind: 'child', id: S2, mode: 'continuable', label: 'worker',
  611. activity: 'inactive', hasChildren: false,
  612. }] as never[],
  613. parentAvailable: true,
  614. }))
  615. const manager = new SessionManager(api)
  616. await manager.refreshSubagents(root)
  617. manager.selectSubagent({ parentSessionId: root, childSessionId: S2, mode: 'continuable' })
  618. expect(manager.get(S2).getSnapshot().subagent).toMatchObject({ parentAvailable: true })
  619. manager.handleHostEnvelope({
  620. rpcId: 'parent-removed' as never,
  621. payload: { type: 'host/session-removed', sessionId: root },
  622. })
  623. expect(manager.getListSnapshot().subagentsByParent[root]?.parentAvailable).toBe(false)
  624. expect(manager.get(S2).getSnapshot().subagent).toMatchObject({ parentAvailable: false })
  625. })
  626. })
  627. describe('remaining branches', () => {
  628. it('refreshList folds a transport throw into the error state', async () => {
  629. const api = new FakeApiClient()
  630. api.onList = () => Promise.reject(new Error('list wire down'))
  631. const manager = new SessionManager(api)
  632. await manager.refreshList()
  633. expect(manager.getListSnapshot()).toMatchObject({ state: 'error', error: { code: 'internal', message: 'list wire down' } })
  634. })
  635. it('refreshList pushes running bits down to already-instantiated sessions', async () => {
  636. const api = new FakeApiClient()
  637. const manager = new SessionManager(api)
  638. const session = manager.get(S1)
  639. api.onList = () => Promise.resolve(ok({ items: [summary(S1, { running: true })] as never[] }))
  640. await manager.refreshList()
  641. expect(session.getSnapshot().running).toBe(true)
  642. })
  643. it('create passes cwd and a preallocated id, folds transport throws, and deduplicates the echo', async () => {
  644. const api = new FakeApiClient()
  645. api.onCreate = () => Promise.resolve(ok({ sessionId: S1 }))
  646. const manager = new SessionManager(api)
  647. await manager.create({ cwd: '/tmp/w', sessionId: S1 })
  648. expect(api.callsOf('session.create')).toEqual([{ cwd: '/tmp/w', sessionId: S1 }])
  649. expect(manager.getListSnapshot().items[0]).toMatchObject({ sessionId: S1, cwd: '/tmp/w' })
  650. await manager.create({ cwd: '/tmp/w' }) // same id returned: no duplicate row
  651. expect(manager.getListSnapshot().items).toHaveLength(1)
  652. api.onCreate = () => Promise.reject(new Error('create wire down'))
  653. expect(await manager.create()).toMatchObject({ ok: false, error: { code: 'internal' } })
  654. // Business error passes through untouched.
  655. api.onCreate = () => Promise.resolve(err({ code: 'internal', message: 'no', details: {} }))
  656. expect(await manager.create()).toMatchObject({ ok: false })
  657. })
  658. it('publishes a real Ungrouped summary from workspace-attach-failed', async () => {
  659. const api = new FakeApiClient()
  660. api.onCreate = () => Promise.resolve(err({
  661. code: 'workspace-attach-failed',
  662. message: 'published but unattached',
  663. details: { sessionId: S1, workspaceId: 'w1' },
  664. } as never))
  665. const manager = new SessionManager(api)
  666. const result = await manager.create({ workspaceId: 'w1' as never, sessionId: S1 })
  667. expect(result).toMatchObject({ ok: false, error: { code: 'workspace-attach-failed' } })
  668. expect(manager.getListSnapshot().items).toEqual([expect.objectContaining({ sessionId: S1 })])
  669. expect(manager.getListSnapshot().items[0]).not.toHaveProperty('cwd')
  670. })
  671. it('reconciles a fork child published before workspace attachment fails', async () => {
  672. const api = new FakeApiClient()
  673. api.onFork = () => Promise.resolve(err({
  674. code: 'workspace-attach-failed',
  675. message: 'forked but unattached',
  676. details: { sessionId: S2, workspaceId: 'w1' },
  677. } as never))
  678. const manager = new SessionManager(api)
  679. const result = await manager.fork({ sessionId: S1 })
  680. expect(result).toMatchObject({ ok: false, error: { code: 'workspace-attach-failed' } })
  681. expect(manager.getListSnapshot().items).toEqual([expect.objectContaining({
  682. sessionId: S2,
  683. parentSessionId: S1,
  684. blank: false,
  685. })])
  686. })
  687. it('reconciles a preallocated id after an ordinary transport failure', async () => {
  688. const api = new FakeApiClient()
  689. api.onCreate = () => Promise.reject(new Error('response lost'))
  690. const manager = new SessionManager(api)
  691. const failed = await manager.create({ workspaceId: 'w1' as never, sessionId: S1 })
  692. expect(failed).toMatchObject({ ok: false, error: { message: 'response lost' } })
  693. expect(manager.getListSnapshot().items).toEqual([])
  694. manager.handleHostEnvelope({
  695. rpcId: 'published-later' as never,
  696. payload: { type: 'host/session-added', blank: true, sessionId: S1, cwd: '/w/one' },
  697. })
  698. expect(manager.getListSnapshot().items).toEqual([
  699. expect.objectContaining({ sessionId: S1, cwd: '/w/one' }),
  700. ])
  701. manager.handleHostEnvelope({
  702. rpcId: 'duplicate-frame' as never,
  703. payload: { type: 'host/session-added', blank: true, sessionId: S1, cwd: '/w/one' },
  704. })
  705. expect(manager.getListSnapshot().items).toHaveLength(1)
  706. })
  707. it('subscribe notifies on list changes and stops after unsubscribe', async () => {
  708. const api = new FakeApiClient()
  709. const manager = new SessionManager(api)
  710. let notified = 0
  711. const unsubscribe = manager.subscribe(() => { notified++ })
  712. await manager.refreshList()
  713. await new Promise(resolve => setTimeout(resolve, 0))
  714. expect(notified).toBeGreaterThan(0)
  715. const seen = notified
  716. unsubscribe()
  717. manager.handleHostEnvelope({ rpcId: 'h' as never, payload: { type: 'host/session-added', blank: true, sessionId: S1 } })
  718. await new Promise(resolve => setTimeout(resolve, 0))
  719. expect(notified).toBe(seen)
  720. })
  721. it('routes stream/error and unknown frames to the documented drops, and dispatches to instantiated sessions', () => {
  722. const api = new FakeApiClient()
  723. const manager = new SessionManager(api)
  724. manager.handleMuxEnvelope({ rpcId: 'e' as never, payload: { type: 'stream/error', error: { code: 'internal', message: 'x', details: {} } } })
  725. manager.handleHostEnvelope({ rpcId: 'e2' as never, payload: { type: 'stream/error', error: { code: 'internal', message: 'x', details: {} } } })
  726. manager.handleHostEnvelope({ rpcId: 'e3' as never, payload: { type: 'future/host-frame' } as never })
  727. const session = manager.get(S1)
  728. manager.handleMuxEnvelope({ rpcId: 'q1' as never, payload: { type: 'question/requested', sessionId: S1, questions: [] } })
  729. expect(session.getSnapshot().pending).toMatchObject([{ kind: 'question' }])
  730. // status flip for an unknown session only touches summaries (no crash).
  731. manager.handleHostEnvelope({ rpcId: 'h9' as never, payload: { type: 'host/session-status', sessionId: S2, running: true } })
  732. manager.handleHostEnvelope({ rpcId: 'ha' as never, payload: { type: 'host/agent-error', sessionId: S2, message: '无实例' } })
  733. })
  734. it('keeps list-entry identity for unchanged rows across an unrelated list change', async () => {
  735. const api = new FakeApiClient()
  736. api.onList = () => Promise.resolve(ok({ items: [summary(S1), summary(S2, { updatedAt: 200 })] as never[] }))
  737. const manager = new SessionManager(api)
  738. await manager.refreshList()
  739. const before = manager.getListSnapshot()
  740. manager.handleHostEnvelope({ rpcId: 'h' as never, payload: { type: 'host/session-status', sessionId: S2, running: true } })
  741. const after = manager.getListSnapshot()
  742. expect(after.items).not.toBe(before.items)
  743. const beforeS1 = before.items.find(e => e.sessionId === S1)
  744. const afterS1 = after.items.find(e => e.sessionId === S1)
  745. expect(afterS1).toBe(beforeS1) // untouched entry keeps identity (entryCache)
  746. // Same-order same-entries snapshot reuses the items array.
  747. manager.handleHostEnvelope({ rpcId: 'h2' as never, payload: { type: 'host/agent-error', sessionId: S1, message: 'x' } })
  748. expect(manager.getListSnapshot().items).toBe(after.items)
  749. })
  750. it('carries parentSessionId from host/session-added into the lineage row', () => {
  751. const api = new FakeApiClient()
  752. const manager = new SessionManager(api)
  753. manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', blank: true, sessionId: S1 } })
  754. manager.handleHostEnvelope({
  755. rpcId: 'h2' as never,
  756. payload: {
  757. type: 'host/session-added', blank: true, sessionId: S2,
  758. parentSessionId: S1, origin: 'subagent',
  759. },
  760. })
  761. const items = manager.getListSnapshot().items
  762. expect(items.find(e => e.sessionId === S2)).toMatchObject({
  763. parentSessionId: S1, origin: 'subagent', depth: 1,
  764. })
  765. })
  766. })
  767. describe('connected generation', () => {
  768. it('refreshes the list and resyncs only opened instances', async () => {
  769. const api = new FakeApiClient()
  770. api.onHistory = () => Promise.resolve(ok({
  771. events: entries(plainTurn(0, 0, 'a', 'b')) as never[],
  772. hasMore: false,
  773. modelSelection: { provider: 'deepseek-official', model: 'deepseek-chat' },
  774. }))
  775. const manager = new SessionManager(api)
  776. const openedSession = manager.get(S1)
  777. await openedSession.open()
  778. manager.get(S2) // instantiated but never opened
  779. const historyCallsBefore = api.callsOf('session.history').length
  780. manager.handleConnected()
  781. await vi.waitFor(() => {
  782. expect(api.callsOf('session.list').length).toBe(1)
  783. // Only the opened instance repulls history; the cold one stays silent.
  784. expect(api.callsOf('session.history').length).toBe(historyCallsBefore + 1)
  785. })
  786. })
  787. it('reloads the durable parent address for a restored child selection', async () => {
  788. const api = new FakeApiClient()
  789. const address = {
  790. parentSessionId: S1, childSessionId: S2, mode: 'continuable' as const,
  791. }
  792. const manager = new SessionManager(api, S2, address)
  793. manager.handleConnected()
  794. await vi.waitFor(() => {
  795. expect(api.callsOf('subagent.list')).toContainEqual({ parentSessionId: S1 })
  796. })
  797. expect(manager.getListSnapshot().currentAddress).toEqual(address)
  798. })
  799. })
  800. describe('pending-interaction list status', () => {
  801. it('tracks approval requests through replay and resolution without instantiation', () => {
  802. const manager = new SessionManager(new FakeApiClient())
  803. manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', sessionId: S1, blank: false } })
  804. expect(manager.getListSnapshot().items[0]?.pendingInteraction).toBeUndefined()
  805. manager.handleMuxEnvelope({ rpcId: 'ra' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'ap1' as never, toolName: 'rm' } })
  806. expect(manager.getListSnapshot().items[0]?.pendingInteraction).toBe('approval')
  807. // Mux-open replay of the same question (same approvalId) is idempotent.
  808. manager.handleMuxEnvelope({ rpcId: 'ra' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'ap1' as never, toolName: 'rm' } })
  809. expect(manager.getListSnapshot().items[0]?.pendingInteraction).toBe('approval')
  810. manager.handleMuxEnvelope({ rpcId: 'rx' as never, payload: { type: 'approval/resolved', sessionId: S1, approvalId: 'ap1' as never, outcome: 'allowed-once' as never } })
  811. expect(manager.getListSnapshot().items[0]?.pendingInteraction).toBeUndefined()
  812. })
  813. it('classifies ordinary questions and renderable plan reviews, then clears by question rpcId', () => {
  814. const manager = new SessionManager(new FakeApiClient())
  815. manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', sessionId: S1, blank: false } })
  816. manager.handleMuxEnvelope({
  817. rpcId: 'q1' as never,
  818. payload: { type: 'question/requested', sessionId: S1, questions: [{ id: 'name', question: 'Name?' }] },
  819. })
  820. expect(manager.getListSnapshot().items[0]?.pendingInteraction).toBe('question')
  821. manager.handleMuxEnvelope({ rpcId: 'qx' as never, payload: { type: 'question/resolved', sessionId: S1, questionRpcId: 'q1' as never, outcome: 'answered' } })
  822. expect(manager.getListSnapshot().items[0]?.pendingInteraction).toBeUndefined()
  823. manager.handleMuxEnvelope({
  824. rpcId: 'q2' as never,
  825. payload: {
  826. type: 'question/requested',
  827. sessionId: S1,
  828. questions: [{
  829. id: 'plan', question: 'Approve?', detail: '# Plan',
  830. options: [{ label: 'Approve' }, { label: 'Refuse' }],
  831. intent: { kind: 'plan-review', approve: 'Approve' },
  832. }],
  833. },
  834. })
  835. expect(manager.getListSnapshot().items[0]?.pendingInteraction).toBe('plan-review')
  836. manager.handleMuxEnvelope({ rpcId: 'qy' as never, payload: { type: 'question/resolved', sessionId: S1, questionRpcId: 'q2' as never, outcome: 'cancelled' } })
  837. expect(manager.getListSnapshot().items[0]?.pendingInteraction).toBeUndefined()
  838. })
  839. it.each([
  840. ['missing detail', {}],
  841. ['multi-select', { detail: '# Plan', multiSelect: true }],
  842. ['more than two options', { detail: '# Plan', options: [{ label: 'Approve' }, { label: 'Refuse' }, { label: 'Revise' }] }],
  843. ['missing approve option', { detail: '# Plan', options: [{ label: 'Refuse' }] }],
  844. ])('keeps an unrenderable %s plan intent on the ordinary question flow', (_name, over) => {
  845. const manager = new SessionManager(new FakeApiClient())
  846. manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', sessionId: S1, blank: false } })
  847. manager.handleMuxEnvelope({
  848. rpcId: 'q-plan' as never,
  849. payload: {
  850. type: 'question/requested', sessionId: S1,
  851. questions: [{
  852. id: 'plan', question: 'Approve?', options: [{ label: 'Approve' }],
  853. intent: { kind: 'plan-review', approve: 'Approve' },
  854. ...over,
  855. }],
  856. },
  857. })
  858. expect(manager.getListSnapshot().items[0]?.pendingInteraction).toBe('question')
  859. })
  860. it('the first question outranks sibling approvals and resolving it reveals the remaining wait', () => {
  861. const manager = new SessionManager(new FakeApiClient())
  862. manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', sessionId: S1, blank: false } })
  863. manager.handleMuxEnvelope({ rpcId: 'r1' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'a1' as never, toolName: 'rm' } })
  864. manager.handleMuxEnvelope({
  865. rpcId: 'q1' as never,
  866. payload: { type: 'question/requested', sessionId: S1, questions: [{ id: 'name', question: 'Name?' }] },
  867. })
  868. expect(manager.getListSnapshot().items[0]?.pendingInteraction).toBe('question')
  869. manager.handleMuxEnvelope({ rpcId: 'qy' as never, payload: { type: 'question/resolved', sessionId: S1, questionRpcId: 'q1' as never, outcome: 'answered' } })
  870. expect(manager.getListSnapshot().items[0]?.pendingInteraction).toBe('approval')
  871. manager.handleMuxEnvelope({ rpcId: 'rx' as never, payload: { type: 'approval/resolved', sessionId: S1, approvalId: 'a1' as never, outcome: 'rejected' as never } })
  872. expect(manager.getListSnapshot().items[0]?.pendingInteraction).toBeUndefined()
  873. manager.handleMuxEnvelope({ rpcId: 'r2' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'a2' as never, toolName: 'rm' } })
  874. manager.handleHostEnvelope({ rpcId: 'h2' as never, payload: { type: 'host/session-removed', sessionId: S1 } })
  875. expect(manager.getListSnapshot().items).toHaveLength(0)
  876. })
  877. it('drops stale status at generation death before replay re-adds live interactions', () => {
  878. const manager = new SessionManager(new FakeApiClient())
  879. manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', sessionId: S1, blank: false } })
  880. manager.handleMuxEnvelope({ rpcId: 'ra' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'ap1' as never, toolName: 'rm' } })
  881. expect(manager.getListSnapshot().items[0]?.pendingInteraction).toBe('approval')
  882. // Generation death clears (resolved-while-disconnected questions send no frame)…
  883. manager.handleDisconnected()
  884. expect(manager.getListSnapshot().items[0]?.pendingInteraction).toBeUndefined()
  885. // …and a replayed frame arriving before onConnected (stream open precedes
  886. // the readiness handshake) survives the later handleConnected untouched.
  887. manager.handleMuxEnvelope({ rpcId: 'ra' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'ap1' as never, toolName: 'rm' } })
  888. manager.handleConnected()
  889. expect(manager.getListSnapshot().items[0]?.pendingInteraction).toBe('approval')
  890. })
  891. it('generation death drops buffered answerable frames (a dead generation cannot be answered)', () => {
  892. const manager = new SessionManager(new FakeApiClient())
  893. manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', sessionId: S1, blank: false } })
  894. // Buffered pre-instantiation: an approval pair and a queued row.
  895. manager.handleMuxEnvelope({ rpcId: 'ra' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'ap1' as never, toolName: 'rm' } })
  896. manager.handleMuxEnvelope({ rpcId: 'q1' as never, payload: { type: 'question/requested', sessionId: S1, questions: [] } })
  897. manager.handleDisconnected()
  898. // Instantiate after the death sweep: no zombie interaction replays (the
  899. // pendingBuffers held only dead-generation rpcIds), so the session mints
  900. // no pending waits.
  901. const session = manager.get(S1)
  902. expect(session.getSnapshot().pending).toEqual([])
  903. })
  904. })
  905. describe('completed reminder', () => {
  906. const status = (rpcId: string, sessionId: SessionId, running: boolean) => ({
  907. rpcId: rpcId as never,
  908. payload: { type: 'host/session-status' as const, sessionId, running },
  909. })
  910. const added = (rpcId: string, sessionId: SessionId) => ({
  911. rpcId: rpcId as never,
  912. payload: { type: 'host/session-added' as const, sessionId, blank: false },
  913. })
  914. const entry = (manager: SessionManager, sessionId: SessionId) =>
  915. manager.getListSnapshot().items.find(item => item.sessionId === sessionId)
  916. it('arms on a running→idle flip of a non-selected session and clears on select', () => {
  917. const manager = new SessionManager(new FakeApiClient())
  918. manager.handleHostEnvelope(added('h1', S1))
  919. manager.handleHostEnvelope(added('h2', S2))
  920. manager.select(S1)
  921. expect(entry(manager, S2)?.completed).toBe(false)
  922. manager.handleHostEnvelope(status('s1', S2, true))
  923. manager.handleHostEnvelope(status('s2', S2, false))
  924. expect(entry(manager, S2)?.completed).toBe(true)
  925. // Opening the session consumes the reminder.
  926. manager.select(S2)
  927. expect(entry(manager, S2)?.completed).toBe(false)
  928. })
  929. it('never arms for the session being watched and re-arms after a switch-away re-run', () => {
  930. const manager = new SessionManager(new FakeApiClient())
  931. manager.handleHostEnvelope(added('h1', S1))
  932. manager.handleHostEnvelope(added('h2', S2))
  933. manager.select(S2)
  934. manager.handleHostEnvelope(status('s1', S2, true))
  935. manager.handleHostEnvelope(status('s2', S2, false))
  936. expect(entry(manager, S2)?.completed).toBe(false) // watched to completion: no reminder
  937. // Switch away; a fresh run completing again arms the reminder.
  938. manager.select(S1)
  939. manager.handleHostEnvelope(status('s3', S2, true))
  940. manager.handleHostEnvelope(status('s4', S2, false))
  941. expect(entry(manager, S2)?.completed).toBe(true)
  942. })
  943. it('a re-run disarms the reminder while running and re-arms on its completion', () => {
  944. const manager = new SessionManager(new FakeApiClient())
  945. manager.handleHostEnvelope(added('h1', S1))
  946. manager.handleHostEnvelope(added('h2', S2))
  947. manager.select(S1)
  948. manager.handleHostEnvelope(status('s1', S2, true))
  949. manager.handleHostEnvelope(status('s2', S2, false))
  950. expect(entry(manager, S2)?.completed).toBe(true)
  951. // The user starts a new run without opening the session: running wins.
  952. manager.handleHostEnvelope(status('s3', S2, true))
  953. expect(entry(manager, S2)?.completed).toBe(false)
  954. manager.handleHostEnvelope(status('s4', S2, false))
  955. expect(entry(manager, S2)?.completed).toBe(true)
  956. })
  957. it('session-removed drops the reminder and a re-add starts clean', () => {
  958. const manager = new SessionManager(new FakeApiClient())
  959. manager.handleHostEnvelope(added('h1', S1))
  960. manager.handleHostEnvelope(added('h2', S2))
  961. manager.select(S1)
  962. manager.handleHostEnvelope(status('s1', S2, true))
  963. manager.handleHostEnvelope(status('s2', S2, false))
  964. expect(entry(manager, S2)?.completed).toBe(true)
  965. manager.handleHostEnvelope({ rpcId: 'rm' as never, payload: { type: 'host/session-removed', sessionId: S2 } })
  966. expect(manager.getListSnapshot().items.find(item => item.sessionId === S2)).toBeUndefined()
  967. manager.handleHostEnvelope(added('h3', S2))
  968. expect(entry(manager, S2)?.completed).toBe(false)
  969. })
  970. it('a list refresh carrying the running→idle transition arms the reminder', async () => {
  971. const api = new FakeApiClient()
  972. api.onList = () => Promise.resolve(ok({ items: [summary(S1), summary(S2, { updatedAt: 200, running: true })] as never[] }))
  973. const manager = new SessionManager(api)
  974. await manager.refreshList()
  975. manager.select(S1)
  976. expect(entry(manager, S2)?.completed).toBe(false)
  977. api.onList = () => Promise.resolve(ok({ items: [summary(S1), summary(S2, { updatedAt: 200, running: false })] as never[] }))
  978. await manager.refreshList()
  979. expect(entry(manager, S2)?.completed).toBe(true)
  980. })
  981. it('never arms for sessions already idle at first observation', async () => {
  982. const api = new FakeApiClient()
  983. api.onList = () => Promise.resolve(ok({ items: [summary(S1), summary(S2, { updatedAt: 200 })] as never[] }))
  984. const manager = new SessionManager(api)
  985. await manager.refreshList()
  986. manager.select(S1)
  987. expect(entry(manager, S2)?.completed).toBe(false)
  988. api.onList = () => Promise.resolve(ok({ items: [summary(S1), summary(S2, { updatedAt: 201 })] as never[] }))
  989. await manager.refreshList()
  990. expect(entry(manager, S2)?.completed).toBe(false)
  991. })
  992. it('arms a completion that happened during an in-flight first pull (baseline running, replayed idle)', async () => {
  993. const api = new FakeApiClient()
  994. const gate = deferred<Awaited<ReturnType<FakeApiClient['onList']>>>()
  995. api.onList = () => gate.promise
  996. const manager = new SessionManager(api)
  997. const refresh = manager.refreshList()
  998. // The session finishes while the first pull is still in flight; the pull
  999. // response recorded it as running at pull time.
  1000. manager.handleHostEnvelope(status('s-mid', S2, false))
  1001. gate.resolve(ok({ items: [summary(S1), summary(S2, { updatedAt: 200, running: true })] as never[] }))
  1002. await refresh
  1003. expect(entry(manager, S2)?.completed).toBe(true)
  1004. })
  1005. it('arms when a session ran and completed entirely between in-flight mutations (baseline idle)', async () => {
  1006. const api = new FakeApiClient()
  1007. const gate = deferred<Awaited<ReturnType<FakeApiClient['onList']>>>()
  1008. api.onList = () => gate.promise
  1009. const manager = new SessionManager(api)
  1010. const refresh = manager.refreshList()
  1011. // The unknown session starts and finishes while the first pull is in
  1012. // flight; the pull-time baseline recorded it idle, so the running→idle
  1013. // edge lives entirely inside the replayed mutations.
  1014. manager.handleHostEnvelope(status('s-start', S2, true))
  1015. manager.handleHostEnvelope(status('s-finish', S2, false))
  1016. gate.resolve(ok({ items: [summary(S1), summary(S2, { updatedAt: 200 })] as never[] }))
  1017. await refresh
  1018. expect(entry(manager, S2)?.completed).toBe(true)
  1019. })
  1020. })
  1021. describe('background-task mirror', () => {
  1022. const view = (over: Partial<{ id: string; status: string; label: string }> = {}) => ({
  1023. id: 'bash-1', kind: 'bash', label: 'pnpm run build', status: 'running', startedAt: 5, ...over,
  1024. })
  1025. const tasksFrame = (sessionId: SessionId, tasks: unknown[]) =>
  1026. ({ rpcId: 't' as never, payload: { type: 'session/tasks', sessionId, tasks } as never })
  1027. it('mirrors the whole set last-wins, keyed per session, with no Session instance needed', () => {
  1028. const manager = new SessionManager(new FakeApiClient())
  1029. manager.handleMuxEnvelope(tasksFrame(S1, [view()]))
  1030. manager.handleMuxEnvelope(tasksFrame(S2, [view({ id: 'pwsh-1', label: 'other' })]))
  1031. const first = manager.getListSnapshot().tasksBySession
  1032. expect(first[S1]).toEqual([view()])
  1033. expect(first[S2]?.[0]?.label).toBe('other')
  1034. // Last-wins: the newer whole set replaces, it does not merge.
  1035. manager.handleMuxEnvelope(tasksFrame(S1, [view({ status: 'completed' })]))
  1036. expect(manager.getListSnapshot().tasksBySession[S1]).toEqual([view({ status: 'completed' })])
  1037. })
  1038. it('stores an emptied set as an absent key so absence and [] read alike', () => {
  1039. const manager = new SessionManager(new FakeApiClient())
  1040. manager.handleMuxEnvelope(tasksFrame(S1, [view()]))
  1041. expect(S1 in manager.getListSnapshot().tasksBySession).toBe(true)
  1042. manager.handleMuxEnvelope(tasksFrame(S1, []))
  1043. expect(S1 in manager.getListSnapshot().tasksBySession).toBe(false)
  1044. })
  1045. it('clears the mirror on re-subscribe, because a task-free generation sends no baseline', () => {
  1046. const manager = new SessionManager(new FakeApiClient())
  1047. manager.handleMuxEnvelope(tasksFrame(S1, [view()]))
  1048. manager.handleMuxEnvelope({
  1049. rpcId: 's' as never,
  1050. payload: { type: 'session/subscribed', sessionId: S1, lastSeq: 3 },
  1051. })
  1052. expect(S1 in manager.getListSnapshot().tasksBySession).toBe(false)
  1053. })
  1054. it('drops the rows when the session is removed, whichever stream lands first', () => {
  1055. const manager = new SessionManager(new FakeApiClient())
  1056. manager.handleHostEnvelope({ rpcId: 'a' as never, payload: { type: 'host/session-added', blank: true, sessionId: S1 } })
  1057. manager.handleMuxEnvelope(tasksFrame(S1, [view()]))
  1058. manager.handleHostEnvelope({ rpcId: 'r' as never, payload: { type: 'host/session-removed', sessionId: S1 } })
  1059. expect(S1 in manager.getListSnapshot().tasksBySession).toBe(false)
  1060. })
  1061. it('notifies list subscribers so an open header re-renders without a poll', async () => {
  1062. const manager = new SessionManager(new FakeApiClient())
  1063. const seen = vi.fn()
  1064. manager.subscribe(seen)
  1065. manager.handleMuxEnvelope(tasksFrame(S1, [view()]))
  1066. // The notifier batches on a microtask; the frame itself is already applied.
  1067. await Promise.resolve()
  1068. expect(seen).toHaveBeenCalled()
  1069. })
  1070. })