manager.client.spec.ts 41 KB

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