executor.spec.ts 11 KB

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