executor.spec.ts 21 KB

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