child-process.spec.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. /**
  2. * The `node:child_process` face over the in-worker shell, and the ladder above
  3. * it: the REAL local subprocess service, running unmodified against this
  4. * module instead of a host kernel. The bash tool walks this same ladder in the
  5. * browser.
  6. *
  7. * A Node test host has no DOM `Worker`, so the commands here run through the
  8. * inline strategy; the worker strategy and its frames are proven in
  9. * `../shell/shell-process.spec.ts`.
  10. *
  11. * `process.kill` is redirected to the worker's process table for the same
  12. * reason the worker does it: the subprocess service polls process-group
  13. * liveness through it, and on a test host those pids belong to real processes.
  14. */
  15. import { afterEach, beforeEach, expect, it, vi } from 'vitest'
  16. import { MemoryVfs } from '@deepseek-ai/dsh-experimental-webworker-runtime/src/storage/memory.ts'
  17. import { setActiveVfs } from '@deepseek-ai/dsh-experimental-webworker-runtime/src/storage/active.ts'
  18. import { spawn, spawnSync } from '@deepseek-ai/dsh-experimental-webworker-runtime/src/node/builtin_modules/implemented/child_process.ts'
  19. import { processAlive, signalProcess } from '@deepseek-ai/dsh-experimental-webworker-runtime/src/node/process-table.ts'
  20. import { spawnSubprocess } from '@deepseek-ai/dsh-subprocess-local/src/spawn.ts'
  21. vi.mock('node:child_process', async () =>
  22. await import('@deepseek-ai/dsh-experimental-webworker-runtime/src/node/builtin_modules/implemented/child_process.ts'))
  23. const WORKSPACE = '/dsh/workspace'
  24. let vfs: MemoryVfs
  25. beforeEach(() => {
  26. vfs = new MemoryVfs()
  27. setActiveVfs(vfs)
  28. vfs.mkdirSync(WORKSPACE, { recursive: true })
  29. vi.spyOn(process, 'kill').mockImplementation((pid: number, signal?: string | number): true => {
  30. if (signal === 0) {
  31. if (processAlive(pid)) return true
  32. const error = new Error('kill ESRCH') as NodeJS.ErrnoException
  33. error.code = 'ESRCH'
  34. throw error
  35. }
  36. signalProcess(pid, (signal ?? 'SIGTERM') as NodeJS.Signals)
  37. return true
  38. })
  39. })
  40. afterEach(() => {
  41. vi.restoreAllMocks()
  42. })
  43. /** Collect one child's stdout, stderr, and settlement. */
  44. async function collect(child: ReturnType<typeof spawn>): Promise<{ stdout: string; stderr: string; code: number | null }> {
  45. let stdout = ''
  46. let stderr = ''
  47. child.stdout?.on('data', (chunk: unknown) => { stdout += String(chunk) })
  48. child.stderr?.on('data', (chunk: unknown) => { stderr += String(chunk) })
  49. const code = await new Promise<number | null>((settle, fail) => {
  50. child.on('close', (value: unknown) => { settle(value as number | null) })
  51. child.on('error', fail)
  52. })
  53. return { stdout, stderr, code }
  54. }
  55. it('runs a bash command line and reports its output through the pipes', async () => {
  56. const child = spawn('bash', ['-c', 'echo hi; echo oops >&2'], { cwd: WORKSPACE })
  57. expect(child.pid).toBeGreaterThan(1)
  58. expect(await collect(child)).toEqual({ stdout: 'hi\n', stderr: 'oops\n', code: 0 })
  59. })
  60. it('runs an explicit argv without re-parsing it as a command line', async () => {
  61. vfs.writeFileSync(`${WORKSPACE}/spaced name.txt`, 'kept\n')
  62. const child = spawn('cat', ['spaced name.txt'], { cwd: WORKSPACE })
  63. expect((await collect(child)).stdout).toBe('kept\n')
  64. })
  65. it('fails a program the command table does not hold the way a missing binary does', async () => {
  66. const child = spawn('nowhere-binary', [], { cwd: WORKSPACE })
  67. // A caller that configures the pipes first (the browser launcher does) must
  68. // reach the ENOENT, not a TypeError on the configuration line.
  69. child.stdout?.setEncoding()
  70. child.stderr?.setEncoding()
  71. const error = await new Promise<NodeJS.ErrnoException>((settle) => {
  72. child.on('error', (value: unknown) => { settle(value as NodeJS.ErrnoException) })
  73. })
  74. expect(error.code).toBe('ENOENT')
  75. expect(error.syscall).toBe('spawn nowhere-binary')
  76. })
  77. it('refuses a command name that is not a string, as Node does', () => {
  78. expect(() => spawn(undefined as unknown as string)).toThrow(/must be a non-empty string/)
  79. })
  80. it('reports that a synchronous run cannot happen, without throwing at the probe', () => {
  81. expect(spawnSync('bwrap').error?.code).toBe('ENOENT')
  82. expect(spawnSync('echo').error?.message).toContain('commands run asynchronously')
  83. })
  84. it('carries a command through the real local subprocess service', async () => {
  85. const handle = spawnSubprocess({
  86. argv: ['bash', '-c', 'echo written > note.txt && cat note.txt'],
  87. cwd: WORKSPACE,
  88. stdio: {
  89. stdin: 'ignore',
  90. stdout: { maxBytes: 64_000 },
  91. stderr: { maxBytes: 64_000 },
  92. },
  93. graceMs: 3_000,
  94. env: {},
  95. })
  96. const outcome = await handle.done
  97. expect(outcome).toEqual({ exitCode: 0, signal: null })
  98. expect(handle.collected.stdout?.readFrom(0).text).toBe('written\n')
  99. expect(vfs.readFileSync(`${WORKSPACE}/note.txt`, 'utf8')).toBe('written\n')
  100. })
  101. it('writes the caller-supplied standard input into the command', async () => {
  102. const handle = spawnSubprocess({
  103. argv: ['bash', '-c', 'grep -c ""'],
  104. cwd: WORKSPACE,
  105. stdio: {
  106. stdin: { data: 'one\ntwo\nthree\n' },
  107. stdout: { maxBytes: 64_000 },
  108. stderr: { maxBytes: 64_000 },
  109. },
  110. graceMs: 3_000,
  111. env: {},
  112. })
  113. await handle.done
  114. expect(handle.collected.stdout?.readFrom(0).text).toBe('3\n')
  115. })
  116. it('kills a running command through the service and reports the signal', async () => {
  117. const handle = spawnSubprocess({
  118. argv: ['bash', '-c', 'sleep 30; echo never'],
  119. cwd: WORKSPACE,
  120. stdio: {
  121. stdin: 'ignore',
  122. stdout: { maxBytes: 64_000 },
  123. stderr: { maxBytes: 64_000 },
  124. },
  125. graceMs: 3_000,
  126. env: {},
  127. })
  128. const started = performance.now()
  129. handle.terminate()
  130. const outcome = await handle.done
  131. expect(outcome.signal).toBe('SIGTERM')
  132. expect(outcome.exitCode).toBeNull()
  133. expect(handle.collected.stdout?.readFrom(0).text).toBe('')
  134. // The command settles on the signal, not on the interval it was waiting out:
  135. // a `sleep` that ignored the abort would hold this handle open for 30s.
  136. expect(performance.now() - started).toBeLessThan(5_000)
  137. })