manager.client.spec.ts 44 KB

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