executor.spec.ts 16 KB

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