manager.spec.ts 52 KB

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