config-session-id.spec.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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('stdio-exact'), model: 'mock' }],
  45. })
  46. expect(exact.agents.get(SessionId('stdio-exact'))?.session.id).toBe('stdio-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('stdio-exact-reload'), 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('stdio-exact-reload'))
  87. }
  88. expect(first).toBeDefined()
  89. first!.send([{ 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('stdio-exact-reload'))
  97. }
  98. expect(second).toBeDefined()
  99. expect(JSON.stringify(second!.session.deriveMessages())).toContain('remember me')
  100. second!.send([{ 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('stdio-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('stdio-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 flushGate = Promise.withResolvers<undefined>()
  119. let flushStarted = false
  120. ctx.on('session/flush', (session) => {
  121. if (session !== first.session) return
  122. flushStarted = true
  123. return flushGate.promise
  124. })
  125. first.inject([{ type: 'text', text: 'persist before replacement' }], {
  126. source: { kind: 'plugin', plugin: 'test' },
  127. })
  128. expect(flushStarted).toBe(true)
  129. const firstDisposal = firstLoop.dispose()
  130. await expect.poll(() => first.status).toBe('disposed')
  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. flushGate.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('stdio-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 flushGate = Promise.withResolvers<undefined>()
  158. ctx.on('session/flush', (session) => {
  159. if (session === first.session) return flushGate.promise
  160. })
  161. first.inject([{ type: 'text', text: 'persist before cancellation' }], {
  162. source: { kind: 'plugin', plugin: 'test' },
  163. })
  164. const firstDisposal = firstLoop.dispose()
  165. await expect.poll(() => first.status).toBe('disposed')
  166. const secondLoop = await ctx.plugin(AgentLoop, config)
  167. await secondLoop.dispose()
  168. expect(ctx.agents.get(sessionId)).toBe(first)
  169. flushGate.resolve(undefined)
  170. await firstDisposal
  171. expect(ctx.agents.get(sessionId)).toBeUndefined()
  172. await ctx.fiber.dispose()
  173. })
  174. it('contains an exact-id persistence lookup failure', async () => {
  175. const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-failure-'))
  176. dirs.push(root)
  177. const ctx = await makeCoreContext()
  178. await ctx.plugin(SessionPersistenceJsonl, { root })
  179. const failure = new Error('persistence index failed')
  180. const listenerFailure = new Error('failure observer failed')
  181. const asyncListenerFailure = new Error('async failure observer failed')
  182. const failures: { sessionId: SessionId; error: unknown }[] = []
  183. ctx.on('agent-loop/config-start-failed', () => { throw listenerFailure })
  184. ctx.on('agent-loop/config-start-failed', () => Promise.reject(asyncListenerFailure) as never)
  185. ctx.on('agent-loop/config-start-failed', (sessionId, error) => {
  186. failures.push({ sessionId, error })
  187. })
  188. vi.spyOn(ctx.sessionPersistence, 'list').mockRejectedValue(failure)
  189. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  190. await ctx.plugin(AgentLoop, {
  191. agents: [{ id: 'main', sessionId: SessionId('stdio-exact-failure'), model: 'mock' }],
  192. })
  193. await expect.poll(() => warn).toHaveBeenCalledWith(expect.stringContaining(
  194. 'config-driven restore of "stdio-exact-failure" failed: Error: persistence index failed',
  195. ))
  196. expect(failures).toEqual([{ sessionId: SessionId('stdio-exact-failure'), error: failure }])
  197. expect(warn).toHaveBeenCalledWith(
  198. 'agent "main": config-start-failed listener threw: Error: failure observer failed',
  199. )
  200. await expect.poll(() => warn).toHaveBeenCalledWith(
  201. 'agent "main": config-start-failed listener rejected: Error: async failure observer failed',
  202. )
  203. expect(ctx.agents.get(SessionId('stdio-exact-failure'))).toBeUndefined()
  204. warn.mockRestore()
  205. await ctx.fiber.dispose()
  206. })
  207. it('contains startup and observer failures whose string coercion throws', async () => {
  208. const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-unrenderable-'))
  209. dirs.push(root)
  210. const ctx = await makeCoreContext()
  211. await ctx.plugin(SessionPersistenceJsonl, { root })
  212. const unrenderable = {
  213. [Symbol.toPrimitive](): never {
  214. throw new Error('coercion escaped')
  215. },
  216. }
  217. const failures: unknown[] = []
  218. ctx.on('agent-loop/config-start-failed', () => { throw unrenderable })
  219. // Deliberately violate the normal Error-only rejection rule to exercise the unknown boundary.
  220. // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
  221. ctx.on('agent-loop/config-start-failed', () => Promise.reject(unrenderable) as never)
  222. ctx.on('agent-loop/config-start-failed', (_sessionId, error) => { failures.push(error) })
  223. vi.spyOn(ctx.sessionPersistence, 'list').mockRejectedValue(unrenderable)
  224. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  225. await ctx.plugin(AgentLoop, {
  226. agents: [{ id: 'main', sessionId: SessionId('stdio-exact-unrenderable'), model: 'mock' }],
  227. })
  228. await expect.poll(() => failures).toEqual([unrenderable])
  229. expect(warn).toHaveBeenCalledWith(
  230. 'agent "main": config-driven restore of "stdio-exact-unrenderable" failed: <unrenderable thrown value>',
  231. )
  232. expect(warn).toHaveBeenCalledWith(
  233. 'agent "main": config-start-failed listener threw: <unrenderable thrown value>',
  234. )
  235. await expect.poll(() => warn).toHaveBeenCalledWith(
  236. 'agent "main": config-start-failed listener rejected: <unrenderable thrown value>',
  237. )
  238. await ctx.fiber.dispose()
  239. })
  240. it.each(['resolve', 'reject'] as const)(
  241. 'joins an exact-id persistence lookup that will %s before AgentLoop disposal completes',
  242. async (outcome) => {
  243. const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-dispose-'))
  244. dirs.push(root)
  245. const ctx = await makeCoreContext()
  246. await ctx.plugin(SessionPersistenceJsonl, { root })
  247. const listing = Promise.withResolvers<Awaited<ReturnType<typeof ctx.sessionPersistence.list>>>()
  248. vi.spyOn(ctx.sessionPersistence, 'list').mockReturnValue(listing.promise)
  249. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  250. const failures: unknown[] = []
  251. ctx.on('agent-loop/config-start-failed', (_sessionId, error) => { failures.push(error) })
  252. const loop = await ctx.plugin(AgentLoop, {
  253. agents: [{ id: 'main', sessionId: SessionId('stdio-exact-dispose'), model: 'mock' }],
  254. })
  255. let disposed = false
  256. const disposal = loop.dispose().then(() => { disposed = true })
  257. await Promise.resolve()
  258. expect(disposed).toBe(false)
  259. if (outcome === 'resolve') listing.resolve([])
  260. else listing.reject(new Error('startup cancelled by teardown'))
  261. await disposal
  262. expect(ctx.agents.get(SessionId('stdio-exact-dispose'))).toBeUndefined()
  263. expect(failures).toEqual([])
  264. expect(warn).not.toHaveBeenCalled()
  265. warn.mockRestore()
  266. await ctx.fiber.dispose()
  267. },
  268. )
  269. it('identity-nests the deferred resume fiber under its labeled owner effect', async () => {
  270. const ctx = new Context()
  271. await ctx.plugin(LlmService)
  272. await ctx.plugin(SessionStore)
  273. await ctx.plugin(SystemPrompt)
  274. await ctx.plugin(ToolRegistry)
  275. await ctx.plugin(AgentRegistry)
  276. const loopFiber = await ctx.plugin(AgentLoop, {
  277. agents: [{ id: SessionId('main'), provider: 'mock', model: 'mock', resumeSessionId: SessionId('deferred') }],
  278. })
  279. const resumeEffect = loopFiber.getEffects().find(effect => effect.label === 'agentLoop.resume(main)')
  280. expect(resumeEffect?.children.map(child => child.label)).toEqual(['ctx.plugin()'])
  281. expect(loopFiber.getEffects().filter(effect => effect.label === 'ctx.plugin()')).toEqual([])
  282. await loopFiber.dispose()
  283. })
  284. it('config-driven create uses a fresh ${id}-session-<uuid> per run (restart-safe)', async () => {
  285. const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-session-'))
  286. dirs.push(root)
  287. const idPattern = /^cfg-session-[0-9a-f-]{36}$/
  288. // Run 1: a config agent persists a turn under a generated session id.
  289. const ctx1 = new Context()
  290. await ctx1.plugin(LlmService)
  291. await ctx1.plugin(SessionStore)
  292. await ctx1.plugin(SystemPrompt)
  293. await ctx1.plugin(ToolRegistry)
  294. await ctx1.plugin(AgentRegistry)
  295. await ctx1.plugin(AgentLoop, { agents: [{ id: SessionId('cfg'), provider: 'mock', model: 'mock' }] })
  296. await ctx1.plugin(SessionPersistenceJsonl, { root })
  297. ctx1.llm.registerAdapter(['mock'], new MockAdapter([textResponse('cfg')]))
  298. const a1 = ctx1.agents.list()[0] as Agent
  299. expect(a1.id).toBe(a1.session.id)
  300. expect(a1.session.id).toMatch(idPattern)
  301. expect(ctx1.agents.get(SessionId('cfg'))).toBeUndefined()
  302. a1.send([{ type: 'text', text: 'q' }], { source: { kind: 'user' } })
  303. await waitForIdle(ctx1, a1)
  304. await ctx1.fiber.dispose()
  305. // Run 2 over the SAME root: a fresh id means no on-disk collision (a fixed
  306. // ${id}-session would crash here with "already has a persisted log").
  307. const ctx2 = new Context()
  308. await ctx2.plugin(LlmService)
  309. await ctx2.plugin(SessionStore)
  310. await ctx2.plugin(SystemPrompt)
  311. await ctx2.plugin(ToolRegistry)
  312. await ctx2.plugin(AgentRegistry)
  313. await ctx2.plugin(AgentLoop, { agents: [{ id: SessionId('cfg'), provider: 'mock', model: 'mock' }] })
  314. await ctx2.plugin(SessionPersistenceJsonl, { root })
  315. ctx2.llm.registerAdapter(['mock'], new MockAdapter([textResponse('cfg2')]))
  316. const a2 = ctx2.agents.list()[0] as Agent
  317. expect(a2.id).toBe(a2.session.id)
  318. expect(a2.session.id).toMatch(idPattern)
  319. expect(a2.session.id).not.toBe(a1.session.id)
  320. a2.send([{ type: 'text', text: 'q2' }], { source: { kind: 'user' } })
  321. await waitForIdle(ctx2, a2)
  322. await ctx2.fiber.dispose()
  323. })
  324. it('config-driven resumeSessionId continues a persisted session (env-var resume)', async () => {
  325. const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-resume-'))
  326. dirs.push(root)
  327. // Run 1: a programmatically-created agent on a KNOWN session id persists a
  328. // completed turn, so run 2 has a concrete id to resume.
  329. const ctx1 = new Context()
  330. await ctx1.plugin(LlmService)
  331. await ctx1.plugin(SessionStore)
  332. await ctx1.plugin(SystemPrompt)
  333. await ctx1.plugin(ToolRegistry)
  334. await ctx1.plugin(AgentRegistry)
  335. await ctx1.plugin(AgentLoop, { agents: [] })
  336. await ctx1.plugin(SessionPersistenceJsonl, { root })
  337. ctx1.llm.registerAdapter(['mock'], new MockAdapter([textResponse('first')]))
  338. const a1 = (await ctx1.agents.create({ sessionId: SessionId('sticky-1') })).agent
  339. a1.send([{ type: 'text', text: 'remember me' }], { source: { kind: 'user' } })
  340. await waitForIdle(ctx1, a1)
  341. await ctx1.fiber.dispose()
  342. // Resume waits for the injected persistence service, so poll until the
  343. // config-created agent appears with its stored history.
  344. const ctx2 = new Context()
  345. await ctx2.plugin(LlmService)
  346. await ctx2.plugin(SessionStore)
  347. await ctx2.plugin(SystemPrompt)
  348. await ctx2.plugin(ToolRegistry)
  349. await ctx2.plugin(AgentRegistry)
  350. await ctx2.plugin(AgentLoop, { agents: [{ id: SessionId('main'), provider: 'mock', model: 'mock', resumeSessionId: SessionId('sticky-1') }] })
  351. await ctx2.plugin(SessionPersistenceJsonl, { root })
  352. ctx2.llm.registerAdapter(['mock'], new MockAdapter([textResponse('second')]))
  353. // The deferred resume runs on a microtask after the backend is available.
  354. let resumed: Agent | undefined
  355. for (let i = 0; i < 50 && !resumed; i++) {
  356. await new Promise(r => setTimeout(r, 5))
  357. resumed = ctx2.agents.get(SessionId('sticky-1'))
  358. }
  359. expect(resumed).toBeDefined()
  360. // The live session id IS the resumed id (NOT a fresh ${id}-session-<uuid>),
  361. // and the prior turn's user message is in the derived history.
  362. expect(resumed!.id).toBe(SessionId('sticky-1'))
  363. expect(resumed!.session.id).toBe('sticky-1')
  364. const derived = resumed!.session.deriveMessages()
  365. expect(JSON.stringify(derived)).toContain('remember me')
  366. await ctx2.fiber.dispose()
  367. })
  368. it('config-driven resume of a missing session is contained: logs a warning, no agent, no crash', async () => {
  369. const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-resume-miss-'))
  370. dirs.push(root)
  371. const ctx = new Context()
  372. await ctx.plugin(LlmService)
  373. await ctx.plugin(SessionStore)
  374. await ctx.plugin(SystemPrompt)
  375. await ctx.plugin(ToolRegistry)
  376. await ctx.plugin(AgentRegistry)
  377. await ctx.plugin(AgentLoop, { agents: [{ id: SessionId('main'), provider: 'mock', model: 'mock', resumeSessionId: SessionId('does-not-exist') }] })
  378. const warn = vi.spyOn((ctx.agentLoop as unknown as { ctx: { logger: { warn: (...a: unknown[]) => void } } }).ctx.logger, 'warn')
  379. .mockImplementation(() => undefined)
  380. await ctx.plugin(SessionPersistenceJsonl, { root })
  381. ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('x')]))
  382. // The deferred resume fails (no such session on disk). It must be contained:
  383. // a warning is logged, no agent is registered, and the app stays up.
  384. await new Promise(r => setTimeout(r, 200))
  385. expect(ctx.agents.list()).toEqual([])
  386. expect(warn).toHaveBeenCalledWith(expect.stringContaining('config-driven resume of "does-not-exist" failed'))
  387. warn.mockRestore()
  388. await ctx.fiber.dispose()
  389. })
  390. })