resume.spec.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  2. import { afterEach, describe, expect, it } from 'vitest'
  3. import { Context } from 'cordis'
  4. import { mkdtemp, rm } from 'node:fs/promises'
  5. import { tmpdir } from 'node:os'
  6. import { join } from 'node:path'
  7. import LlmService from '@deepseek-ai/dsh-llm'
  8. import SessionStore, { SESSION_FORMAT_VERSION, Session, SessionId } from '@deepseek-ai/dsh-session'
  9. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  10. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  11. import ToolRegistry from '@deepseek-ai/dsh-tools'
  12. import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
  13. import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
  14. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  15. import { MockAdapter, textResponse } from './mock-adapter.ts'
  16. const dirs: string[] = []
  17. afterEach(async () => { for (const d of dirs.splice(0)) await rm(d, { recursive: true, force: true }) })
  18. async function persistentHarness(adapter: MockAdapter): Promise<{ ctx: Context; root: string }> {
  19. const root = await mkdtemp(join(tmpdir(), 'dsh-resume-'))
  20. dirs.push(root)
  21. return { ctx: await mountPersistentHarness(root, adapter), root }
  22. }
  23. async function mountPersistentHarness(root: string, adapter: MockAdapter): Promise<Context> {
  24. const ctx = new Context()
  25. await ctx.plugin(LlmService)
  26. await ctx.plugin(SessionStore)
  27. await ctx.plugin(SystemPrompt)
  28. await ctx.plugin(ToolRegistry)
  29. await ctx.plugin(AgentRegistry)
  30. await ctx.plugin(AgentLoop, { agents: [] })
  31. await ctx.plugin(SessionPersistenceJsonl, { root })
  32. ctx.llm.registerAdapter(['mock'], adapter)
  33. return ctx
  34. }
  35. async function persistSession(sessionId: SessionId): Promise<string> {
  36. const { ctx, root } = await persistentHarness(new MockAdapter([textResponse('seed')]))
  37. // Persistence deliberately has no artifact for a truly empty session. A
  38. // balanced completed turn is the smallest resumable log and avoids running
  39. // the model merely to construct this lifecycle fixture.
  40. const seed: SessionEvent[] = [
  41. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  42. { type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'completed' } } },
  43. ]
  44. const session = ctx.sessions.create(sessionId, { seed })
  45. await ctx.sessions.flush(session)
  46. await ctx.fiber.dispose()
  47. return root
  48. }
  49. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  50. return new Promise((resolve) => {
  51. const dispose = ctx.on('agent/status', (subject, status) => {
  52. if (subject === agent && status === 'idle') { dispose(); resolve() }
  53. })
  54. })
  55. }
  56. /** Fail a lifecycle regression promptly instead of waiting for Vitest's suite timeout. */
  57. async function promptly<T>(task: Promise<T>): Promise<T> {
  58. const timeout = Promise.withResolvers<never>()
  59. const timer = setTimeout(() => { timeout.reject(new Error('lifecycle task did not settle promptly')) }, 1000)
  60. try {
  61. return await Promise.race([task, timeout.promise])
  62. } finally {
  63. clearTimeout(timer)
  64. }
  65. }
  66. /** Throw an arbitrary callback value to exercise the public unknown-error boundary. */
  67. function throwUnknown(value: unknown): never {
  68. throw value
  69. }
  70. describe('the session-persistence Agent Note: AgentLoop factory create/resume', () => {
  71. it('resumes a session persisted before messages gained identities', async () => {
  72. const sessionId = SessionId('pre-identity-resume')
  73. const first = await persistentHarness(new MockAdapter([]))
  74. await first.ctx.sessionPersistence.create({
  75. version: SESSION_FORMAT_VERSION,
  76. id: sessionId,
  77. createdAt: 1,
  78. })
  79. await first.ctx.sessionPersistence.append(sessionId, [
  80. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  81. {
  82. type: 'user/message',
  83. seq: 1,
  84. time: 2,
  85. data: { content: [{ type: 'text', text: 'old question' }], source: { kind: 'user' } },
  86. surfaceOp: 'append',
  87. },
  88. { type: 'step/start', seq: 2, time: 3, data: { turn: 1, step: 1 } },
  89. {
  90. type: 'assistant/message',
  91. seq: 3,
  92. time: 4,
  93. data: {
  94. turn: 1,
  95. step: 1,
  96. content: [{ type: 'text', text: 'old answer' }],
  97. provenance: { provider: 'mock', model: 'mock' },
  98. },
  99. surfaceOp: 'append',
  100. },
  101. { type: 'step/end', seq: 4, time: 5, data: { turn: 1, step: 1 } },
  102. { type: 'turn/end', seq: 5, time: 6, data: { turn: 1, reason: { kind: 'completed' } } },
  103. ] as unknown as SessionEvent[])
  104. await first.ctx.fiber.dispose()
  105. const ctx = await mountPersistentHarness(first.root, new MockAdapter([textResponse('new answer')]))
  106. const handle = await ctx.agents.resume({
  107. resumeSessionId: sessionId,
  108. agentOptions: { provider: 'mock', model: 'mock' },
  109. })
  110. expect(handle.agent.session.deriveMessages()).toMatchObject([
  111. { id: `legacy-message:${sessionId}:1`, role: 'user' },
  112. { id: `legacy-message:${sessionId}:3`, role: 'assistant' },
  113. ])
  114. handle.agent.followup(createUserMessage({
  115. content: [{ type: 'text', text: 'new question' }],
  116. source: { kind: 'user' },
  117. }))
  118. await waitForIdle(ctx, handle.agent)
  119. expect(handle.agent.session.deriveMessages()).toHaveLength(4)
  120. expect(handle.agent.session.events.at(-1)).toMatchObject({
  121. type: 'turn/end',
  122. data: { reason: { kind: 'completed' } },
  123. })
  124. await handle.dispose()
  125. await ctx.fiber.dispose()
  126. })
  127. it('normalizes a non-Error resume publication failure for rollback and rethrows it', async () => {
  128. const sessionId = SessionId('unknown-resume-failure-s')
  129. const root = await persistSession(sessionId)
  130. const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
  131. const failure = { source: 'resume' }
  132. ctx.on('session/created', () => throwUnknown(failure))
  133. await expect(ctx.agents.resume({
  134. resumeSessionId: sessionId,
  135. })).rejects.toBe(failure)
  136. expect(ctx.agents.get(SessionId('unknown-resume-failure'))).toBeUndefined()
  137. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  138. await ctx.fiber.dispose()
  139. })
  140. it('createAgent uses the caller-supplied sessionId (not ${id}-session)', async () => {
  141. const adapter = new MockAdapter([textResponse('hi')])
  142. const { ctx } = await persistentHarness(adapter)
  143. const { agent } = await ctx.agents.create({ sessionId: SessionId('custom-session'), meta: { cwd: '/w' } })
  144. expect(agent.session.id).toBe('custom-session')
  145. expect(agent.session.header.cwd).toBe('/w')
  146. await ctx.fiber.dispose()
  147. })
  148. it('createAgent rejects a duplicate identity without orphaning a session', async () => {
  149. const adapter = new MockAdapter([textResponse('hi')])
  150. const { ctx } = await persistentHarness(adapter)
  151. const sessionId = SessionId('sess-a')
  152. await ctx.agents.create({ sessionId })
  153. await expect(ctx.agents.create({ sessionId })).rejects.toThrow(/already exists/)
  154. expect(ctx.sessions.list()).toHaveLength(1)
  155. await ctx.fiber.dispose()
  156. })
  157. it('resume cannot crash-repair a turn owned by a live agent', async () => {
  158. const { ctx } = await persistentHarness(new MockAdapter([textResponse('unused')]))
  159. const sessionId = SessionId('live-resume-race')
  160. const first = (await ctx.agents.create({ sessionId })).agent
  161. first.session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  162. await ctx.sessions.flush(first.session)
  163. await expect(ctx.agents.resume({ resumeSessionId: sessionId }))
  164. .rejects.toThrow(/live turn is open/)
  165. first.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  166. await ctx.sessions.flush(first.session)
  167. const loaded = await ctx.sessionPersistence.load(sessionId)
  168. expect(loaded.events.map(event => event.type)).toEqual(['turn/start', 'turn/end'])
  169. expect(loaded.events.at(-1)).toMatchObject({
  170. type: 'turn/end',
  171. data: { reason: { kind: 'completed' } },
  172. })
  173. await ctx.fiber.dispose()
  174. })
  175. it('createAgent works without meta (no cwd)', async () => {
  176. const adapter = new MockAdapter([textResponse('hi')])
  177. const { ctx } = await persistentHarness(adapter)
  178. const { agent } = await ctx.agents.create({ sessionId: SessionId('nometa-session') })
  179. expect(agent.session.id).toBe('nometa-session')
  180. expect(agent.session.header.cwd).toBeUndefined()
  181. await ctx.fiber.dispose()
  182. })
  183. it('resume of a session with no cwd carries an undefined cwd header', async () => {
  184. // Lifecycle 1: create a no-cwd session and run a turn.
  185. const adapter1 = new MockAdapter([textResponse('a')])
  186. const { ctx: ctx1, root } = await persistentHarness(adapter1)
  187. const a1 = (await ctx1.agents.create({ sessionId: SessionId('nocwd-sess') })).agent
  188. a1.followup(createUserMessage({ content: [{ type: 'text', text: 'q' }], source: { kind: 'user' } }))
  189. await waitForIdle(ctx1, a1)
  190. await ctx1.fiber.dispose()
  191. // Lifecycle 2: resume it; the header cwd stays undefined (no-cwd branch).
  192. const adapter2 = new MockAdapter([textResponse('b')])
  193. const ctx2 = new Context()
  194. await ctx2.plugin(LlmService)
  195. await ctx2.plugin(SessionStore)
  196. await ctx2.plugin(SystemPrompt)
  197. await ctx2.plugin(ToolRegistry)
  198. await ctx2.plugin(AgentRegistry)
  199. await ctx2.plugin(AgentLoop, { agents: [] })
  200. await ctx2.plugin(SessionPersistenceJsonl, { root })
  201. ctx2.llm.registerAdapter(['mock'], adapter2)
  202. const a2 = (await ctx2.agents.resume({ resumeSessionId: SessionId('nocwd-sess') })).agent
  203. expect(a2.session.header.cwd).toBeUndefined()
  204. await ctx2.fiber.dispose()
  205. })
  206. it('agent/session-start fires "startup" for createAgent and "resume" for resume()', async () => {
  207. // Lifecycle 1: a fresh createAgent emits session-start with source 'startup'.
  208. const adapter1 = new MockAdapter([textResponse('a')])
  209. const { ctx: ctx1, root } = await persistentHarness(adapter1)
  210. const sources1: string[] = []
  211. ctx1.on('agent/session-start', (_agent, source) => void sources1.push(source))
  212. const a1 = (await ctx1.agents.create({ sessionId: SessionId('start-sess') })).agent
  213. expect(sources1).toEqual(['startup'])
  214. a1.followup(createUserMessage({ content: [{ type: 'text', text: 'q' }], source: { kind: 'user' } }))
  215. await waitForIdle(ctx1, a1)
  216. await ctx1.fiber.dispose()
  217. // Lifecycle 2: resuming the persisted session emits session-start 'resume'.
  218. const adapter2 = new MockAdapter([textResponse('b')])
  219. const ctx2 = new Context()
  220. await ctx2.plugin(LlmService)
  221. await ctx2.plugin(SessionStore)
  222. await ctx2.plugin(SystemPrompt)
  223. await ctx2.plugin(ToolRegistry)
  224. await ctx2.plugin(AgentRegistry)
  225. await ctx2.plugin(AgentLoop, { agents: [] })
  226. await ctx2.plugin(SessionPersistenceJsonl, { root })
  227. ctx2.llm.registerAdapter(['mock'], adapter2)
  228. const sources2: string[] = []
  229. ctx2.on('agent/session-start', (_agent, source) => void sources2.push(source))
  230. await ctx2.agents.resume({ resumeSessionId: SessionId('start-sess') })
  231. expect(sources2).toEqual(['resume'])
  232. await ctx2.fiber.dispose()
  233. })
  234. it('resume awaits setup while unpublished, then publishes a fully composed world in order', async () => {
  235. const sessionId = SessionId('resume-setup-success')
  236. const root = await persistSession(sessionId)
  237. const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
  238. const gate = Promise.withResolvers<undefined>()
  239. const setupStarted = Promise.withResolvers<undefined>()
  240. const order: string[] = []
  241. ctx.on('session/created', (session) => {
  242. expect(ctx.sessions.get(session.id)).toBe(session)
  243. expect(ctx.agents.get(sessionId)?.session).toBe(session)
  244. order.push('session/created')
  245. })
  246. ctx.on('agent/created', (agent) => {
  247. expect(agent.status).toBe('idle')
  248. order.push('agent/created')
  249. })
  250. ctx.on('agent/session-start', (agent) => {
  251. expect(() => { agent.cancel({ kind: 'user' }) }).not.toThrow()
  252. order.push('agent/session-start')
  253. })
  254. const resuming = ctx.agents.resume({
  255. resumeSessionId: sessionId,
  256. agentOptions: { provider: 'mock', model: 'mock' },
  257. setup: async (agentCtx) => {
  258. expect(agentCtx.agent?.id).toBe(sessionId)
  259. // The two persisted events plus the end-seed marker.
  260. expect(agentCtx.agent?.session.events).toHaveLength(3)
  261. agentCtx.on('session/created', () => void order.push('setup-listener:session/created'))
  262. agentCtx.on('agent/created', () => void order.push('setup-listener:agent/created'))
  263. order.push('setup:start')
  264. setupStarted.resolve(undefined)
  265. await gate.promise
  266. order.push('setup:end')
  267. },
  268. })
  269. await setupStarted.promise
  270. expect(ctx.agents.get(sessionId)).toBeUndefined()
  271. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  272. expect(order).toEqual(['setup:start'])
  273. gate.resolve(undefined)
  274. const handle = await resuming
  275. expect(order).toEqual([
  276. 'setup:start',
  277. 'setup:end',
  278. 'session/created',
  279. 'setup-listener:session/created',
  280. 'agent/created',
  281. 'setup-listener:agent/created',
  282. 'agent/session-start',
  283. ])
  284. await handle.dispose()
  285. await ctx.fiber.dispose()
  286. })
  287. it('successful resume disposal retires its caller-owned transaction effects', async () => {
  288. const sessionId = SessionId('resume-retired-effects-s')
  289. const root = await persistSession(sessionId)
  290. const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
  291. const handle = await ctx.agents.resume({
  292. resumeSessionId: sessionId,
  293. agentOptions: { provider: 'mock', model: 'mock' },
  294. })
  295. const transactionLabels = [`agentLoop.lifecycle(${sessionId})`]
  296. expect(ctx.fiber.getEffects().map(effect => effect.label)).toEqual(expect.arrayContaining(transactionLabels))
  297. await handle.dispose()
  298. expect(ctx.fiber.getEffects().filter(effect => transactionLabels.includes(effect.label))).toEqual([])
  299. await ctx.fiber.dispose()
  300. })
  301. it('resume setup rejection publishes nothing, unwinds, and releases the identity', async () => {
  302. const sessionId = SessionId('resume-setup-reject')
  303. const root = await persistSession(sessionId)
  304. const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
  305. const published: string[] = []
  306. ctx.on('session/created', () => void published.push('session/created'))
  307. ctx.on('agent/created', () => void published.push('agent/created'))
  308. ctx.on('agent/session-start', () => void published.push('agent/session-start'))
  309. await expect(ctx.agents.resume({
  310. resumeSessionId: sessionId,
  311. agentOptions: { provider: 'mock', model: 'mock' },
  312. setup: async () => {
  313. await Promise.resolve()
  314. throw new Error('resume setup failed')
  315. },
  316. })).rejects.toThrow('resume setup failed')
  317. expect(published).toEqual([])
  318. expect(ctx.agents.get(sessionId)).toBeUndefined()
  319. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  320. const retry = await ctx.agents.resume({
  321. resumeSessionId: sessionId,
  322. agentOptions: { provider: 'mock', model: 'mock' },
  323. })
  324. await retry.dispose()
  325. await ctx.fiber.dispose()
  326. })
  327. it('owner unload aborts resume setup and cannot publish after the callback settles', async () => {
  328. const sessionId = SessionId('resume-setup-owner-unload')
  329. const root = await persistSession(sessionId)
  330. const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
  331. const gate = Promise.withResolvers<undefined>()
  332. const setupStarted = Promise.withResolvers<undefined>()
  333. const published: string[] = []
  334. ctx.on('session/created', () => void published.push('session/created'))
  335. ctx.on('agent/created', () => void published.push('agent/created'))
  336. let resuming!: ReturnType<typeof ctx.agents.resume>
  337. const owner = await ctx.plugin(Object.assign((inner: Context) => {
  338. resuming = inner.agents.resume({
  339. resumeSessionId: sessionId,
  340. agentOptions: { provider: 'mock', model: 'mock' },
  341. setup: async () => {
  342. setupStarted.resolve(undefined)
  343. await gate.promise
  344. },
  345. })
  346. }, { inject: ['agents'] }))
  347. await setupStarted.promise
  348. await owner.dispose()
  349. await expect(resuming).rejects.toThrow(/owner disposed during setup/)
  350. expect(published).toEqual([])
  351. expect(ctx.agents.get(sessionId)).toBeUndefined()
  352. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  353. gate.resolve(undefined)
  354. await Promise.resolve()
  355. expect(published).toEqual([])
  356. await ctx.fiber.dispose()
  357. })
  358. it('owner unload aborts a never-settling persistence load, releases the identity, and blocks late publication', async () => {
  359. const sessionId = SessionId('resume-load-owner-unload')
  360. const root = await persistSession(sessionId)
  361. const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
  362. const snapshot = await ctx.sessionPersistence.load(sessionId)
  363. const lateLoad = Promise.withResolvers<typeof snapshot>()
  364. const loadStarted = Promise.withResolvers<undefined>()
  365. let loads = 0
  366. ctx.sessionPersistence.load = (id) => {
  367. expect(id).toBe(sessionId)
  368. loads += 1
  369. if (loads === 1) {
  370. loadStarted.resolve(undefined)
  371. return lateLoad.promise
  372. }
  373. return Promise.resolve(structuredClone(snapshot))
  374. }
  375. const published: string[] = []
  376. ctx.on('session/created', () => void published.push('session/created'))
  377. ctx.on('agent/created', () => void published.push('agent/created'))
  378. ctx.on('agent/session-start', () => void published.push('agent/session-start'))
  379. let resuming!: ReturnType<typeof ctx.agents.resume>
  380. const owner = await ctx.plugin(Object.assign((inner: Context) => {
  381. resuming = inner.agents.resume({ resumeSessionId: sessionId, agentOptions: { provider: 'mock', model: 'mock' } })
  382. }, { inject: ['agents'] }))
  383. await loadStarted.promise
  384. const rejection = expect(promptly(resuming)).rejects.toThrow(/owner disposed during setup/)
  385. await promptly(owner.dispose())
  386. expect(published).toEqual([])
  387. expect(ctx.agents.get(sessionId)).toBeUndefined()
  388. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  389. // owner.dispose() awaited transaction settlement, so the same identities
  390. // can be reused before awaiting the public rejection.
  391. const retry = await promptly(ctx.agents.resume({ resumeSessionId: sessionId, agentOptions: { provider: 'mock', model: 'mock' } }))
  392. await rejection
  393. expect(loads).toBe(2)
  394. expect(published).toEqual(['session/created', 'agent/created', 'agent/session-start'])
  395. // Settlement of the abandoned backend promise cannot resume the old
  396. // transaction or emit a second publication after the retry owns the ids.
  397. lateLoad.resolve(structuredClone(snapshot))
  398. await Promise.resolve()
  399. await Promise.resolve()
  400. expect(ctx.agents.get(sessionId)).toBe(retry.agent)
  401. expect(ctx.sessions.get(sessionId)).toBe(retry.agent.session)
  402. expect(published).toEqual(['session/created', 'agent/created', 'agent/session-start'])
  403. await retry.dispose()
  404. await ctx.fiber.dispose()
  405. })
  406. it('AgentLoop unload aborts persistence load and awaits wrapper settlement', async () => {
  407. const sessionId = SessionId('resume-load-factory-unload')
  408. const root = await persistSession(sessionId)
  409. const ctx = new Context()
  410. await ctx.plugin(LlmService)
  411. await ctx.plugin(SessionStore)
  412. await ctx.plugin(SystemPrompt)
  413. await ctx.plugin(ToolRegistry)
  414. await ctx.plugin(AgentRegistry)
  415. const loopFiber = await ctx.plugin(AgentLoop, { agents: [] })
  416. await ctx.plugin(SessionPersistenceJsonl, { root })
  417. ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('next')]))
  418. const snapshot = await ctx.sessionPersistence.load(sessionId)
  419. const lateLoad = Promise.withResolvers<typeof snapshot>()
  420. const loadStarted = Promise.withResolvers<undefined>()
  421. ctx.sessionPersistence.load = (id) => {
  422. expect(id).toBe(sessionId)
  423. loadStarted.resolve(undefined)
  424. return lateLoad.promise
  425. }
  426. const published: string[] = []
  427. ctx.on('session/created', () => void published.push('session/created'))
  428. ctx.on('agent/created', () => void published.push('agent/created'))
  429. const resuming = ctx.agents.resume({ resumeSessionId: sessionId, agentOptions: { provider: 'mock', model: 'mock' } })
  430. await loadStarted.promise
  431. const rejection = expect(promptly(resuming)).rejects.toThrow(/agent loop is not active/)
  432. await promptly(loopFiber.dispose())
  433. await rejection
  434. expect(published).toEqual([])
  435. expect(ctx.agents.get(sessionId)).toBeUndefined()
  436. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  437. lateLoad.resolve(structuredClone(snapshot))
  438. await Promise.resolve()
  439. await Promise.resolve()
  440. expect(published).toEqual([])
  441. await ctx.fiber.dispose()
  442. })
  443. it('resume of a forked session preserves the lineage, seed boundary, and delegation depth in the header', async () => {
  444. // Lifecycle 1: persist a FORKED session (carries parentSession + seedLength
  445. // in its header) by creating it with a complete-turn seed — the write path
  446. // materializes the fork (header + seed) on disk.
  447. const seed: SessionEvent[] = [
  448. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  449. { type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'completed' } } },
  450. ]
  451. const adapter1 = new MockAdapter([textResponse('a')])
  452. const { ctx: ctx1, root } = await persistentHarness(adapter1)
  453. const forked = ctx1.sessions.create(SessionId('forked-sess'), {
  454. seed,
  455. meta: { cwd: '/w', parentSession: SessionId('parent-sess'), seedLength: seed.length, delegationDepth: 1 },
  456. })
  457. await ctx1.sessions.flush(forked)
  458. await ctx1.fiber.dispose()
  459. // Lifecycle 2: resume it; the parentSession + seedLength header survives the
  460. // round-trip (exercises resume's parentSession- and seedLength-present
  461. // branches). seedLength must come from the PERSISTED header, not from the
  462. // resume seed length (which is the whole stored log, not the original
  463. // boundary).
  464. const adapter2 = new MockAdapter([textResponse('b')])
  465. const ctx2 = new Context()
  466. await ctx2.plugin(LlmService)
  467. await ctx2.plugin(SessionStore)
  468. await ctx2.plugin(SystemPrompt)
  469. await ctx2.plugin(ToolRegistry)
  470. await ctx2.plugin(AgentRegistry)
  471. await ctx2.plugin(AgentLoop, { agents: [] })
  472. await ctx2.plugin(SessionPersistenceJsonl, { root })
  473. ctx2.llm.registerAdapter(['mock'], adapter2)
  474. const a2 = (await ctx2.agents.resume({ resumeSessionId: SessionId('forked-sess') })).agent
  475. expect(a2.session.header.parentSession).toBe('parent-sess')
  476. expect(a2.session.header.cwd).toBe('/w')
  477. expect(a2.session.header.seedLength).toBe(seed.length)
  478. // The recursion budget survives resume — a dropped depth would let a
  479. // resumed child delegate as if it were top-level.
  480. expect(a2.session.header.delegationDepth).toBe(1)
  481. await ctx2.fiber.dispose()
  482. })
  483. it('an idle inject() survives persist + resume without a synthetic turn', async () => {
  484. const adapter1 = new MockAdapter([textResponse('answer')])
  485. const { ctx: ctx1, root } = await persistentHarness(adapter1)
  486. const a1 = (await ctx1.agents.create({ sessionId: SessionId('inject-sess'), meta: { cwd: '/w' } })).agent
  487. a1.followup(createUserMessage({ content: [{ type: 'text', text: 'q' }], source: { kind: 'user' } }))
  488. await waitForIdle(ctx1, a1)
  489. a1.inject(createUserMessage({ content: [{ type: 'text', text: 'background task 42 finished' }], source: { kind: 'plugin', plugin: 'tool-bash' } }))
  490. await a1.whenIdle()
  491. await ctx1.fiber.dispose()
  492. // Lifecycle 2: resume; the injected context is still in the derived history.
  493. const adapter2 = new MockAdapter([textResponse('next')])
  494. const ctx2 = new Context()
  495. await ctx2.plugin(LlmService)
  496. await ctx2.plugin(SessionStore)
  497. await ctx2.plugin(SystemPrompt)
  498. await ctx2.plugin(ToolRegistry)
  499. await ctx2.plugin(AgentRegistry)
  500. await ctx2.plugin(AgentLoop, { agents: [] })
  501. await ctx2.plugin(SessionPersistenceJsonl, { root })
  502. ctx2.llm.registerAdapter(['mock'], adapter2)
  503. const a2 = (await ctx2.agents.resume({ resumeSessionId: SessionId('inject-sess') })).agent
  504. const flat = JSON.stringify(a2.session.deriveMessages())
  505. expect(flat).toContain('background task 42 finished')
  506. await ctx2.fiber.dispose()
  507. })
  508. it('resume reloads a persisted session: history + turn numbering continue, no duplicate seqs', async () => {
  509. // Lifecycle 1: run one full turn, persisting it.
  510. const adapter1 = new MockAdapter([textResponse('first answer')])
  511. const { ctx: ctx1, root } = await persistentHarness(adapter1)
  512. const a1 = (await ctx1.agents.create({ sessionId: SessionId('sess-resume'), meta: { cwd: '/w' } })).agent
  513. a1.followup(createUserMessage({ content: [{ type: 'text', text: 'first question' }], source: { kind: 'user' } }))
  514. await waitForIdle(ctx1, a1)
  515. const events1 = [...a1.session.events]
  516. const seqs1 = events1.map(e => e.seq)
  517. expect(seqs1).toEqual([...seqs1].sort((x, y) => x - y)) // contiguous
  518. await ctx1.fiber.dispose()
  519. // Lifecycle 2: a brand-new context over the SAME root; resume the session.
  520. const adapter2 = new MockAdapter([textResponse('second answer')])
  521. const ctx2 = new Context()
  522. await ctx2.plugin(LlmService)
  523. await ctx2.plugin(SessionStore)
  524. await ctx2.plugin(SystemPrompt)
  525. await ctx2.plugin(ToolRegistry)
  526. await ctx2.plugin(AgentRegistry)
  527. await ctx2.plugin(AgentLoop, { agents: [] })
  528. await ctx2.plugin(SessionPersistenceJsonl, { root })
  529. ctx2.llm.registerAdapter(['mock'], adapter2)
  530. const a2 = (await ctx2.agents.resume({ resumeSessionId: SessionId('sess-resume') })).agent
  531. // The resumed session carries the prior history…
  532. expect(a2.session.id).toBe('sess-resume')
  533. // …followed by one end-seed event marking the constructor seed.
  534. expect(a2.session.events.length).toBe(events1.length + 1)
  535. expect(a2.session.firstLiveSeq).toBe(events1.length)
  536. expect(a2.session.events.at(-1)?.type).toBe('session/end-seed')
  537. const replay = new Session(SessionId('replay'), events1)
  538. expect(a2.session.deriveMessages()).toEqual(replay.deriveMessages())
  539. // …and a new turn continues numbering (turn 2) with contiguous seqs.
  540. a2.followup(createUserMessage({ content: [{ type: 'text', text: 'second question' }], source: { kind: 'user' } }))
  541. await waitForIdle(ctx2, a2)
  542. const allSeqs = a2.session.events.map(e => e.seq)
  543. expect(allSeqs).toEqual(allSeqs.map((_, i) => i)) // 0..N contiguous, no duplicates
  544. const turnStarts = a2.session.events.filter(e => e.type === 'turn/start')
  545. expect(turnStarts.map(e => e.type === 'turn/start' && e.data.turn)).toEqual([1, 2])
  546. await ctx2.fiber.dispose()
  547. })
  548. it('resume rejects when session persistence is not configured', async () => {
  549. // A harness WITHOUT the persistence plugin.
  550. const adapter = new MockAdapter([textResponse('x')])
  551. const ctx = new Context()
  552. await ctx.plugin(LlmService)
  553. await ctx.plugin(SessionStore)
  554. await ctx.plugin(SystemPrompt)
  555. await ctx.plugin(ToolRegistry)
  556. await ctx.plugin(AgentRegistry)
  557. await ctx.plugin(AgentLoop, { agents: [] })
  558. ctx.llm.registerAdapter(['mock'], adapter)
  559. await expect(ctx.agents.resume({ resumeSessionId: SessionId('nope') }))
  560. .rejects.toThrow(/session persistence is not configured/)
  561. await ctx.fiber.dispose()
  562. })
  563. })
  564. describe('creation and resume cancellation edges', () => {
  565. it('rejects create() with a pre-aborted signal, including a non-Error reason', async () => {
  566. const { ctx } = await persistentHarness(new MockAdapter([]))
  567. const errorReason = new AbortController()
  568. errorReason.abort(new Error('caller gave up'))
  569. await expect(promptly(ctx.agents.create({
  570. sessionId: SessionId('pre-aborted-error'),
  571. agentOptions: { provider: 'mock', model: 'mock' },
  572. signal: errorReason.signal,
  573. }))).rejects.toThrow('caller gave up')
  574. // A non-Error reason is wrapped into the creation-aborted error.
  575. const stringReason = new AbortController()
  576. stringReason.abort('operator string reason')
  577. await expect(promptly(ctx.agents.create({
  578. sessionId: SessionId('pre-aborted-string'),
  579. agentOptions: { provider: 'mock', model: 'mock' },
  580. signal: stringReason.signal,
  581. }))).rejects.toThrow(/creation aborted/)
  582. expect(ctx.agents.get(SessionId('pre-aborted-error'))).toBeUndefined()
  583. expect(ctx.agents.get(SessionId('pre-aborted-string'))).toBeUndefined()
  584. await ctx.fiber.dispose()
  585. })
  586. it('a non-Error abort reason arriving during setup is wrapped for the caller', async () => {
  587. const { ctx } = await persistentHarness(new MockAdapter([]))
  588. const controller = new AbortController()
  589. const setupEntered = Promise.withResolvers<undefined>()
  590. const setupGate = Promise.withResolvers<undefined>()
  591. const creating = ctx.agents.create({
  592. sessionId: SessionId('setup-string-abort'),
  593. agentOptions: { provider: 'mock', model: 'mock' },
  594. signal: controller.signal,
  595. async setup() {
  596. setupEntered.resolve(undefined)
  597. await setupGate.promise
  598. },
  599. })
  600. await setupEntered.promise
  601. controller.abort('mid-setup string reason')
  602. setupGate.resolve(undefined)
  603. await expect(promptly(creating)).rejects.toThrow(/creation aborted/)
  604. expect(ctx.agents.get(SessionId('setup-string-abort'))).toBeUndefined()
  605. await ctx.fiber.dispose()
  606. })
  607. it('resume with a pre-aborted caller signal rejects out of the load race', async () => {
  608. const sessionId = SessionId('resume-pre-aborted')
  609. const root = await persistSession(sessionId)
  610. const ctx = await mountPersistentHarness(root, new MockAdapter([]))
  611. const controller = new AbortController()
  612. controller.abort(new Error('resume abandoned'))
  613. await expect(promptly(ctx.agents.resume({
  614. resumeSessionId: sessionId,
  615. agentOptions: { provider: 'mock', model: 'mock' },
  616. signal: controller.signal,
  617. }))).rejects.toThrow('resume abandoned')
  618. expect(ctx.agents.get(sessionId)).toBeUndefined()
  619. await ctx.fiber.dispose()
  620. })
  621. it('factory teardown during a hung resume load rejects with loop-inactive', async () => {
  622. const sessionId = SessionId('resume-loop-teardown')
  623. const root = await persistSession(sessionId)
  624. const ctx = await mountPersistentHarness(root, new MockAdapter([]))
  625. const snapshot = await ctx.sessionPersistence.load(sessionId)
  626. const gate = Promise.withResolvers<typeof snapshot>()
  627. const loadStarted = Promise.withResolvers<undefined>()
  628. ctx.sessionPersistence.load = () => {
  629. loadStarted.resolve(undefined)
  630. return gate.promise
  631. }
  632. const resuming = ctx.agents.resume({
  633. resumeSessionId: sessionId,
  634. agentOptions: { provider: 'mock', model: 'mock' },
  635. })
  636. await loadStarted.promise
  637. // Resolve the load only after teardown began: the post-load ownership
  638. // check, not the abort race, must reject the wrapper.
  639. const rejection = expect(promptly(resuming)).rejects.toThrow()
  640. const disposal = ctx.fiber.dispose()
  641. gate.resolve(structuredClone(snapshot))
  642. await rejection
  643. await disposal
  644. })
  645. })
  646. describe('configured-start failure edges', () => {
  647. it('a non-Error mid-load abort reason is wrapped for the resume caller', async () => {
  648. const sessionId = SessionId('resume-string-mid-abort')
  649. const root = await persistSession(sessionId)
  650. const ctx = await mountPersistentHarness(root, new MockAdapter([]))
  651. const gate = Promise.withResolvers<never>()
  652. gate.promise.catch(() => undefined)
  653. const loadStarted = Promise.withResolvers<undefined>()
  654. ctx.sessionPersistence.load = () => {
  655. loadStarted.resolve(undefined)
  656. return gate.promise
  657. }
  658. const controller = new AbortController()
  659. const resuming = ctx.agents.resume({
  660. resumeSessionId: sessionId,
  661. agentOptions: { provider: 'mock', model: 'mock' },
  662. signal: controller.signal,
  663. })
  664. await loadStarted.promise
  665. controller.abort('operator string reason')
  666. await expect(promptly(resuming)).rejects.toThrow(/creation aborted/)
  667. expect(ctx.agents.get(sessionId)).toBeUndefined()
  668. await ctx.fiber.dispose()
  669. })
  670. it('a failing exact-id restore over an existing artifact stays loud', async () => {
  671. const sessionId = SessionId('config-existing-corrupt')
  672. const root = await persistSession(sessionId)
  673. const ctx = await mountPersistentHarness(root, new MockAdapter([]))
  674. // The artifact exists (list reports it) but its load fails: this is
  675. // corruption, not first creation — the failure must be reported, and no
  676. // fresh same-id session may shadow the broken one.
  677. ctx.sessionPersistence.load = () => Promise.reject(new Error('artifact corrupt'))
  678. const configured = new Context()
  679. await configured.plugin(LlmService)
  680. await configured.plugin(SessionStore)
  681. await configured.plugin(SystemPrompt)
  682. await configured.plugin(ToolRegistry)
  683. await configured.plugin(AgentRegistry)
  684. await configured.plugin(SessionPersistenceJsonl, { root })
  685. configured.llm.registerAdapter(['mock'], new MockAdapter([]))
  686. configured.sessionPersistence.load = id => ctx.sessionPersistence.load(id)
  687. const configFailures: unknown[] = []
  688. configured.on('agent-loop/config-start-failed', (_id, error) => { configFailures.push(error) })
  689. const configWarnings: string[] = []
  690. const configWarn = configured.logger.warn.bind(configured.logger)
  691. configured.logger.warn = ((...args: unknown[]) => {
  692. if (typeof args[0] === 'string') configWarnings.push(args[0])
  693. return (configWarn as (...a: unknown[]) => unknown)(...args)
  694. }) as typeof configured.logger.warn
  695. const loop = await configured.plugin(AgentLoop, {
  696. agents: [{ id: 'main', sessionId, provider: 'mock', model: 'mock' }],
  697. })
  698. await expect.poll(() => configFailures.length).toBe(1)
  699. expect(configFailures[0]).toBeInstanceOf(Error)
  700. expect((configFailures[0] as Error).message).toBe('artifact corrupt')
  701. expect(configWarnings.some(w => w.includes('config-driven restore'))).toBe(true)
  702. expect(configured.agents.get(sessionId)).toBeUndefined()
  703. await loop.dispose()
  704. await configured.fiber.dispose()
  705. await ctx.fiber.dispose()
  706. })
  707. it('suppresses a configured-resume failure that lands after teardown', async () => {
  708. const sessionId = SessionId('config-late-resume-failure')
  709. const root = await persistSession(sessionId)
  710. const ctx = await mountPersistentHarness(root, new MockAdapter([]))
  711. const gate = Promise.withResolvers<never>()
  712. gate.promise.catch(() => undefined)
  713. const loadStarted = Promise.withResolvers<undefined>()
  714. ctx.sessionPersistence.load = () => {
  715. loadStarted.resolve(undefined)
  716. return gate.promise
  717. }
  718. const failures: unknown[] = []
  719. ctx.on('agent-loop/config-start-failed', (_id, error) => { failures.push(error) })
  720. const configured = new Context()
  721. await configured.plugin(LlmService)
  722. await configured.plugin(SessionStore)
  723. await configured.plugin(SystemPrompt)
  724. await configured.plugin(ToolRegistry)
  725. await configured.plugin(AgentRegistry)
  726. await configured.plugin(SessionPersistenceJsonl, { root })
  727. configured.llm.registerAdapter(['mock'], new MockAdapter([]))
  728. configured.sessionPersistence.load = id => ctx.sessionPersistence.load(id)
  729. configured.on('agent-loop/config-start-failed', (_id, error) => { failures.push(error) })
  730. const loop = await configured.plugin(AgentLoop, {
  731. agents: [{ id: 'main', resumeSessionId: sessionId, provider: 'mock', model: 'mock' }],
  732. })
  733. await loadStarted.promise
  734. const disposal = loop.dispose()
  735. gate.reject(new Error('late backend failure'))
  736. await disposal
  737. await new Promise(r => setTimeout(r, 20))
  738. // Ownership deactivated before the failure landed: the report is dropped.
  739. expect(failures).toEqual([])
  740. await configured.fiber.dispose()
  741. await ctx.fiber.dispose()
  742. })
  743. })