resume.spec.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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. expect(agentCtx.agent?.session.events).toHaveLength(2)
  260. agentCtx.on('session/created', () => void order.push('setup-listener:session/created'))
  261. agentCtx.on('agent/created', () => void order.push('setup-listener:agent/created'))
  262. order.push('setup:start')
  263. setupStarted.resolve(undefined)
  264. await gate.promise
  265. order.push('setup:end')
  266. },
  267. })
  268. await setupStarted.promise
  269. expect(ctx.agents.get(sessionId)).toBeUndefined()
  270. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  271. expect(order).toEqual(['setup:start'])
  272. gate.resolve(undefined)
  273. const handle = await resuming
  274. expect(order).toEqual([
  275. 'setup:start',
  276. 'setup:end',
  277. 'session/created',
  278. 'setup-listener:session/created',
  279. 'agent/created',
  280. 'setup-listener:agent/created',
  281. 'agent/session-start',
  282. ])
  283. await handle.dispose()
  284. await ctx.fiber.dispose()
  285. })
  286. it('successful resume disposal retires its caller-owned transaction effects', async () => {
  287. const sessionId = SessionId('resume-retired-effects-s')
  288. const root = await persistSession(sessionId)
  289. const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
  290. const handle = await ctx.agents.resume({
  291. resumeSessionId: sessionId,
  292. agentOptions: { provider: 'mock', model: 'mock' },
  293. })
  294. const transactionLabels = [`agentLoop.lifecycle(${sessionId})`]
  295. expect(ctx.fiber.getEffects().map(effect => effect.label)).toEqual(expect.arrayContaining(transactionLabels))
  296. await handle.dispose()
  297. expect(ctx.fiber.getEffects().filter(effect => transactionLabels.includes(effect.label))).toEqual([])
  298. await ctx.fiber.dispose()
  299. })
  300. it('resume setup rejection publishes nothing, unwinds, and releases the identity', async () => {
  301. const sessionId = SessionId('resume-setup-reject')
  302. const root = await persistSession(sessionId)
  303. const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
  304. const published: string[] = []
  305. ctx.on('session/created', () => void published.push('session/created'))
  306. ctx.on('agent/created', () => void published.push('agent/created'))
  307. ctx.on('agent/session-start', () => void published.push('agent/session-start'))
  308. await expect(ctx.agents.resume({
  309. resumeSessionId: sessionId,
  310. agentOptions: { provider: 'mock', model: 'mock' },
  311. setup: async () => {
  312. await Promise.resolve()
  313. throw new Error('resume setup failed')
  314. },
  315. })).rejects.toThrow('resume setup failed')
  316. expect(published).toEqual([])
  317. expect(ctx.agents.get(sessionId)).toBeUndefined()
  318. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  319. const retry = await ctx.agents.resume({
  320. resumeSessionId: sessionId,
  321. agentOptions: { provider: 'mock', model: 'mock' },
  322. })
  323. await retry.dispose()
  324. await ctx.fiber.dispose()
  325. })
  326. it('owner unload aborts resume setup and cannot publish after the callback settles', async () => {
  327. const sessionId = SessionId('resume-setup-owner-unload')
  328. const root = await persistSession(sessionId)
  329. const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
  330. const gate = Promise.withResolvers<undefined>()
  331. const setupStarted = Promise.withResolvers<undefined>()
  332. const published: string[] = []
  333. ctx.on('session/created', () => void published.push('session/created'))
  334. ctx.on('agent/created', () => void published.push('agent/created'))
  335. let resuming!: ReturnType<typeof ctx.agents.resume>
  336. const owner = await ctx.plugin(Object.assign((inner: Context) => {
  337. resuming = inner.agents.resume({
  338. resumeSessionId: sessionId,
  339. agentOptions: { provider: 'mock', model: 'mock' },
  340. setup: async () => {
  341. setupStarted.resolve(undefined)
  342. await gate.promise
  343. },
  344. })
  345. }, { inject: ['agents'] }))
  346. await setupStarted.promise
  347. await owner.dispose()
  348. await expect(resuming).rejects.toThrow(/owner disposed during setup/)
  349. expect(published).toEqual([])
  350. expect(ctx.agents.get(sessionId)).toBeUndefined()
  351. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  352. gate.resolve(undefined)
  353. await Promise.resolve()
  354. expect(published).toEqual([])
  355. await ctx.fiber.dispose()
  356. })
  357. it('owner unload aborts a never-settling persistence load, releases the identity, and blocks late publication', async () => {
  358. const sessionId = SessionId('resume-load-owner-unload')
  359. const root = await persistSession(sessionId)
  360. const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
  361. const snapshot = await ctx.sessionPersistence.load(sessionId)
  362. const lateLoad = Promise.withResolvers<typeof snapshot>()
  363. const loadStarted = Promise.withResolvers<undefined>()
  364. let loads = 0
  365. ctx.sessionPersistence.load = (id) => {
  366. expect(id).toBe(sessionId)
  367. loads += 1
  368. if (loads === 1) {
  369. loadStarted.resolve(undefined)
  370. return lateLoad.promise
  371. }
  372. return Promise.resolve(structuredClone(snapshot))
  373. }
  374. const published: string[] = []
  375. ctx.on('session/created', () => void published.push('session/created'))
  376. ctx.on('agent/created', () => void published.push('agent/created'))
  377. ctx.on('agent/session-start', () => void published.push('agent/session-start'))
  378. let resuming!: ReturnType<typeof ctx.agents.resume>
  379. const owner = await ctx.plugin(Object.assign((inner: Context) => {
  380. resuming = inner.agents.resume({ resumeSessionId: sessionId, agentOptions: { provider: 'mock', model: 'mock' } })
  381. }, { inject: ['agents'] }))
  382. await loadStarted.promise
  383. const rejection = expect(promptly(resuming)).rejects.toThrow(/owner disposed during setup/)
  384. await promptly(owner.dispose())
  385. expect(published).toEqual([])
  386. expect(ctx.agents.get(sessionId)).toBeUndefined()
  387. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  388. // owner.dispose() awaited transaction settlement, so the same identities
  389. // can be reused before awaiting the public rejection.
  390. const retry = await promptly(ctx.agents.resume({ resumeSessionId: sessionId, agentOptions: { provider: 'mock', model: 'mock' } }))
  391. await rejection
  392. expect(loads).toBe(2)
  393. expect(published).toEqual(['session/created', 'agent/created', 'agent/session-start'])
  394. // Settlement of the abandoned backend promise cannot resume the old
  395. // transaction or emit a second publication after the retry owns the ids.
  396. lateLoad.resolve(structuredClone(snapshot))
  397. await Promise.resolve()
  398. await Promise.resolve()
  399. expect(ctx.agents.get(sessionId)).toBe(retry.agent)
  400. expect(ctx.sessions.get(sessionId)).toBe(retry.agent.session)
  401. expect(published).toEqual(['session/created', 'agent/created', 'agent/session-start'])
  402. await retry.dispose()
  403. await ctx.fiber.dispose()
  404. })
  405. it('AgentLoop unload aborts persistence load and awaits wrapper settlement', async () => {
  406. const sessionId = SessionId('resume-load-factory-unload')
  407. const root = await persistSession(sessionId)
  408. const ctx = new Context()
  409. await ctx.plugin(LlmService)
  410. await ctx.plugin(SessionStore)
  411. await ctx.plugin(SystemPrompt)
  412. await ctx.plugin(ToolRegistry)
  413. await ctx.plugin(AgentRegistry)
  414. const loopFiber = await ctx.plugin(AgentLoop, { agents: [] })
  415. await ctx.plugin(SessionPersistenceJsonl, { root })
  416. ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('next')]))
  417. const snapshot = await ctx.sessionPersistence.load(sessionId)
  418. const lateLoad = Promise.withResolvers<typeof snapshot>()
  419. const loadStarted = Promise.withResolvers<undefined>()
  420. ctx.sessionPersistence.load = (id) => {
  421. expect(id).toBe(sessionId)
  422. loadStarted.resolve(undefined)
  423. return lateLoad.promise
  424. }
  425. const published: string[] = []
  426. ctx.on('session/created', () => void published.push('session/created'))
  427. ctx.on('agent/created', () => void published.push('agent/created'))
  428. const resuming = ctx.agents.resume({ resumeSessionId: sessionId, agentOptions: { provider: 'mock', model: 'mock' } })
  429. await loadStarted.promise
  430. const rejection = expect(promptly(resuming)).rejects.toThrow(/agent loop is not active/)
  431. await promptly(loopFiber.dispose())
  432. await rejection
  433. expect(published).toEqual([])
  434. expect(ctx.agents.get(sessionId)).toBeUndefined()
  435. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  436. lateLoad.resolve(structuredClone(snapshot))
  437. await Promise.resolve()
  438. await Promise.resolve()
  439. expect(published).toEqual([])
  440. await ctx.fiber.dispose()
  441. })
  442. it('resume of a forked session preserves the lineage, seed boundary, and delegation depth in the header', async () => {
  443. // Lifecycle 1: persist a FORKED session (carries parentSession + seedLength
  444. // in its header) by creating it with a complete-turn seed — the write path
  445. // materializes the fork (header + seed) on disk.
  446. const seed: SessionEvent[] = [
  447. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  448. { type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'completed' } } },
  449. ]
  450. const adapter1 = new MockAdapter([textResponse('a')])
  451. const { ctx: ctx1, root } = await persistentHarness(adapter1)
  452. const forked = ctx1.sessions.create(SessionId('forked-sess'), {
  453. seed,
  454. meta: { cwd: '/w', parentSession: SessionId('parent-sess'), seedLength: seed.length, delegationDepth: 1 },
  455. })
  456. await ctx1.sessions.flush(forked)
  457. await ctx1.fiber.dispose()
  458. // Lifecycle 2: resume it; the parentSession + seedLength header survives the
  459. // round-trip (exercises resume's parentSession- and seedLength-present
  460. // branches). seedLength must come from the PERSISTED header, not from the
  461. // resume seed length (which is the whole stored log, not the original
  462. // boundary).
  463. const adapter2 = new MockAdapter([textResponse('b')])
  464. const ctx2 = new Context()
  465. await ctx2.plugin(LlmService)
  466. await ctx2.plugin(SessionStore)
  467. await ctx2.plugin(SystemPrompt)
  468. await ctx2.plugin(ToolRegistry)
  469. await ctx2.plugin(AgentRegistry)
  470. await ctx2.plugin(AgentLoop, { agents: [] })
  471. await ctx2.plugin(SessionPersistenceJsonl, { root })
  472. ctx2.llm.registerAdapter(['mock'], adapter2)
  473. const a2 = (await ctx2.agents.resume({ resumeSessionId: SessionId('forked-sess') })).agent
  474. expect(a2.session.header.parentSession).toBe('parent-sess')
  475. expect(a2.session.header.cwd).toBe('/w')
  476. expect(a2.session.header.seedLength).toBe(seed.length)
  477. // The recursion budget survives resume — a dropped depth would let a
  478. // resumed child delegate as if it were top-level.
  479. expect(a2.session.header.delegationDepth).toBe(1)
  480. await ctx2.fiber.dispose()
  481. })
  482. it('an idle inject() survives persist + resume without a synthetic turn', async () => {
  483. const adapter1 = new MockAdapter([textResponse('answer')])
  484. const { ctx: ctx1, root } = await persistentHarness(adapter1)
  485. const a1 = (await ctx1.agents.create({ sessionId: SessionId('inject-sess'), meta: { cwd: '/w' } })).agent
  486. a1.followup(createUserMessage({ content: [{ type: 'text', text: 'q' }], source: { kind: 'user' } }))
  487. await waitForIdle(ctx1, a1)
  488. a1.inject(createUserMessage({ content: [{ type: 'text', text: 'background task 42 finished' }], source: { kind: 'plugin', plugin: 'tool-bash' } }))
  489. await a1.whenIdle()
  490. await ctx1.fiber.dispose()
  491. // Lifecycle 2: resume; the injected context is still in the derived history.
  492. const adapter2 = new MockAdapter([textResponse('next')])
  493. const ctx2 = new Context()
  494. await ctx2.plugin(LlmService)
  495. await ctx2.plugin(SessionStore)
  496. await ctx2.plugin(SystemPrompt)
  497. await ctx2.plugin(ToolRegistry)
  498. await ctx2.plugin(AgentRegistry)
  499. await ctx2.plugin(AgentLoop, { agents: [] })
  500. await ctx2.plugin(SessionPersistenceJsonl, { root })
  501. ctx2.llm.registerAdapter(['mock'], adapter2)
  502. const a2 = (await ctx2.agents.resume({ resumeSessionId: SessionId('inject-sess') })).agent
  503. const flat = JSON.stringify(a2.session.deriveMessages())
  504. expect(flat).toContain('background task 42 finished')
  505. await ctx2.fiber.dispose()
  506. })
  507. it('resume reloads a persisted session: history + turn numbering continue, no duplicate seqs', async () => {
  508. // Lifecycle 1: run one full turn, persisting it.
  509. const adapter1 = new MockAdapter([textResponse('first answer')])
  510. const { ctx: ctx1, root } = await persistentHarness(adapter1)
  511. const a1 = (await ctx1.agents.create({ sessionId: SessionId('sess-resume'), meta: { cwd: '/w' } })).agent
  512. a1.followup(createUserMessage({ content: [{ type: 'text', text: 'first question' }], source: { kind: 'user' } }))
  513. await waitForIdle(ctx1, a1)
  514. const events1 = [...a1.session.events]
  515. const seqs1 = events1.map(e => e.seq)
  516. expect(seqs1).toEqual([...seqs1].sort((x, y) => x - y)) // contiguous
  517. await ctx1.fiber.dispose()
  518. // Lifecycle 2: a brand-new context over the SAME root; resume the session.
  519. const adapter2 = new MockAdapter([textResponse('second answer')])
  520. const ctx2 = new Context()
  521. await ctx2.plugin(LlmService)
  522. await ctx2.plugin(SessionStore)
  523. await ctx2.plugin(SystemPrompt)
  524. await ctx2.plugin(ToolRegistry)
  525. await ctx2.plugin(AgentRegistry)
  526. await ctx2.plugin(AgentLoop, { agents: [] })
  527. await ctx2.plugin(SessionPersistenceJsonl, { root })
  528. ctx2.llm.registerAdapter(['mock'], adapter2)
  529. const a2 = (await ctx2.agents.resume({ resumeSessionId: SessionId('sess-resume') })).agent
  530. // The resumed session carries the prior history…
  531. expect(a2.session.id).toBe('sess-resume')
  532. expect(a2.session.events.length).toBe(events1.length)
  533. const replay = new Session(SessionId('replay'), events1)
  534. expect(a2.session.deriveMessages()).toEqual(replay.deriveMessages())
  535. // …and a new turn continues numbering (turn 2) with contiguous seqs.
  536. a2.followup(createUserMessage({ content: [{ type: 'text', text: 'second question' }], source: { kind: 'user' } }))
  537. await waitForIdle(ctx2, a2)
  538. const allSeqs = a2.session.events.map(e => e.seq)
  539. expect(allSeqs).toEqual(allSeqs.map((_, i) => i)) // 0..N contiguous, no duplicates
  540. const turnStarts = a2.session.events.filter(e => e.type === 'turn/start')
  541. expect(turnStarts.map(e => e.type === 'turn/start' && e.data.turn)).toEqual([1, 2])
  542. await ctx2.fiber.dispose()
  543. })
  544. it('resume rejects when session persistence is not configured', async () => {
  545. // A harness WITHOUT the persistence plugin.
  546. const adapter = new MockAdapter([textResponse('x')])
  547. const ctx = new Context()
  548. await ctx.plugin(LlmService)
  549. await ctx.plugin(SessionStore)
  550. await ctx.plugin(SystemPrompt)
  551. await ctx.plugin(ToolRegistry)
  552. await ctx.plugin(AgentRegistry)
  553. await ctx.plugin(AgentLoop, { agents: [] })
  554. ctx.llm.registerAdapter(['mock'], adapter)
  555. await expect(ctx.agents.resume({ resumeSessionId: SessionId('nope') }))
  556. .rejects.toThrow(/session persistence is not configured/)
  557. await ctx.fiber.dispose()
  558. })
  559. })
  560. describe('creation and resume cancellation edges', () => {
  561. it('rejects create() with a pre-aborted signal, including a non-Error reason', async () => {
  562. const { ctx } = await persistentHarness(new MockAdapter([]))
  563. const errorReason = new AbortController()
  564. errorReason.abort(new Error('caller gave up'))
  565. await expect(promptly(ctx.agents.create({
  566. sessionId: SessionId('pre-aborted-error'),
  567. agentOptions: { provider: 'mock', model: 'mock' },
  568. signal: errorReason.signal,
  569. }))).rejects.toThrow('caller gave up')
  570. // A non-Error reason is wrapped into the creation-aborted error.
  571. const stringReason = new AbortController()
  572. stringReason.abort('operator string reason')
  573. await expect(promptly(ctx.agents.create({
  574. sessionId: SessionId('pre-aborted-string'),
  575. agentOptions: { provider: 'mock', model: 'mock' },
  576. signal: stringReason.signal,
  577. }))).rejects.toThrow(/creation aborted/)
  578. expect(ctx.agents.get(SessionId('pre-aborted-error'))).toBeUndefined()
  579. expect(ctx.agents.get(SessionId('pre-aborted-string'))).toBeUndefined()
  580. await ctx.fiber.dispose()
  581. })
  582. it('a non-Error abort reason arriving during setup is wrapped for the caller', async () => {
  583. const { ctx } = await persistentHarness(new MockAdapter([]))
  584. const controller = new AbortController()
  585. const setupEntered = Promise.withResolvers<undefined>()
  586. const setupGate = Promise.withResolvers<undefined>()
  587. const creating = ctx.agents.create({
  588. sessionId: SessionId('setup-string-abort'),
  589. agentOptions: { provider: 'mock', model: 'mock' },
  590. signal: controller.signal,
  591. async setup() {
  592. setupEntered.resolve(undefined)
  593. await setupGate.promise
  594. },
  595. })
  596. await setupEntered.promise
  597. controller.abort('mid-setup string reason')
  598. setupGate.resolve(undefined)
  599. await expect(promptly(creating)).rejects.toThrow(/creation aborted/)
  600. expect(ctx.agents.get(SessionId('setup-string-abort'))).toBeUndefined()
  601. await ctx.fiber.dispose()
  602. })
  603. it('resume with a pre-aborted caller signal rejects out of the load race', async () => {
  604. const sessionId = SessionId('resume-pre-aborted')
  605. const root = await persistSession(sessionId)
  606. const ctx = await mountPersistentHarness(root, new MockAdapter([]))
  607. const controller = new AbortController()
  608. controller.abort(new Error('resume abandoned'))
  609. await expect(promptly(ctx.agents.resume({
  610. resumeSessionId: sessionId,
  611. agentOptions: { provider: 'mock', model: 'mock' },
  612. signal: controller.signal,
  613. }))).rejects.toThrow('resume abandoned')
  614. expect(ctx.agents.get(sessionId)).toBeUndefined()
  615. await ctx.fiber.dispose()
  616. })
  617. it('factory teardown during a hung resume load rejects with loop-inactive', async () => {
  618. const sessionId = SessionId('resume-loop-teardown')
  619. const root = await persistSession(sessionId)
  620. const ctx = await mountPersistentHarness(root, new MockAdapter([]))
  621. const snapshot = await ctx.sessionPersistence.load(sessionId)
  622. const gate = Promise.withResolvers<typeof snapshot>()
  623. const loadStarted = Promise.withResolvers<undefined>()
  624. ctx.sessionPersistence.load = () => {
  625. loadStarted.resolve(undefined)
  626. return gate.promise
  627. }
  628. const resuming = ctx.agents.resume({
  629. resumeSessionId: sessionId,
  630. agentOptions: { provider: 'mock', model: 'mock' },
  631. })
  632. await loadStarted.promise
  633. // Resolve the load only after teardown began: the post-load ownership
  634. // check, not the abort race, must reject the wrapper.
  635. const rejection = expect(promptly(resuming)).rejects.toThrow()
  636. const disposal = ctx.fiber.dispose()
  637. gate.resolve(structuredClone(snapshot))
  638. await rejection
  639. await disposal
  640. })
  641. })
  642. describe('configured-start failure edges', () => {
  643. it('a non-Error mid-load abort reason is wrapped for the resume caller', async () => {
  644. const sessionId = SessionId('resume-string-mid-abort')
  645. const root = await persistSession(sessionId)
  646. const ctx = await mountPersistentHarness(root, new MockAdapter([]))
  647. const gate = Promise.withResolvers<never>()
  648. gate.promise.catch(() => undefined)
  649. const loadStarted = Promise.withResolvers<undefined>()
  650. ctx.sessionPersistence.load = () => {
  651. loadStarted.resolve(undefined)
  652. return gate.promise
  653. }
  654. const controller = new AbortController()
  655. const resuming = ctx.agents.resume({
  656. resumeSessionId: sessionId,
  657. agentOptions: { provider: 'mock', model: 'mock' },
  658. signal: controller.signal,
  659. })
  660. await loadStarted.promise
  661. controller.abort('operator string reason')
  662. await expect(promptly(resuming)).rejects.toThrow(/creation aborted/)
  663. expect(ctx.agents.get(sessionId)).toBeUndefined()
  664. await ctx.fiber.dispose()
  665. })
  666. it('a failing exact-id restore over an existing artifact stays loud', async () => {
  667. const sessionId = SessionId('config-existing-corrupt')
  668. const root = await persistSession(sessionId)
  669. const ctx = await mountPersistentHarness(root, new MockAdapter([]))
  670. // The artifact exists (list reports it) but its load fails: this is
  671. // corruption, not first creation — the failure must be reported, and no
  672. // fresh same-id session may shadow the broken one.
  673. ctx.sessionPersistence.load = () => Promise.reject(new Error('artifact corrupt'))
  674. const configured = new Context()
  675. await configured.plugin(LlmService)
  676. await configured.plugin(SessionStore)
  677. await configured.plugin(SystemPrompt)
  678. await configured.plugin(ToolRegistry)
  679. await configured.plugin(AgentRegistry)
  680. await configured.plugin(SessionPersistenceJsonl, { root })
  681. configured.llm.registerAdapter(['mock'], new MockAdapter([]))
  682. configured.sessionPersistence.load = id => ctx.sessionPersistence.load(id)
  683. const configFailures: unknown[] = []
  684. configured.on('agent-loop/config-start-failed', (_id, error) => { configFailures.push(error) })
  685. const configWarnings: string[] = []
  686. const configWarn = configured.logger.warn.bind(configured.logger)
  687. configured.logger.warn = ((...args: unknown[]) => {
  688. if (typeof args[0] === 'string') configWarnings.push(args[0])
  689. return (configWarn as (...a: unknown[]) => unknown)(...args)
  690. }) as typeof configured.logger.warn
  691. const loop = await configured.plugin(AgentLoop, {
  692. agents: [{ id: 'main', sessionId, provider: 'mock', model: 'mock' }],
  693. })
  694. await expect.poll(() => configFailures.length).toBe(1)
  695. expect(configFailures[0]).toBeInstanceOf(Error)
  696. expect((configFailures[0] as Error).message).toBe('artifact corrupt')
  697. expect(configWarnings.some(w => w.includes('config-driven restore'))).toBe(true)
  698. expect(configured.agents.get(sessionId)).toBeUndefined()
  699. await loop.dispose()
  700. await configured.fiber.dispose()
  701. await ctx.fiber.dispose()
  702. })
  703. it('suppresses a configured-resume failure that lands after teardown', async () => {
  704. const sessionId = SessionId('config-late-resume-failure')
  705. const root = await persistSession(sessionId)
  706. const ctx = await mountPersistentHarness(root, new MockAdapter([]))
  707. const gate = Promise.withResolvers<never>()
  708. gate.promise.catch(() => undefined)
  709. const loadStarted = Promise.withResolvers<undefined>()
  710. ctx.sessionPersistence.load = () => {
  711. loadStarted.resolve(undefined)
  712. return gate.promise
  713. }
  714. const failures: unknown[] = []
  715. ctx.on('agent-loop/config-start-failed', (_id, error) => { failures.push(error) })
  716. const configured = new Context()
  717. await configured.plugin(LlmService)
  718. await configured.plugin(SessionStore)
  719. await configured.plugin(SystemPrompt)
  720. await configured.plugin(ToolRegistry)
  721. await configured.plugin(AgentRegistry)
  722. await configured.plugin(SessionPersistenceJsonl, { root })
  723. configured.llm.registerAdapter(['mock'], new MockAdapter([]))
  724. configured.sessionPersistence.load = id => ctx.sessionPersistence.load(id)
  725. configured.on('agent-loop/config-start-failed', (_id, error) => { failures.push(error) })
  726. const loop = await configured.plugin(AgentLoop, {
  727. agents: [{ id: 'main', resumeSessionId: sessionId, provider: 'mock', model: 'mock' }],
  728. })
  729. await loadStarted.promise
  730. const disposal = loop.dispose()
  731. gate.reject(new Error('late backend failure'))
  732. await disposal
  733. await new Promise(r => setTimeout(r, 20))
  734. // Ownership deactivated before the failure landed: the report is dropped.
  735. expect(failures).toEqual([])
  736. await configured.fiber.dispose()
  737. await ctx.fiber.dispose()
  738. })
  739. })