config-session-id.spec.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  2. import { afterEach, describe, expect, it, vi } from 'vitest'
  3. import { Context } from '@deepseek-ai/cordis'
  4. import { mkdtemp, rm } from 'node:fs/promises'
  5. import { tmpdir } from 'node:os'
  6. import { join } from 'node:path'
  7. import LlmRuntime from '@deepseek-ai/dsh-llm'
  8. import SessionStore, { 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 ToolRuntime from '@deepseek-ai/dsh-tools'
  12. import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
  13. import type { SessionHandle } from '@deepseek-ai/dsh-session-persistence'
  14. import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
  15. import AgentLoop, { CONFIGURED_AGENT_IDENTITIES_KEY } from '@deepseek-ai/dsh-agent-loop'
  16. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  17. import { MockAdapter, textResponse } from './mock-adapter.ts'
  18. const dirs: string[] = []
  19. afterEach(async () => { for (const d of dirs.splice(0)) await rm(d, { recursive: true, force: true }) })
  20. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  21. return new Promise((resolve) => {
  22. const dispose = ctx.on('agent/status', ({ agent: subject, status }) => {
  23. if (subject === agent && status === 'idle') { dispose(); resolve() }
  24. })
  25. })
  26. }
  27. async function makeCoreContext(): Promise<Context> {
  28. const ctx = new Context()
  29. await ctx.plugin(LlmRuntime)
  30. await ctx.plugin(SessionStore)
  31. await ctx.plugin(SessionProjectionRegistry)
  32. await ctx.plugin(SystemPrompt)
  33. await ctx.plugin(ToolRuntime)
  34. await ctx.plugin(AgentRegistry)
  35. return ctx
  36. }
  37. /** Read one stored session's physical validated log through a read handle. */
  38. async function readStoredEvents(ctx: Context, sessionId: SessionId): Promise<readonly SessionEvent[]> {
  39. const handle = await ctx.sessionPersistence.open(sessionId, 'read')
  40. try {
  41. return (await handle.read()).events
  42. } finally {
  43. await handle.close()
  44. }
  45. }
  46. describe('config-driven session id', () => {
  47. it('applies launcher identities by configured id without changing unmatched entries', async () => {
  48. const ctx = await makeCoreContext()
  49. ctx.provide(CONFIGURED_AGENT_IDENTITIES_KEY, {
  50. fresh: { id: SessionId('launcher-fresh'), resume: false },
  51. resumed: { id: SessionId('launcher-resumed'), resume: true },
  52. })
  53. await ctx.plugin(AgentLoop, {
  54. agents: [
  55. { id: 'fresh', sessionId: SessionId('config-fresh'), model: 'mock' },
  56. { id: 'resumed', sessionId: SessionId('config-resumed'), model: 'mock' },
  57. { id: 'unchanged', sessionId: SessionId('config-unchanged'), model: 'mock' },
  58. ],
  59. })
  60. await expect.poll(() => ctx.agents.get(SessionId('launcher-fresh'))).toBeDefined()
  61. expect(ctx.agents.get(SessionId('launcher-fresh'))?.session.id).toBe('launcher-fresh')
  62. expect(ctx.agents.get(SessionId('launcher-resumed'))).toBeUndefined()
  63. expect(ctx.agents.get(SessionId('config-resumed'))).toBeUndefined()
  64. await expect.poll(() => ctx.agents.get(SessionId('config-unchanged'))).toBeDefined()
  65. expect(ctx.agents.get(SessionId('config-unchanged'))?.session.id).toBe('config-unchanged')
  66. await ctx.fiber.dispose()
  67. })
  68. it('rejects an empty exact id before publishing an agent', async () => {
  69. const ctx = await makeCoreContext()
  70. await expect(ctx.plugin(AgentLoop, {
  71. agents: [{ id: 'main', sessionId: SessionId(''), model: 'mock' }],
  72. })).rejects.toThrow('expected string length >= 1')
  73. expect(ctx.agents.get(SessionId(''))).toBeUndefined()
  74. await ctx.fiber.dispose()
  75. })
  76. it('accepts one exact fresh id and rejects it alongside a resume id', async () => {
  77. const exact = await makeCoreContext()
  78. await exact.plugin(AgentLoop, {
  79. agents: [{ id: 'main', sessionId: SessionId('config-exact'), model: 'mock' }],
  80. })
  81. await expect.poll(() => exact.agents.get(SessionId('config-exact'))).toBeDefined()
  82. expect(exact.agents.get(SessionId('config-exact'))?.session.id).toBe('config-exact')
  83. await exact.fiber.dispose()
  84. const conflicting = await makeCoreContext()
  85. await expect(conflicting.plugin(AgentLoop, {
  86. agents: [{
  87. id: 'main',
  88. sessionId: SessionId('fresh'),
  89. resumeSessionId: SessionId('persisted'),
  90. model: 'mock',
  91. }],
  92. })).rejects.toThrow('sessionId and resumeSessionId are mutually exclusive')
  93. await conflicting.fiber.dispose()
  94. })
  95. it('rejects duplicate exact ids before asynchronous configured startup', async () => {
  96. const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-duplicate-'))
  97. dirs.push(root)
  98. const ctx = await makeCoreContext()
  99. await ctx.plugin(JsonlSessionPersistence, { root })
  100. const outcome = await ctx.plugin(AgentLoop, {
  101. agents: [
  102. { id: 'first', sessionId: SessionId('shared'), model: 'mock' },
  103. { id: 'second', sessionId: SessionId('shared'), model: 'mock' },
  104. ],
  105. }).then(() => undefined, (error: unknown) => error)
  106. const published = ctx.agents.get(SessionId('shared'))
  107. await ctx.fiber.dispose()
  108. expect(outcome).toEqual(new Error('agents "first" and "second" use duplicate exact session identity "shared"'))
  109. expect(published).toBeUndefined()
  110. })
  111. it('restores a materialized exact id across an AgentLoop-only reload', async () => {
  112. const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-reload-'))
  113. dirs.push(root)
  114. const ctx = await makeCoreContext()
  115. await ctx.plugin(JsonlSessionPersistence, { root })
  116. ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('first'), textResponse('second')]))
  117. const config = { agents: [{ id: 'main', sessionId: SessionId('config-exact-reload'), provider: 'mock', model: 'mock' }] }
  118. const firstLoop = await ctx.plugin(AgentLoop, config)
  119. await expect.poll(() => ctx.agents.get(SessionId('config-exact-reload')), { timeout: 5_000 }).toBeDefined()
  120. const first = ctx.agents.get(SessionId('config-exact-reload'))!
  121. first.followup(createUserMessage({ content: [{ type: 'text', text: 'remember me' }], source: { kind: 'user' } }))
  122. await waitForIdle(ctx, first)
  123. await firstLoop.dispose()
  124. const secondLoop = await ctx.plugin(AgentLoop, config)
  125. await expect.poll(() => ctx.agents.get(SessionId('config-exact-reload')), { timeout: 5_000 }).toBeDefined()
  126. const second = ctx.agents.get(SessionId('config-exact-reload'))!
  127. expect(JSON.stringify(second.session.deriveMessages())).toContain('remember me')
  128. second.followup(createUserMessage({ content: [{ type: 'text', text: 'continue' }], source: { kind: 'user' } }))
  129. await waitForIdle(ctx, second)
  130. await ctx.sessions.flush(second.session)
  131. const stored = await readStoredEvents(ctx, SessionId('config-exact-reload'))
  132. expect(stored.filter(event => event.type === 'turn/start')).toHaveLength(2)
  133. await secondLoop.dispose()
  134. await ctx.fiber.dispose()
  135. })
  136. it('waits for a draining exact-id lifecycle during an overlapping reload', async () => {
  137. const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-overlap-'))
  138. dirs.push(root)
  139. const ctx = await makeCoreContext()
  140. await ctx.plugin(JsonlSessionPersistence, { root })
  141. ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('saved')]))
  142. const sessionId = SessionId('config-exact-overlap')
  143. const config = { agents: [{ id: 'main', sessionId, provider: 'mock', model: 'mock' }] }
  144. const firstLoop = await ctx.plugin(AgentLoop, config)
  145. await expect.poll(() => ctx.agents.get(sessionId)).toBeDefined()
  146. const first = ctx.agents.get(sessionId) as Agent
  147. const cleanupGate = Promise.withResolvers<undefined>()
  148. const cleanupStarted = Promise.withResolvers<undefined>()
  149. first.ctx.effect(() => async () => {
  150. cleanupStarted.resolve(undefined)
  151. await cleanupGate.promise
  152. })
  153. const idle = waitForIdle(ctx, first)
  154. first.followup(createUserMessage({ content: [{ type: 'text', text: 'persist before replacement' }], source: { kind: 'user' } }))
  155. await idle
  156. await ctx.sessions.flush(first.session)
  157. expect(JSON.stringify(await readStoredEvents(ctx, sessionId)))
  158. .toContain('persist before replacement')
  159. const firstDisposal = firstLoop.dispose()
  160. await cleanupStarted.promise
  161. expect(first.status).toBe('idle')
  162. const failures: unknown[] = []
  163. ctx.on('agent-loop/config-start-failed', ({ error }) => { failures.push(error) })
  164. const secondLoop = await ctx.plugin(AgentLoop, config)
  165. await new Promise(resolve => setTimeout(resolve, 0))
  166. expect(ctx.agents.get(sessionId)).toBe(first)
  167. expect(failures).toEqual([])
  168. cleanupGate.resolve(undefined)
  169. await firstDisposal
  170. await expect.poll(() => ctx.agents.get(sessionId)).toBeDefined()
  171. const second = ctx.agents.get(sessionId) as Agent
  172. expect(second).not.toBe(first)
  173. expect(JSON.stringify(second.session.deriveMessages())).toContain('persist before replacement')
  174. expect(failures).toEqual([])
  175. await secondLoop.dispose()
  176. await ctx.fiber.dispose()
  177. })
  178. it('cancels an exact-id reload while the prior lifecycle is still draining', async () => {
  179. const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-cancel-'))
  180. dirs.push(root)
  181. const ctx = await makeCoreContext()
  182. await ctx.plugin(JsonlSessionPersistence, { root })
  183. const sessionId = SessionId('config-exact-cancel')
  184. const config = { agents: [{ id: 'main', sessionId, model: 'mock' }] }
  185. const firstLoop = await ctx.plugin(AgentLoop, config)
  186. await expect.poll(() => ctx.agents.get(sessionId)).toBeDefined()
  187. const first = ctx.agents.get(sessionId) as Agent
  188. const cleanupGate = Promise.withResolvers<undefined>()
  189. const cleanupStarted = Promise.withResolvers<undefined>()
  190. first.ctx.effect(() => async () => {
  191. cleanupStarted.resolve(undefined)
  192. await cleanupGate.promise
  193. })
  194. first.inject(createUserMessage({ content: [{ type: 'text', text: 'persist before cancellation' }], source: { kind: 'plugin', plugin: 'test' } }))
  195. await ctx.sessions.flush(first.session)
  196. expect(JSON.stringify(await readStoredEvents(ctx, sessionId)))
  197. .toContain('persist before cancellation')
  198. const firstDisposal = firstLoop.dispose()
  199. await cleanupStarted.promise
  200. expect(first.status).toBe('idle')
  201. const secondLoop = await ctx.plugin(AgentLoop, config)
  202. await secondLoop.dispose()
  203. expect(ctx.agents.get(sessionId)).toBe(first)
  204. cleanupGate.resolve(undefined)
  205. await firstDisposal
  206. expect(ctx.agents.get(sessionId)).toBeUndefined()
  207. await ctx.fiber.dispose()
  208. })
  209. it('contains a configured fresh-create failure without persistence', async () => {
  210. const ctx = await makeCoreContext()
  211. const failures: unknown[] = []
  212. ctx.on('agent-loop/config-start-failed', ({ error }) => { failures.push(error) })
  213. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  214. // A relative cwd fails session preparation inside the plain create path
  215. // (no backend mounted): the failure is reported, not crashed on.
  216. await ctx.plugin(AgentLoop, {
  217. agents: [{ id: 'main', model: 'mock', cwd: 'relative' }],
  218. })
  219. await expect.poll(() => failures.length).toBe(1)
  220. expect(failures[0]).toBeInstanceOf(Error)
  221. expect((failures[0] as Error).message).toMatch(/absolute path/)
  222. expect(warn).toHaveBeenCalledWith(expect.stringContaining('config-driven restore'))
  223. expect(ctx.agents.list()).toEqual([])
  224. warn.mockRestore()
  225. await ctx.fiber.dispose()
  226. })
  227. it('contains an exact-id persistence open failure', async () => {
  228. const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-failure-'))
  229. dirs.push(root)
  230. const ctx = await makeCoreContext()
  231. await ctx.plugin(JsonlSessionPersistence, { root })
  232. const failure = new Error('persistence index failed')
  233. const listenerFailure = new Error('failure observer failed')
  234. const asyncListenerFailure = new Error('async failure observer failed')
  235. const failures: { sessionId: SessionId; error: unknown }[] = []
  236. ctx.on('agent-loop/config-start-failed', () => { throw listenerFailure })
  237. ctx.on('agent-loop/config-start-failed', () => Promise.reject(asyncListenerFailure) as never)
  238. ctx.on('agent-loop/config-start-failed', ({ sessionId, error }) => {
  239. failures.push({ sessionId, error })
  240. })
  241. vi.spyOn(ctx.sessionPersistence, 'open').mockRejectedValue(failure)
  242. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  243. await ctx.plugin(AgentLoop, {
  244. agents: [{ id: 'main', sessionId: SessionId('config-exact-failure'), model: 'mock' }],
  245. })
  246. await expect.poll(() => warn).toHaveBeenCalledWith(expect.stringContaining(
  247. 'config-driven restore of "config-exact-failure" failed: persistence index failed',
  248. ))
  249. expect(failures).toEqual([{ sessionId: SessionId('config-exact-failure'), error: failure }])
  250. expect(warn).toHaveBeenCalledWith(
  251. 'agent "main": config-start-failed listener threw: failure observer failed',
  252. )
  253. await expect.poll(() => warn).toHaveBeenCalledWith(
  254. 'agent "main": config-start-failed listener rejected: async failure observer failed',
  255. )
  256. expect(ctx.agents.get(SessionId('config-exact-failure'))).toBeUndefined()
  257. warn.mockRestore()
  258. await ctx.fiber.dispose()
  259. })
  260. it('contains startup and observer failures whose string coercion throws', async () => {
  261. const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-unrenderable-'))
  262. dirs.push(root)
  263. const ctx = await makeCoreContext()
  264. await ctx.plugin(JsonlSessionPersistence, { root })
  265. const unrenderable = {
  266. [Symbol.toPrimitive](): never {
  267. throw new Error('coercion escaped')
  268. },
  269. }
  270. const failures: unknown[] = []
  271. ctx.on('agent-loop/config-start-failed', () => { throw unrenderable })
  272. // Deliberately violate the normal Error-only rejection rule to exercise the unknown boundary.
  273. // oxlint-disable-next-line typescript/prefer-promise-reject-errors
  274. ctx.on('agent-loop/config-start-failed', () => Promise.reject(unrenderable) as never)
  275. ctx.on('agent-loop/config-start-failed', ({ error }) => { failures.push(error) })
  276. vi.spyOn(ctx.sessionPersistence, 'open').mockRejectedValue(unrenderable)
  277. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  278. await ctx.plugin(AgentLoop, {
  279. agents: [{ id: 'main', sessionId: SessionId('config-exact-unrenderable'), model: 'mock' }],
  280. })
  281. await expect.poll(() => failures).toEqual([unrenderable])
  282. expect(warn).toHaveBeenCalledWith(
  283. 'agent "main": config-driven restore of "config-exact-unrenderable" failed: <unrenderable value>',
  284. )
  285. expect(warn).toHaveBeenCalledWith(
  286. 'agent "main": config-start-failed listener threw: <unrenderable value>',
  287. )
  288. await expect.poll(() => warn).toHaveBeenCalledWith(
  289. 'agent "main": config-start-failed listener rejected: <unrenderable value>',
  290. )
  291. await ctx.fiber.dispose()
  292. })
  293. it.each(['resolve', 'reject'] as const)(
  294. 'abandons an exact-id open that later %ss when AgentLoop disposal starts',
  295. async (outcome) => {
  296. const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-dispose-'))
  297. dirs.push(root)
  298. const ctx = await makeCoreContext()
  299. await ctx.plugin(JsonlSessionPersistence, { root })
  300. const opening = Promise.withResolvers<SessionHandle>()
  301. vi.spyOn(ctx.sessionPersistence, 'open').mockReturnValue(opening.promise)
  302. const closed = vi.fn(async () => {})
  303. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  304. const failures: unknown[] = []
  305. ctx.on('agent-loop/config-start-failed', ({ error }) => { failures.push(error) })
  306. const loop = await ctx.plugin(AgentLoop, {
  307. agents: [{ id: 'main', sessionId: SessionId('config-exact-dispose'), model: 'mock' }],
  308. })
  309. await loop.dispose()
  310. if (outcome === 'resolve') {
  311. opening.resolve({ close: closed } as unknown as SessionHandle)
  312. } else {
  313. opening.reject(new Error('startup cancelled by teardown'))
  314. }
  315. await Promise.resolve()
  316. // The abandoned handle is closed; the rejected open is silently released.
  317. if (outcome === 'resolve') await expect.poll(() => closed).toHaveBeenCalledOnce()
  318. expect(ctx.agents.get(SessionId('config-exact-dispose'))).toBeUndefined()
  319. expect(failures).toEqual([])
  320. expect(warn).not.toHaveBeenCalled()
  321. warn.mockRestore()
  322. await ctx.fiber.dispose()
  323. },
  324. )
  325. it('identity-nests the deferred resume fiber under its labeled owner effect', async () => {
  326. const ctx = new Context()
  327. await ctx.plugin(LlmRuntime)
  328. await ctx.plugin(SessionStore)
  329. await ctx.plugin(SessionProjectionRegistry)
  330. await ctx.plugin(SystemPrompt)
  331. await ctx.plugin(ToolRuntime)
  332. await ctx.plugin(AgentRegistry)
  333. const loopFiber = await ctx.plugin(AgentLoop, {
  334. agents: [{ id: SessionId('main'), provider: 'mock', model: 'mock', resumeSessionId: SessionId('deferred') }],
  335. })
  336. const resumeEffect = loopFiber.getEffects().find(effect => effect.label === 'agentLoop.resume(main)')
  337. expect(resumeEffect?.children.map(child => child.label)).toEqual(['ctx.plugin()'])
  338. // Exactly one plugin effect sits at the fiber's own level — the optional
  339. // settings wiring, whose `ctx.inject` cordis labels like any other plugin.
  340. // A resumed agent joining it there is the regression this pins.
  341. expect(loopFiber.getEffects().filter(effect => effect.label === 'ctx.plugin()')).toHaveLength(1)
  342. await loopFiber.dispose()
  343. })
  344. it('config-driven create uses a fresh ${id}-session-<uuid> per run (restart-safe)', async () => {
  345. const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-session-'))
  346. dirs.push(root)
  347. const idPattern = /^cfg-session-[0-9a-f-]{36}$/
  348. // Run 1: a config agent persists a turn under a generated session id.
  349. const ctx1 = new Context()
  350. await ctx1.plugin(LlmRuntime)
  351. await ctx1.plugin(SessionStore)
  352. await ctx1.plugin(SessionProjectionRegistry)
  353. await ctx1.plugin(SystemPrompt)
  354. await ctx1.plugin(ToolRuntime)
  355. await ctx1.plugin(AgentRegistry)
  356. await ctx1.plugin(JsonlSessionPersistence, { root })
  357. await ctx1.plugin(AgentLoop, { agents: [{ id: SessionId('cfg'), provider: 'mock', model: 'mock' }] })
  358. ctx1.llm.registerAdapter(['mock'], new MockAdapter([textResponse('cfg')]))
  359. await expect.poll(() => ctx1.agents.list().length).toBe(1)
  360. const a1 = ctx1.agents.list()[0] as Agent
  361. expect(a1.id).toBe(a1.session.id)
  362. expect(a1.session.id).toMatch(idPattern)
  363. expect(ctx1.agents.get(SessionId('cfg'))).toBeUndefined()
  364. a1.followup(createUserMessage({ content: [{ type: 'text', text: 'q' }], source: { kind: 'user' } }))
  365. await waitForIdle(ctx1, a1)
  366. await ctx1.sessions.flush(a1.session)
  367. expect(JSON.stringify(await readStoredEvents(ctx1, a1.session.id))).toContain('cfg')
  368. await ctx1.fiber.dispose()
  369. // Run 2 over the SAME root: a fresh id means no on-disk collision (a fixed
  370. // ${id}-session would crash here with "already exists").
  371. const ctx2 = new Context()
  372. await ctx2.plugin(LlmRuntime)
  373. await ctx2.plugin(SessionStore)
  374. await ctx2.plugin(SessionProjectionRegistry)
  375. await ctx2.plugin(SystemPrompt)
  376. await ctx2.plugin(ToolRuntime)
  377. await ctx2.plugin(AgentRegistry)
  378. await ctx2.plugin(JsonlSessionPersistence, { root })
  379. await ctx2.plugin(AgentLoop, { agents: [{ id: SessionId('cfg'), provider: 'mock', model: 'mock' }] })
  380. ctx2.llm.registerAdapter(['mock'], new MockAdapter([textResponse('cfg2')]))
  381. await expect.poll(() => ctx2.agents.list().length).toBe(1)
  382. const a2 = ctx2.agents.list()[0] as Agent
  383. expect(a2.id).toBe(a2.session.id)
  384. expect(a2.session.id).toMatch(idPattern)
  385. expect(a2.session.id).not.toBe(a1.session.id)
  386. a2.followup(createUserMessage({ content: [{ type: 'text', text: 'q2' }], source: { kind: 'user' } }))
  387. await waitForIdle(ctx2, a2)
  388. await ctx2.fiber.dispose()
  389. })
  390. it('config-driven resumeSessionId continues a persisted session', async () => {
  391. const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-resume-'))
  392. dirs.push(root)
  393. // Run 1: a programmatically-created agent on a KNOWN session id persists a
  394. // completed turn, so run 2 has a concrete id to resume.
  395. const ctx1 = new Context()
  396. await ctx1.plugin(LlmRuntime)
  397. await ctx1.plugin(SessionStore)
  398. await ctx1.plugin(SessionProjectionRegistry)
  399. await ctx1.plugin(SystemPrompt)
  400. await ctx1.plugin(ToolRuntime)
  401. await ctx1.plugin(AgentRegistry)
  402. await ctx1.plugin(JsonlSessionPersistence, { root })
  403. await ctx1.plugin(AgentLoop, { agents: [] })
  404. ctx1.llm.registerAdapter(['mock'], new MockAdapter([textResponse('first')]))
  405. const h1 = await ctx1.agents.create({ sessionId: SessionId('sticky-1'), agentOptions: { provider: 'mock', model: 'mock' } })
  406. h1.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'remember me' }], source: { kind: 'user' } }))
  407. await waitForIdle(ctx1, h1.agent)
  408. await h1.dispose()
  409. await ctx1.fiber.dispose()
  410. // Resume waits for the injected persistence service, so poll until the
  411. // config-created agent appears with its stored history.
  412. const ctx2 = new Context()
  413. await ctx2.plugin(LlmRuntime)
  414. await ctx2.plugin(SessionStore)
  415. await ctx2.plugin(SessionProjectionRegistry)
  416. await ctx2.plugin(SystemPrompt)
  417. await ctx2.plugin(ToolRuntime)
  418. await ctx2.plugin(AgentRegistry)
  419. await ctx2.plugin(AgentLoop, { agents: [{ id: SessionId('main'), provider: 'mock', model: 'mock', resumeSessionId: SessionId('sticky-1') }] })
  420. await ctx2.plugin(JsonlSessionPersistence, { root })
  421. ctx2.llm.registerAdapter(['mock'], new MockAdapter([textResponse('second')]))
  422. // The deferred resume runs after the backend is available.
  423. await expect.poll(() => ctx2.agents.get(SessionId('sticky-1')), { timeout: 5_000 }).toBeDefined()
  424. const resumed = ctx2.agents.get(SessionId('sticky-1'))!
  425. // The live session id IS the resumed id (NOT a fresh ${id}-session-<uuid>),
  426. // and the prior turn's user message is in the derived history.
  427. expect(resumed.id).toBe(SessionId('sticky-1'))
  428. expect(resumed.session.id).toBe('sticky-1')
  429. const derived = resumed.session.deriveMessages()
  430. expect(JSON.stringify(derived)).toContain('remember me')
  431. await ctx2.fiber.dispose()
  432. })
  433. it('config-driven resume of a missing session is contained: logs a warning, no agent, no crash', async () => {
  434. const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-resume-miss-'))
  435. dirs.push(root)
  436. const ctx = new Context()
  437. await ctx.plugin(LlmRuntime)
  438. await ctx.plugin(SessionStore)
  439. await ctx.plugin(SessionProjectionRegistry)
  440. await ctx.plugin(SystemPrompt)
  441. await ctx.plugin(ToolRuntime)
  442. await ctx.plugin(AgentRegistry)
  443. await ctx.plugin(AgentLoop, { agents: [{ id: SessionId('main'), provider: 'mock', model: 'mock', resumeSessionId: SessionId('does-not-exist') }] })
  444. const warn = vi.spyOn((ctx.agentLoop as unknown as { ctx: { logger: { warn: (...a: unknown[]) => void } } }).ctx.logger, 'warn')
  445. .mockImplementation(() => undefined)
  446. await ctx.plugin(JsonlSessionPersistence, { root })
  447. ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('x')]))
  448. // The deferred resume fails (no such session on disk). It must be contained:
  449. // a warning is logged, no agent is registered, and the app stays up.
  450. await expect.poll(() => warn.mock.calls.some(call =>
  451. typeof call[0] === 'string' && call[0].includes('config-driven resume of "does-not-exist" failed'),
  452. )).toBe(true)
  453. expect(ctx.agents.list()).toEqual([])
  454. warn.mockRestore()
  455. await ctx.fiber.dispose()
  456. })
  457. })
  458. describe('startup reporting after factory teardown', () => {
  459. it('suppresses the configured-restore failure report once the loop is disposed', async () => {
  460. const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-disposed-report-'))
  461. dirs.push(root)
  462. const ctx = await makeCoreContext()
  463. await ctx.plugin(JsonlSessionPersistence, { root })
  464. ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('x')]))
  465. // A restore open that hangs until after the loop is gone: the eventual
  466. // failure lands with ownership inactive and must be silently dropped.
  467. const gate = Promise.withResolvers<SessionHandle>()
  468. // The teardown path may drop the pending open without awaiting it.
  469. gate.promise.catch(() => undefined)
  470. vi.spyOn(ctx.sessionPersistence, 'open').mockReturnValue(gate.promise)
  471. const failures: unknown[] = []
  472. ctx.on('agent-loop/config-start-failed', ({ error }) => { failures.push(error) })
  473. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  474. const loop = await ctx.plugin(AgentLoop, {
  475. agents: [{ id: 'main', sessionId: SessionId('config-disposed-report'), model: 'mock' }],
  476. })
  477. const disposal = loop.dispose()
  478. gate.reject(new Error('backend failed after teardown began'))
  479. await disposal
  480. await new Promise(r => setTimeout(r, 20))
  481. expect(failures).toEqual([])
  482. expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('config-driven restore'))
  483. warn.mockRestore()
  484. await ctx.fiber.dispose()
  485. })
  486. })