1
0

session-cold.host.spec.ts 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  1. /**
  2. * Cold-session and degenerate-composition paths of the Session Controller:
  3. * metadata-only listing, Agent-free history reads, subagent ownership
  4. * isolation, and prompt failure mapping.
  5. */
  6. import { SESSION_FORMAT_VERSION, SessionLogOffset, SessionSeq } from '@deepseek-ai/dsh-session'
  7. import { describe, expect, it, vi } from 'vitest'
  8. import { Context } from '@deepseek-ai/cordis'
  9. import SessionStore from '@deepseek-ai/dsh-session'
  10. import AgentRegistry from '@deepseek-ai/dsh-agent'
  11. import { SessionHistoryController } from '@deepseek-ai/dsh-api-session-controller/src/history.ts'
  12. import { subagentIdentityProjectionDefinition } from '@deepseek-ai/dsh-subagent/src/projection.ts'
  13. import TypertRegistry from '@deepseek-ai/dsh-typert-registry'
  14. import { createUserMessage, MessageId } from '@deepseek-ai/dsh-llm'
  15. import { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent'
  16. import type { Agent } from '@deepseek-ai/dsh-agent'
  17. import type { Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
  18. import type { SessionPromptRequest, SessionRequestId } from '../src/types.ts'
  19. import {
  20. SessionPersistenceRevision,
  21. type SessionPersistenceSnapshot,
  22. } from '@deepseek-ai/dsh-session-persistence'
  23. import { ApiSessionList } from '../src/list.ts'
  24. import {
  25. createSessionTestRemote,
  26. installSessionReadTestServices,
  27. testSessionPersistence,
  28. } from './test-remote.ts'
  29. const sid = (id: string): SessionId => id as SessionId
  30. function request<P>(payload: P): P {
  31. return payload
  32. }
  33. let nextRequestId = 1
  34. function promptRequest(
  35. payload: Omit<SessionPromptRequest, 'requestId'>,
  36. ): SessionPromptRequest {
  37. return {
  38. ...payload,
  39. requestId: `cold-${String(nextRequestId++)}` as SessionRequestId,
  40. }
  41. }
  42. function header(id: string, createdAt: number, extra: Partial<SessionHeader> = {}): SessionHeader {
  43. return { version: SESSION_FORMAT_VERSION, id: sid(id), createdAt, isSeeded: false, cwd: '/proj', ...extra }
  44. }
  45. function providePersistence(ctx: Context, persistence: Record<string, unknown>): () => void {
  46. return ctx.provide('sessionPersistence', testSessionPersistence(ctx, persistence) as never)
  47. }
  48. function statSnapshot(
  49. meta: SessionHeader,
  50. metrics: Partial<Pick<SessionPersistenceSnapshot, 'eventCount' | 'sizeBytes'>> = {},
  51. ): SessionPersistenceSnapshot {
  52. return { header: meta, revision: SessionPersistenceRevision(`test:${meta.id}:stat`), ...metrics }
  53. }
  54. /** A stored log whose only event is the seed boundary: still blank. */
  55. function blankEvents(): SessionEvent[] {
  56. return [{ type: 'session/end-seed', seq: SessionSeq(0), time: 700, data: {} }] as SessionEvent[]
  57. }
  58. /** A stored log with one human prompt at time 1200: proven non-blank. */
  59. function conversationEvents(): SessionEvent[] {
  60. return [
  61. { type: 'turn/start', seq: SessionSeq(0), time: 800, data: { turn: 1 } },
  62. {
  63. type: 'user/message', seq: SessionSeq(1), time: 1200,
  64. data: createUserMessage({ content: [{ type: 'text', text: 'worked' }], source: { kind: 'user' } }),
  65. surfaceOp: 'append',
  66. },
  67. ] as SessionEvent[]
  68. }
  69. describe('sessions.list cold merge', () => {
  70. it('serves cold rows from cached projections when stat offers no size metadata', async () => {
  71. const ctx = new Context()
  72. await ctx.plugin(SessionStore)
  73. const metas: SessionHeader[] = [
  74. header('cached-blank', 100),
  75. header('cached-conversation', 200),
  76. header('uncached', 300, { parentSession: sid('session-parent'), origin: 'subagent' }),
  77. header('seeded-cold', 450, { isSeeded: true }),
  78. { version: SESSION_FORMAT_VERSION, id: sid('missing-cwd'), createdAt: 800, isSeeded: false },
  79. ]
  80. const inspect = vi.fn()
  81. providePersistence(ctx, {
  82. list: () => Promise.resolve(metas),
  83. inspect,
  84. })
  85. const cacheCalls: string[] = []
  86. ctx.provide('sessionProjectionCache', {
  87. cachedSnapshot: (meta: SessionHeader) => {
  88. cacheCalls.push(String(meta.id))
  89. if (meta.id === sid('cached-blank')) {
  90. return { asOfSeq: 0, values: { sessionListMetadata: { blank: true, lastPromptAt: null } } }
  91. }
  92. if (meta.id === sid('cached-conversation')) {
  93. return { asOfSeq: 1, values: { sessionListMetadata: { blank: false, lastPromptAt: 1000 } } }
  94. }
  95. return undefined
  96. },
  97. } as never)
  98. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  99. const response = await remote.list(request({}))
  100. expect(response.ok).toBe(true)
  101. if (!response.ok) throw new Error('unreachable')
  102. const byId = Object.fromEntries(response.value.items.map(item => [item.sessionId, item]))
  103. expect(byId['cached-blank']).toMatchObject({ blank: true, updatedAt: 100, running: false })
  104. expect(byId['cached-conversation']).toMatchObject({ blank: false, updatedAt: 1000 })
  105. // A cache miss with a metadata-less stat leaves blankness unknown; the row stays visible.
  106. expect(byId['uncached']).toMatchObject({
  107. blank: false,
  108. updatedAt: 300,
  109. parentSessionId: 'session-parent',
  110. origin: 'subagent',
  111. })
  112. expect(byId['missing-cwd']).toBeUndefined()
  113. // A cold seeded header never consults the cache: its cut is not 0, so a
  114. // cut-0 lookup would alias a different projection identity.
  115. expect(byId['seeded-cold']).toMatchObject({ blank: false, updatedAt: 450 })
  116. expect(cacheCalls).not.toContain('seeded-cold')
  117. expect(inspect).not.toHaveBeenCalled()
  118. })
  119. it('fully observes only small possibly-blank logs gated by stat eventCount', async () => {
  120. const ctx = new Context()
  121. await ctx.plugin(SessionStore)
  122. const metas: SessionHeader[] = [
  123. header('small-blank', 100),
  124. header('small-conversation', 200),
  125. header('large-unknown', 300),
  126. header('cached-nonblank', 400),
  127. header('vanished', 600),
  128. { version: SESSION_FORMAT_VERSION, id: sid('missing-cwd'), createdAt: 800, isSeeded: false },
  129. ]
  130. const inspect = vi.fn(async (id: SessionId) => {
  131. if (id === sid('small-blank')) return { meta: metas[0]!, events: blankEvents() }
  132. if (id === sid('small-conversation')) return { meta: metas[1]!, events: conversationEvents() }
  133. throw new Error(`unexpected cold read: ${id}`)
  134. })
  135. const stat = vi.fn(async (id: SessionId) => {
  136. if (id === sid('small-blank')) return statSnapshot(metas[0]!, { eventCount: 1 })
  137. if (id === sid('small-conversation')) return statSnapshot(metas[1]!, { eventCount: 2 })
  138. if (id === sid('large-unknown')) return statSnapshot(metas[2]!, { eventCount: 17 })
  139. if (id === sid('vanished')) return undefined
  140. throw new Error(`unexpected stat: ${id}`)
  141. })
  142. providePersistence(ctx, {
  143. list: () => Promise.resolve(metas),
  144. stat,
  145. inspect,
  146. })
  147. ctx.provide('sessionProjectionCache', {
  148. cachedSnapshot: (meta: SessionHeader) => {
  149. if (meta.id === sid('small-blank')) {
  150. return { asOfSeq: 0, values: { sessionListMetadata: { blank: true, lastPromptAt: null } } }
  151. }
  152. if (meta.id === sid('small-conversation')) {
  153. return { asOfSeq: 0, values: { sessionListMetadata: { blank: true, lastPromptAt: 900 } } }
  154. }
  155. if (meta.id === sid('cached-nonblank')) {
  156. return { asOfSeq: 1, values: { sessionListMetadata: { blank: false, lastPromptAt: 1000 } } }
  157. }
  158. return undefined
  159. },
  160. hydratePrepared: (session: Session, events: readonly SessionEvent[]) =>
  161. ctx.sessionProjections.hydrate(session, {}, events, SessionLogOffset(0)),
  162. } as never)
  163. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  164. const response = await remote.list(request({}))
  165. expect(response.ok).toBe(true)
  166. if (!response.ok) throw new Error('unreachable')
  167. const byId = Object.fromEntries(response.value.items.map(item => [item.sessionId, item]))
  168. expect(byId['small-blank']).toMatchObject({ blank: true, updatedAt: 100, running: false })
  169. expect(byId['small-conversation']).toMatchObject({ blank: false, updatedAt: 1200 })
  170. expect(byId['large-unknown']).toMatchObject({ blank: false, updatedAt: 300 })
  171. expect(byId['cached-nonblank']).toMatchObject({ blank: false, updatedAt: 1000 })
  172. expect(byId['vanished']).toMatchObject({ blank: false, updatedAt: 600 })
  173. expect(byId['missing-cwd']).toBeUndefined()
  174. // A cache row proving blank:false is never re-probed.
  175. expect(stat.mock.calls.map(([id]) => id)).not.toContain(sid('cached-nonblank'))
  176. expect(inspect).toHaveBeenCalledTimes(2)
  177. expect(inspect.mock.calls.map(([id]) => id)).toEqual(expect.arrayContaining([
  178. sid('small-blank'),
  179. sid('small-conversation'),
  180. ]))
  181. })
  182. it('falls back to the stat sizeBytes gate when no eventCount is offered', async () => {
  183. const ctx = new Context()
  184. await ctx.plugin(SessionStore)
  185. const metas = [header('small-jsonl', 100), header('large-jsonl', 200)]
  186. const inspect = vi.fn(async (id: SessionId) => {
  187. if (id === sid('small-jsonl')) return { meta: metas[0]!, events: conversationEvents() }
  188. throw new Error(`unexpected cold read: ${id}`)
  189. })
  190. providePersistence(ctx, {
  191. list: () => Promise.resolve(metas),
  192. stat: (id: SessionId) => Promise.resolve(id === sid('small-jsonl')
  193. ? statSnapshot(metas[0]!, { sizeBytes: 1024 })
  194. : statSnapshot(metas[1]!, { sizeBytes: 1025 })),
  195. inspect,
  196. })
  197. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  198. const response = await remote.list(request({}))
  199. if (!response.ok) throw new Error('list failed')
  200. const byId = Object.fromEntries(response.value.items.map(item => [item.sessionId, item]))
  201. expect(byId['small-jsonl']).toMatchObject({ blank: false, updatedAt: 1200 })
  202. expect(byId['large-jsonl']).toMatchObject({ blank: false, updatedAt: 200 })
  203. expect(inspect).toHaveBeenCalledTimes(1)
  204. expect(inspect).toHaveBeenCalledWith(sid('small-jsonl'), expect.anything())
  205. })
  206. it('skips the observation when stat offers neither eventCount nor sizeBytes', async () => {
  207. const ctx = new Context()
  208. await ctx.plugin(SessionStore)
  209. const meta = header('no-metrics', 100)
  210. const inspect = vi.fn()
  211. const stat = vi.fn(async () => statSnapshot(meta))
  212. providePersistence(ctx, {
  213. list: () => Promise.resolve([meta]),
  214. stat,
  215. inspect,
  216. })
  217. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  218. const response = await remote.list(request({}))
  219. if (!response.ok) throw new Error('list failed')
  220. expect(response.value.items).toEqual([
  221. expect.objectContaining({ sessionId: meta.id, blank: false, updatedAt: meta.createdAt }),
  222. ])
  223. expect(stat).toHaveBeenCalledOnce()
  224. expect(inspect).not.toHaveBeenCalled()
  225. })
  226. it('can disable both probe gates without hiding cold Sessions or calling stat', async () => {
  227. const ctx = new Context()
  228. await ctx.plugin(SessionStore)
  229. const meta = header('probe-disabled', 100)
  230. const inspect = vi.fn()
  231. const stat = vi.fn()
  232. providePersistence(ctx, {
  233. list: () => Promise.resolve([meta]),
  234. stat,
  235. inspect,
  236. })
  237. const remote = createSessionTestRemote(ctx, {
  238. defaultModelSelection: () => ({ provider: 'p', model: 'm' }),
  239. cwd: '/tmp',
  240. coldBlankProbeMaxEvents: 0,
  241. coldBlankProbeMaxBytes: 0,
  242. })
  243. const response = await remote.list(request({}))
  244. if (!response.ok) throw new Error('unreachable')
  245. expect(response.value.items).toEqual([
  246. expect.objectContaining({ sessionId: meta.id, blank: false, updatedAt: meta.createdAt }),
  247. ])
  248. expect(stat).not.toHaveBeenCalled()
  249. expect(inspect).not.toHaveBeenCalled()
  250. })
  251. it('treats zero as disabling one gate without falling back to the other metric', async () => {
  252. const bench = async (
  253. metrics: Partial<Pick<SessionPersistenceSnapshot, 'eventCount' | 'sizeBytes'>>,
  254. thresholds: { coldBlankProbeMaxEvents?: number; coldBlankProbeMaxBytes?: number },
  255. ) => {
  256. const ctx = new Context()
  257. await ctx.plugin(SessionStore)
  258. const meta = header('gate-off', 100)
  259. const inspect = vi.fn()
  260. providePersistence(ctx, {
  261. list: () => Promise.resolve([meta]),
  262. stat: () => Promise.resolve(statSnapshot(meta, metrics)),
  263. inspect,
  264. })
  265. const remote = createSessionTestRemote(ctx, {
  266. defaultModelSelection: () => ({ provider: 'p', model: 'm' }),
  267. cwd: '/tmp',
  268. ...thresholds,
  269. })
  270. const response = await remote.list(request({}))
  271. if (!response.ok) throw new Error('list failed')
  272. expect(response.value.items).toEqual([
  273. expect.objectContaining({ sessionId: meta.id, blank: false }),
  274. ])
  275. expect(inspect).not.toHaveBeenCalled()
  276. }
  277. // An offered eventCount never falls through to the byte gate, even disabled.
  278. await bench({ eventCount: 1, sizeBytes: 10 }, { coldBlankProbeMaxEvents: 0 })
  279. await bench({ sizeBytes: 10 }, { coldBlankProbeMaxBytes: 0 })
  280. })
  281. it('prefers a Session that attaches during its bounded cold observation', async () => {
  282. const ctx = new Context()
  283. await ctx.plugin(SessionStore)
  284. await ctx.plugin(AgentRegistry)
  285. const meta = header('attached-during-probe', 100)
  286. providePersistence(ctx, {
  287. list: () => Promise.resolve([meta]),
  288. stat: () => {
  289. const session = ctx.sessions.create(meta.id, {
  290. meta,
  291. seed: [{ type: 'turn/start', seq: SessionSeq(0), time: 200, data: { turn: 1 } }],
  292. })
  293. ctx.agents.register({ id: session.id, session, status: 'running', ctx } as Agent)
  294. return Promise.resolve(statSnapshot(meta, { eventCount: 1 }))
  295. },
  296. })
  297. const remote = createSessionTestRemote(ctx, {
  298. defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp',
  299. })
  300. const response = await remote.list(request({}))
  301. if (!response.ok) throw new Error('list failed')
  302. expect(response.value.items).toEqual([
  303. expect.objectContaining({ sessionId: meta.id, running: true, blank: false }),
  304. ])
  305. await ctx.fiber.dispose()
  306. })
  307. it('serves a session whose cold stat fails as visible instead of failing the list', async () => {
  308. const ctx = new Context()
  309. await ctx.plugin(SessionStore)
  310. const meta = header('broken-stat', 100)
  311. providePersistence(ctx, {
  312. list: () => Promise.resolve([meta]),
  313. stat: () => Promise.reject(new Error('stat failed')),
  314. })
  315. const warned = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  316. const remote = createSessionTestRemote(ctx, {
  317. defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp',
  318. })
  319. const response = await remote.list(request({}))
  320. if (!response.ok) throw new Error('list failed')
  321. expect(response.value.items).toEqual([
  322. expect.objectContaining({ sessionId: meta.id, running: false }),
  323. ])
  324. expect(warned.mock.calls.join('\n')).toContain('cold stat for "broken-stat" failed')
  325. warned.mockRestore()
  326. await ctx.fiber.dispose()
  327. })
  328. it('a stat rejection after cancellation propagates instead of degrading', async () => {
  329. const ctx = new Context()
  330. await ctx.plugin(SessionStore)
  331. const meta = header('stat-abort', 100)
  332. const controller = new AbortController()
  333. providePersistence(ctx, {
  334. list: () => Promise.resolve([meta]),
  335. stat: () => {
  336. controller.abort(new Error('caller left'))
  337. return Promise.reject(new Error('stat failed'))
  338. },
  339. })
  340. const remote = createSessionTestRemote(ctx, {
  341. defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp',
  342. })
  343. await expect(remote.list(request({}), controller.signal)).resolves.toMatchObject({
  344. ok: false,
  345. error: { code: 'gateway/cancelled' },
  346. })
  347. await ctx.fiber.dispose()
  348. })
  349. it('serves a small cold Session as visible when its observation fails', async () => {
  350. const ctx = new Context()
  351. await ctx.plugin(SessionStore)
  352. const meta = header('read-failure', 700)
  353. const inspect = vi.fn(async () => { throw new Error('simulated read failure') })
  354. providePersistence(ctx, {
  355. list: () => Promise.resolve([meta]),
  356. stat: () => Promise.resolve(statSnapshot(meta, { eventCount: 1 })),
  357. inspect,
  358. })
  359. const remote = createSessionTestRemote(ctx, {
  360. defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp',
  361. })
  362. const response = await remote.list(request({}))
  363. if (!response.ok) throw new Error('list failed')
  364. expect(response.value.items).toEqual([
  365. expect.objectContaining({ sessionId: meta.id, blank: false, updatedAt: 700 }),
  366. ])
  367. expect(inspect).toHaveBeenCalledOnce()
  368. })
  369. it('supports an unsignalled probe whose observation has no projection block', async () => {
  370. const ctx = new Context()
  371. await ctx.plugin(SessionStore)
  372. await ctx.plugin(AgentRegistry)
  373. installSessionReadTestServices(ctx)
  374. const meta = header('unprojected-small', 100)
  375. ctx.provide('sessionPersistence', {
  376. list: () => Promise.resolve([meta]),
  377. stat: () => Promise.resolve(statSnapshot(meta, { eventCount: 0 })),
  378. } as never)
  379. vi.spyOn(ctx.sessionQuery, 'listSessions').mockResolvedValue([{
  380. header: meta, live: false, persisted: true,
  381. }])
  382. vi.spyOn(ctx.sessionQuery, 'observeSession').mockResolvedValue({
  383. source: 'prepared', header: meta, inheritedEventCount: SessionLogOffset(0), events: [], cursor: -1,
  384. retain: vi.fn(), [Symbol.dispose]: vi.fn(),
  385. })
  386. const list = new ApiSessionList(ctx, { coldBlankProbeMaxEvents: 16, coldBlankProbeMaxBytes: 1024 })
  387. await expect(list.list()).resolves.toEqual([
  388. expect.objectContaining({ sessionId: meta.id, blank: false }),
  389. ])
  390. await ctx.fiber.dispose()
  391. })
  392. it('serves a cold row visible when no persistence service can stat it', async () => {
  393. const ctx = new Context()
  394. await ctx.plugin(SessionStore)
  395. installSessionReadTestServices(ctx)
  396. const meta = header('service-less', 100)
  397. vi.spyOn(ctx.sessionQuery, 'listSessions').mockResolvedValue([{
  398. header: meta, live: false, persisted: true,
  399. }])
  400. const list = new ApiSessionList(ctx, { coldBlankProbeMaxEvents: 16, coldBlankProbeMaxBytes: 1024 })
  401. await expect(list.list()).resolves.toEqual([
  402. expect.objectContaining({ sessionId: meta.id, blank: false }),
  403. ])
  404. await ctx.fiber.dispose()
  405. })
  406. it('prefers a live row attached during the query without folding its seed', async () => {
  407. const ctx = new Context()
  408. await ctx.plugin(SessionStore)
  409. await ctx.plugin(AgentRegistry)
  410. const meta = header('attached-during-list', 100)
  411. const started = Promise.withResolvers<undefined>()
  412. const release = Promise.withResolvers<undefined>()
  413. providePersistence(ctx, {
  414. list: async () => {
  415. started.resolve(undefined)
  416. await release.promise
  417. return [meta]
  418. },
  419. })
  420. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  421. const listing = remote.list(request({}))
  422. await started.promise
  423. const session = ctx.sessions.create(meta.id, {
  424. seed: [
  425. { type: 'turn/start', seq: SessionSeq(0), time: 200, data: { turn: 1 } },
  426. {
  427. type: 'user/message', seq: SessionSeq(1), time: 300,
  428. data: createUserMessage({ content: [{ type: 'text', text: 'live' }], source: { kind: 'user' } }),
  429. surfaceOp: 'append',
  430. },
  431. ],
  432. meta: {
  433. ...meta.cwd === undefined ? {} : { cwd: meta.cwd },
  434. createdAt: meta.createdAt,
  435. },
  436. })
  437. ctx.agents.register({ id: session.id, session, status: 'running', ctx } as Agent)
  438. release.resolve(undefined)
  439. const response = await listing
  440. if (!response.ok) throw new Error('list failed')
  441. expect(response.value.items).toEqual([
  442. expect.objectContaining({
  443. sessionId: meta.id,
  444. blank: false,
  445. running: true,
  446. updatedAt: 100,
  447. }),
  448. ])
  449. })
  450. })
  451. describe('attached updatedAt tracks human prompts', () => {
  452. it('ignores pickup and non-prompt work after the latest human message', async () => {
  453. const ctx = new Context()
  454. await ctx.plugin(SessionStore)
  455. await ctx.plugin(AgentRegistry)
  456. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  457. await new Promise(resolve => setTimeout(resolve, 0))
  458. // Old work, resumed just now: the log tail would report the pickup.
  459. const worked = 1_000_000
  460. const resumed = ctx.sessions.create(sid('resumed-untouched'), {
  461. seed: [
  462. { type: 'turn/start', seq: SessionSeq(0), time: worked, data: { turn: 1 } },
  463. {
  464. type: 'user/message', seq: SessionSeq(1), time: worked,
  465. data: createUserMessage({ content: [{ type: 'text', text: 'worked' }], source: { kind: 'user' } }),
  466. surfaceOp: 'append',
  467. },
  468. { type: 'turn/end', seq: SessionSeq(2), time: worked + 1, data: { turn: 1, reason: { kind: 'completed' } } },
  469. ],
  470. meta: { cwd: '/proj', createdAt: 500 },
  471. })
  472. ctx.agents.register({ id: resumed.id, session: resumed, status: 'idle', ctx } as Agent)
  473. const boundary = resumed.snapshotEvents().at(-1)
  474. expect(boundary?.type).toBe('session/end-seed')
  475. expect(boundary?.time).toBeGreaterThan(worked)
  476. const listed = await remote.list(request({}))
  477. if (!listed.ok) throw new Error('list failed')
  478. const summary = listed.value.items.find(item => item.sessionId === 'resumed-untouched')
  479. expect(summary?.updatedAt).toBe(500)
  480. // A lifecycle boundary is not a human update.
  481. resumed.append('turn/start', { turn: 2 })
  482. const afterBoundary = await remote.list(request({}))
  483. if (!afterBoundary.ok) throw new Error('list failed')
  484. expect(afterBoundary.value.items.find(item => item.sessionId === 'resumed-untouched')?.updatedAt)
  485. .toBe(worked)
  486. const prompt = resumed.append('user/message', createUserMessage({
  487. content: [{ type: 'text', text: 'new prompt' }],
  488. source: { kind: 'user' },
  489. }), { surfaceOp: 'append' })
  490. const after = await remote.list(request({}))
  491. if (!after.ok) throw new Error('list failed')
  492. const moved = after.value.items.find(item => item.sessionId === 'resumed-untouched')
  493. expect(moved?.updatedAt).toBe(prompt.time)
  494. })
  495. })
  496. describe('cold history recovery view', () => {
  497. it('serves the stored interrupted prefix verbatim without activating the session', async () => {
  498. // Semantic crash repair is the resuming agent loop's job (it appends the
  499. // closers durably through its write handle); a cold history read shows the
  500. // stored prefix exactly as persisted.
  501. const ctx = new Context()
  502. await ctx.plugin(SessionStore)
  503. const sessionId = sid('session-interrupted')
  504. const meta = header(sessionId, 1000)
  505. const events = [{ type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1 } }] as SessionEvent[]
  506. providePersistence(ctx, {
  507. list: () => Promise.resolve([structuredClone(meta)]),
  508. inspect: () => Promise.resolve({ meta: structuredClone(meta), events: structuredClone(events) }),
  509. })
  510. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  511. const history = await remote.page({
  512. address: { kind: 'session', sessionId },
  513. throughSeq: 0,
  514. beforeSeq: 1,
  515. maxMessages: 10,
  516. })
  517. if (!history.ok) throw new Error('history failed')
  518. expect(history.value.records.map(record => record.event)).toMatchInlineSnapshot(`
  519. [
  520. {
  521. "data": {
  522. "turn": 1,
  523. },
  524. "seq": 0,
  525. "time": 1,
  526. "type": "turn/start",
  527. },
  528. ]
  529. `)
  530. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  531. await ctx.fiber.dispose()
  532. })
  533. })
  534. describe('Remote Agent and Session lookup policy', () => {
  535. it('deduplicates a cold resume across Agent and Session parameters', async () => {
  536. const ctx = new Context()
  537. await ctx.plugin(TypertRegistry)
  538. await ctx.plugin(SessionStore)
  539. await ctx.plugin(AgentRegistry)
  540. const sessionId = sid('session-remote-cold')
  541. const meta = header(sessionId, 1000)
  542. const inspect = vi.fn(() => Promise.resolve({ meta, events: [] as SessionEvent[] }))
  543. providePersistence(ctx, {
  544. list: () => Promise.resolve([meta]),
  545. inspect,
  546. })
  547. const resumedSession = { id: sessionId, header: meta, events: [] } as unknown as import('@deepseek-ai/dsh-session').Session
  548. const resumedAgent = { id: sessionId, session: resumedSession, status: 'idle', ctx } as Agent
  549. const release = Promise.withResolvers<undefined>()
  550. const resume = vi.spyOn(ctx.agents, 'resume').mockImplementation(async () => {
  551. await release.promise
  552. return { agent: resumedAgent, dispose: () => Promise.resolve() }
  553. })
  554. const defaultAgentLookup = ctx.typert.lookups.get('agent')
  555. const defaultSessionLookup = ctx.typert.lookups.get('session')
  556. createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  557. await vi.waitFor(() => {
  558. expect(ctx.typert.lookups.get('agent')).not.toBe(defaultAgentLookup)
  559. expect(ctx.typert.lookups.get('session')).not.toBe(defaultSessionLookup)
  560. })
  561. const agentLookup = ctx.typert.lookups.get('agent')
  562. const sessionLookup = ctx.typert.lookups.get('session')
  563. if (agentLookup === undefined || sessionLookup === undefined) throw new Error('core lookup providers were not mounted')
  564. const resolvedAgent = Promise.resolve(agentLookup.resolve(sessionId))
  565. const resolvedSession = Promise.resolve(sessionLookup.resolve(sessionId))
  566. await vi.waitFor(() => { expect(resume).toHaveBeenCalledOnce() })
  567. release.resolve(undefined)
  568. await expect(resolvedAgent).resolves.toBe(resumedAgent)
  569. await expect(resolvedSession).resolves.toBe(resumedSession)
  570. expect(inspect).toHaveBeenCalledOnce()
  571. })
  572. it('preserves the subagent ownership fence for cold and live Remote lookups', async () => {
  573. const ctx = new Context()
  574. await ctx.plugin(TypertRegistry)
  575. await ctx.plugin(SessionStore)
  576. await ctx.plugin(AgentRegistry)
  577. const coldId = sid('session-remote-cold-child')
  578. const coldMeta = header(coldId, 1000, {
  579. parentSession: sid('session-parent'),
  580. origin: 'subagent',
  581. })
  582. const inspect = vi.fn(() => Promise.resolve({ meta: coldMeta, events: [] as SessionEvent[] }))
  583. providePersistence(ctx, {
  584. list: () => Promise.resolve([coldMeta]),
  585. inspect,
  586. })
  587. const liveSession = ctx.sessions.create(sid('session-remote-live-child'), {
  588. meta: { cwd: '/proj', parentSession: sid('session-parent'), origin: 'subagent' },
  589. })
  590. const liveAgent = { id: liveSession.id, session: liveSession, status: 'idle', ctx } as Agent
  591. ctx.agents.register(liveAgent)
  592. const resume = vi.spyOn(ctx.agents, 'resume')
  593. const defaultAgentLookup = ctx.typert.lookups.get('agent')
  594. const defaultSessionLookup = ctx.typert.lookups.get('session')
  595. createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  596. await vi.waitFor(() => {
  597. expect(ctx.typert.lookups.get('agent')).not.toBe(defaultAgentLookup)
  598. expect(ctx.typert.lookups.get('session')).not.toBe(defaultSessionLookup)
  599. })
  600. const agentLookup = ctx.typert.lookups.get('agent')
  601. const sessionLookup = ctx.typert.lookups.get('session')
  602. if (agentLookup === undefined || sessionLookup === undefined) throw new Error('core lookup providers were not mounted')
  603. const ownershipFailure = {
  604. code: 'session/agent-busy',
  605. details: { reason: 'use subagent delivery for this child session' },
  606. }
  607. const coldFailure = Promise.resolve(agentLookup.resolve(coldId))
  608. const liveFailure = Promise.resolve(sessionLookup.resolve(liveSession.id))
  609. await expect(coldFailure).rejects.toMatchObject(ownershipFailure)
  610. await expect(liveFailure).rejects.toMatchObject(ownershipFailure)
  611. expect(resume).not.toHaveBeenCalled()
  612. expect(inspect).toHaveBeenCalledOnce()
  613. })
  614. })
  615. describe('subagent ownership fence', () => {
  616. it('reads a cold child without an Agent and rejects generic resume or adoption', async () => {
  617. const ctx = new Context()
  618. await ctx.plugin(SessionStore)
  619. await ctx.plugin(AgentRegistry)
  620. const sessionId = sid('session-child')
  621. const meta = header('session-child', 1000, {
  622. parentSession: sid('session-parent'),
  623. origin: 'subagent',
  624. })
  625. const events = [
  626. { type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  627. {
  628. type: 'user/message',
  629. seq: SessionSeq(1),
  630. time: 2,
  631. data: createUserMessage({ content: [{ type: 'text', text: 'work' }], source: { kind: 'user' } }),
  632. surfaceOp: 'append',
  633. },
  634. {
  635. type: 'subagent/descriptor',
  636. seq: SessionSeq(2),
  637. time: 3,
  638. data: snapshotSubagentDescriptor({
  639. mode: 'continuable',
  640. provider: 'spawn',
  641. label: 'child',
  642. }),
  643. },
  644. { type: 'turn/end', seq: SessionSeq(3), time: 4, data: { turn: 1, reason: { kind: 'completed' } } },
  645. ] as SessionEvent[]
  646. const inspect = vi.fn(() => Promise.resolve({ meta, events }))
  647. providePersistence(ctx, {
  648. list: () => Promise.resolve([meta]),
  649. inspect,
  650. })
  651. const resume = vi.spyOn(ctx.agents, 'resume')
  652. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  653. ctx.sessionProjections.register(subagentIdentityProjectionDefinition)
  654. const history = await new SessionHistoryController(
  655. ctx,
  656. (observation) => { observation[Symbol.dispose]() },
  657. ).page({
  658. address: {
  659. kind: 'subagent',
  660. parentSessionId: meta.parentSession as SessionId,
  661. childSessionId: sessionId,
  662. mode: 'continuable',
  663. },
  664. throughSeq: 3,
  665. }, new AbortController().signal)
  666. expect(history.records.map(record => record.event.type))
  667. .toEqual(events.map(event => event.type))
  668. expect(ctx.agents.get(sessionId)).toBeUndefined()
  669. const prompt = await remote.prompt(promptRequest({
  670. sessionId,
  671. mode: 'queue',
  672. content: [{ type: 'text', text: 'follow up' }],
  673. }))
  674. expect(prompt.ok).toBe(false)
  675. if (!prompt.ok) {
  676. expect(prompt.error).toMatchObject({
  677. code: 'session/agent-busy',
  678. details: { reason: 'use subagent delivery for this child session' },
  679. })
  680. }
  681. const create = await remote.create(request({ sessionId, cwd: '/proj' }))
  682. expect(create.ok).toBe(false)
  683. if (!create.ok) expect(create.error.code).toBe('session/agent-busy')
  684. expect(resume).not.toHaveBeenCalled()
  685. expect(ctx.agents.get(sessionId)).toBeUndefined()
  686. // One log open serves all three cold reads: the observation cache reuses
  687. // the prepared Session while the stat revision is unchanged.
  688. expect(inspect).toHaveBeenCalledTimes(1)
  689. })
  690. it('no longer treats a descriptor-only cold child without origin as subagent-owned', async () => {
  691. const ctx = new Context()
  692. await ctx.plugin(SessionStore)
  693. await ctx.plugin(AgentRegistry)
  694. const sessionId = sid('session-legacy-child')
  695. const meta = header('session-legacy-child', 1000, {
  696. parentSession: sid('session-parent'),
  697. })
  698. const events = [
  699. {
  700. type: 'subagent/descriptor',
  701. seq: SessionSeq(0),
  702. time: 1,
  703. data: { version: 2, mode: 'continuable', provider: 'spawn', label: 'child' },
  704. },
  705. ] as SessionEvent[]
  706. providePersistence(ctx, {
  707. list: () => Promise.resolve([meta]),
  708. inspect: () => Promise.resolve({ meta, events }) })
  709. // Stores whose headers predate `origin` classify a child only through the
  710. // descriptor event; the pre-release decision stops recognizing them, so
  711. // the ownership fence lets generic resume reach the registry instead of
  712. // answering `agent-busy`.
  713. const resume = vi.spyOn(ctx.agents, 'resume')
  714. .mockRejectedValue(new Error('registry unavailable in this bench'))
  715. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  716. const prompt = await remote.prompt(promptRequest({
  717. sessionId,
  718. mode: 'queue',
  719. content: [{ type: 'text', text: 'follow up' }],
  720. }))
  721. expect(resume).toHaveBeenCalledTimes(1)
  722. expect(prompt.ok).toBe(false)
  723. if (!prompt.ok) expect(prompt.error.code).toBe('gateway/internal')
  724. })
  725. it('rejects origin-marked and runtime-owned live children from generic controls', async () => {
  726. const ctx = new Context()
  727. await ctx.plugin(SessionStore)
  728. await ctx.plugin(AgentRegistry)
  729. const parentSession = ctx.sessions.create(sid('session-parent'), { meta: { cwd: '/proj' } })
  730. const parent = { id: parentSession.id, session: parentSession, status: 'idle', ctx } as Agent
  731. ctx.agents.register(parent)
  732. const originSession = ctx.sessions.create(sid('session-origin-child'), {
  733. meta: { cwd: '/proj', parentSession: parent.id, origin: 'subagent' },
  734. })
  735. const cancel = vi.fn()
  736. const updateInbox = vi.fn(() => 'applied' as const)
  737. const originChild = {
  738. id: originSession.id,
  739. session: originSession,
  740. status: 'idle',
  741. ctx,
  742. cancel,
  743. updateInbox,
  744. } as unknown as Agent
  745. ctx.agents.register(originChild)
  746. const startingSession = ctx.sessions.create(sid('session-starting-child'), {
  747. meta: { cwd: '/proj', parentSession: parent.id },
  748. })
  749. const startingChild = { id: startingSession.id, session: startingSession, status: 'idle', ctx } as Agent
  750. ctx.agents.enter(startingChild, parent)
  751. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  752. const stopped = await remote.cancel(request({ sessionId: originChild.id }))
  753. expect(stopped.ok).toBe(false)
  754. if (!stopped.ok) expect(stopped.error.code).toBe('session/agent-busy')
  755. expect(cancel).not.toHaveBeenCalled()
  756. const queued = await remote.updateQueue(request({
  757. sessionId: originChild.id,
  758. itemId: MessageId('queued-item'),
  759. action: { kind: 'remove' },
  760. }))
  761. expect(queued.ok).toBe(false)
  762. if (!queued.ok) expect(queued.error.code).toBe('session/agent-busy')
  763. expect(updateInbox).not.toHaveBeenCalled()
  764. const selection = await remote.selectModel(request({
  765. sessionId: startingChild.id,
  766. provider: 'p',
  767. model: 'm',
  768. }))
  769. expect(selection.ok).toBe(false)
  770. if (!selection.ok) expect(selection.error.code).toBe('session/agent-busy')
  771. const create = await remote.create(request({ sessionId: originChild.id, cwd: '/proj' }))
  772. expect(create.ok).toBe(false)
  773. if (!create.ok) expect(create.error.code).toBe('session/agent-busy')
  774. expect(ctx.agents.get(originChild.id)).toBe(originChild)
  775. })
  776. it('does not classify an ordinary fork from an inherited ancestor descriptor', async () => {
  777. const ctx = new Context()
  778. await ctx.plugin(SessionStore)
  779. await ctx.plugin(AgentRegistry)
  780. const session = ctx.sessions.create(sid('session-ordinary-fork'), {
  781. seed: [{
  782. type: 'subagent/descriptor',
  783. seq: SessionSeq(0),
  784. time: 1,
  785. data: { version: 2, mode: 'continuable', provider: 'spawn', label: 'ancestor' },
  786. }],
  787. meta: { cwd: '/proj', parentSession: sid('session-source'), isSeeded: true },
  788. inheritedEventCount: SessionLogOffset(1),
  789. })
  790. const followup = vi.fn()
  791. const agent = { id: session.id, session, status: 'idle', ctx, followup } as unknown as Agent
  792. ctx.agents.register(agent)
  793. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  794. const response = await remote.prompt(promptRequest({
  795. sessionId: agent.id,
  796. mode: 'queue',
  797. content: [{ type: 'text', text: 'ordinary work' }],
  798. }))
  799. expect(response.ok).toBe(true)
  800. expect(followup).toHaveBeenCalledOnce()
  801. })
  802. it('canonicalizes a supplied browser zone on the exact prompt and rejects invalid names', async () => {
  803. const ctx = new Context()
  804. await ctx.plugin(SessionStore)
  805. await ctx.plugin(AgentRegistry)
  806. const session = ctx.sessions.create(sid('session-browser-zone'), { meta: { cwd: '/proj' } })
  807. const followup = vi.fn()
  808. const agent = { id: session.id, session, status: 'idle', ctx, followup } as unknown as Agent
  809. ctx.agents.register(agent)
  810. const remote = createSessionTestRemote(ctx, {
  811. defaultModelSelection: () => ({ provider: 'p', model: 'm' }),
  812. cwd: '/tmp',
  813. })
  814. const alias = 'US/Pacific'
  815. const canonical = new Intl.DateTimeFormat('en-US', { timeZone: alias })
  816. .resolvedOptions().timeZone
  817. const zonedRequest = promptRequest({
  818. sessionId: agent.id,
  819. mode: 'queue' as const,
  820. content: [{ type: 'text' as const, text: 'zoned work' }],
  821. clientTimeZone: alias,
  822. })
  823. await expect(remote.prompt(zonedRequest)).resolves.toMatchObject({ ok: true })
  824. expect(followup).toHaveBeenNthCalledWith(1, expect.objectContaining({
  825. source: { kind: 'user', rpcId: zonedRequest.requestId, clientTimeZone: canonical },
  826. }))
  827. const utcRequest = promptRequest({
  828. sessionId: agent.id,
  829. mode: 'queue' as const,
  830. content: [{ type: 'text' as const, text: 'UTC work' }],
  831. clientTimeZone: 'UTC',
  832. })
  833. await expect(remote.prompt(utcRequest)).resolves.toMatchObject({ ok: true })
  834. expect(followup).toHaveBeenNthCalledWith(2, expect.objectContaining({
  835. source: { kind: 'user', rpcId: utcRequest.requestId, clientTimeZone: 'UTC' },
  836. }))
  837. const unzonedRequest = promptRequest({
  838. sessionId: agent.id,
  839. mode: 'queue' as const,
  840. content: [{ type: 'text' as const, text: 'headless work' }],
  841. })
  842. await expect(remote.prompt(unzonedRequest)).resolves.toMatchObject({ ok: true })
  843. expect(followup).toHaveBeenNthCalledWith(3, expect.objectContaining({
  844. source: { kind: 'user', rpcId: unzonedRequest.requestId },
  845. }))
  846. for (const clientTimeZone of ['', ' UTC', 'CST', 'Not/A_Real_Zone']) {
  847. const invalid = await remote.prompt(promptRequest({
  848. sessionId: agent.id,
  849. mode: 'queue' as const,
  850. content: [{ type: 'text' as const, text: 'invalid zone' }],
  851. clientTimeZone,
  852. }))
  853. expect(invalid).toMatchObject({
  854. ok: false,
  855. error: {
  856. code: 'session/invalid-time-zone',
  857. message: 'clientTimeZone must be UTC or a valid IANA Area/Location name',
  858. details: { value: clientTimeZone },
  859. },
  860. })
  861. }
  862. expect(followup).toHaveBeenCalledTimes(3)
  863. })
  864. })
  865. describe('degenerate composition (no persistence, no factory)', () => {
  866. it('lists no cold rows and reports an absent point source as not found', async () => {
  867. const ctx = new Context()
  868. await ctx.plugin(SessionStore)
  869. await ctx.plugin(AgentRegistry)
  870. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  871. const listed = await remote.list(request({}))
  872. expect(listed.ok).toBe(true)
  873. if (listed.ok) expect(listed.value.items).toEqual([])
  874. // No persistence means cold history cannot inspect a transcript.
  875. const response = await remote.page({
  876. address: { kind: 'session', sessionId: sid('session-ghost') },
  877. throughSeq: -1,
  878. })
  879. expect(response.ok).toBe(false)
  880. if (!response.ok) {
  881. expect(response.error.code).toBe('session/not-found')
  882. }
  883. })
  884. it('maps a missing direct persistence read to session-not-found', async () => {
  885. const ctx = new Context()
  886. await ctx.plugin(SessionStore)
  887. await ctx.plugin(AgentRegistry)
  888. const inspect = vi.fn()
  889. const stat = vi.fn(() => Promise.resolve(undefined))
  890. providePersistence(ctx, {
  891. list: () => Promise.resolve([]),
  892. stat,
  893. inspect,
  894. })
  895. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  896. const response = await remote.page({
  897. address: { kind: 'session', sessionId: sid('session-missing') },
  898. throughSeq: -1,
  899. })
  900. expect(response.ok).toBe(false)
  901. if (!response.ok) expect(response.error.code).toBe('session/not-found')
  902. // Absence is decided by the stat preflight; the log itself is never opened.
  903. expect(stat).toHaveBeenCalledOnce()
  904. expect(inspect).not.toHaveBeenCalled()
  905. })
  906. })
  907. describe('sessions.prompt synchronous rejection', () => {
  908. it('maps a synchronous send throw (disposed/invalid input) to agent-busy with the reason attached', async () => {
  909. const ctx = new Context()
  910. await ctx.plugin(SessionStore)
  911. await ctx.plugin(AgentRegistry)
  912. const session = ctx.sessions.create(sid('session-throwing'))
  913. // A live structural stub whose delivery verbs throw synchronously, the
  914. // shape a disposed loop presents at this gateway boundary.
  915. ctx.agents.register({
  916. id: session.id,
  917. session,
  918. status: 'idle',
  919. ctx,
  920. followup: () => { throw new Error('agent "session-throwing" lifecycle disposed') },
  921. steer: () => { throw new Error('agent "session-throwing" lifecycle disposed') },
  922. } as unknown as Agent)
  923. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  924. for (const mode of ['queue', 'steer'] as const) {
  925. const response = await remote.prompt(promptRequest({
  926. sessionId: session.id, mode, content: [{ type: 'text' as const, text: 'x' }],
  927. }))
  928. expect(response.ok).toBe(false)
  929. if (!response.ok) {
  930. expect(response.error.code).toBe('session/agent-busy')
  931. expect(response.error.message).toBe('prompt rejected')
  932. expect(response.error.details).toEqual({
  933. reason: 'Error: agent "session-throwing" lifecycle disposed',
  934. })
  935. }
  936. }
  937. })
  938. it('classifies a raced cold-resume ID collision as agent-busy', async () => {
  939. const ctx = new Context()
  940. await ctx.plugin(SessionStore)
  941. await ctx.plugin(AgentRegistry)
  942. const sessionId = sid('race-resume')
  943. const meta: SessionHeader = header('race-resume', 1000)
  944. providePersistence(ctx, {
  945. list: () => Promise.resolve([meta]),
  946. inspect: () => Promise.resolve({ meta, events: [] as SessionEvent[] }) })
  947. // The raced winner: a live parent-owned subagent publishes the identity
  948. // while the generic cold resume is in flight, so the resume collides.
  949. const parentSession = ctx.sessions.create(sid('race-parent'), { meta: { cwd: '/proj' } })
  950. const parent = { id: parentSession.id, session: parentSession, status: 'idle', ctx } as Agent
  951. ctx.agents.register(parent)
  952. const childSession = ctx.sessions.create(sessionId, {
  953. meta: { cwd: '/proj', parentSession: parent.id, origin: 'subagent' },
  954. })
  955. const child = { id: sessionId, session: childSession, status: 'idle', ctx } as unknown as Agent
  956. vi.spyOn(ctx.agents, 'resume').mockImplementationOnce(async () => {
  957. // The parent's `enter()` wins the identity between the pre-resume
  958. // re-check and publication; the generic resume then collides.
  959. ctx.agents.register(child)
  960. throw new Error('session id already published')
  961. })
  962. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  963. const selection = await remote.selectModel(request({ sessionId, provider: 'p', model: 'm' }))
  964. expect(selection.ok).toBe(false)
  965. if (!selection.ok) {
  966. expect(selection.error).toMatchObject({
  967. code: 'session/agent-busy',
  968. details: { reason: 'use subagent delivery for this child session' },
  969. })
  970. }
  971. })
  972. })