config-session-id.spec.ts 21 KB

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