resume.spec.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. import { afterEach, describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { mkdtemp, rm } from 'node:fs/promises'
  4. import { tmpdir } from 'node:os'
  5. import { join } from 'node:path'
  6. import LlmService from '@deepseek-ai/dsh-llm'
  7. import SessionStore, { Session, SessionId } from '@deepseek-ai/dsh-session'
  8. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  9. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  10. import ToolRegistry from '@deepseek-ai/dsh-tools'
  11. import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
  12. import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
  13. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  14. import { MockAdapter, textResponse } from './mock-adapter.ts'
  15. const dirs: string[] = []
  16. afterEach(async () => { for (const d of dirs.splice(0)) await rm(d, { recursive: true, force: true }) })
  17. async function persistentHarness(adapter: MockAdapter): Promise<{ ctx: Context; root: string }> {
  18. const root = await mkdtemp(join(tmpdir(), 'dsh-resume-'))
  19. dirs.push(root)
  20. return { ctx: await mountPersistentHarness(root, adapter), root }
  21. }
  22. async function mountPersistentHarness(root: string, adapter: MockAdapter): Promise<Context> {
  23. const ctx = new Context()
  24. await ctx.plugin(LlmService)
  25. await ctx.plugin(SessionStore)
  26. await ctx.plugin(SystemPrompt)
  27. await ctx.plugin(ToolRegistry)
  28. await ctx.plugin(AgentRegistry)
  29. await ctx.plugin(AgentLoop, { agents: [] })
  30. await ctx.plugin(SessionPersistenceJsonl, { root })
  31. ctx.llm.registerAdapter(['mock'], adapter)
  32. return ctx
  33. }
  34. async function persistSession(sessionId: SessionId): Promise<string> {
  35. const { ctx, root } = await persistentHarness(new MockAdapter([textResponse('seed')]))
  36. // Persistence deliberately has no artifact for a truly empty session. A
  37. // balanced completed turn is the smallest resumable log and avoids running
  38. // the model merely to construct this lifecycle fixture.
  39. const seed: SessionEvent[] = [
  40. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  41. { type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'completed' } } },
  42. ]
  43. const session = ctx.sessions.create(sessionId, { seed })
  44. await ctx.sessions.flush(session)
  45. await ctx.fiber.dispose()
  46. return root
  47. }
  48. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  49. return new Promise((resolve) => {
  50. const dispose = ctx.on('agent/status', (subject, status) => {
  51. if (subject === agent && status === 'idle') { dispose(); resolve() }
  52. })
  53. })
  54. }
  55. /** Fail a lifecycle regression promptly instead of waiting for Vitest's suite timeout. */
  56. async function promptly<T>(task: Promise<T>): Promise<T> {
  57. const timeout = Promise.withResolvers<never>()
  58. const timer = setTimeout(() => { timeout.reject(new Error('lifecycle task did not settle promptly')) }, 1000)
  59. try {
  60. return await Promise.race([task, timeout.promise])
  61. } finally {
  62. clearTimeout(timer)
  63. }
  64. }
  65. /** Throw an arbitrary callback value to exercise the public unknown-error boundary. */
  66. function throwUnknown(value: unknown): never {
  67. throw value
  68. }
  69. describe('the session-persistence Agent Note: AgentLoop factory create/resume', () => {
  70. it('normalizes a non-Error resume publication failure for rollback and rethrows it', async () => {
  71. const sessionId = SessionId('unknown-resume-failure-s')
  72. const root = await persistSession(sessionId)
  73. const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
  74. const failure = { source: 'resume' }
  75. ctx.on('session/created', () => throwUnknown(failure))
  76. await expect(ctx.agents.resume({
  77. resumeSessionId: sessionId,
  78. })).rejects.toBe(failure)
  79. expect(ctx.agents.get(SessionId('unknown-resume-failure'))).toBeUndefined()
  80. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  81. await ctx.fiber.dispose()
  82. })
  83. it('createAgent uses the caller-supplied sessionId (not ${id}-session)', async () => {
  84. const adapter = new MockAdapter([textResponse('hi')])
  85. const { ctx } = await persistentHarness(adapter)
  86. const { agent } = await ctx.agents.create({ sessionId: SessionId('custom-session'), meta: { cwd: '/w' } })
  87. expect(agent.session.id).toBe('custom-session')
  88. expect(agent.session.header.cwd).toBe('/w')
  89. await ctx.fiber.dispose()
  90. })
  91. it('createAgent rejects a duplicate identity without orphaning a session', async () => {
  92. const adapter = new MockAdapter([textResponse('hi')])
  93. const { ctx } = await persistentHarness(adapter)
  94. const sessionId = SessionId('sess-a')
  95. await ctx.agents.create({ sessionId })
  96. await expect(ctx.agents.create({ sessionId })).rejects.toThrow(/already exists/)
  97. expect(ctx.sessions.list()).toHaveLength(1)
  98. await ctx.fiber.dispose()
  99. })
  100. it('createAgent works without meta (no cwd)', async () => {
  101. const adapter = new MockAdapter([textResponse('hi')])
  102. const { ctx } = await persistentHarness(adapter)
  103. const { agent } = await ctx.agents.create({ sessionId: SessionId('nometa-session') })
  104. expect(agent.session.id).toBe('nometa-session')
  105. expect(agent.session.header.cwd).toBeUndefined()
  106. await ctx.fiber.dispose()
  107. })
  108. it('resume of a session with no cwd carries an undefined cwd header', async () => {
  109. // Lifecycle 1: create a no-cwd session and run a turn.
  110. const adapter1 = new MockAdapter([textResponse('a')])
  111. const { ctx: ctx1, root } = await persistentHarness(adapter1)
  112. const a1 = (await ctx1.agents.create({ sessionId: SessionId('nocwd-sess') })).agent
  113. a1.send([{ type: 'text', text: 'q' }], { source: { kind: 'user' } })
  114. await waitForIdle(ctx1, a1)
  115. await ctx1.fiber.dispose()
  116. // Lifecycle 2: resume it; the header cwd stays undefined (no-cwd branch).
  117. const adapter2 = new MockAdapter([textResponse('b')])
  118. const ctx2 = new Context()
  119. await ctx2.plugin(LlmService)
  120. await ctx2.plugin(SessionStore)
  121. await ctx2.plugin(SystemPrompt)
  122. await ctx2.plugin(ToolRegistry)
  123. await ctx2.plugin(AgentRegistry)
  124. await ctx2.plugin(AgentLoop, { agents: [] })
  125. await ctx2.plugin(SessionPersistenceJsonl, { root })
  126. ctx2.llm.registerAdapter(['mock'], adapter2)
  127. const a2 = (await ctx2.agents.resume({ resumeSessionId: SessionId('nocwd-sess') })).agent
  128. expect(a2.session.header.cwd).toBeUndefined()
  129. await ctx2.fiber.dispose()
  130. })
  131. it('agent/session-start fires "startup" for createAgent and "resume" for resume()', async () => {
  132. // Lifecycle 1: a fresh createAgent emits session-start with source 'startup'.
  133. const adapter1 = new MockAdapter([textResponse('a')])
  134. const { ctx: ctx1, root } = await persistentHarness(adapter1)
  135. const sources1: string[] = []
  136. ctx1.on('agent/session-start', (_agent, source) => void sources1.push(source))
  137. const a1 = (await ctx1.agents.create({ sessionId: SessionId('start-sess') })).agent
  138. expect(sources1).toEqual(['startup'])
  139. a1.send([{ type: 'text', text: 'q' }], { source: { kind: 'user' } })
  140. await waitForIdle(ctx1, a1)
  141. await ctx1.fiber.dispose()
  142. // Lifecycle 2: resuming the persisted session emits session-start 'resume'.
  143. const adapter2 = new MockAdapter([textResponse('b')])
  144. const ctx2 = new Context()
  145. await ctx2.plugin(LlmService)
  146. await ctx2.plugin(SessionStore)
  147. await ctx2.plugin(SystemPrompt)
  148. await ctx2.plugin(ToolRegistry)
  149. await ctx2.plugin(AgentRegistry)
  150. await ctx2.plugin(AgentLoop, { agents: [] })
  151. await ctx2.plugin(SessionPersistenceJsonl, { root })
  152. ctx2.llm.registerAdapter(['mock'], adapter2)
  153. const sources2: string[] = []
  154. ctx2.on('agent/session-start', (_agent, source) => void sources2.push(source))
  155. await ctx2.agents.resume({ resumeSessionId: SessionId('start-sess') })
  156. expect(sources2).toEqual(['resume'])
  157. await ctx2.fiber.dispose()
  158. })
  159. it('resume awaits setup while unpublished, then publishes a fully composed world in order', async () => {
  160. const sessionId = SessionId('resume-setup-success')
  161. const root = await persistSession(sessionId)
  162. const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
  163. const gate = Promise.withResolvers<undefined>()
  164. const setupStarted = Promise.withResolvers<undefined>()
  165. const order: string[] = []
  166. ctx.on('session/created', (session) => {
  167. expect(ctx.sessions.get(session.id)).toBe(session)
  168. expect(ctx.agents.get(sessionId)?.session).toBe(session)
  169. order.push('session/created')
  170. })
  171. ctx.on('agent/created', (agent) => {
  172. expect(agent.status).toBe('idle')
  173. order.push('agent/created')
  174. })
  175. ctx.on('agent/session-start', (agent) => {
  176. expect(() => { agent.cancel('now live') }).not.toThrow()
  177. order.push('agent/session-start')
  178. })
  179. const resuming = ctx.agents.resume({
  180. resumeSessionId: sessionId,
  181. agentOptions: { provider: 'mock', model: 'mock' },
  182. setup: async (agentCtx) => {
  183. expect(agentCtx.agent?.id).toBe(sessionId)
  184. expect(agentCtx.agent?.session.events).toHaveLength(2)
  185. agentCtx.on('session/created', () => void order.push('setup-listener:session/created'))
  186. agentCtx.on('agent/created', () => void order.push('setup-listener:agent/created'))
  187. order.push('setup:start')
  188. setupStarted.resolve(undefined)
  189. await gate.promise
  190. order.push('setup:end')
  191. },
  192. })
  193. await setupStarted.promise
  194. expect(ctx.agents.get(sessionId)).toBeUndefined()
  195. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  196. expect(order).toEqual(['setup:start'])
  197. gate.resolve(undefined)
  198. const handle = await resuming
  199. expect(order).toEqual([
  200. 'setup:start',
  201. 'setup:end',
  202. 'session/created',
  203. 'setup-listener:session/created',
  204. 'agent/created',
  205. 'setup-listener:agent/created',
  206. 'agent/session-start',
  207. ])
  208. await handle.dispose()
  209. await ctx.fiber.dispose()
  210. })
  211. it('successful resume disposal retires its caller-owned transaction effects', async () => {
  212. const sessionId = SessionId('resume-retired-effects-s')
  213. const root = await persistSession(sessionId)
  214. const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
  215. const handle = await ctx.agents.resume({
  216. resumeSessionId: sessionId,
  217. agentOptions: { provider: 'mock', model: 'mock' },
  218. })
  219. const transactionLabels = [
  220. `agentLoop.owner(${sessionId})`,
  221. `agentLoop.lifecycle(${sessionId})`,
  222. ]
  223. expect(ctx.fiber.getEffects().map(effect => effect.label)).toEqual(expect.arrayContaining(transactionLabels))
  224. await handle.dispose()
  225. expect(ctx.fiber.getEffects().filter(effect => transactionLabels.includes(effect.label))).toEqual([])
  226. await ctx.fiber.dispose()
  227. })
  228. it('resume setup rejection publishes nothing, unwinds, and releases the identity', async () => {
  229. const sessionId = SessionId('resume-setup-reject')
  230. const root = await persistSession(sessionId)
  231. const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
  232. const published: string[] = []
  233. ctx.on('session/created', () => void published.push('session/created'))
  234. ctx.on('agent/created', () => void published.push('agent/created'))
  235. ctx.on('agent/session-start', () => void published.push('agent/session-start'))
  236. await expect(ctx.agents.resume({
  237. resumeSessionId: sessionId,
  238. agentOptions: { provider: 'mock', model: 'mock' },
  239. setup: async () => {
  240. await Promise.resolve()
  241. throw new Error('resume setup failed')
  242. },
  243. })).rejects.toThrow('resume setup failed')
  244. expect(published).toEqual([])
  245. expect(ctx.agents.get(sessionId)).toBeUndefined()
  246. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  247. const retry = await ctx.agents.resume({
  248. resumeSessionId: sessionId,
  249. agentOptions: { provider: 'mock', model: 'mock' },
  250. })
  251. await retry.dispose()
  252. await ctx.fiber.dispose()
  253. })
  254. it('owner unload aborts resume setup and cannot publish after the callback settles', async () => {
  255. const sessionId = SessionId('resume-setup-owner-unload')
  256. const root = await persistSession(sessionId)
  257. const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
  258. const gate = Promise.withResolvers<undefined>()
  259. const setupStarted = Promise.withResolvers<undefined>()
  260. const published: string[] = []
  261. ctx.on('session/created', () => void published.push('session/created'))
  262. ctx.on('agent/created', () => void published.push('agent/created'))
  263. let resuming!: ReturnType<typeof ctx.agents.resume>
  264. const owner = await ctx.plugin(Object.assign((inner: Context) => {
  265. resuming = inner.agents.resume({
  266. resumeSessionId: sessionId,
  267. agentOptions: { provider: 'mock', model: 'mock' },
  268. setup: async () => {
  269. setupStarted.resolve(undefined)
  270. await gate.promise
  271. },
  272. })
  273. }, { inject: ['agents'] }))
  274. await setupStarted.promise
  275. await owner.dispose()
  276. await expect(resuming).rejects.toThrow(/owner disposed during setup/)
  277. expect(published).toEqual([])
  278. expect(ctx.agents.get(sessionId)).toBeUndefined()
  279. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  280. gate.resolve(undefined)
  281. await Promise.resolve()
  282. expect(published).toEqual([])
  283. await ctx.fiber.dispose()
  284. })
  285. it('owner unload aborts a never-settling persistence load, releases the identity, and blocks late publication', async () => {
  286. const sessionId = SessionId('resume-load-owner-unload')
  287. const root = await persistSession(sessionId)
  288. const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
  289. const snapshot = await ctx.sessionPersistence.load(sessionId)
  290. const lateLoad = Promise.withResolvers<typeof snapshot>()
  291. const loadStarted = Promise.withResolvers<undefined>()
  292. let loads = 0
  293. ctx.sessionPersistence.load = (id) => {
  294. expect(id).toBe(sessionId)
  295. loads += 1
  296. if (loads === 1) {
  297. loadStarted.resolve(undefined)
  298. return lateLoad.promise
  299. }
  300. return Promise.resolve(structuredClone(snapshot))
  301. }
  302. const published: string[] = []
  303. ctx.on('session/created', () => void published.push('session/created'))
  304. ctx.on('agent/created', () => void published.push('agent/created'))
  305. ctx.on('agent/session-start', () => void published.push('agent/session-start'))
  306. let resuming!: ReturnType<typeof ctx.agents.resume>
  307. const owner = await ctx.plugin(Object.assign((inner: Context) => {
  308. resuming = inner.agents.resume({ resumeSessionId: sessionId, agentOptions: { provider: 'mock', model: 'mock' } })
  309. }, { inject: ['agents'] }))
  310. await loadStarted.promise
  311. const rejection = expect(promptly(resuming)).rejects.toThrow(/owner disposed during setup/)
  312. await promptly(owner.dispose())
  313. expect(published).toEqual([])
  314. expect(ctx.agents.get(sessionId)).toBeUndefined()
  315. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  316. // owner.dispose() awaited transaction settlement, so the same identities
  317. // can be reused before awaiting the public rejection.
  318. const retry = await promptly(ctx.agents.resume({ resumeSessionId: sessionId, agentOptions: { provider: 'mock', model: 'mock' } }))
  319. await rejection
  320. expect(loads).toBe(2)
  321. expect(published).toEqual(['session/created', 'agent/created', 'agent/session-start'])
  322. // Settlement of the abandoned backend promise cannot resume the old
  323. // transaction or emit a second publication after the retry owns the ids.
  324. lateLoad.resolve(structuredClone(snapshot))
  325. await Promise.resolve()
  326. await Promise.resolve()
  327. expect(ctx.agents.get(sessionId)).toBe(retry.agent)
  328. expect(ctx.sessions.get(sessionId)).toBe(retry.agent.session)
  329. expect(published).toEqual(['session/created', 'agent/created', 'agent/session-start'])
  330. await retry.dispose()
  331. await ctx.fiber.dispose()
  332. })
  333. it('AgentLoop unload aborts persistence load and awaits wrapper settlement', async () => {
  334. const sessionId = SessionId('resume-load-factory-unload')
  335. const root = await persistSession(sessionId)
  336. const ctx = new Context()
  337. await ctx.plugin(LlmService)
  338. await ctx.plugin(SessionStore)
  339. await ctx.plugin(SystemPrompt)
  340. await ctx.plugin(ToolRegistry)
  341. await ctx.plugin(AgentRegistry)
  342. const loopFiber = await ctx.plugin(AgentLoop, { agents: [] })
  343. await ctx.plugin(SessionPersistenceJsonl, { root })
  344. ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('next')]))
  345. const snapshot = await ctx.sessionPersistence.load(sessionId)
  346. const lateLoad = Promise.withResolvers<typeof snapshot>()
  347. const loadStarted = Promise.withResolvers<undefined>()
  348. ctx.sessionPersistence.load = (id) => {
  349. expect(id).toBe(sessionId)
  350. loadStarted.resolve(undefined)
  351. return lateLoad.promise
  352. }
  353. const published: string[] = []
  354. ctx.on('session/created', () => void published.push('session/created'))
  355. ctx.on('agent/created', () => void published.push('agent/created'))
  356. const resuming = ctx.agents.resume({ resumeSessionId: sessionId, agentOptions: { provider: 'mock', model: 'mock' } })
  357. await loadStarted.promise
  358. const rejection = expect(promptly(resuming)).rejects.toThrow(/agent loop is not active/)
  359. await promptly(loopFiber.dispose())
  360. await rejection
  361. expect(published).toEqual([])
  362. expect(ctx.agents.get(sessionId)).toBeUndefined()
  363. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  364. lateLoad.resolve(structuredClone(snapshot))
  365. await Promise.resolve()
  366. await Promise.resolve()
  367. expect(published).toEqual([])
  368. await ctx.fiber.dispose()
  369. })
  370. it('resume of a forked session preserves the lineage, seed boundary, and delegation depth in the header', async () => {
  371. // Lifecycle 1: persist a FORKED session (carries parentSession + seedLength
  372. // in its header) by creating it with a complete-turn seed — the write path
  373. // materializes the fork (header + seed) on disk.
  374. const seed: SessionEvent[] = [
  375. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  376. { type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'completed' } } },
  377. ]
  378. const adapter1 = new MockAdapter([textResponse('a')])
  379. const { ctx: ctx1, root } = await persistentHarness(adapter1)
  380. const forked = ctx1.sessions.create(SessionId('forked-sess'), {
  381. seed,
  382. meta: { cwd: '/w', parentSession: SessionId('parent-sess'), seedLength: seed.length, delegationDepth: 1 },
  383. })
  384. await ctx1.parallel('session/flush', forked)
  385. await ctx1.fiber.dispose()
  386. // Lifecycle 2: resume it; the parentSession + seedLength header survives the
  387. // round-trip (exercises resume's parentSession- and seedLength-present
  388. // branches). seedLength must come from the PERSISTED header, not from the
  389. // resume seed length (which is the whole stored log, not the original
  390. // boundary).
  391. const adapter2 = new MockAdapter([textResponse('b')])
  392. const ctx2 = new Context()
  393. await ctx2.plugin(LlmService)
  394. await ctx2.plugin(SessionStore)
  395. await ctx2.plugin(SystemPrompt)
  396. await ctx2.plugin(ToolRegistry)
  397. await ctx2.plugin(AgentRegistry)
  398. await ctx2.plugin(AgentLoop, { agents: [] })
  399. await ctx2.plugin(SessionPersistenceJsonl, { root })
  400. ctx2.llm.registerAdapter(['mock'], adapter2)
  401. const a2 = (await ctx2.agents.resume({ resumeSessionId: SessionId('forked-sess') })).agent
  402. expect(a2.session.header.parentSession).toBe('parent-sess')
  403. expect(a2.session.header.cwd).toBe('/w')
  404. expect(a2.session.header.seedLength).toBe(seed.length)
  405. // The recursion budget survives resume — a dropped depth would let a
  406. // resumed child delegate as if it were top-level.
  407. expect(a2.session.header.delegationDepth).toBe(1)
  408. await ctx2.fiber.dispose()
  409. })
  410. it('an idle inject() is flushed durably on its own (survives without explicit flush/dispose)', async () => {
  411. // Idle injection creates and flushes a one-shot turn. No explicit flush or
  412. // clean disposal follows, so disk presence proves its own checkpoint ran.
  413. const adapter1 = new MockAdapter([textResponse('answer')])
  414. const { ctx: ctx1, root } = await persistentHarness(adapter1)
  415. const a1 = (await ctx1.agents.create({ sessionId: SessionId('inject-sess'), meta: { cwd: '/w' } })).agent
  416. a1.send([{ type: 'text', text: 'q' }], { source: { kind: 'user' } })
  417. await waitForIdle(ctx1, a1)
  418. a1.inject([{ type: 'text', text: 'background task 42 finished' }], { source: { kind: 'plugin', plugin: 'tool-bash' } })
  419. // Let inject()'s fire-and-forget flush settle (NO explicit flush/dispose).
  420. await new Promise(r => setTimeout(r, 30))
  421. // A SEPARATE backend reads the on-disk log — proving the inject persisted
  422. // itself, not a later dispose drain.
  423. const probe = new Context()
  424. await probe.plugin(SessionStore)
  425. await probe.plugin(SessionPersistenceJsonl, { root })
  426. const loaded = await probe.sessionPersistence.load(SessionId('inject-sess'))
  427. expect(JSON.stringify(loaded.events)).toContain('background task 42 finished')
  428. await probe.fiber.dispose()
  429. await ctx1.fiber.dispose()
  430. })
  431. it('an idle inject() survives persist + resume (turn-enclosed, not dropped as crash tail)', async () => {
  432. // Turn enclosure keeps idle context out of crash-tail repair, so it must
  433. // survive persistence and resume.
  434. const adapter1 = new MockAdapter([textResponse('answer')])
  435. const { ctx: ctx1, root } = await persistentHarness(adapter1)
  436. const a1 = (await ctx1.agents.create({ sessionId: SessionId('inject-sess'), meta: { cwd: '/w' } })).agent
  437. a1.send([{ type: 'text', text: 'q' }], { source: { kind: 'user' } })
  438. await waitForIdle(ctx1, a1)
  439. a1.inject([{ type: 'text', text: 'background task 42 finished' }], { source: { kind: 'plugin', plugin: 'tool-bash' } })
  440. await ctx1.parallel('session/flush', a1.session)
  441. await ctx1.fiber.dispose()
  442. // Lifecycle 2: resume; the injected context is still in the derived history.
  443. const adapter2 = new MockAdapter([textResponse('next')])
  444. const ctx2 = new Context()
  445. await ctx2.plugin(LlmService)
  446. await ctx2.plugin(SessionStore)
  447. await ctx2.plugin(SystemPrompt)
  448. await ctx2.plugin(ToolRegistry)
  449. await ctx2.plugin(AgentRegistry)
  450. await ctx2.plugin(AgentLoop, { agents: [] })
  451. await ctx2.plugin(SessionPersistenceJsonl, { root })
  452. ctx2.llm.registerAdapter(['mock'], adapter2)
  453. const a2 = (await ctx2.agents.resume({ resumeSessionId: SessionId('inject-sess') })).agent
  454. const flat = JSON.stringify(a2.session.deriveMessages())
  455. expect(flat).toContain('background task 42 finished')
  456. await ctx2.fiber.dispose()
  457. })
  458. it('resume reloads a persisted session: history + turn numbering continue, no duplicate seqs', async () => {
  459. // Lifecycle 1: run one full turn, persisting it.
  460. const adapter1 = new MockAdapter([textResponse('first answer')])
  461. const { ctx: ctx1, root } = await persistentHarness(adapter1)
  462. const a1 = (await ctx1.agents.create({ sessionId: SessionId('sess-resume'), meta: { cwd: '/w' } })).agent
  463. a1.send([{ type: 'text', text: 'first question' }], { source: { kind: 'user' } })
  464. await waitForIdle(ctx1, a1)
  465. const events1 = [...a1.session.events]
  466. const seqs1 = events1.map(e => e.seq)
  467. expect(seqs1).toEqual([...seqs1].sort((x, y) => x - y)) // contiguous
  468. await ctx1.fiber.dispose()
  469. // Lifecycle 2: a brand-new context over the SAME root; resume the session.
  470. const adapter2 = new MockAdapter([textResponse('second answer')])
  471. const ctx2 = new Context()
  472. await ctx2.plugin(LlmService)
  473. await ctx2.plugin(SessionStore)
  474. await ctx2.plugin(SystemPrompt)
  475. await ctx2.plugin(ToolRegistry)
  476. await ctx2.plugin(AgentRegistry)
  477. await ctx2.plugin(AgentLoop, { agents: [] })
  478. await ctx2.plugin(SessionPersistenceJsonl, { root })
  479. ctx2.llm.registerAdapter(['mock'], adapter2)
  480. const a2 = (await ctx2.agents.resume({ resumeSessionId: SessionId('sess-resume') })).agent
  481. // The resumed session carries the prior history…
  482. expect(a2.session.id).toBe('sess-resume')
  483. expect(a2.session.events.length).toBe(events1.length)
  484. const replay = new Session(SessionId('replay'), events1)
  485. expect(a2.session.deriveMessages()).toEqual(replay.deriveMessages())
  486. // …and a new turn continues numbering (turn 2) with contiguous seqs.
  487. a2.send([{ type: 'text', text: 'second question' }], { source: { kind: 'user' } })
  488. await waitForIdle(ctx2, a2)
  489. const allSeqs = a2.session.events.map(e => e.seq)
  490. expect(allSeqs).toEqual(allSeqs.map((_, i) => i)) // 0..N contiguous, no duplicates
  491. const turnStarts = a2.session.events.filter(e => e.type === 'turn/start')
  492. expect(turnStarts.map(e => e.type === 'turn/start' && e.data.turn)).toEqual([1, 2])
  493. await ctx2.fiber.dispose()
  494. })
  495. it('resume rejects when session persistence is not configured', async () => {
  496. // A harness WITHOUT the persistence plugin.
  497. const adapter = new MockAdapter([textResponse('x')])
  498. const ctx = new Context()
  499. await ctx.plugin(LlmService)
  500. await ctx.plugin(SessionStore)
  501. await ctx.plugin(SystemPrompt)
  502. await ctx.plugin(ToolRegistry)
  503. await ctx.plugin(AgentRegistry)
  504. await ctx.plugin(AgentLoop, { agents: [] })
  505. ctx.llm.registerAdapter(['mock'], adapter)
  506. await expect(ctx.agents.resume({ resumeSessionId: SessionId('nope') }))
  507. .rejects.toThrow(/session persistence is not configured/)
  508. await ctx.fiber.dispose()
  509. })
  510. })