manager.client.spec.ts 42 KB

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