executor.spec.ts 14 KB

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