executor.spec.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. import { mkdtempSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { describe, expect, it, vi } from 'vitest'
  5. import { Context } from 'cordis'
  6. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  7. import { BashTaskId } from '@deepseek-ai/dsh-bash'
  8. import type { BashTaskRead } from '@deepseek-ai/dsh-bash'
  9. const spillDir = mkdtempSync(join(tmpdir(), 'dsh-bash-exec-spec-'))
  10. async function setup(config: ConstructorParameters<typeof LocalBashExecutor>[1] = {}) {
  11. const ctx = new Context()
  12. // A short kill grace via the REAL config path, so escalation tests stay fast.
  13. await ctx.plugin(LocalBashExecutor, { graceMs: 200, ...config })
  14. const bash = ctx.bash as LocalBashExecutor
  15. bash.internals = { spillDir }
  16. return { ctx, bash }
  17. }
  18. /** Poll until a pid no longer exists. */
  19. async function waitGone(pid: number, timeoutMs = 5_000): Promise<void> {
  20. const deadline = Date.now() + timeoutMs
  21. while (Date.now() < deadline) {
  22. try {
  23. process.kill(pid, 0)
  24. } catch {
  25. return
  26. }
  27. await new Promise(resolve => setTimeout(resolve, 20))
  28. }
  29. throw new Error(`pid ${pid} still alive after ${timeoutMs}ms`)
  30. }
  31. async function readUntil(
  32. bash: LocalBashExecutor,
  33. id: BashTaskId,
  34. expected: string,
  35. timeoutMs = 5_000,
  36. ): Promise<BashTaskRead> {
  37. const deadline = Date.now() + timeoutMs
  38. let last: BashTaskRead | undefined
  39. let delta = ''
  40. while (Date.now() < deadline) {
  41. last = bash.readOutput(id)
  42. delta += last.delta
  43. if (delta.includes(expected)) return { ...last, delta }
  44. await new Promise(resolve => setTimeout(resolve, 20))
  45. }
  46. throw new Error(`task ${id} output did not include ${JSON.stringify(expected)}; output was ${JSON.stringify(delta)}, last delta was ${JSON.stringify(last?.delta ?? '')}`)
  47. }
  48. describe('LocalBashExecutor.run', () => {
  49. it('resolves with output and the effective timeout', async () => {
  50. const { bash } = await setup({ timeoutMs: 5_000 })
  51. const result = await bash.run(bash.resolve({ command: 'echo hi' }))
  52. expect(result.exitCode).toBe(0)
  53. expect(result.stdout.text).toBe('hi\n')
  54. expect(result.timeoutMs).toBe(5_000)
  55. })
  56. it('uses config cwd, overridable per call', async () => {
  57. const { bash } = await setup({ cwd: '/tmp' })
  58. const fromConfig = await bash.run(bash.resolve({ command: 'pwd' }))
  59. expect(fromConfig.stdout.text.trim()).toMatch(/\/tmp$/)
  60. const fromCall = await bash.run(bash.resolve({ command: 'pwd', workdir: '/' }))
  61. expect(fromCall.stdout.text.trim()).toBe('/')
  62. })
  63. it('defaults cwd to process.cwd()', async () => {
  64. const { bash } = await setup()
  65. const result = await bash.run(bash.resolve({ command: 'pwd' }))
  66. expect(result.stdout.text.trim()).toBe(process.cwd())
  67. })
  68. it('caps per-call timeouts at maxTimeoutMs', async () => {
  69. const { bash } = await setup({ timeoutMs: 1_000, maxTimeoutMs: 2_000 })
  70. const result = await bash.run(bash.resolve({ command: 'true', timeoutMs: 99_999 }))
  71. expect(result.timeoutMs).toBe(2_000)
  72. })
  73. it('rejects invalid numeric config and timeout overrides', async () => {
  74. await expect(setup({ timeoutMs: Number.NaN })).rejects.toThrow(/timeoutMs/)
  75. await expect(setup({ maxTimeoutMs: 0 })).rejects.toThrow(/maxTimeoutMs/)
  76. await expect(setup({ maxOutputBytes: -1 })).rejects.toThrow(/maxOutputBytes/)
  77. await expect(setup({ graceMs: 0 })).rejects.toThrow(/graceMs/)
  78. const { bash } = await setup()
  79. expect(() => bash.resolve({ command: 'true', timeoutMs: Number.NaN })).toThrow(/request\.timeoutMs/)
  80. expect(() => bash.resolve({ command: 'true', timeoutMs: -1 })).toThrow(/request\.timeoutMs/)
  81. })
  82. it('kill escalation uses the configured graceMs (a TERM-trapping task dies by SIGKILL)', async () => {
  83. const { bash } = await setup() // setup pins graceMs: 200 via config
  84. const task = bash.start(bash.resolve({ command: 'trap \'\' TERM; echo ready; while :; do sleep 60 & wait $!; done' }))
  85. await readUntil(bash, task.id, 'ready\n')
  86. bash.kill(task.id)
  87. await task.done
  88. expect(task.signal).toBe('SIGKILL')
  89. })
  90. it('per-call timeout takes precedence under the cap and kills on expiry', async () => {
  91. const { bash } = await setup({ timeoutMs: 60_000 })
  92. const result = await bash.run(bash.resolve({ command: 'sleep 60', timeoutMs: 100 }))
  93. expect(result.timedOut).toBe(true)
  94. // Mutually exclusive: a timeout classifies as timedOut, never also aborted.
  95. expect(result.aborted).toBe(false)
  96. expect(result.timeoutMs).toBe(100)
  97. })
  98. it('propagates abort signals', async () => {
  99. const { bash } = await setup()
  100. const controller = new AbortController()
  101. const pending = bash.run(bash.resolve({ command: 'sleep 60', signal: controller.signal }))
  102. setTimeout(() => { controller.abort() }, 50)
  103. const result = await pending
  104. expect(result.aborted).toBe(true)
  105. // Mutually exclusive: an upstream cancel classifies as aborted, never also timedOut.
  106. expect(result.timedOut).toBe(false)
  107. })
  108. it('classifies a self-killed command as neither timed out nor aborted', async () => {
  109. // The command kills itself (SIGTERM) with no timeout and no upstream abort:
  110. // the deadline signal never fires, so both classifications are false — the
  111. // fused-signal classification reports the cause that cut the command short,
  112. // and here nothing the executor owns did.
  113. const { bash } = await setup({ timeoutMs: 60_000 })
  114. const result = await bash.run(bash.resolve({ command: 'kill -TERM $$' }))
  115. expect(result.signal).toBe('SIGTERM')
  116. expect(result.timedOut).toBe(false)
  117. expect(result.aborted).toBe(false)
  118. })
  119. it('rejects on spawn failure (bad workdir)', async () => {
  120. const { bash } = await setup()
  121. await expect(bash.run(bash.resolve({ command: 'true', workdir: '/nonexistent-dsh' }))).rejects.toThrow(/ENOENT/)
  122. })
  123. it('resolve() carries stdin/env onto the spec, and run() threads them to the command', async () => {
  124. const { bash } = await setup()
  125. const spec = bash.resolve({ command: 'cat; echo "[$DSH_SEAM_VAR]"', stdin: 'piped\n', env: { DSH_SEAM_VAR: 'env-ok' } })
  126. // resolve() keeps the stdin/env fields verbatim (optional, no default).
  127. expect(spec.stdin).toBe('piped\n')
  128. expect(spec.env).toEqual({ DSH_SEAM_VAR: 'env-ok' })
  129. const result = await bash.run(spec)
  130. expect(result.stdout.text).toBe('piped\n[env-ok]\n')
  131. })
  132. it('resolve() omits stdin/env when the request supplies neither', async () => {
  133. const { bash } = await setup()
  134. const spec = bash.resolve({ command: 'true' })
  135. expect('stdin' in spec).toBe(false)
  136. expect('env' in spec).toBe(false)
  137. })
  138. })
  139. describe('LocalBashExecutor background tasks', () => {
  140. it('start returns immediately with a registered running task', async () => {
  141. const { bash } = await setup()
  142. const before = Date.now()
  143. const task = bash.start(bash.resolve({ command: 'sleep 0.2; echo done' }))
  144. expect(Date.now() - before).toBeLessThan(150)
  145. expect(task.status).toBe('running')
  146. expect(bash.get(task.id)).toBe(task)
  147. expect(bash.list()).toContain(task)
  148. await task.done
  149. expect(task.status).toBe('completed')
  150. expect(task.exitCode).toBe(0)
  151. })
  152. it('assigns sequential ids', async () => {
  153. const { bash } = await setup()
  154. const first = bash.start(bash.resolve({ command: 'true' }))
  155. const second = bash.start(bash.resolve({ command: 'true' }))
  156. expect(first.id).toBe('bash-1')
  157. expect(second.id).toBe('bash-2')
  158. await Promise.all([first.done, second.done])
  159. })
  160. it('threads stdin and extra env into a background task', async () => {
  161. const { bash } = await setup()
  162. const task = bash.start(bash.resolve({
  163. command: 'cat; echo "[$DSH_BG_VAR]"',
  164. stdin: 'bg-stdin\n',
  165. env: { DSH_BG_VAR: 'bg-env' },
  166. }))
  167. const read = await readUntil(bash, task.id, '[bg-env]')
  168. expect(read.delta).toContain('bg-stdin')
  169. await task.done
  170. expect(task.exitCode).toBe(0)
  171. })
  172. it('readOutput returns increments without re-delivery', async () => {
  173. const { bash } = await setup()
  174. const task = bash.start(bash.resolve({ command: 'echo first; sleep 1; echo second' }))
  175. const first = await readUntil(bash, task.id, 'first\n')
  176. expect(first.delta).toBe('first\n')
  177. expect(first.lossy).toBe(false)
  178. await task.done
  179. const second = bash.readOutput(task.id)
  180. expect(second.delta).toBe('second\n')
  181. const third = bash.readOutput(task.id)
  182. expect(third.delta).toBe('')
  183. })
  184. it('readOutput marks stderr sections', async () => {
  185. const { bash } = await setup()
  186. const task = bash.start(bash.resolve({ command: 'echo out; echo err >&2' }))
  187. await task.done
  188. const read = bash.readOutput(task.id)
  189. expect(read.delta).toBe('out\n[stderr]\nerr\n')
  190. })
  191. it('readOutput reports stderr-only deltas without a leading newline', async () => {
  192. const { bash } = await setup()
  193. const task = bash.start(bash.resolve({ command: 'echo err >&2' }))
  194. await task.done
  195. expect(bash.readOutput(task.id).delta).toBe('[stderr]\nerr\n')
  196. })
  197. it('readOutput flags lossy reads and reports spill paths', async () => {
  198. const { bash } = await setup({ maxOutputBytes: 100 })
  199. const task = bash.start(bash.resolve({ command: 'for i in $(seq 1 100); do printf "line-%04d\\n" $i; done' }))
  200. await task.done
  201. const read = bash.readOutput(task.id)
  202. // Window slid past offset 0 → lossy, spill path points at the full stream.
  203. expect(read.lossy).toBe(true)
  204. expect(read.stdoutSpillPath).toBeDefined()
  205. })
  206. it('readOutput throws for unknown ids', async () => {
  207. const { bash } = await setup()
  208. expect(() => bash.readOutput(BashTaskId('nope'))).toThrow(/unknown bash task "nope"/)
  209. })
  210. it('kill terminates the process group and reports status killed', async () => {
  211. const { bash } = await setup()
  212. const task = bash.start(bash.resolve({ command: 'sleep 60' }))
  213. expect(bash.kill(task.id)).toBe(true)
  214. await task.done
  215. expect(task.status).toBe('killed')
  216. expect(task.signal).toBe('SIGTERM')
  217. })
  218. it('kill returns false for finished tasks and throws for unknown ids', async () => {
  219. const { bash } = await setup()
  220. const task = bash.start(bash.resolve({ command: 'true' }))
  221. await task.done
  222. expect(bash.kill(task.id)).toBe(false)
  223. expect(() => bash.kill(BashTaskId('nope'))).toThrow(/unknown bash task "nope"/)
  224. })
  225. it('notifies onTaskDone listeners on completion', async () => {
  226. const { bash } = await setup()
  227. const seen: [string, string][] = []
  228. bash.onTaskDone(task => void seen.push([task.id, task.status]))
  229. const task = bash.start(bash.resolve({ command: 'true' }))
  230. await task.done
  231. expect(seen).toEqual([[task.id, 'completed']])
  232. })
  233. it('notifies onTaskDone for killed tasks too', async () => {
  234. const { bash } = await setup()
  235. const listener = vi.fn()
  236. bash.onTaskDone(listener)
  237. const task = bash.start(bash.resolve({ command: 'sleep 60' }))
  238. bash.kill(task.id)
  239. await task.done
  240. expect(listener).toHaveBeenCalledWith(task)
  241. expect(task.status).toBe('killed')
  242. })
  243. it('marks tasks killed when the background spawn itself fails', async () => {
  244. const { bash } = await setup()
  245. const listener = vi.fn()
  246. bash.onTaskDone(listener)
  247. const task = bash.start(bash.resolve({ command: 'true', workdir: '/nonexistent-dsh' }))
  248. await task.done
  249. expect(task.status).toBe('killed')
  250. expect(listener).toHaveBeenCalledWith(task)
  251. expect(bash.readOutput(task.id).delta).toContain('spawn failed')
  252. })
  253. it('readOutput adds a separator only when stdout lacks a trailing newline', async () => {
  254. const { bash } = await setup()
  255. const task = bash.start(bash.resolve({ command: 'printf out; echo err >&2' }))
  256. await task.done
  257. expect(bash.readOutput(task.id).delta).toBe('out\n[stderr]\nerr\n')
  258. })
  259. it('readOutput reports stderr spill paths', async () => {
  260. const { bash } = await setup({ maxOutputBytes: 100 })
  261. const task = bash.start(bash.resolve({ command: 'for i in $(seq 1 100); do printf "line-%04d\\n" $i >&2; done' }))
  262. await task.done
  263. const read = bash.readOutput(task.id)
  264. expect(read.lossy).toBe(true)
  265. expect(read.stderrSpillPath).toBeDefined()
  266. expect(read.delta).toContain('[stderr]')
  267. })
  268. it('disposing with already-finished tasks only kills the running ones', async () => {
  269. const ctx = new Context()
  270. const fiber = await ctx.plugin(LocalBashExecutor, { graceMs: 200 })
  271. const bash = ctx.bash as LocalBashExecutor
  272. bash.internals = { spillDir }
  273. const finished = bash.start(bash.resolve({ command: 'true' }))
  274. await finished.done
  275. const running = bash.start(bash.resolve({ command: 'sleep 60' }))
  276. await fiber.dispose()
  277. await running.done
  278. expect(finished.status).toBe('completed')
  279. expect(running.signal).toBe('SIGTERM')
  280. expect(bash.list()).toEqual([])
  281. })
  282. it('disposing the executor fiber kills running tasks (no orphans)', async () => {
  283. const ctx = new Context()
  284. const fiber = await ctx.plugin(LocalBashExecutor, { graceMs: 200 })
  285. const bash = ctx.bash as LocalBashExecutor
  286. bash.internals = { spillDir }
  287. const listener = vi.fn()
  288. bash.onTaskDone(listener)
  289. const task = bash.start(bash.resolve({ command: 'sleep 60' }))
  290. const running = bash.get(task.id)!
  291. await new Promise(resolve => setTimeout(resolve, 50))
  292. // Grab the pid before dispose clears the registry.
  293. const pid = (running as unknown as { running: { pid: number } }).running.pid
  294. await fiber.dispose()
  295. await waitGone(pid)
  296. expect(bash.list()).toEqual([])
  297. // Listener silenced by base-class teardown — no late notifications.
  298. expect(listener).not.toHaveBeenCalled()
  299. })
  300. })
  301. describe('executor cancellation, callback, and disposal contracts', () => {
  302. it('start honors a pre-aborted or later-aborted AbortSignal', async () => {
  303. const { bash } = await setup()
  304. const controller = new AbortController()
  305. const task = bash.start(bash.resolve({ command: 'sleep 60', signal: controller.signal }))
  306. controller.abort()
  307. await task.done
  308. expect(task.status).toBe('killed')
  309. expect(task.signal).toBe('SIGTERM')
  310. })
  311. it('a throwing onTaskDone listener does not reject task.done or starve later listeners', async () => {
  312. const { bash } = await setup()
  313. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  314. const second = vi.fn()
  315. try {
  316. bash.onTaskDone(() => { throw new Error('listener bug') })
  317. bash.onTaskDone(second)
  318. const task = bash.start(bash.resolve({ command: 'true' }))
  319. await expect(task.done).resolves.toBeUndefined()
  320. expect(second).toHaveBeenCalledWith(task)
  321. expect(errorSpy).toHaveBeenCalled()
  322. } finally {
  323. errorSpy.mockRestore()
  324. }
  325. })
  326. it('dispose AWAITS a TERM-trapping process (SIGKILL escalation included)', async () => {
  327. const ctx = new Context()
  328. const fiber = await ctx.plugin(LocalBashExecutor, { graceMs: 200 })
  329. const bash = ctx.bash as LocalBashExecutor
  330. bash.internals = { spillDir }
  331. const task = bash.start(bash.resolve({ command: 'trap \'\' TERM; sleep 60' }))
  332. await new Promise(resolve => setTimeout(resolve, 100))
  333. const pid = (task as unknown as { running: { pid: number } }).running.pid
  334. await fiber.dispose()
  335. // Disposal itself waited: the pid must already be gone, no grace left.
  336. expect(() => process.kill(pid, 0)).toThrow()
  337. expect(task.status).toBe('killed')
  338. })
  339. })