executor.spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. import { mkdtempSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { describe, expect, it } from 'vitest'
  5. import { Context } from 'cordis'
  6. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  7. import type { BashProcess } from '@deepseek-ai/dsh-bash'
  8. const spillDir = mkdtempSync(join(tmpdir(), 'dsh-bash-exec-spec-'))
  9. async function setup(config: ConstructorParameters<typeof LocalBashExecutor>[1] = {}) {
  10. const ctx = new Context()
  11. // A short kill grace via the REAL config path, so escalation tests stay fast.
  12. await ctx.plugin(LocalBashExecutor, { graceMs: 200, ...config })
  13. const bash = ctx.bash as LocalBashExecutor
  14. bash.internals = { spillDir }
  15. return { ctx, bash }
  16. }
  17. /**
  18. * Poll a handle's consuming readOutput until the ACCUMULATED delta contains
  19. * `expected`; returns the accumulation (reads never re-deliver, so the caller
  20. * gets everything produced up to the match).
  21. */
  22. async function readUntil(proc: BashProcess, expected: string, timeoutMs = 5_000): Promise<string> {
  23. const deadline = Date.now() + timeoutMs
  24. let all = ''
  25. while (Date.now() < deadline) {
  26. all += proc.readOutput().delta
  27. if (all.includes(expected)) return all
  28. await new Promise(resolve => setTimeout(resolve, 20))
  29. }
  30. throw new Error(`process output did not include ${JSON.stringify(expected)}; accumulated ${JSON.stringify(all)}`)
  31. }
  32. describe('LocalBashExecutor.run', () => {
  33. it('resolves with output and the effective timeout', async () => {
  34. const { bash } = await setup({ timeoutMs: 5_000 })
  35. const result = await bash.run(bash.resolve({ command: 'echo hi' }))
  36. expect(result.exitCode).toBe(0)
  37. expect(result.stdout.text).toBe('hi\n')
  38. expect(result.timeoutMs).toBe(5_000)
  39. })
  40. it('uses config cwd, overridable per call', async () => {
  41. const { bash } = await setup({ cwd: '/tmp' })
  42. const fromConfig = await bash.run(bash.resolve({ command: 'pwd' }))
  43. expect(fromConfig.stdout.text.trim()).toMatch(/\/tmp$/)
  44. const fromCall = await bash.run(bash.resolve({ command: 'pwd', workdir: '/' }))
  45. expect(fromCall.stdout.text.trim()).toBe('/')
  46. })
  47. it('defaults cwd to process.cwd()', async () => {
  48. const { bash } = await setup()
  49. const result = await bash.run(bash.resolve({ command: 'pwd' }))
  50. expect(result.stdout.text.trim()).toBe(process.cwd())
  51. })
  52. it('caps per-call timeouts at maxTimeoutMs', async () => {
  53. const { bash } = await setup({ timeoutMs: 1_000, maxTimeoutMs: 2_000 })
  54. const result = await bash.run(bash.resolve({ command: 'true', timeoutMs: 99_999 }))
  55. expect(result.timeoutMs).toBe(2_000)
  56. })
  57. it('rejects invalid numeric config and timeout overrides', async () => {
  58. await expect(setup({ timeoutMs: Number.NaN })).rejects.toThrow(/timeoutMs/)
  59. await expect(setup({ maxTimeoutMs: 0 })).rejects.toThrow(/maxTimeoutMs/)
  60. await expect(setup({ maxOutputBytes: -1 })).rejects.toThrow(/maxOutputBytes/)
  61. await expect(setup({ graceMs: 0 })).rejects.toThrow(/graceMs/)
  62. const { bash } = await setup()
  63. expect(() => bash.resolve({ command: 'true', timeoutMs: Number.NaN })).toThrow(/request\.timeoutMs/)
  64. expect(() => bash.resolve({ command: 'true', timeoutMs: -1 })).toThrow(/request\.timeoutMs/)
  65. })
  66. it('per-call timeout takes precedence under the cap and kills on expiry', async () => {
  67. const { bash } = await setup({ timeoutMs: 60_000 })
  68. const result = await bash.run(bash.resolve({ command: 'sleep 60', timeoutMs: 100 }))
  69. expect(result.timedOut).toBe(true)
  70. expect(result.timeoutMs).toBe(100)
  71. })
  72. it('propagates abort signals', async () => {
  73. const { bash } = await setup()
  74. const controller = new AbortController()
  75. const pending = bash.run(bash.resolve({ command: 'sleep 60', signal: controller.signal }))
  76. setTimeout(() => { controller.abort() }, 50)
  77. const result = await pending
  78. expect(result.aborted).toBe(true)
  79. })
  80. it('rejects on spawn failure (bad workdir)', async () => {
  81. const { bash } = await setup()
  82. await expect(bash.run(bash.resolve({ command: 'true', workdir: '/nonexistent-dsh' }))).rejects.toThrow(/ENOENT/)
  83. })
  84. it('resolve() carries stdin/env onto the spec, and run() threads them to the command', async () => {
  85. const { bash } = await setup()
  86. const spec = bash.resolve({ command: 'cat; echo "[$DSH_SEAM_VAR]"', stdin: 'piped\n', env: { DSH_SEAM_VAR: 'env-ok' } })
  87. // resolve() keeps the stdin/env fields verbatim (optional, no default).
  88. expect(spec.stdin).toBe('piped\n')
  89. expect(spec.env).toEqual({ DSH_SEAM_VAR: 'env-ok' })
  90. const result = await bash.run(spec)
  91. expect(result.stdout.text).toBe('piped\n[env-ok]\n')
  92. })
  93. it('resolve() omits stdin/env when the request supplies neither', async () => {
  94. const { bash } = await setup()
  95. const spec = bash.resolve({ command: 'true' })
  96. expect('stdin' in spec).toBe(false)
  97. expect('env' in spec).toBe(false)
  98. })
  99. })
  100. describe('LocalBashExecutor.start (background process handles)', () => {
  101. it('start returns immediately with a running handle that settles as completed', async () => {
  102. const { bash } = await setup()
  103. const before = Date.now()
  104. const proc = bash.start(bash.resolve({ command: 'sleep 0.2; echo done' }))
  105. expect(Date.now() - before).toBeLessThan(150)
  106. expect(proc.command).toBe('sleep 0.2; echo done')
  107. expect(proc.status).toBe('running')
  108. await proc.done
  109. expect(proc.status).toBe('completed')
  110. expect(proc.exitCode).toBe(0)
  111. })
  112. it('threads stdin and extra env into a background process', async () => {
  113. const { bash } = await setup()
  114. const proc = bash.start(bash.resolve({
  115. command: 'cat; echo "[$DSH_BG_VAR]"',
  116. stdin: 'bg-stdin\n',
  117. env: { DSH_BG_VAR: 'bg-env' },
  118. }))
  119. const output = await readUntil(proc, '[bg-env]')
  120. expect(output).toContain('bg-stdin')
  121. await proc.done
  122. expect(proc.exitCode).toBe(0)
  123. })
  124. it('readOutput is consuming: increments are never re-delivered, and reads stay valid after exit', async () => {
  125. const { bash } = await setup()
  126. const proc = bash.start(bash.resolve({ command: 'echo first; sleep 1; echo second' }))
  127. const first = await readUntil(proc, 'first\n')
  128. expect(first).toBe('first\n')
  129. await proc.done
  130. // Read-after-exit returns the remaining buffered output — once.
  131. const second = proc.readOutput()
  132. expect(second.delta).toBe('second\n')
  133. expect(second.lossy).toBe(false)
  134. expect(proc.readOutput().delta).toBe('')
  135. })
  136. it('readOutput marks stderr sections', async () => {
  137. const { bash } = await setup()
  138. const proc = bash.start(bash.resolve({ command: 'echo out; echo err >&2' }))
  139. await proc.done
  140. expect(proc.readOutput().delta).toBe('out\n[stderr]\nerr\n')
  141. })
  142. it('readOutput reports stderr-only deltas without a leading newline', async () => {
  143. const { bash } = await setup()
  144. const proc = bash.start(bash.resolve({ command: 'echo err >&2' }))
  145. await proc.done
  146. expect(proc.readOutput().delta).toBe('[stderr]\nerr\n')
  147. })
  148. it('readOutput adds a separator only when stdout lacks a trailing newline', async () => {
  149. const { bash } = await setup()
  150. const proc = bash.start(bash.resolve({ command: 'printf out; echo err >&2' }))
  151. await proc.done
  152. expect(proc.readOutput().delta).toBe('out\n[stderr]\nerr\n')
  153. })
  154. it('readOutput flags lossy reads and reports stdout spill paths', async () => {
  155. const { bash } = await setup({ maxOutputBytes: 100 })
  156. const proc = bash.start(bash.resolve({ command: 'for i in $(seq 1 100); do printf "line-%04d\\n" $i; done' }))
  157. await proc.done
  158. const read = proc.readOutput()
  159. // Window slid past offset 0 → lossy, spill path points at the full stream.
  160. expect(read.lossy).toBe(true)
  161. expect(read.stdoutSpillPath).toBeDefined()
  162. })
  163. it('readOutput reports stderr spill paths', async () => {
  164. const { bash } = await setup({ maxOutputBytes: 100 })
  165. const proc = bash.start(bash.resolve({ command: 'for i in $(seq 1 100); do printf "line-%04d\\n" $i >&2; done' }))
  166. await proc.done
  167. const read = proc.readOutput()
  168. expect(read.lossy).toBe(true)
  169. expect(read.stderrSpillPath).toBeDefined()
  170. expect(read.delta).toContain('[stderr]')
  171. })
  172. it('kill() terminates the process group: true once, false after settlement', async () => {
  173. const { bash } = await setup()
  174. const proc = bash.start(bash.resolve({ command: 'sleep 60' }))
  175. expect(proc.kill()).toBe(true)
  176. await proc.done
  177. expect(proc.status).toBe('killed')
  178. expect(proc.signal).toBe('SIGTERM')
  179. expect(proc.kill()).toBe(false)
  180. })
  181. it('kill() returns false for a naturally completed process', async () => {
  182. const { bash } = await setup()
  183. const proc = bash.start(bash.resolve({ command: 'true' }))
  184. await proc.done
  185. expect(proc.status).toBe('completed')
  186. expect(proc.kill()).toBe(false)
  187. })
  188. it('kill escalation uses the configured graceMs (a TERM-trapping process dies by SIGKILL)', async () => {
  189. const { bash } = await setup() // setup pins graceMs: 200 via config
  190. // The child echoes AFTER arming the trap, so waiting for the marker
  191. // guarantees SIGTERM is already ignored when the kill lands (a fixed sleep
  192. // is load-flaky: a slow spawn would take the SIGTERM before the trap).
  193. const proc = bash.start(bash.resolve({ command: 'trap \'\' TERM; echo armed; sleep 60' }))
  194. await readUntil(proc, 'armed')
  195. proc.kill()
  196. await proc.done
  197. expect(proc.status).toBe('killed')
  198. expect(proc.signal).toBe('SIGKILL')
  199. })
  200. it('a spec.signal abort settles the handle as killed, not completed', async () => {
  201. const { bash } = await setup()
  202. const controller = new AbortController()
  203. const proc = bash.start(bash.resolve({ command: 'sleep 60', signal: controller.signal }))
  204. controller.abort()
  205. await proc.done
  206. expect(proc.status).toBe('killed')
  207. expect(proc.signal).toBe('SIGTERM')
  208. })
  209. it('a background spawn failure settles as killed with the error readable on stderr', async () => {
  210. const { bash } = await setup()
  211. const proc = bash.start(bash.resolve({ command: 'true', workdir: '/nonexistent-dsh' }))
  212. // done resolves (never rejects) even though the process never ran.
  213. await expect(proc.done).resolves.toBeUndefined()
  214. expect(proc.status).toBe('killed')
  215. expect(proc.readOutput().delta).toContain('spawn failed:')
  216. })
  217. })
  218. describe('LocalBashExecutor disposal', () => {
  219. it('disposing the fiber kills running processes and AWAITS their exit (no orphans, SIGKILL escalation included)', async () => {
  220. const ctx = new Context()
  221. const fiber = await ctx.plugin(LocalBashExecutor, { graceMs: 200 })
  222. const bash = ctx.bash as LocalBashExecutor
  223. bash.internals = { spillDir }
  224. // The child prints its own pid ($$ = the detached bash group leader) so
  225. // the test can probe liveness through the public read surface alone.
  226. const proc = bash.start(bash.resolve({ command: 'trap \'\' TERM; echo $$; sleep 60' }))
  227. const pid = Number((await readUntil(proc, '\n')).trim())
  228. expect(Number.isInteger(pid) && pid > 0).toBe(true)
  229. await fiber.dispose()
  230. // Disposal itself waited: the pid must already be gone, no grace left —
  231. // even for a TERM-trapping child held until the SIGKILL escalation landed.
  232. expect(() => process.kill(pid, 0)).toThrow()
  233. expect(proc.status).toBe('killed')
  234. await proc.done
  235. })
  236. it('settled processes already left the live map: dispose does not touch them', async () => {
  237. const ctx = new Context()
  238. const fiber = await ctx.plugin(LocalBashExecutor, { graceMs: 200 })
  239. const bash = ctx.bash as LocalBashExecutor
  240. bash.internals = { spillDir }
  241. const finished = bash.start(bash.resolve({ command: 'echo done' }))
  242. await finished.done
  243. expect(finished.status).toBe('completed')
  244. const running = bash.start(bash.resolve({ command: 'sleep 60' }))
  245. await fiber.dispose()
  246. // The teardown marks every LIVE entry killed; a settled process had
  247. // already left the map, so its status stays completed.
  248. expect(finished.status).toBe('completed')
  249. expect(running.status).toBe('killed')
  250. await running.done
  251. expect(running.signal).toBe('SIGTERM')
  252. })
  253. })