config-session-id.spec.ts 22 KB

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