manager.client.spec.ts 41 KB

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