manager.client.spec.ts 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  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('subagent.history')).toEqual([
  281. { parentSessionId: S1, childSessionId: S2, mode: 'continuable', throughSeq: -1, maxMessages: 50 },
  282. ])
  283. expect(api.callsOf('subagent.prompt')).toEqual([
  284. {
  285. parentSessionId: S1, childSessionId: S2, mode: 'continuable',
  286. content: [{ type: 'text', text: 'continue' }],
  287. clientTimeZone: new Intl.DateTimeFormat().resolvedOptions().timeZone,
  288. },
  289. ])
  290. expect(api.callsOf('session.history')).toEqual([])
  291. expect(api.callsOf('session.prompt')).toEqual([])
  292. const listCalls = api.callsOf('subagent.list').length
  293. manager.handleSessionStatus(S2, false)
  294. expect(manager.getListSnapshot().subagentsByParent[S1]?.entries[0]).toMatchObject({
  295. kind: 'child', id: S2, activity: 'inactive',
  296. })
  297. expect(api.callsOf('subagent.list')).toHaveLength(listCalls)
  298. manager.handleSessionRemoved(S2)
  299. expect(manager.getListSnapshot().items.find(item => item.sessionId === S2)).toMatchObject({
  300. origin: 'subagent', parentSessionId: S1, running: false,
  301. })
  302. expect(manager.get(S2).getSnapshot()).toMatchObject({
  303. removed: false,
  304. subagent: {
  305. address: { parentSessionId: S1, childSessionId: S2, mode: 'continuable' },
  306. },
  307. })
  308. })
  309. it('refetches debounced membership only while the parent catalog is open', async () => {
  310. vi.useFakeTimers()
  311. try {
  312. const api = new FakeApiClient()
  313. const manager = new SessionManager(api, fakeRemote(api))
  314. await manager.refreshSubagents(S1)
  315. manager.setSubagentCatalogOpen(S1, true)
  316. await Promise.resolve()
  317. const baseline = api.callsOf('subagent.list').length
  318. manager.handleSessionAdded(summary(S2, { parentSessionId: S1 }))
  319. manager.handleSessionAdded(summary('fk-m3' as SessionId, { parentSessionId: S1 }))
  320. await vi.advanceTimersByTimeAsync(50)
  321. expect(api.callsOf('subagent.list')).toHaveLength(baseline + 1)
  322. manager.setSubagentCatalogOpen(S1, false)
  323. manager.handleSessionAdded(summary('fk-m4' as SessionId, { parentSessionId: S1 }))
  324. await vi.advanceTimersByTimeAsync(50)
  325. expect(api.callsOf('subagent.list')).toHaveLength(baseline + 1)
  326. } finally {
  327. vi.useRealTimers()
  328. }
  329. })
  330. it('marks a loaded parent row expandable only for a direct subagent publication', async () => {
  331. const api = new FakeApiClient()
  332. const root = 'fk-root' as SessionId
  333. api.onSubagentList = () => Promise.resolve(ok({
  334. entries: [
  335. {
  336. kind: 'child', id: S1, mode: 'continuable', label: 'parent',
  337. activity: 'inactive', hasChildren: false,
  338. },
  339. {
  340. kind: 'child', id: S2, mode: 'continuable', label: 'ordinary parent',
  341. activity: 'inactive', hasChildren: false,
  342. },
  343. ] as never[],
  344. parentAvailable: true,
  345. }))
  346. const manager = new SessionManager(api, fakeRemote(api))
  347. await manager.refreshSubagents(root)
  348. manager.handleSessionAdded(summary('fk-grandchild' as SessionId, {
  349. parentSessionId: S1, origin: 'subagent',
  350. }))
  351. manager.handleSessionAdded(summary('fk-fork' as SessionId, { parentSessionId: S2 }))
  352. expect(manager.getListSnapshot().subagentsByParent[root]?.entries).toMatchObject([
  353. { kind: 'child', id: S1, hasChildren: true },
  354. { kind: 'child', id: S2, hasChildren: false },
  355. ])
  356. })
  357. it('preserves a live expandability hint across only the older in-flight catalog response', async () => {
  358. const api = new FakeApiClient()
  359. const root = 'fk-root' as SessionId
  360. const response = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  361. api.onSubagentList = () => response.promise
  362. const manager = new SessionManager(api, fakeRemote(api))
  363. const refresh = manager.refreshSubagents(root)
  364. manager.handleSessionAdded(summary('fk-grandchild' as SessionId, {
  365. parentSessionId: S1, origin: 'subagent',
  366. }))
  367. response.resolve(ok({
  368. entries: [{
  369. kind: 'child', id: S1, mode: 'continuable', label: 'parent',
  370. activity: 'inactive', hasChildren: false,
  371. }] as never[],
  372. parentAvailable: true,
  373. }))
  374. await refresh
  375. expect(manager.getListSnapshot().subagentsByParent[root]?.entries).toMatchObject([
  376. { kind: 'child', id: S1, hasChildren: true },
  377. ])
  378. api.onSubagentList = () => Promise.resolve(ok({
  379. entries: [{
  380. kind: 'child', id: S1, mode: 'continuable', label: 'parent',
  381. activity: 'inactive', hasChildren: false,
  382. }] as never[],
  383. parentAvailable: true,
  384. }))
  385. await manager.refreshSubagents(root)
  386. expect(manager.getListSnapshot().subagentsByParent[root]?.entries).toMatchObject([
  387. { kind: 'child', id: S1, hasChildren: false },
  388. ])
  389. })
  390. it('replays status frames over an older in-flight catalog response', async () => {
  391. const api = new FakeApiClient()
  392. const root = 'fk-root' as SessionId
  393. const response = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  394. api.onSubagentList = () => response.promise
  395. const manager = new SessionManager(api, fakeRemote(api))
  396. const refresh = manager.refreshSubagents(root)
  397. manager.handleSessionStatus(S1, false)
  398. manager.handleSessionStatus(S2, true)
  399. response.resolve(ok({
  400. entries: [
  401. {
  402. kind: 'child', id: S1, mode: 'continuable', label: 'stopped',
  403. activity: 'running', hasChildren: false,
  404. },
  405. {
  406. kind: 'child', id: S2, mode: 'continuable', label: 'started',
  407. activity: 'inactive', hasChildren: false,
  408. },
  409. ] as never[],
  410. parentAvailable: true,
  411. }))
  412. await refresh
  413. expect(manager.getListSnapshot().subagentsByParent[root]?.entries).toMatchObject([
  414. { kind: 'child', id: S1, activity: 'inactive' },
  415. { kind: 'child', id: S2, activity: 'running' },
  416. ])
  417. })
  418. it('marks a detached catalog child inactive without requiring a selected address', async () => {
  419. const api = new FakeApiClient()
  420. api.onSubagentList = () => Promise.resolve(ok({
  421. entries: [{
  422. kind: 'child', id: S2, mode: 'continuable', label: 'worker',
  423. activity: 'running', hasChildren: false,
  424. }] as never[],
  425. parentAvailable: true,
  426. }))
  427. const manager = new SessionManager(api, fakeRemote(api))
  428. await manager.refreshSubagents(S1)
  429. manager.handleSessionRemoved(S2)
  430. expect(manager.getListSnapshot().subagentsByParent[S1]?.entries).toMatchObject([
  431. { kind: 'child', id: S2, activity: 'inactive' },
  432. ])
  433. })
  434. it('coalesces overlapping catalog reads without scheduling a trailing pull', async () => {
  435. const api = new FakeApiClient()
  436. const root = 'fk-root' as SessionId
  437. const first = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  438. api.onSubagentList = () => first.promise
  439. const manager = new SessionManager(api, fakeRemote(api))
  440. const refresh = manager.refreshSubagents(root)
  441. expect(manager.refreshSubagents(root)).toBe(refresh)
  442. api.onSubagentList = () => Promise.resolve(ok({ entries: [], parentAvailable: true }))
  443. first.resolve(ok({ entries: [], parentAvailable: true }))
  444. await refresh
  445. expect(api.callsOf('subagent.list')).toHaveLength(1)
  446. })
  447. it('runs one trailing catalog refresh for a membership change coalesced into an in-flight pull', async () => {
  448. vi.useFakeTimers()
  449. try {
  450. const api = new FakeApiClient()
  451. const root = 'fk-root' as SessionId
  452. const first = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  453. const second = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  454. api.onSubagentList = () => first.promise
  455. const manager = new SessionManager(api, fakeRemote(api), root)
  456. const refresh = manager.refreshSubagents(root)
  457. // A membership frame arrives while the pull is in flight; the debounced
  458. // refresh it schedules fires 50ms later and is coalesced into the pull —
  459. // which was requested before the new child existed. The stale mark must
  460. // queue one trailing pull carrying the change.
  461. manager.handleSessionAdded(summary(S2, { parentSessionId: root }))
  462. await vi.advanceTimersByTimeAsync(50)
  463. api.onSubagentList = () => second.promise
  464. first.resolve(ok({
  465. entries: [{
  466. kind: 'child', id: S1, mode: 'continuable', label: 'older',
  467. activity: 'inactive', hasChildren: false,
  468. }] as never[],
  469. parentAvailable: true,
  470. }))
  471. await refresh
  472. // The trailing pull is already in flight (kicked synchronously in finally).
  473. second.resolve(ok({
  474. entries: [
  475. {
  476. kind: 'child', id: S1, mode: 'continuable', label: 'older',
  477. activity: 'inactive', hasChildren: false,
  478. },
  479. {
  480. kind: 'child', id: S2, mode: 'continuable', label: 'new child',
  481. activity: 'inactive', hasChildren: false,
  482. },
  483. ] as never[],
  484. parentAvailable: true,
  485. }))
  486. await second.promise
  487. expect(api.callsOf('subagent.list')).toHaveLength(2)
  488. expect(manager.getListSnapshot().subagentsByParent[root]?.entries).toMatchObject([
  489. { kind: 'child', id: S1, label: 'older' },
  490. { kind: 'child', id: S2, label: 'new child' },
  491. ])
  492. } finally {
  493. vi.useRealTimers()
  494. }
  495. })
  496. it('keeps removal invalidation across a stale success and failed trailing pull', async () => {
  497. const api = new FakeApiClient()
  498. const root = 'fk-root' as SessionId
  499. const child = () => ({
  500. kind: 'child' as const, id: S2, mode: 'continuable' as const, label: 'worker',
  501. activity: 'inactive' as const, hasChildren: false,
  502. })
  503. const first = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  504. api.onSubagentList = () => first.promise
  505. const manager = new SessionManager(api, fakeRemote(api))
  506. const refresh = manager.refreshSubagents(root)
  507. first.resolve(ok({ entries: [child()] as never[], parentAvailable: true }))
  508. await refresh
  509. manager.selectSubagent({ parentSessionId: root, childSessionId: S2, mode: 'continuable' })
  510. // The removal lands while a second pull is in flight: the invalidation
  511. // must survive the pre-removal ok response, so one trailing pull runs.
  512. const mid = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  513. api.onSubagentList = () => mid.promise
  514. const midRefresh = manager.refreshSubagents(root)
  515. manager.handleSessionRemoved(root)
  516. const trailing = deferred<Awaited<ReturnType<FakeApiClient['onSubagentList']>>>()
  517. api.onSubagentList = () => trailing.promise
  518. mid.resolve(ok({ entries: [child()] as never[], parentAvailable: true }))
  519. await midRefresh
  520. expect(manager.getListSnapshot().subagentsByParent[root]?.parentAvailable).toBe(false)
  521. expect(manager.get(S2).getSnapshot().subagent).toMatchObject({ parentAvailable: false })
  522. trailing.resolve(err({ code: 'internal', message: 'trailing pull failed', details: {} }))
  523. await vi.waitFor(() => {
  524. expect(manager.getListSnapshot().subagentsByParent[root]).toMatchObject({
  525. state: 'error',
  526. parentAvailable: false,
  527. })
  528. })
  529. const rootCalls = api.callsOf('subagent.list')
  530. .filter(call => (call as { parentSessionId: SessionId }).parentSessionId === root)
  531. expect(rootCalls).toHaveLength(3)
  532. expect(manager.getListSnapshot().subagentsByParent[root]?.parentAvailable).toBe(false)
  533. expect(manager.get(S2).getSnapshot().subagent).toMatchObject({ parentAvailable: false })
  534. })
  535. it('invalidates catalog availability when the owning parent is removed', async () => {
  536. const api = new FakeApiClient()
  537. const root = 'fk-root' as SessionId
  538. api.onSubagentList = () => Promise.resolve(ok({
  539. entries: [{
  540. kind: 'child', id: S2, mode: 'continuable', label: 'worker',
  541. activity: 'inactive', hasChildren: false,
  542. }] as never[],
  543. parentAvailable: true,
  544. }))
  545. const manager = new SessionManager(api, fakeRemote(api))
  546. await manager.refreshSubagents(root)
  547. manager.selectSubagent({ parentSessionId: root, childSessionId: S2, mode: 'continuable' })
  548. expect(manager.get(S2).getSnapshot().subagent).toMatchObject({ parentAvailable: true })
  549. manager.handleSessionRemoved(root)
  550. expect(manager.getListSnapshot().subagentsByParent[root]?.parentAvailable).toBe(false)
  551. expect(manager.get(S2).getSnapshot().subagent).toMatchObject({ parentAvailable: false })
  552. })
  553. })
  554. describe('remaining branches', () => {
  555. it('refreshList folds a transport throw into the error state', async () => {
  556. const api = new FakeApiClient()
  557. api.onList = () => Promise.reject(new Error('list wire down'))
  558. const manager = new SessionManager(api, fakeRemote(api))
  559. await manager.refreshList()
  560. expect(manager.getListSnapshot()).toMatchObject({ state: 'error', error: { code: 'internal', message: 'list wire down' } })
  561. })
  562. it('refreshList pushes running bits down to already-instantiated sessions', async () => {
  563. const api = new FakeApiClient()
  564. const manager = new SessionManager(api, fakeRemote(api))
  565. const session = manager.get(S1)
  566. api.onList = () => Promise.resolve(ok({ items: [summary(S1, { running: true })] as never[] }))
  567. await manager.refreshList()
  568. expect(session.getSnapshot().running).toBe(true)
  569. })
  570. it('create passes cwd and a preallocated id, folds transport throws, and deduplicates the echo', async () => {
  571. const api = new FakeApiClient()
  572. api.onCreate = () => Promise.resolve(ok({ sessionId: S1 }))
  573. const manager = new SessionManager(api, fakeRemote(api))
  574. await manager.create({ cwd: '/tmp/w', sessionId: S1 })
  575. expect(api.callsOf('session.create')).toEqual([{ cwd: '/tmp/w', sessionId: S1 }])
  576. expect(manager.getListSnapshot().items[0]).toMatchObject({ sessionId: S1, cwd: '/tmp/w' })
  577. await manager.create({ cwd: '/tmp/w' }) // same id returned: no duplicate row
  578. expect(manager.getListSnapshot().items).toHaveLength(1)
  579. api.onCreate = () => Promise.reject(new Error('create wire down'))
  580. expect(await manager.create()).toMatchObject({ ok: false, error: { code: 'internal' } })
  581. // Business error passes through untouched.
  582. api.onCreate = () => Promise.resolve(err({ code: 'internal', message: 'no', details: {} }))
  583. expect(await manager.create()).toMatchObject({ ok: false })
  584. })
  585. it('publishes a real Ungrouped summary from workspace-attach-failed', async () => {
  586. const api = new FakeApiClient()
  587. api.onCreate = () => Promise.resolve(err({
  588. code: 'workspace-attach-failed',
  589. message: 'published but unattached',
  590. details: { sessionId: S1, workspaceId: 'w1' },
  591. } as never))
  592. const manager = new SessionManager(api, fakeRemote(api))
  593. const result = await manager.create({ workspaceId: 'w1' as never, sessionId: S1 })
  594. expect(result).toMatchObject({ ok: false, error: { code: 'workspace-attach-failed' } })
  595. expect(manager.getListSnapshot().items).toEqual([expect.objectContaining({ sessionId: S1 })])
  596. expect(manager.getListSnapshot().items[0]).not.toHaveProperty('cwd')
  597. })
  598. it('reconciles a fork child published before workspace attachment fails', async () => {
  599. const api = new FakeApiClient()
  600. api.onFork = () => Promise.resolve(err({
  601. code: 'workspace-attach-failed',
  602. message: 'forked but unattached',
  603. details: { sessionId: S2, workspaceId: 'w1' },
  604. } as never))
  605. const manager = new SessionManager(api, fakeRemote(api))
  606. const result = await manager.fork({ sessionId: S1 })
  607. expect(result).toMatchObject({ ok: false, error: { code: 'workspace-attach-failed' } })
  608. expect(manager.getListSnapshot().items).toEqual([expect.objectContaining({
  609. sessionId: S2,
  610. parentSessionId: S1,
  611. blank: false,
  612. })])
  613. })
  614. it('reconciles a preallocated id after an ordinary transport failure', async () => {
  615. const api = new FakeApiClient()
  616. api.onCreate = () => Promise.reject(new Error('response lost'))
  617. const manager = new SessionManager(api, fakeRemote(api))
  618. const failed = await manager.create({ workspaceId: 'w1' as never, sessionId: S1 })
  619. expect(failed).toMatchObject({ ok: false, error: { message: 'response lost' } })
  620. expect(manager.getListSnapshot().items).toEqual([])
  621. manager.handleSessionAdded(summary(S1, { blank: true, cwd: '/w/one' }))
  622. expect(manager.getListSnapshot().items).toEqual([
  623. expect.objectContaining({ sessionId: S1, cwd: '/w/one' }),
  624. ])
  625. manager.handleSessionAdded(summary(S1, { blank: true, cwd: '/w/one' }))
  626. expect(manager.getListSnapshot().items).toHaveLength(1)
  627. })
  628. it('subscribe notifies on list changes and stops after unsubscribe', async () => {
  629. const api = new FakeApiClient()
  630. const manager = new SessionManager(api, fakeRemote(api))
  631. let notified = 0
  632. const unsubscribe = manager.subscribe(() => { notified++ })
  633. await manager.refreshList()
  634. await new Promise(resolve => setTimeout(resolve, 0))
  635. expect(notified).toBeGreaterThan(0)
  636. const seen = notified
  637. unsubscribe()
  638. manager.handleSessionAdded(summary(S1, { blank: true }))
  639. await new Promise(resolve => setTimeout(resolve, 0))
  640. expect(notified).toBe(seen)
  641. })
  642. it('ignores Host status and error events for sessions without an instance', () => {
  643. const api = new FakeApiClient()
  644. const manager = new SessionManager(api, fakeRemote(api))
  645. manager.handleSessionStatus(S2, true)
  646. manager.handleSessionError(S2, '无实例')
  647. })
  648. it('keeps list-entry identity for unchanged rows across an unrelated list change', async () => {
  649. const api = new FakeApiClient()
  650. api.onList = () => Promise.resolve(ok({ items: [summary(S1), summary(S2, { updatedAt: 200 })] as never[] }))
  651. const manager = new SessionManager(api, fakeRemote(api))
  652. await manager.refreshList()
  653. const before = manager.getListSnapshot()
  654. manager.handleSessionStatus(S2, true)
  655. const after = manager.getListSnapshot()
  656. expect(after.items).not.toBe(before.items)
  657. const beforeS1 = before.items.find(e => e.sessionId === S1)
  658. const afterS1 = after.items.find(e => e.sessionId === S1)
  659. expect(afterS1).toBe(beforeS1) // untouched entry keeps identity (entryCache)
  660. // Same-order same-entries snapshot reuses the items array.
  661. manager.handleSessionError(S1, 'x')
  662. expect(manager.getListSnapshot().items).toBe(after.items)
  663. })
  664. it('carries parentSessionId from the added event into the lineage row', () => {
  665. const api = new FakeApiClient()
  666. const manager = new SessionManager(api, fakeRemote(api))
  667. manager.handleSessionAdded(summary(S1, { blank: true }))
  668. manager.handleSessionAdded(summary(S2, {
  669. blank: true, parentSessionId: S1, origin: 'subagent',
  670. }))
  671. const items = manager.getListSnapshot().items
  672. expect(items.find(e => e.sessionId === S2)).toMatchObject({
  673. parentSessionId: S1, origin: 'subagent', depth: 1,
  674. })
  675. })
  676. })
  677. describe('connected generation', () => {
  678. it('refreshes query baselines without rebuilding independently resumed Session sources', async () => {
  679. const api = new FakeApiClient()
  680. api.onHistory = () => Promise.resolve(ok({
  681. events: entries(plainTurn(0, 0, 'a', 'b')) as never[],
  682. hasMore: false,
  683. modelSelection: { provider: 'deepseek-official', model: 'deepseek-chat' },
  684. }))
  685. const manager = new SessionManager(api, fakeRemote(api))
  686. const openedSession = manager.get(S1)
  687. await openedSession.open()
  688. manager.get(S2) // instantiated but never opened
  689. const historyCallsBefore = api.callsOf('session.history').length
  690. manager.handleConnected()
  691. await vi.waitFor(() => {
  692. expect(api.callsOf('session.list').length).toBe(1)
  693. })
  694. expect(api.callsOf('session.history')).toHaveLength(historyCallsBefore)
  695. })
  696. it('reloads the durable parent address for a restored child selection', async () => {
  697. const api = new FakeApiClient()
  698. const address = {
  699. parentSessionId: S1, childSessionId: S2, mode: 'continuable' as const,
  700. }
  701. const manager = new SessionManager(api, fakeRemote(api), S2, address)
  702. manager.handleConnected()
  703. await vi.waitFor(() => {
  704. expect(api.callsOf('subagent.list')).toContainEqual({ parentSessionId: S1 })
  705. })
  706. expect(manager.getListSnapshot().currentAddress).toEqual(address)
  707. })
  708. })
  709. describe('completed reminder', () => {
  710. const status = (manager: SessionManager, sessionId: SessionId, running: boolean): void => {
  711. manager.handleSessionStatus(sessionId, running)
  712. }
  713. const added = (manager: SessionManager, sessionId: SessionId): void => {
  714. manager.handleSessionAdded(summary(sessionId))
  715. }
  716. const entry = (manager: SessionManager, sessionId: SessionId) =>
  717. manager.getListSnapshot().items.find(item => item.sessionId === sessionId)
  718. it('arms on a running→idle flip of a non-selected session and clears on select', () => {
  719. const manager = makeManager()
  720. added(manager, S1)
  721. added(manager, S2)
  722. manager.select(S1)
  723. expect(entry(manager, S2)?.completed).toBe(false)
  724. status(manager, S2, true)
  725. status(manager, S2, false)
  726. expect(entry(manager, S2)?.completed).toBe(true)
  727. // Opening the session consumes the reminder.
  728. manager.select(S2)
  729. expect(entry(manager, S2)?.completed).toBe(false)
  730. })
  731. it('never arms for the session being watched and re-arms after a switch-away re-run', () => {
  732. const manager = makeManager()
  733. added(manager, S1)
  734. added(manager, S2)
  735. manager.select(S2)
  736. status(manager, S2, true)
  737. status(manager, S2, false)
  738. expect(entry(manager, S2)?.completed).toBe(false) // watched to completion: no reminder
  739. // Switch away; a fresh run completing again arms the reminder.
  740. manager.select(S1)
  741. status(manager, S2, true)
  742. status(manager, S2, false)
  743. expect(entry(manager, S2)?.completed).toBe(true)
  744. })
  745. it('a re-run disarms the reminder while running and re-arms on its completion', () => {
  746. const manager = makeManager()
  747. added(manager, S1)
  748. added(manager, S2)
  749. manager.select(S1)
  750. status(manager, S2, true)
  751. status(manager, S2, false)
  752. expect(entry(manager, S2)?.completed).toBe(true)
  753. // The user starts a new run without opening the session: running wins.
  754. status(manager, S2, true)
  755. expect(entry(manager, S2)?.completed).toBe(false)
  756. status(manager, S2, false)
  757. expect(entry(manager, S2)?.completed).toBe(true)
  758. })
  759. it('session-removed drops the reminder and a re-add starts clean', () => {
  760. const manager = makeManager()
  761. added(manager, S1)
  762. added(manager, S2)
  763. manager.select(S1)
  764. status(manager, S2, true)
  765. status(manager, S2, false)
  766. expect(entry(manager, S2)?.completed).toBe(true)
  767. manager.handleSessionRemoved(S2)
  768. expect(manager.getListSnapshot().items.find(item => item.sessionId === S2)).toBeUndefined()
  769. added(manager, S2)
  770. expect(entry(manager, S2)?.completed).toBe(false)
  771. })
  772. it('a list refresh carrying the running→idle transition arms the reminder', async () => {
  773. const api = new FakeApiClient()
  774. api.onList = () => Promise.resolve(ok({ items: [summary(S1), summary(S2, { updatedAt: 200, running: true })] as never[] }))
  775. const manager = new SessionManager(api, fakeRemote(api))
  776. await manager.refreshList()
  777. manager.select(S1)
  778. expect(entry(manager, S2)?.completed).toBe(false)
  779. api.onList = () => Promise.resolve(ok({ items: [summary(S1), summary(S2, { updatedAt: 200, running: false })] as never[] }))
  780. await manager.refreshList()
  781. expect(entry(manager, S2)?.completed).toBe(true)
  782. })
  783. it('never arms for sessions already idle at first observation', async () => {
  784. const api = new FakeApiClient()
  785. api.onList = () => Promise.resolve(ok({ items: [summary(S1), summary(S2, { updatedAt: 200 })] as never[] }))
  786. const manager = new SessionManager(api, fakeRemote(api))
  787. await manager.refreshList()
  788. manager.select(S1)
  789. expect(entry(manager, S2)?.completed).toBe(false)
  790. api.onList = () => Promise.resolve(ok({ items: [summary(S1), summary(S2, { updatedAt: 201 })] as never[] }))
  791. await manager.refreshList()
  792. expect(entry(manager, S2)?.completed).toBe(false)
  793. })
  794. it('arms a completion that happened during an in-flight first pull (baseline running, replayed idle)', async () => {
  795. const api = new FakeApiClient()
  796. const gate = deferred<Awaited<ReturnType<FakeApiClient['onList']>>>()
  797. api.onList = () => gate.promise
  798. const manager = new SessionManager(api, fakeRemote(api))
  799. const refresh = manager.refreshList()
  800. // The session finishes while the first pull is still in flight; the pull
  801. // response recorded it as running at pull time.
  802. status(manager, S2, false)
  803. gate.resolve(ok({ items: [summary(S1), summary(S2, { updatedAt: 200, running: true })] as never[] }))
  804. await refresh
  805. expect(entry(manager, S2)?.completed).toBe(true)
  806. })
  807. it('arms when a session ran and completed entirely between in-flight mutations (baseline idle)', async () => {
  808. const api = new FakeApiClient()
  809. const gate = deferred<Awaited<ReturnType<FakeApiClient['onList']>>>()
  810. api.onList = () => gate.promise
  811. const manager = new SessionManager(api, fakeRemote(api))
  812. const refresh = manager.refreshList()
  813. // The unknown session starts and finishes while the first pull is in
  814. // flight; the pull-time baseline recorded it idle, so the running→idle
  815. // edge lives entirely inside the replayed mutations.
  816. status(manager, S2, true)
  817. status(manager, S2, false)
  818. gate.resolve(ok({ items: [summary(S1), summary(S2, { updatedAt: 200 })] as never[] }))
  819. await refresh
  820. expect(entry(manager, S2)?.completed).toBe(true)
  821. })
  822. })
  823. describe('background-job mirror', () => {
  824. const view = (over: Partial<{ id: string; status: string; label: string }> = {}) => ({
  825. id: 'bash-1', kind: 'bash', label: 'pnpm run build', status: 'running', startedAt: 5, ...over,
  826. })
  827. const tasksFrame = (
  828. sessionId: SessionId,
  829. jobs: unknown[],
  830. ): Extract<SessionControlFrame, { type: 'jobs' }> => ({
  831. type: 'jobs', sessionId, jobs: jobs as never,
  832. })
  833. it('mirrors the whole set last-wins, keyed per session, with no Session instance needed', () => {
  834. const manager = makeManager()
  835. manager.handleControlFrame(tasksFrame(S1, [view()]))
  836. manager.handleControlFrame(tasksFrame(S2, [view({ id: 'pwsh-1', label: 'other' })]))
  837. const first = manager.getListSnapshot().jobsBySession
  838. expect(first[S1]).toEqual([view()])
  839. expect(first[S2]?.[0]?.label).toBe('other')
  840. // Last-wins: the newer whole set replaces, it does not merge.
  841. manager.handleControlFrame(tasksFrame(S1, [view({ status: 'completed' })]))
  842. expect(manager.getListSnapshot().jobsBySession[S1]).toEqual([view({ status: 'completed' })])
  843. })
  844. it('stores an emptied set as an absent key so absence and [] read alike', () => {
  845. const manager = makeManager()
  846. manager.handleControlFrame(tasksFrame(S1, [view()]))
  847. expect(S1 in manager.getListSnapshot().jobsBySession).toBe(true)
  848. manager.handleControlFrame(tasksFrame(S1, []))
  849. expect(S1 in manager.getListSnapshot().jobsBySession).toBe(false)
  850. })
  851. it('clears the mirror when the next control baseline has no jobs', () => {
  852. const manager = makeManager()
  853. manager.handleControlFrame(tasksFrame(S1, [view()]))
  854. manager.handleControlFrame({
  855. type: 'baseline',
  856. value: { queues: {}, jobs: {}, projections: {} },
  857. })
  858. expect(S1 in manager.getListSnapshot().jobsBySession).toBe(false)
  859. })
  860. it('drops the rows when the session is removed, whichever stream lands first', () => {
  861. const manager = makeManager()
  862. manager.handleSessionAdded(summary(S1, { blank: true }))
  863. manager.handleControlFrame(tasksFrame(S1, [view()]))
  864. manager.handleSessionRemoved(S1)
  865. expect(S1 in manager.getListSnapshot().jobsBySession).toBe(false)
  866. })
  867. it('notifies list subscribers so an open header re-renders without a poll', async () => {
  868. const manager = makeManager()
  869. const seen = vi.fn()
  870. manager.subscribe(seen)
  871. manager.handleControlFrame(tasksFrame(S1, [view()]))
  872. // The notifier batches on a microtask; the frame itself is already applied.
  873. await Promise.resolve()
  874. expect(seen).toHaveBeenCalled()
  875. })
  876. })