executor.spec.ts 12 KB

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