manager.client.spec.ts 49 KB

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