manager.client.spec.ts 41 KB

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