executor.spec.ts 22 KB

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