executor.spec.ts 14 KB

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