config-session-id.spec.ts 22 KB

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