1
0

config-session-id.spec.ts 21 KB

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