config-session-id.spec.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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, { AgentId } from '@deepseek-ai/dsh-agent'
  11. import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
  12. import AgentLoop, { ReactLoopAgent } 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: ReactLoopAgent): 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. describe('config-driven session id', () => {
  24. it('config-driven create uses a fresh ${id}-session-<uuid> per run (restart-safe)', async () => {
  25. const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-session-'))
  26. dirs.push(root)
  27. const idPattern = /^cfg-session-[0-9a-f-]{36}$/
  28. // Run 1: a config agent persists a turn under a generated session id.
  29. const ctx1 = new Context()
  30. await ctx1.plugin(LlmService)
  31. await ctx1.plugin(SessionStore)
  32. await ctx1.plugin(SystemPrompt)
  33. await ctx1.plugin(ToolRegistry)
  34. await ctx1.plugin(AgentRegistry)
  35. await ctx1.plugin(AgentLoop, { agents: [{ id: AgentId('cfg'), model: 'mock' }] })
  36. await ctx1.plugin(SessionPersistenceJsonl, { root })
  37. ctx1.llm.registerAdapter(['mock'], new MockAdapter([textResponse('cfg')]))
  38. const a1 = ctx1.agents.get(AgentId('cfg')) as ReactLoopAgent
  39. expect(a1.session.id).toMatch(idPattern)
  40. a1.send([{ type: 'text', text: 'q' }], { source: { kind: 'user' } })
  41. await waitForIdle(ctx1, a1)
  42. await ctx1.fiber.dispose()
  43. // Run 2 over the SAME root: a fresh id means no on-disk collision (a fixed
  44. // ${id}-session would crash here with "already has a persisted log").
  45. const ctx2 = new Context()
  46. await ctx2.plugin(LlmService)
  47. await ctx2.plugin(SessionStore)
  48. await ctx2.plugin(SystemPrompt)
  49. await ctx2.plugin(ToolRegistry)
  50. await ctx2.plugin(AgentRegistry)
  51. await ctx2.plugin(AgentLoop, { agents: [{ id: AgentId('cfg'), model: 'mock' }] })
  52. await ctx2.plugin(SessionPersistenceJsonl, { root })
  53. ctx2.llm.registerAdapter(['mock'], new MockAdapter([textResponse('cfg2')]))
  54. const a2 = ctx2.agents.get(AgentId('cfg')) as ReactLoopAgent
  55. expect(a2.session.id).toMatch(idPattern)
  56. expect(a2.session.id).not.toBe(a1.session.id)
  57. a2.send([{ type: 'text', text: 'q2' }], { source: { kind: 'user' } })
  58. await waitForIdle(ctx2, a2)
  59. await ctx2.fiber.dispose()
  60. })
  61. it('config-driven resumeSessionId continues a persisted session (env-var resume)', async () => {
  62. const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-resume-'))
  63. dirs.push(root)
  64. // Run 1: a programmatically-created agent on a KNOWN session id persists a
  65. // completed turn, so run 2 has a concrete id to resume.
  66. const ctx1 = new Context()
  67. await ctx1.plugin(LlmService)
  68. await ctx1.plugin(SessionStore)
  69. await ctx1.plugin(SystemPrompt)
  70. await ctx1.plugin(ToolRegistry)
  71. await ctx1.plugin(AgentRegistry)
  72. await ctx1.plugin(AgentLoop, { agents: [] })
  73. await ctx1.plugin(SessionPersistenceJsonl, { root })
  74. ctx1.llm.registerAdapter(['mock'], new MockAdapter([textResponse('first')]))
  75. const a1 = (await ctx1.agents.create({ agentId: AgentId('main'), sessionId: SessionId('sticky-1') })).agent as ReactLoopAgent
  76. a1.send([{ type: 'text', text: 'remember me' }], { source: { kind: 'user' } })
  77. await waitForIdle(ctx1, a1)
  78. await ctx1.fiber.dispose()
  79. // Run 2: a CONFIG agent with resumeSessionId continues that session. The
  80. // resume is deferred until sessionPersistence loads (ctx.inject), so wait
  81. // for the agent to appear, then assert it is on the resumed id with history.
  82. const ctx2 = new Context()
  83. await ctx2.plugin(LlmService)
  84. await ctx2.plugin(SessionStore)
  85. await ctx2.plugin(SystemPrompt)
  86. await ctx2.plugin(ToolRegistry)
  87. await ctx2.plugin(AgentRegistry)
  88. await ctx2.plugin(AgentLoop, { agents: [{ id: AgentId('main'), model: 'mock', resumeSessionId: SessionId('sticky-1') }] })
  89. await ctx2.plugin(SessionPersistenceJsonl, { root })
  90. ctx2.llm.registerAdapter(['mock'], new MockAdapter([textResponse('second')]))
  91. // The deferred resume runs on a microtask after the backend is available.
  92. let resumed: ReactLoopAgent | undefined
  93. for (let i = 0; i < 50 && !resumed; i++) {
  94. await new Promise(r => setTimeout(r, 5))
  95. resumed = ctx2.agents.get(AgentId('main')) as ReactLoopAgent | undefined
  96. }
  97. expect(resumed).toBeDefined()
  98. // The live session id IS the resumed id (NOT a fresh ${id}-session-<uuid>),
  99. // and the prior turn's user message is in the derived history.
  100. expect(resumed!.session.id).toBe('sticky-1')
  101. const derived = resumed!.session.deriveMessages()
  102. expect(JSON.stringify(derived)).toContain('remember me')
  103. await ctx2.fiber.dispose()
  104. })
  105. it('config-driven resume of a missing session is contained: logs a warning, no agent, no crash', async () => {
  106. const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-resume-miss-'))
  107. dirs.push(root)
  108. const ctx = new Context()
  109. await ctx.plugin(LlmService)
  110. await ctx.plugin(SessionStore)
  111. await ctx.plugin(SystemPrompt)
  112. await ctx.plugin(ToolRegistry)
  113. await ctx.plugin(AgentRegistry)
  114. await ctx.plugin(AgentLoop, { agents: [{ id: AgentId('main'), model: 'mock', resumeSessionId: SessionId('does-not-exist') }] })
  115. const warn = vi.spyOn((ctx.agentLoop as unknown as { ctx: { logger: { warn: (...a: unknown[]) => void } } }).ctx.logger, 'warn')
  116. .mockImplementation(() => undefined)
  117. await ctx.plugin(SessionPersistenceJsonl, { root })
  118. ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('x')]))
  119. // The deferred resume fails (no such session on disk). It must be contained:
  120. // a warning is logged, no 'main' agent is registered, and the app stays up.
  121. await new Promise(r => setTimeout(r, 200))
  122. expect(ctx.agents.get(AgentId('main'))).toBeUndefined()
  123. expect(warn).toHaveBeenCalledWith(expect.stringContaining('config-driven resume of "does-not-exist" failed'))
  124. warn.mockRestore()
  125. await ctx.fiber.dispose()
  126. })
  127. })