config-session-id.spec.ts 23 KB

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