time-context.e2e.ts 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'
  2. import { mkdtemp, readFile, readdir, rm } from 'node:fs/promises'
  3. import { tmpdir } from 'node:os'
  4. import { join } from 'node:path'
  5. import { fileURLToPath } from 'node:url'
  6. import { afterEach, describe, expect, it } from 'vitest'
  7. import { foldRequestHeader, type SessionEvent } from '@deepseek-ai/dsh-session'
  8. const binScript = fileURLToPath(new URL('../../../examples/stdio-demo/src/bin.ts', import.meta.url))
  9. const configPath = fileURLToPath(new URL('./fixtures/cordis.yml', import.meta.url))
  10. const repoTsconfig = fileURLToPath(new URL('../../../../tsconfig.json', import.meta.url))
  11. const tsxLoader = fileURLToPath(import.meta.resolve('tsx'))
  12. const PROCESS_TIMEOUT_MS = 30_000
  13. const TEST_TIMEOUT_MS = PROCESS_TIMEOUT_MS + 15_000
  14. const FIRST_REPLY = 'You said: "first". Try "echo <something>" to see a tool call.'
  15. let child: ChildProcessWithoutNullStreams | undefined
  16. let workdir: string | undefined
  17. afterEach(async () => {
  18. if (child !== undefined && child.exitCode === null) child.kill('SIGKILL')
  19. child = undefined
  20. if (workdir !== undefined) await rm(workdir, { recursive: true, force: true })
  21. workdir = undefined
  22. })
  23. async function jsonlFiles(dir: string): Promise<string[]> {
  24. const entries = await readdir(dir, { withFileTypes: true })
  25. const paths = await Promise.all(entries.map(async (entry) => {
  26. const path = join(dir, entry.name)
  27. if (entry.isDirectory()) return jsonlFiles(path)
  28. return entry.isFile() && entry.name.endsWith('.jsonl') ? [path] : []
  29. }))
  30. return paths.flat()
  31. }
  32. async function runTwoTurns(): Promise<{ stdout: string; stderr: string }> {
  33. workdir = await mkdtemp(join(tmpdir(), 'time-context-e2e-'))
  34. const cwd = workdir
  35. return new Promise((resolve, reject) => {
  36. const proc = spawn(
  37. process.execPath,
  38. ['--expose-internals', '--import', tsxLoader, binScript, configPath],
  39. {
  40. cwd,
  41. env: {
  42. ...process.env,
  43. TZ: 'Asia/Shanghai',
  44. TSX_TSCONFIG_PATH: repoTsconfig,
  45. DSH_HOME: join(cwd, '.dsh'),
  46. DSH_AGENTS_HOME: join(cwd, '.agents'),
  47. },
  48. stdio: ['pipe', 'pipe', 'pipe'],
  49. },
  50. )
  51. child = proc
  52. let stdout = ''
  53. let stderr = ''
  54. let sentSecond = false
  55. proc.stdout.setEncoding('utf8')
  56. proc.stdout.on('data', (chunk: string) => {
  57. stdout += chunk
  58. if (!sentSecond && stdout.includes(`${FIRST_REPLY}\n> `)) {
  59. sentSecond = true
  60. proc.stdin.end('second\n')
  61. }
  62. })
  63. proc.stderr.setEncoding('utf8')
  64. proc.stderr.on('data', (chunk: string) => { stderr += chunk })
  65. const timer = setTimeout(() => {
  66. proc.kill('SIGKILL')
  67. reject(new Error(`time-context e2e did not exit within ${PROCESS_TIMEOUT_MS / 1_000}s. stdout:\n${stdout}\nstderr:\n${stderr}`))
  68. }, PROCESS_TIMEOUT_MS)
  69. proc.on('exit', (code) => {
  70. clearTimeout(timer)
  71. if (code === 0) resolve({ stdout, stderr })
  72. else reject(new Error(`time-context e2e exited ${code}. stdout:\n${stdout}\nstderr:\n${stderr}`))
  73. })
  74. proc.on('error', (error) => { clearTimeout(timer); reject(error) })
  75. proc.stdin.write('first\n')
  76. })
  77. }
  78. describe('time-context through a real cordis.yml and stdio process', () => {
  79. it('uses the process zone and persists both first-turn and elapsed-time request context', async () => {
  80. const { stdout, stderr } = await runTwoTurns()
  81. expect(stderr).not.toContain('UNHANDLED')
  82. expect(stdout).toContain('time-context e2e ready.')
  83. expect(stdout).toContain(FIRST_REPLY)
  84. expect(stdout).toContain('You said: "second".')
  85. const logs = await jsonlFiles(join(workdir as string, '.sessions'))
  86. expect(logs).toHaveLength(1)
  87. const lines = (await readFile(logs[0] as string, 'utf8')).trimEnd().split('\n')
  88. const events = lines.slice(1).map(line => JSON.parse(line) as SessionEvent)
  89. expect(events.filter(event => event.type === 'turn/end')).toHaveLength(2)
  90. const firstHeader = events.find(event => event.type === 'request/header')
  91. if (firstHeader?.type !== 'request/header') throw new Error('missing initial request/header event')
  92. expect(firstHeader.data.header.system).toMatch(
  93. /Current time: \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+08:00\[Asia\/Shanghai\]/,
  94. )
  95. expect(firstHeader.data.header.system).toContain(
  96. 'Time since previous message: unavailable (no earlier message in this session).',
  97. )
  98. const finalSystem = foldRequestHeader(events)?.system
  99. expect(finalSystem).toContain('[Asia/Shanghai]')
  100. expect(finalSystem).toMatch(
  101. /Time since previous message: (?:\d+d )?(?:\d+h )?(?:\d+m )?\d+s\./,
  102. )
  103. }, TEST_TIMEOUT_MS)
  104. })