resume.spec.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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('resume cannot crash-repair a turn owned by a live agent', async () => {
  101. const { ctx } = await persistentHarness(new MockAdapter([textResponse('unused')]))
  102. const sessionId = SessionId('live-resume-race')
  103. const first = (await ctx.agents.create({ sessionId })).agent
  104. first.session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  105. await ctx.sessions.flush(first.session)
  106. await expect(ctx.agents.resume({ resumeSessionId: sessionId }))
  107. .rejects.toThrow(/live turn is open/)
  108. first.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  109. await ctx.sessions.flush(first.session)
  110. const loaded = await ctx.sessionPersistence.load(sessionId)
  111. expect(loaded.events.map(event => event.type)).toEqual(['turn/start', 'turn/end'])
  112. expect(loaded.events.at(-1)).toMatchObject({
  113. type: 'turn/end',
  114. data: { reason: { kind: 'completed' } },
  115. })
  116. await ctx.fiber.dispose()
  117. })
  118. it('createAgent works without meta (no cwd)', async () => {
  119. const adapter = new MockAdapter([textResponse('hi')])
  120. const { ctx } = await persistentHarness(adapter)
  121. const { agent } = await ctx.agents.create({ sessionId: SessionId('nometa-session') })
  122. expect(agent.session.id).toBe('nometa-session')
  123. expect(agent.session.header.cwd).toBeUndefined()
  124. await ctx.fiber.dispose()
  125. })
  126. it('resume of a session with no cwd carries an undefined cwd header', async () => {
  127. // Lifecycle 1: create a no-cwd session and run a turn.
  128. const adapter1 = new MockAdapter([textResponse('a')])
  129. const { ctx: ctx1, root } = await persistentHarness(adapter1)
  130. const a1 = (await ctx1.agents.create({ sessionId: SessionId('nocwd-sess') })).agent
  131. a1.followup([{ type: 'text', text: 'q' }], { source: { kind: 'user' } })
  132. await waitForIdle(ctx1, a1)
  133. await ctx1.fiber.dispose()
  134. // Lifecycle 2: resume it; the header cwd stays undefined (no-cwd branch).
  135. const adapter2 = new MockAdapter([textResponse('b')])
  136. const ctx2 = new Context()
  137. await ctx2.plugin(LlmService)
  138. await ctx2.plugin(SessionStore)
  139. await ctx2.plugin(SystemPrompt)
  140. await ctx2.plugin(ToolRegistry)
  141. await ctx2.plugin(AgentRegistry)
  142. await ctx2.plugin(AgentLoop, { agents: [] })
  143. await ctx2.plugin(SessionPersistenceJsonl, { root })
  144. ctx2.llm.registerAdapter(['mock'], adapter2)
  145. const a2 = (await ctx2.agents.resume({ resumeSessionId: SessionId('nocwd-sess') })).agent
  146. expect(a2.session.header.cwd).toBeUndefined()
  147. await ctx2.fiber.dispose()
  148. })
  149. it('agent/session-start fires "startup" for createAgent and "resume" for resume()', async () => {
  150. // Lifecycle 1: a fresh createAgent emits session-start with source 'startup'.
  151. const adapter1 = new MockAdapter([textResponse('a')])
  152. const { ctx: ctx1, root } = await persistentHarness(adapter1)
  153. const sources1: string[] = []
  154. ctx1.on('agent/session-start', (_agent, source) => void sources1.push(source))
  155. const a1 = (await ctx1.agents.create({ sessionId: SessionId('start-sess') })).agent
  156. expect(sources1).toEqual(['startup'])
  157. a1.followup([{ type: 'text', text: 'q' }], { source: { kind: 'user' } })
  158. await waitForIdle(ctx1, a1)
  159. await ctx1.fiber.dispose()
  160. // Lifecycle 2: resuming the persisted session emits session-start 'resume'.
  161. const adapter2 = new MockAdapter([textResponse('b')])
  162. const ctx2 = new Context()
  163. await ctx2.plugin(LlmService)
  164. await ctx2.plugin(SessionStore)
  165. await ctx2.plugin(SystemPrompt)
  166. await ctx2.plugin(ToolRegistry)
  167. await ctx2.plugin(AgentRegistry)
  168. await ctx2.plugin(AgentLoop, { agents: [] })
  169. await ctx2.plugin(SessionPersistenceJsonl, { root })
  170. ctx2.llm.registerAdapter(['mock'], adapter2)
  171. const sources2: string[] = []
  172. ctx2.on('agent/session-start', (_agent, source) => void sources2.push(source))
  173. await ctx2.agents.resume({ resumeSessionId: SessionId('start-sess') })
  174. expect(sources2).toEqual(['resume'])
  175. await ctx2.fiber.dispose()
  176. })
  177. it('resume awaits setup while unpublished, then publishes a fully composed world in order', async () => {
  178. const sessionId = SessionId('resume-setup-success')
  179. const root = await persistSession(sessionId)
  180. const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
  181. const gate = Promise.withResolvers<undefined>()
  182. const setupStarted = Promise.withResolvers<undefined>()
  183. const order: string[] = []
  184. ctx.on('session/created', (session) => {
  185. expect(ctx.sessions.get(session.id)).toBe(session)
  186. expect(ctx.agents.get(sessionId)?.session).toBe(session)
  187. order.push('session/created')
  188. })
  189. ctx.on('agent/created', (agent) => {
  190. expect(agent.status).toBe('idle')
  191. order.push('agent/created')
  192. })
  193. ctx.on('agent/session-start', (agent) => {
  194. expect(() => { agent.cancel({ kind: 'user' }) }).not.toThrow()
  195. order.push('agent/session-start')
  196. })
  197. const resuming = ctx.agents.resume({
  198. resumeSessionId: sessionId,
  199. agentOptions: { provider: 'mock', model: 'mock' },
  200. setup: async (agentCtx) => {
  201. expect(agentCtx.agent?.id).toBe(sessionId)
  202. expect(agentCtx.agent?.session.events).toHaveLength(2)
  203. agentCtx.on('session/created', () => void order.push('setup-listener:session/created'))
  204. agentCtx.on('agent/created', () => void order.push('setup-listener:agent/created'))
  205. order.push('setup:start')
  206. setupStarted.resolve(undefined)
  207. await gate.promise
  208. order.push('setup:end')
  209. },
  210. })
  211. await setupStarted.promise
  212. expect(ctx.agents.get(sessionId)).toBeUndefined()
  213. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  214. expect(order).toEqual(['setup:start'])
  215. gate.resolve(undefined)
  216. const handle = await resuming
  217. expect(order).toEqual([
  218. 'setup:start',
  219. 'setup:end',
  220. 'session/created',
  221. 'setup-listener:session/created',
  222. 'agent/created',
  223. 'setup-listener:agent/created',
  224. 'agent/session-start',
  225. ])
  226. await handle.dispose()
  227. await ctx.fiber.dispose()
  228. })
  229. it('successful resume disposal retires its caller-owned transaction effects', async () => {
  230. const sessionId = SessionId('resume-retired-effects-s')
  231. const root = await persistSession(sessionId)
  232. const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
  233. const handle = await ctx.agents.resume({
  234. resumeSessionId: sessionId,
  235. agentOptions: { provider: 'mock', model: 'mock' },
  236. })
  237. const transactionLabels = [
  238. `agentLoop.owner(${sessionId})`,
  239. `agentLoop.lifecycle(${sessionId})`,
  240. ]
  241. expect(ctx.fiber.getEffects().map(effect => effect.label)).toEqual(expect.arrayContaining(transactionLabels))
  242. await handle.dispose()
  243. expect(ctx.fiber.getEffects().filter(effect => transactionLabels.includes(effect.label))).toEqual([])
  244. await ctx.fiber.dispose()
  245. })
  246. it('resume setup rejection publishes nothing, unwinds, and releases the identity', async () => {
  247. const sessionId = SessionId('resume-setup-reject')
  248. const root = await persistSession(sessionId)
  249. const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
  250. const published: string[] = []
  251. ctx.on('session/created', () => void published.push('session/created'))
  252. ctx.on('agent/created', () => void published.push('agent/created'))
  253. ctx.on('agent/session-start', () => void published.push('agent/session-start'))
  254. await expect(ctx.agents.resume({
  255. resumeSessionId: sessionId,
  256. agentOptions: { provider: 'mock', model: 'mock' },
  257. setup: async () => {
  258. await Promise.resolve()
  259. throw new Error('resume setup failed')
  260. },
  261. })).rejects.toThrow('resume setup failed')
  262. expect(published).toEqual([])
  263. expect(ctx.agents.get(sessionId)).toBeUndefined()
  264. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  265. const retry = await ctx.agents.resume({
  266. resumeSessionId: sessionId,
  267. agentOptions: { provider: 'mock', model: 'mock' },
  268. })
  269. await retry.dispose()
  270. await ctx.fiber.dispose()
  271. })
  272. it('owner unload aborts resume setup and cannot publish after the callback settles', async () => {
  273. const sessionId = SessionId('resume-setup-owner-unload')
  274. const root = await persistSession(sessionId)
  275. const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
  276. const gate = Promise.withResolvers<undefined>()
  277. const setupStarted = Promise.withResolvers<undefined>()
  278. const published: string[] = []
  279. ctx.on('session/created', () => void published.push('session/created'))
  280. ctx.on('agent/created', () => void published.push('agent/created'))
  281. let resuming!: ReturnType<typeof ctx.agents.resume>
  282. const owner = await ctx.plugin(Object.assign((inner: Context) => {
  283. resuming = inner.agents.resume({
  284. resumeSessionId: sessionId,
  285. agentOptions: { provider: 'mock', model: 'mock' },
  286. setup: async () => {
  287. setupStarted.resolve(undefined)
  288. await gate.promise
  289. },
  290. })
  291. }, { inject: ['agents'] }))
  292. await setupStarted.promise
  293. await owner.dispose()
  294. await expect(resuming).rejects.toThrow(/owner disposed during setup/)
  295. expect(published).toEqual([])
  296. expect(ctx.agents.get(sessionId)).toBeUndefined()
  297. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  298. gate.resolve(undefined)
  299. await Promise.resolve()
  300. expect(published).toEqual([])
  301. await ctx.fiber.dispose()
  302. })
  303. it('owner unload aborts a never-settling persistence load, releases the identity, and blocks late publication', async () => {
  304. const sessionId = SessionId('resume-load-owner-unload')
  305. const root = await persistSession(sessionId)
  306. const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
  307. const snapshot = await ctx.sessionPersistence.load(sessionId)
  308. const lateLoad = Promise.withResolvers<typeof snapshot>()
  309. const loadStarted = Promise.withResolvers<undefined>()
  310. let loads = 0
  311. ctx.sessionPersistence.load = (id) => {
  312. expect(id).toBe(sessionId)
  313. loads += 1
  314. if (loads === 1) {
  315. loadStarted.resolve(undefined)
  316. return lateLoad.promise
  317. }
  318. return Promise.resolve(structuredClone(snapshot))
  319. }
  320. const published: string[] = []
  321. ctx.on('session/created', () => void published.push('session/created'))
  322. ctx.on('agent/created', () => void published.push('agent/created'))
  323. ctx.on('agent/session-start', () => void published.push('agent/session-start'))
  324. let resuming!: ReturnType<typeof ctx.agents.resume>
  325. const owner = await ctx.plugin(Object.assign((inner: Context) => {
  326. resuming = inner.agents.resume({ resumeSessionId: sessionId, agentOptions: { provider: 'mock', model: 'mock' } })
  327. }, { inject: ['agents'] }))
  328. await loadStarted.promise
  329. const rejection = expect(promptly(resuming)).rejects.toThrow(/owner disposed during setup/)
  330. await promptly(owner.dispose())
  331. expect(published).toEqual([])
  332. expect(ctx.agents.get(sessionId)).toBeUndefined()
  333. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  334. // owner.dispose() awaited transaction settlement, so the same identities
  335. // can be reused before awaiting the public rejection.
  336. const retry = await promptly(ctx.agents.resume({ resumeSessionId: sessionId, agentOptions: { provider: 'mock', model: 'mock' } }))
  337. await rejection
  338. expect(loads).toBe(2)
  339. expect(published).toEqual(['session/created', 'agent/created', 'agent/session-start'])
  340. // Settlement of the abandoned backend promise cannot resume the old
  341. // transaction or emit a second publication after the retry owns the ids.
  342. lateLoad.resolve(structuredClone(snapshot))
  343. await Promise.resolve()
  344. await Promise.resolve()
  345. expect(ctx.agents.get(sessionId)).toBe(retry.agent)
  346. expect(ctx.sessions.get(sessionId)).toBe(retry.agent.session)
  347. expect(published).toEqual(['session/created', 'agent/created', 'agent/session-start'])
  348. await retry.dispose()
  349. await ctx.fiber.dispose()
  350. })
  351. it('AgentLoop unload aborts persistence load and awaits wrapper settlement', async () => {
  352. const sessionId = SessionId('resume-load-factory-unload')
  353. const root = await persistSession(sessionId)
  354. const ctx = new Context()
  355. await ctx.plugin(LlmService)
  356. await ctx.plugin(SessionStore)
  357. await ctx.plugin(SystemPrompt)
  358. await ctx.plugin(ToolRegistry)
  359. await ctx.plugin(AgentRegistry)
  360. const loopFiber = await ctx.plugin(AgentLoop, { agents: [] })
  361. await ctx.plugin(SessionPersistenceJsonl, { root })
  362. ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('next')]))
  363. const snapshot = await ctx.sessionPersistence.load(sessionId)
  364. const lateLoad = Promise.withResolvers<typeof snapshot>()
  365. const loadStarted = Promise.withResolvers<undefined>()
  366. ctx.sessionPersistence.load = (id) => {
  367. expect(id).toBe(sessionId)
  368. loadStarted.resolve(undefined)
  369. return lateLoad.promise
  370. }
  371. const published: string[] = []
  372. ctx.on('session/created', () => void published.push('session/created'))
  373. ctx.on('agent/created', () => void published.push('agent/created'))
  374. const resuming = ctx.agents.resume({ resumeSessionId: sessionId, agentOptions: { provider: 'mock', model: 'mock' } })
  375. await loadStarted.promise
  376. const rejection = expect(promptly(resuming)).rejects.toThrow(/agent loop is not active/)
  377. await promptly(loopFiber.dispose())
  378. await rejection
  379. expect(published).toEqual([])
  380. expect(ctx.agents.get(sessionId)).toBeUndefined()
  381. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  382. lateLoad.resolve(structuredClone(snapshot))
  383. await Promise.resolve()
  384. await Promise.resolve()
  385. expect(published).toEqual([])
  386. await ctx.fiber.dispose()
  387. })
  388. it('resume of a forked session preserves the lineage, seed boundary, and delegation depth in the header', async () => {
  389. // Lifecycle 1: persist a FORKED session (carries parentSession + seedLength
  390. // in its header) by creating it with a complete-turn seed — the write path
  391. // materializes the fork (header + seed) on disk.
  392. const seed: SessionEvent[] = [
  393. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  394. { type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'completed' } } },
  395. ]
  396. const adapter1 = new MockAdapter([textResponse('a')])
  397. const { ctx: ctx1, root } = await persistentHarness(adapter1)
  398. const forked = ctx1.sessions.create(SessionId('forked-sess'), {
  399. seed,
  400. meta: { cwd: '/w', parentSession: SessionId('parent-sess'), seedLength: seed.length, delegationDepth: 1 },
  401. })
  402. await ctx1.sessions.flush(forked)
  403. await ctx1.fiber.dispose()
  404. // Lifecycle 2: resume it; the parentSession + seedLength header survives the
  405. // round-trip (exercises resume's parentSession- and seedLength-present
  406. // branches). seedLength must come from the PERSISTED header, not from the
  407. // resume seed length (which is the whole stored log, not the original
  408. // boundary).
  409. const adapter2 = new MockAdapter([textResponse('b')])
  410. const ctx2 = new Context()
  411. await ctx2.plugin(LlmService)
  412. await ctx2.plugin(SessionStore)
  413. await ctx2.plugin(SystemPrompt)
  414. await ctx2.plugin(ToolRegistry)
  415. await ctx2.plugin(AgentRegistry)
  416. await ctx2.plugin(AgentLoop, { agents: [] })
  417. await ctx2.plugin(SessionPersistenceJsonl, { root })
  418. ctx2.llm.registerAdapter(['mock'], adapter2)
  419. const a2 = (await ctx2.agents.resume({ resumeSessionId: SessionId('forked-sess') })).agent
  420. expect(a2.session.header.parentSession).toBe('parent-sess')
  421. expect(a2.session.header.cwd).toBe('/w')
  422. expect(a2.session.header.seedLength).toBe(seed.length)
  423. // The recursion budget survives resume — a dropped depth would let a
  424. // resumed child delegate as if it were top-level.
  425. expect(a2.session.header.delegationDepth).toBe(1)
  426. await ctx2.fiber.dispose()
  427. })
  428. it('an idle inject() is flushed durably on its own (survives without explicit flush/dispose)', async () => {
  429. // Idle injection creates and flushes a one-shot turn. No explicit flush or
  430. // clean disposal follows, so disk presence proves its own checkpoint ran.
  431. const adapter1 = new MockAdapter([textResponse('answer')])
  432. const { ctx: ctx1, root } = await persistentHarness(adapter1)
  433. const a1 = (await ctx1.agents.create({ sessionId: SessionId('inject-sess'), meta: { cwd: '/w' } })).agent
  434. a1.followup([{ type: 'text', text: 'q' }], { source: { kind: 'user' } })
  435. await waitForIdle(ctx1, a1)
  436. a1.inject([{ type: 'text', text: 'background task 42 finished' }], { source: { kind: 'plugin', plugin: 'tool-bash' } })
  437. // Let inject()'s fire-and-forget flush settle (NO explicit flush/dispose).
  438. await new Promise(r => setTimeout(r, 30))
  439. // A SEPARATE backend reads the on-disk log — proving the inject persisted
  440. // itself, not a later dispose drain.
  441. const probe = new Context()
  442. await probe.plugin(SessionStore)
  443. await probe.plugin(SessionPersistenceJsonl, { root })
  444. const loaded = await probe.sessionPersistence.load(SessionId('inject-sess'))
  445. expect(JSON.stringify(loaded.events)).toContain('background task 42 finished')
  446. await probe.fiber.dispose()
  447. await ctx1.fiber.dispose()
  448. })
  449. it('an idle inject() survives persist + resume (turn-enclosed, not dropped as crash tail)', async () => {
  450. // Turn enclosure keeps idle context out of crash-tail repair, so it must
  451. // survive persistence and resume.
  452. const adapter1 = new MockAdapter([textResponse('answer')])
  453. const { ctx: ctx1, root } = await persistentHarness(adapter1)
  454. const a1 = (await ctx1.agents.create({ sessionId: SessionId('inject-sess'), meta: { cwd: '/w' } })).agent
  455. a1.followup([{ type: 'text', text: 'q' }], { source: { kind: 'user' } })
  456. await waitForIdle(ctx1, a1)
  457. a1.inject([{ type: 'text', text: 'background task 42 finished' }], { source: { kind: 'plugin', plugin: 'tool-bash' } })
  458. await ctx1.sessions.flush(a1.session)
  459. await ctx1.fiber.dispose()
  460. // Lifecycle 2: resume; the injected context is still in the derived history.
  461. const adapter2 = new MockAdapter([textResponse('next')])
  462. const ctx2 = new Context()
  463. await ctx2.plugin(LlmService)
  464. await ctx2.plugin(SessionStore)
  465. await ctx2.plugin(SystemPrompt)
  466. await ctx2.plugin(ToolRegistry)
  467. await ctx2.plugin(AgentRegistry)
  468. await ctx2.plugin(AgentLoop, { agents: [] })
  469. await ctx2.plugin(SessionPersistenceJsonl, { root })
  470. ctx2.llm.registerAdapter(['mock'], adapter2)
  471. const a2 = (await ctx2.agents.resume({ resumeSessionId: SessionId('inject-sess') })).agent
  472. const flat = JSON.stringify(a2.session.deriveMessages())
  473. expect(flat).toContain('background task 42 finished')
  474. await ctx2.fiber.dispose()
  475. })
  476. it('resume reloads a persisted session: history + turn numbering continue, no duplicate seqs', async () => {
  477. // Lifecycle 1: run one full turn, persisting it.
  478. const adapter1 = new MockAdapter([textResponse('first answer')])
  479. const { ctx: ctx1, root } = await persistentHarness(adapter1)
  480. const a1 = (await ctx1.agents.create({ sessionId: SessionId('sess-resume'), meta: { cwd: '/w' } })).agent
  481. a1.followup([{ type: 'text', text: 'first question' }], { source: { kind: 'user' } })
  482. await waitForIdle(ctx1, a1)
  483. const events1 = [...a1.session.events]
  484. const seqs1 = events1.map(e => e.seq)
  485. expect(seqs1).toEqual([...seqs1].sort((x, y) => x - y)) // contiguous
  486. await ctx1.fiber.dispose()
  487. // Lifecycle 2: a brand-new context over the SAME root; resume the session.
  488. const adapter2 = new MockAdapter([textResponse('second answer')])
  489. const ctx2 = new Context()
  490. await ctx2.plugin(LlmService)
  491. await ctx2.plugin(SessionStore)
  492. await ctx2.plugin(SystemPrompt)
  493. await ctx2.plugin(ToolRegistry)
  494. await ctx2.plugin(AgentRegistry)
  495. await ctx2.plugin(AgentLoop, { agents: [] })
  496. await ctx2.plugin(SessionPersistenceJsonl, { root })
  497. ctx2.llm.registerAdapter(['mock'], adapter2)
  498. const a2 = (await ctx2.agents.resume({ resumeSessionId: SessionId('sess-resume') })).agent
  499. // The resumed session carries the prior history…
  500. expect(a2.session.id).toBe('sess-resume')
  501. expect(a2.session.events.length).toBe(events1.length)
  502. const replay = new Session(SessionId('replay'), events1)
  503. expect(a2.session.deriveMessages()).toEqual(replay.deriveMessages())
  504. // …and a new turn continues numbering (turn 2) with contiguous seqs.
  505. a2.followup([{ type: 'text', text: 'second question' }], { source: { kind: 'user' } })
  506. await waitForIdle(ctx2, a2)
  507. const allSeqs = a2.session.events.map(e => e.seq)
  508. expect(allSeqs).toEqual(allSeqs.map((_, i) => i)) // 0..N contiguous, no duplicates
  509. const turnStarts = a2.session.events.filter(e => e.type === 'turn/start')
  510. expect(turnStarts.map(e => e.type === 'turn/start' && e.data.turn)).toEqual([1, 2])
  511. await ctx2.fiber.dispose()
  512. })
  513. it('resume rejects when session persistence is not configured', async () => {
  514. // A harness WITHOUT the persistence plugin.
  515. const adapter = new MockAdapter([textResponse('x')])
  516. const ctx = new Context()
  517. await ctx.plugin(LlmService)
  518. await ctx.plugin(SessionStore)
  519. await ctx.plugin(SystemPrompt)
  520. await ctx.plugin(ToolRegistry)
  521. await ctx.plugin(AgentRegistry)
  522. await ctx.plugin(AgentLoop, { agents: [] })
  523. ctx.llm.registerAdapter(['mock'], adapter)
  524. await expect(ctx.agents.resume({ resumeSessionId: SessionId('nope') }))
  525. .rejects.toThrow(/session persistence is not configured/)
  526. await ctx.fiber.dispose()
  527. })
  528. })