executor.spec.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. /**
  2. * Real-process tests for `@deepseek-ai/dsh-pwsh-local`: the LOCAL subprocess
  3. * service plus a REAL pwsh executable, exercised through the executor seam
  4. * (`resolve` → `run`/`start`). These verify the world — actual PowerShell
  5. * runs, output capture, truncation and spill, deadlines, kill escalation, and
  6. * the background-handle contract. The suite self-skips when no usable `pwsh`
  7. * resolves (a CI accommodation for hosts without PowerShell); the pure unit tests
  8. * (config validation, executable resolution) run on every platform. PowerShell
  9. * writes CRLF on Windows, so exact text assertions normalize line endings.
  10. */
  11. import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
  12. import { tmpdir } from 'node:os'
  13. import { join } from 'node:path'
  14. import { spawnSync } from 'node:child_process'
  15. import { describe, expect, it } from 'vitest'
  16. import { Context } from 'cordis'
  17. import { PwshLocalExecutor, ENCODING_PREAMBLE, candidatePwshPaths, resolvePwshPath } from '@deepseek-ai/dsh-pwsh-local'
  18. import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local'
  19. import SubprocessService from '@deepseek-ai/dsh-subprocess'
  20. import type { SubprocessHandle, SubprocessOutputReader, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess'
  21. import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
  22. import type { BashProcess } from '@deepseek-ai/dsh-bash'
  23. const spillDir = mkdtempSync(join(tmpdir(), 'dsh-pwsh-exec-spec-'))
  24. // The probe follows the executor's own resolution (Program Files installs on
  25. // Windows are found even when bare `pwsh` is not on PATH).
  26. const hasPwsh = spawnSync(resolvePwshPath(), ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '$true'], { encoding: 'utf8' }).status === 0
  27. /** Normalize PowerShell's platform line endings (CRLF on Windows, LF elsewhere). */
  28. const lf = (text: string): string => text.replace(/\r\n/g, '\n')
  29. /** Case-insensitive path equality on Windows (Get-Location may re-case the drive). */
  30. function samePath(actual: string, expected: string): boolean {
  31. const norm = (value: string) => (process.platform === 'win32' ? value.toLowerCase() : value)
  32. return norm(actual) === norm(expected)
  33. }
  34. async function setup(config: ConstructorParameters<typeof PwshLocalExecutor>[1] = {}) {
  35. const ctx = new Context()
  36. await ctx.plugin(LocalSubprocessService)
  37. ;(ctx.subprocess as LocalSubprocessService).internals = { spillDir }
  38. // A short kill grace via the REAL config path, so escalation tests stay fast.
  39. await ctx.plugin(PwshLocalExecutor, { graceMs: 200, ...config })
  40. const bash = ctx.bash as PwshLocalExecutor
  41. return { ctx, bash }
  42. }
  43. /**
  44. * Poll a handle's consuming readOutput until the ACCUMULATED delta contains
  45. * `expected`; returns the accumulation (reads never re-deliver, so the caller
  46. * gets everything produced up to the match).
  47. */
  48. async function readUntil(proc: BashProcess, expected: string, timeoutMs = 5_000): Promise<string> {
  49. const deadline = Date.now() + timeoutMs
  50. let all = ''
  51. while (Date.now() < deadline) {
  52. all += proc.readOutput().delta
  53. if (lf(all).includes(expected)) return lf(all)
  54. await new Promise(resolve => setTimeout(resolve, 20))
  55. }
  56. throw new Error(`process output did not include ${JSON.stringify(expected)}; accumulated ${JSON.stringify(lf(all))}`)
  57. }
  58. describe('resolvePwshPath and candidatePwshPaths (pure, every platform)', () => {
  59. it('trusts an explicit configured path verbatim', () => {
  60. expect(resolvePwshPath('C:\\custom\\pwsh.exe')).toBe('C:\\custom\\pwsh.exe')
  61. expect(resolvePwshPath('pwsh')).toBe('pwsh')
  62. })
  63. it('falls through an empty configured path to platform resolution', () => {
  64. // SystemRoot points at a non-existent tree so the Windows PowerShell 5.1
  65. // fallback candidate cannot exist either.
  66. expect(resolvePwshPath('', { PATH: 'P:\\Store', SystemRoot: 'S:\\no-windows' }, 'win32')).toBe('pwsh')
  67. })
  68. it('returns pwsh on non-Windows platforms regardless of the environment', () => {
  69. expect(resolvePwshPath(undefined, { ProgramFiles: 'P:\\Program Files' }, 'linux')).toBe('pwsh')
  70. expect(resolvePwshPath(undefined, { PATH: 'P:\\Store' }, 'darwin')).toBe('pwsh')
  71. })
  72. it('lists PowerShell 7, PATH entries (quotes stripped), then Windows PowerShell 5.1 on win32', () => {
  73. const candidates = candidatePwshPaths({
  74. ProgramFiles: 'P:\\Program Files',
  75. SystemRoot: 'S:\\Windows',
  76. PATH: ';"Q:\\quoted store";' + ';',
  77. })
  78. expect(candidates).toEqual([
  79. join('P:\\Program Files', 'PowerShell', '7', 'pwsh.exe'),
  80. join('Q:\\quoted store', 'pwsh.exe'),
  81. join('S:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
  82. ])
  83. // A missing PATH contributes no entries (the empty-string fallback).
  84. expect(candidatePwshPaths({ ProgramFiles: 'P:\\Program Files', SystemRoot: 'S:\\Windows' }))
  85. .toEqual([
  86. join('P:\\Program Files', 'PowerShell', '7', 'pwsh.exe'),
  87. join('S:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
  88. ])
  89. })
  90. it('returns the first EXISTING win32 candidate, else pwsh', () => {
  91. const dir = mkdtempSync(join(tmpdir(), 'dsh-pwsh-resolve-'))
  92. const store = join(dir, 'store')
  93. mkdirSync(store, { recursive: true })
  94. writeFileSync(join(store, 'pwsh.exe'), '')
  95. // The existing PATH entry wins over the non-existent Program Files install.
  96. expect(resolvePwshPath(undefined, { ProgramFiles: join(dir, 'missing'), PATH: store }, 'win32'))
  97. .toBe(join(store, 'pwsh.exe'))
  98. // No candidate exists anywhere (SystemRoot points at a non-existent tree,
  99. // so even the Windows PowerShell 5.1 fallback cannot exist) → the
  100. // PATH-resolution fallback.
  101. expect(resolvePwshPath(undefined, { ProgramFiles: join(dir, 'missing'), PATH: join(dir, 'empty'), SystemRoot: join(dir, 'no-windows') }, 'win32'))
  102. .toBe('pwsh')
  103. })
  104. })
  105. describe('spawn construction (pure, every platform)', () => {
  106. /** A subprocess service that records spawn specs and settles instantly. */
  107. class CapturingSubprocessService extends SubprocessService {
  108. specs: SubprocessSpawnSpec[] = []
  109. private readonly reader: SubprocessOutputReader = {
  110. readFrom: () => ({ text: '', lossy: false, nextOffset: 0 }),
  111. }
  112. override spawn(spec: SubprocessSpawnSpec): SubprocessHandle {
  113. this.specs.push(spec)
  114. return {
  115. pid: -1,
  116. stdin: undefined,
  117. stdout: undefined,
  118. stderr: undefined,
  119. collected: { stdout: this.reader, stderr: this.reader },
  120. done: Promise.resolve({ exitCode: 0, signal: null }),
  121. terminate: () => {},
  122. waitForExit: async () => true,
  123. }
  124. }
  125. }
  126. it('runs every command as ONE argv element under the UTF-8 encoding preamble', async () => {
  127. const ctx = new Context()
  128. const subprocess = new CapturingSubprocessService(ctx)
  129. await ctx.plugin(PwshLocalExecutor)
  130. await ctx.bash.run(ctx.bash.resolve({ command: 'Write-Output 你好' }))
  131. expect(subprocess.specs).toHaveLength(1)
  132. const { argv } = subprocess.specs[0]!
  133. expect(argv.slice(0, 5)).toEqual([expect.any(String), '-NoLogo', '-NoProfile', '-NonInteractive', '-Command'])
  134. expect(argv[5]).toBe(`${ENCODING_PREAMBLE}Write-Output 你好`)
  135. expect(ENCODING_PREAMBLE).toContain('[Console]::OutputEncoding')
  136. expect(ENCODING_PREAMBLE).toContain('$OutputEncoding')
  137. })
  138. })
  139. describe.skipIf(!hasPwsh)('PwshLocalExecutor.run', () => {
  140. it('resolves with output and the effective timeout', async () => {
  141. const { bash } = await setup({ timeoutMs: 5_000 })
  142. const result = await bash.run(bash.resolve({ command: 'Write-Output hi' }))
  143. expect(result.exitCode).toBe(0)
  144. expect(lf(result.stdout.text)).toBe('hi\n')
  145. expect(result.timeoutMs).toBe(5_000)
  146. })
  147. it('uses config cwd, overridable per call', async () => {
  148. const first = mkdtempSync(join(tmpdir(), 'dsh-pwsh-cwd-a-'))
  149. const second = mkdtempSync(join(tmpdir(), 'dsh-pwsh-cwd-b-'))
  150. const { bash } = await setup({ cwd: first })
  151. const fromConfig = await bash.run(bash.resolve({ command: '(Get-Location).Path' }))
  152. expect(samePath(fromConfig.stdout.text.trim(), first)).toBe(true)
  153. const fromCall = await bash.run(bash.resolve({ command: '(Get-Location).Path', workdir: second }))
  154. expect(samePath(fromCall.stdout.text.trim(), second)).toBe(true)
  155. })
  156. it('defaults cwd to process.cwd()', async () => {
  157. const { bash } = await setup()
  158. const result = await bash.run(bash.resolve({ command: '(Get-Location).Path' }))
  159. expect(samePath(result.stdout.text.trim(), process.cwd())).toBe(true)
  160. })
  161. it('caps per-call timeouts at maxTimeoutMs', async () => {
  162. const { bash } = await setup({ timeoutMs: 1_000, maxTimeoutMs: 2_000 })
  163. const result = await bash.run(bash.resolve({ command: 'Write-Output ok', timeoutMs: 99_999 }))
  164. expect(result.timeoutMs).toBe(2_000)
  165. })
  166. it('rejects invalid numeric config and timeout overrides', async () => {
  167. await expect(setup({ timeoutMs: Number.NaN })).rejects.toThrow(/timeoutMs/)
  168. await expect(setup({ maxTimeoutMs: 0 })).rejects.toThrow(/maxTimeoutMs/)
  169. await expect(setup({ maxOutputBytes: -1 })).rejects.toThrow(/maxOutputBytes/)
  170. await expect(setup({ maxSpillBytes: 0 })).rejects.toThrow(/maxSpillBytes/)
  171. await expect(setup({ graceMs: 0 })).rejects.toThrow(/graceMs/)
  172. await expect(setup({ graceMs: MAX_TIMER_DELAY_MS + 1 }))
  173. .rejects.toThrow(`graceMs must be no greater than ${MAX_TIMER_DELAY_MS}`)
  174. const { bash } = await setup()
  175. expect(() => bash.resolve({ command: 'Write-Output ok', timeoutMs: Number.NaN })).toThrow(/request\.timeoutMs/)
  176. expect(() => bash.resolve({ command: 'Write-Output ok', timeoutMs: -1 })).toThrow(/request\.timeoutMs/)
  177. expect(() => bash.resolve({ command: 'Write-Output ok', stdoutMaxBytes: Number.NaN })).toThrow(/request\.stdoutMaxBytes/)
  178. expect(() => bash.resolve({ command: 'Write-Output ok', stdoutMaxBytes: -1 })).toThrow(/request\.stdoutMaxBytes/)
  179. })
  180. it('defaults stdoutMaxBytes to maxOutputBytes and lets foreground callers raise stdout only', async () => {
  181. const { bash } = await setup({ maxOutputBytes: 100 })
  182. expect(bash.resolve({ command: 'Write-Output ok' }).stdoutMaxBytes).toBe(100)
  183. // Raw Console writes avoid PowerShell's own line-ending and formatting
  184. // layers, so the byte counts are exact on every platform.
  185. const result = await bash.run(bash.resolve({
  186. command: '[Console]::Out.Write("x" * 500); [Console]::Error.WriteLine("e" * 500)',
  187. stdoutMaxBytes: 500,
  188. }))
  189. expect(result.stdout.text).toBe('x'.repeat(500))
  190. expect(result.stdout.truncated).toBe(false)
  191. expect(result.stderr.truncated).toBe(true)
  192. expect(result.stderr.text.length).toBeLessThanOrEqual(100)
  193. })
  194. it('per-call timeout takes precedence under the cap and kills on expiry', async () => {
  195. const { bash } = await setup({ timeoutMs: 60_000 })
  196. const result = await bash.run(bash.resolve({ command: 'Start-Sleep -Seconds 60', timeoutMs: 100 }))
  197. expect(result.timedOut).toBe(true)
  198. // Mutually exclusive: a timeout classifies as timedOut, never also aborted.
  199. expect(result.aborted).toBe(false)
  200. expect(result.timeoutMs).toBe(100)
  201. })
  202. it('propagates abort signals', async () => {
  203. const { bash } = await setup()
  204. const controller = new AbortController()
  205. const pending = bash.run(bash.resolve({ command: 'Start-Sleep -Seconds 60', signal: controller.signal }))
  206. setTimeout(() => { controller.abort() }, 50)
  207. const result = await pending
  208. expect(result.aborted).toBe(true)
  209. // Mutually exclusive: an upstream cancel classifies as aborted, never also timedOut.
  210. expect(result.timedOut).toBe(false)
  211. })
  212. it('classifies a self-killed command as neither timed out nor aborted', async () => {
  213. const { bash } = await setup({ timeoutMs: 60_000 })
  214. const result = await bash.run(bash.resolve({ command: 'Stop-Process -Id $PID' }))
  215. expect(result.timedOut).toBe(false)
  216. expect(result.aborted).toBe(false)
  217. // Windows reports a forced termination without a signal; POSIX reports the
  218. // terminating signal PowerShell chose (SIGTERM, or SIGKILL for the hard kill).
  219. if (process.platform === 'win32') {
  220. expect(result.signal).toBeNull()
  221. } else {
  222. expect(['SIGTERM', 'SIGKILL']).toContain(result.signal)
  223. }
  224. })
  225. it('rejects on spawn failure (bad workdir)', async () => {
  226. const { bash } = await setup()
  227. await expect(bash.run(bash.resolve({ command: 'Write-Output ok', workdir: '/nonexistent-dsh' }))).rejects.toThrow(/ENOENT/)
  228. })
  229. it('resolve() carries stdin/env/dshEnv onto the spec, and run() threads them to the command', async () => {
  230. const { bash } = await setup()
  231. const spec = bash.resolve({
  232. command: '$s = ([Console]::In.ReadToEnd()).TrimEnd(); Write-Output $s; Write-Output "[$env:SEAM_VAR][$env:DSH_SEAM_VAR]"',
  233. stdin: 'piped\n',
  234. env: { SEAM_VAR: 'env-ok' },
  235. dshEnv: { DSH_SEAM_VAR: 'dsh-ok' },
  236. })
  237. // resolve() keeps the optional input/environment fields verbatim.
  238. expect(spec.stdin).toBe('piped\n')
  239. expect(spec.env).toEqual({ SEAM_VAR: 'env-ok' })
  240. expect(spec.dshEnv).toEqual({ DSH_SEAM_VAR: 'dsh-ok' })
  241. const result = await bash.run(spec)
  242. expect(lf(result.stdout.text)).toBe('piped\n[env-ok][dsh-ok]\n')
  243. })
  244. it('resolve() omits stdin/env/dshEnv when the request supplies none', async () => {
  245. const { bash } = await setup()
  246. const spec = bash.resolve({ command: 'Write-Output ok' })
  247. expect('stdin' in spec).toBe(false)
  248. expect('env' in spec).toBe(false)
  249. expect('dshEnv' in spec).toBe(false)
  250. })
  251. })
  252. describe.skipIf(!hasPwsh)('PwshLocalExecutor.start (background process handles)', () => {
  253. it('start returns immediately with a running handle that settles as completed', async () => {
  254. const { bash } = await setup()
  255. const before = Date.now()
  256. const proc = bash.start(bash.resolve({ command: 'Start-Sleep -Milliseconds 200; Write-Output done' }))
  257. expect(Date.now() - before).toBeLessThan(150)
  258. expect(proc.status).toBe('running')
  259. await proc.done
  260. expect(proc.status).toBe('completed')
  261. expect(proc.exitCode).toBe(0)
  262. })
  263. it('threads stdin and extra env into a background process', async () => {
  264. const { bash } = await setup()
  265. const proc = bash.start(bash.resolve({
  266. command: '$s = ([Console]::In.ReadToEnd()).TrimEnd(); Write-Output $s; Write-Output "[$env:BG_VAR][$env:DSH_BG_VAR]"',
  267. stdin: 'bg-stdin\n',
  268. env: { BG_VAR: 'bg-env' },
  269. dshEnv: { DSH_BG_VAR: 'bg-dsh-env' },
  270. }))
  271. const output = await readUntil(proc, '[bg-env][bg-dsh-env]')
  272. expect(output).toBe('bg-stdin\n[bg-env][bg-dsh-env]\n')
  273. await proc.done
  274. expect(proc.exitCode).toBe(0)
  275. })
  276. it('readOutput is consuming: increments are never re-delivered, and reads stay valid after exit', async () => {
  277. const { bash } = await setup()
  278. const proc = bash.start(bash.resolve({ command: 'Write-Output first; Start-Sleep -Seconds 1; Write-Output second' }))
  279. const first = await readUntil(proc, 'first\n')
  280. expect(lf(first)).toBe('first\n')
  281. await proc.done
  282. // Read-after-exit returns the remaining buffered output — once.
  283. const second = proc.readOutput()
  284. expect(lf(second.delta)).toBe('second\n')
  285. expect(second.lossy).toBe(false)
  286. expect(proc.readOutput().delta).toBe('')
  287. })
  288. it('readOutput marks stderr sections', async () => {
  289. const { bash } = await setup()
  290. const proc = bash.start(bash.resolve({ command: 'Write-Output out; [Console]::Error.WriteLine("err")' }))
  291. await proc.done
  292. expect(lf(proc.readOutput().delta)).toBe('out\n[stderr]\nerr\n')
  293. })
  294. it('readOutput reports stderr-only deltas without a leading newline', async () => {
  295. const { bash } = await setup()
  296. const proc = bash.start(bash.resolve({ command: '[Console]::Error.WriteLine("err")' }))
  297. await proc.done
  298. expect(lf(proc.readOutput().delta)).toBe('[stderr]\nerr\n')
  299. })
  300. it('readOutput adds a separator only when stdout lacks a trailing newline', async () => {
  301. const { bash } = await setup()
  302. const proc = bash.start(bash.resolve({ command: '[Console]::Out.Write("out"); [Console]::Error.WriteLine("err")' }))
  303. await proc.done
  304. expect(lf(proc.readOutput().delta)).toBe('out\n[stderr]\nerr\n')
  305. })
  306. it('readOutput flags lossy reads and reports stdout spill paths', async () => {
  307. const { bash } = await setup({ maxOutputBytes: 100 })
  308. const proc = bash.start(bash.resolve({ command: '1..100 | ForEach-Object { "line-$_" }' }))
  309. await proc.done
  310. const read = proc.readOutput()
  311. // Window slid past offset 0 → lossy, spill path points at the full stream.
  312. expect(read.lossy).toBe(true)
  313. expect(read.stdoutSpillPath).toBeDefined()
  314. })
  315. it('readOutput reports stderr spill paths', async () => {
  316. const { bash } = await setup({ maxOutputBytes: 100 })
  317. const proc = bash.start(bash.resolve({ command: '1..100 | ForEach-Object { [Console]::Error.WriteLine("line-$_") }' }))
  318. await proc.done
  319. const read = proc.readOutput()
  320. expect(read.lossy).toBe(true)
  321. expect(read.stderrSpillPath).toBeDefined()
  322. expect(lf(read.delta)).toContain('[stderr]')
  323. })
  324. it('kill() terminates the process tree: true once, false after settlement', async () => {
  325. const { bash } = await setup()
  326. const proc = bash.start(bash.resolve({ command: 'Start-Sleep -Seconds 60' }))
  327. expect(proc.kill()).toBe(true)
  328. await proc.done
  329. expect(proc.status).toBe('killed')
  330. expect(proc.kill()).toBe(false)
  331. })
  332. it('kill() returns false for a naturally completed process', async () => {
  333. const { bash } = await setup()
  334. const proc = bash.start(bash.resolve({ command: 'Write-Output ok' }))
  335. await proc.done
  336. expect(proc.status).toBe('completed')
  337. expect(proc.kill()).toBe(false)
  338. })
  339. it('a spec.signal abort settles the handle as killed, not completed', async () => {
  340. const { bash } = await setup()
  341. const controller = new AbortController()
  342. const proc = bash.start(bash.resolve({ command: 'Start-Sleep -Seconds 60', signal: controller.signal }))
  343. controller.abort()
  344. await proc.done
  345. expect(proc.status).toBe('killed')
  346. })
  347. it.skipIf(process.platform === 'win32')('a self-signal exit settles the handle as killed, not completed (POSIX)', async () => {
  348. const { bash } = await setup()
  349. const proc = bash.start(bash.resolve({ command: 'Stop-Process -Id $PID' }))
  350. await proc.done
  351. expect(proc.status).toBe('killed')
  352. expect(proc.exitCode).toBeNull()
  353. // PowerShell picks SIGTERM for Stop-Process, SIGKILL for the hard kill.
  354. expect(['SIGTERM', 'SIGKILL']).toContain(proc.signal)
  355. })
  356. it('a background spawn failure settles as killed with the error readable on stderr', async () => {
  357. const { bash } = await setup()
  358. const proc = bash.start(bash.resolve({ command: 'Write-Output ok', workdir: '/nonexistent-dsh' }))
  359. // done resolves (never rejects) even though the process never ran.
  360. await expect(proc.done).resolves.toBeUndefined()
  361. expect(proc.status).toBe('killed')
  362. expect(proc.readOutput().delta).toContain('spawn failed:')
  363. })
  364. })
  365. describe.skipIf(!hasPwsh)('process lifecycle ownership (the subprocess service, not the executor)', () => {
  366. it('a background process survives executor-fiber disposal and dies with the subprocess service', async () => {
  367. const ctx = new Context()
  368. const managerFiber = await ctx.plugin(LocalSubprocessService)
  369. ;(ctx.subprocess as LocalSubprocessService).internals = { spillDir }
  370. const executorFiber = await ctx.plugin(PwshLocalExecutor, { graceMs: 200 })
  371. const bash = ctx.bash as PwshLocalExecutor
  372. // The child prints its own pid so the test can probe liveness through the
  373. // public read surface alone.
  374. const proc = bash.start(bash.resolve({ command: 'Write-Output $PID; Start-Sleep -Seconds 60' }))
  375. const pid = Number((await readUntil(proc, '\n')).trim())
  376. expect(Number.isInteger(pid) && pid > 0).toBe(true)
  377. // Executor reload/disposal leaves background work running — the
  378. // handle stays live and readable, mirroring the task runtime's
  379. // registrations-outlive-producer-fibers contract.
  380. await executorFiber.dispose()
  381. expect(proc.status).toBe('running')
  382. expect(() => process.kill(pid, 0)).not.toThrow()
  383. // Service disposal kills the group and AWAITS its exit (no orphans).
  384. await managerFiber.dispose()
  385. expect(() => process.kill(pid, 0)).toThrow()
  386. await proc.done
  387. // POSIX reports the kill as a signal; Windows reports a forced
  388. // termination as exit 1 with no signal (indistinguishable from a crash),
  389. // so the status stamp follows the platform's exit facts.
  390. expect(proc.status).toBe(process.platform === 'win32' ? 'completed' : 'killed')
  391. })
  392. it('service disposal settles running handles and leaves settled ones untouched', async () => {
  393. const ctx = new Context()
  394. const managerFiber = await ctx.plugin(LocalSubprocessService)
  395. ;(ctx.subprocess as LocalSubprocessService).internals = { spillDir }
  396. await ctx.plugin(PwshLocalExecutor, { graceMs: 200 })
  397. const bash = ctx.bash as PwshLocalExecutor
  398. const finished = bash.start(bash.resolve({ command: 'Write-Output done' }))
  399. await finished.done
  400. expect(finished.status).toBe('completed')
  401. const running = bash.start(bash.resolve({ command: 'Start-Sleep -Seconds 60' }))
  402. await managerFiber.dispose()
  403. // A settled process was untouched; the live one was terminated and joined.
  404. expect(finished.status).toBe('completed')
  405. await running.done
  406. expect(running.status).toBe(process.platform === 'win32' ? 'completed' : 'killed')
  407. })
  408. })