config-session-id.spec.ts 7.2 KB

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