executor.spec.ts 15 KB

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