executor.spec.ts 16 KB

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