executor.spec.ts 12 KB

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