executor.spec.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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, symlinkSync, 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 LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
  19. import SubprocessRuntime 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 { ShellProcess } from '@deepseek-ai/dsh-shell'
  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(LocalSubprocessRuntime)
  39. ;(ctx.subprocess as LocalSubprocessRuntime).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.shell 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: ShellProcess, 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. it('accepts a link-shaped PATH candidate whose target cannot be stat-ed', () => {
  117. // Store app execution aliases stat as EACCES but lstat as a link; a
  118. // dangling symlink reproduces that split on every platform.
  119. const dir = mkdtempSync(join(tmpdir(), 'dsh-pwsh-resolve-link-'))
  120. const store = join(dir, 'store')
  121. mkdirSync(store, { recursive: true })
  122. const link = join(store, 'pwsh.exe')
  123. symlinkSync(join(dir, 'no-such-target.exe'), link)
  124. expect(resolvePwshPath(undefined, { ProgramFiles: join(dir, 'missing'), PATH: store }, 'win32'))
  125. .toBe(link)
  126. })
  127. it('skips a directory candidate and falls through to the PATH-resolution default', () => {
  128. const dir = mkdtempSync(join(tmpdir(), 'dsh-pwsh-resolve-dir-'))
  129. const store = join(dir, 'store')
  130. mkdirSync(join(store, 'pwsh.exe'), { recursive: true })
  131. expect(resolvePwshPath(undefined, {
  132. ProgramFiles: join(dir, 'missing'),
  133. PATH: store,
  134. SystemRoot: join(dir, 'no-windows'),
  135. }, 'win32')).toBe('pwsh')
  136. })
  137. })
  138. describe('spawn construction (pure, every platform)', () => {
  139. /** A subprocess service that records spawn specs and settles instantly. */
  140. class CapturingSubprocessRuntime extends SubprocessRuntime {
  141. specs: SubprocessSpawnSpec[] = []
  142. override async resolveExecutable(command: string): Promise<string> { return command }
  143. override spawnTerminal(): Promise<never> { throw new Error('pwsh spawns pipes, never terminals') }
  144. private readonly reader: SubprocessOutputReader = {
  145. readFrom: () => ({ text: '', lossy: false, nextOffset: 0 }),
  146. }
  147. override spawn(spec: SubprocessSpawnSpec): SubprocessHandle {
  148. this.specs.push(spec)
  149. return {
  150. pid: -1,
  151. stdin: undefined,
  152. stdout: undefined,
  153. stderr: undefined,
  154. collected: { stdout: this.reader, stderr: this.reader },
  155. done: Promise.resolve({ exitCode: 0, signal: null }),
  156. terminate: () => {},
  157. waitForExit: async () => true,
  158. }
  159. }
  160. }
  161. it('runs every command as ONE argv element under the UTF-8 encoding preamble', async () => {
  162. const ctx = new Context()
  163. const subprocess = new CapturingSubprocessRuntime(ctx)
  164. await ctx.plugin(PwshLocalExecutor)
  165. await ctx.shell.run(ctx.shell.resolve({ command: 'Write-Output 你好' }))
  166. expect(subprocess.specs).toHaveLength(1)
  167. const { argv } = subprocess.specs[0]!
  168. expect(argv.slice(0, 5)).toEqual([expect.any(String), '-NoLogo', '-NoProfile', '-NonInteractive', '-Command'])
  169. expect(argv[5]).toBe(`${ENCODING_PREAMBLE}Write-Output 你好`)
  170. expect(ENCODING_PREAMBLE).toContain('[Console]::OutputEncoding')
  171. expect(ENCODING_PREAMBLE).toContain('$OutputEncoding')
  172. })
  173. })
  174. describe.skipIf(!hasPwsh)('PwshLocalExecutor.run', () => {
  175. it('resolves with output and the effective timeout', { timeout: 15_000 }, async () => {
  176. const { bash } = await setup({ timeoutMs: 10_000 })
  177. const result = await bash.run(bash.resolve({ command: 'Write-Output hi' }))
  178. expect(result.exitCode).toBe(0)
  179. expect(lf(result.stdout.text)).toBe('hi\n')
  180. expect(result.timeoutMs).toBe(10_000)
  181. })
  182. it('uses config cwd, overridable per call', async () => {
  183. const first = mkdtempSync(join(tmpdir(), 'dsh-pwsh-cwd-a-'))
  184. const second = mkdtempSync(join(tmpdir(), 'dsh-pwsh-cwd-b-'))
  185. const { bash } = await setup({ cwd: first })
  186. const fromConfig = await bash.run(bash.resolve({ command: '(Get-Location).Path' }))
  187. expect(samePath(fromConfig.stdout.text.trim(), first)).toBe(true)
  188. const fromCall = await bash.run(bash.resolve({ command: '(Get-Location).Path', workdir: second }))
  189. expect(samePath(fromCall.stdout.text.trim(), second)).toBe(true)
  190. })
  191. it('defaults cwd to process.cwd()', async () => {
  192. const { bash } = await setup()
  193. const result = await bash.run(bash.resolve({ command: '(Get-Location).Path' }))
  194. expect(samePath(result.stdout.text.trim(), process.cwd())).toBe(true)
  195. })
  196. it('caps per-call timeouts at maxTimeoutMs', async () => {
  197. const { bash } = await setup({ timeoutMs: 1_000, maxTimeoutMs: 2_000 })
  198. const result = await bash.run(bash.resolve({ command: 'Write-Output ok', timeoutMs: 99_999 }))
  199. expect(result.timeoutMs).toBe(2_000)
  200. })
  201. it('rejects invalid numeric config and timeout overrides', async () => {
  202. await expect(setup({ timeoutMs: Number.NaN })).rejects.toThrow(/timeoutMs/)
  203. await expect(setup({ maxTimeoutMs: 0 })).rejects.toThrow(/maxTimeoutMs/)
  204. await expect(setup({ maxOutputBytes: -1 })).rejects.toThrow(/maxOutputBytes/)
  205. await expect(setup({ maxSpillBytes: 0 })).rejects.toThrow(/maxSpillBytes/)
  206. await expect(setup({ graceMs: 0 })).rejects.toThrow(/graceMs/)
  207. await expect(setup({ graceMs: MAX_TIMER_DELAY_MS + 1 }))
  208. .rejects.toThrow(`graceMs must be no greater than ${MAX_TIMER_DELAY_MS}`)
  209. const { bash } = await setup()
  210. expect(() => bash.resolve({ command: 'Write-Output ok', timeoutMs: Number.NaN })).toThrow(/request\.timeoutMs/)
  211. expect(() => bash.resolve({ command: 'Write-Output ok', timeoutMs: -1 })).toThrow(/request\.timeoutMs/)
  212. expect(() => bash.resolve({ command: 'Write-Output ok', stdoutMaxBytes: Number.NaN })).toThrow(/request\.stdoutMaxBytes/)
  213. expect(() => bash.resolve({ command: 'Write-Output ok', stdoutMaxBytes: -1 })).toThrow(/request\.stdoutMaxBytes/)
  214. })
  215. it('defaults stdoutMaxBytes to maxOutputBytes and lets foreground callers raise stdout only', async () => {
  216. const { bash } = await setup({ maxOutputBytes: 100 })
  217. expect(bash.resolve({ command: 'Write-Output ok' }).stdoutMaxBytes).toBe(100)
  218. // Raw Console writes avoid PowerShell's own line-ending and formatting
  219. // layers, so the byte counts are exact on every platform.
  220. const result = await bash.run(bash.resolve({
  221. command: '[Console]::Out.Write("x" * 500); [Console]::Error.WriteLine("e" * 500)',
  222. stdoutMaxBytes: 500,
  223. }))
  224. expect(result.stdout.text).toBe('x'.repeat(500))
  225. expect(result.stdout.truncated).toBe(false)
  226. expect(result.stderr.truncated).toBe(true)
  227. expect(result.stderr.text.length).toBeLessThanOrEqual(100)
  228. })
  229. it('per-call timeout takes precedence under the cap and kills on expiry', async () => {
  230. const { bash } = await setup({ timeoutMs: 60_000 })
  231. const result = await bash.run(bash.resolve({ command: 'Start-Sleep -Seconds 60', timeoutMs: 100 }))
  232. expect(result.timedOut).toBe(true)
  233. // Mutually exclusive: a timeout classifies as timedOut, never also aborted.
  234. expect(result.aborted).toBe(false)
  235. expect(result.timeoutMs).toBe(100)
  236. })
  237. it('propagates abort signals', async () => {
  238. const { bash } = await setup()
  239. const controller = new AbortController()
  240. const pending = bash.run(bash.resolve({ command: 'Start-Sleep -Seconds 60', signal: controller.signal }))
  241. setTimeout(() => { controller.abort() }, 50)
  242. const result = await pending
  243. expect(result.aborted).toBe(true)
  244. // Mutually exclusive: an upstream cancel classifies as aborted, never also timedOut.
  245. expect(result.timedOut).toBe(false)
  246. })
  247. it('classifies a self-killed command as neither timed out nor aborted', async () => {
  248. const { bash } = await setup({ timeoutMs: 60_000 })
  249. const result = await bash.run(bash.resolve({ command: 'Stop-Process -Id $PID' }))
  250. expect(result.timedOut).toBe(false)
  251. expect(result.aborted).toBe(false)
  252. // Windows reports a forced termination without a signal; POSIX reports the
  253. // terminating signal PowerShell chose (SIGTERM, or SIGKILL for the hard kill).
  254. if (process.platform === 'win32') {
  255. expect(result.signal).toBeNull()
  256. } else {
  257. expect(['SIGTERM', 'SIGKILL']).toContain(result.signal)
  258. }
  259. })
  260. it('rejects on spawn failure (bad workdir)', async () => {
  261. const { bash } = await setup()
  262. await expect(bash.run(bash.resolve({ command: 'Write-Output ok', workdir: '/nonexistent-dsh' }))).rejects.toThrow(/ENOENT/)
  263. })
  264. it('resolve() carries stdin/env/dshEnv onto the spec, and run() threads them to the command', async () => {
  265. const { bash } = await setup()
  266. const spec = bash.resolve({
  267. command: '$s = ([Console]::In.ReadToEnd()).TrimEnd(); Write-Output $s; Write-Output "[$env:SEAM_VAR][$env:DSH_SEAM_VAR]"',
  268. stdin: 'piped\n',
  269. env: { SEAM_VAR: 'env-ok' },
  270. dshEnv: { DSH_SEAM_VAR: 'dsh-ok' },
  271. })
  272. // resolve() keeps the optional input/environment fields verbatim.
  273. expect(spec.stdin).toBe('piped\n')
  274. expect(spec.env).toEqual({ SEAM_VAR: 'env-ok' })
  275. expect(spec.dshEnv).toEqual({ DSH_SEAM_VAR: 'dsh-ok' })
  276. const result = await bash.run(spec)
  277. expect(lf(result.stdout.text)).toBe('piped\n[env-ok][dsh-ok]\n')
  278. })
  279. it('resolve() omits stdin/env/dshEnv when the request supplies none', async () => {
  280. const { bash } = await setup()
  281. const spec = bash.resolve({ command: 'Write-Output ok' })
  282. expect('stdin' in spec).toBe(false)
  283. expect('env' in spec).toBe(false)
  284. expect('dshEnv' in spec).toBe(false)
  285. })
  286. })
  287. describe.skipIf(!hasPwsh)('PwshLocalExecutor.start (background process handles)', () => {
  288. it('start returns immediately with a running handle that settles as completed', async () => {
  289. const { bash } = await setup()
  290. const before = Date.now()
  291. // The sleep outlasts any realistic spawn latency, so returning while the
  292. // child still sleeps proves start() does not wait for completion.
  293. const proc = bash.start(bash.resolve({ command: 'Start-Sleep -Milliseconds 2000; Write-Output done' }))
  294. expect(Date.now() - before).toBeLessThan(1000)
  295. expect(proc.status).toBe('running')
  296. await proc.done
  297. expect(proc.status).toBe('completed')
  298. expect(proc.exitCode).toBe(0)
  299. })
  300. it('threads stdin and extra env into a background process', async () => {
  301. const { bash } = await setup()
  302. const proc = bash.start(bash.resolve({
  303. command: '$s = ([Console]::In.ReadToEnd()).TrimEnd(); Write-Output $s; Write-Output "[$env:BG_VAR][$env:DSH_BG_VAR]"',
  304. stdin: 'bg-stdin\n',
  305. env: { BG_VAR: 'bg-env' },
  306. dshEnv: { DSH_BG_VAR: 'bg-dsh-env' },
  307. }))
  308. const partialOutput = await readUntil(proc, '[bg-env][bg-dsh-env]')
  309. await proc.done
  310. const output = partialOutput + lf(proc.readOutput().delta)
  311. expect(output).toBe('bg-stdin\n[bg-env][bg-dsh-env]\n')
  312. expect(proc.exitCode).toBe(0)
  313. })
  314. it('readOutput is consuming: increments are never re-delivered, and reads stay valid after exit', async () => {
  315. const { bash } = await setup()
  316. const proc = bash.start(bash.resolve({ command: 'Write-Output first; Start-Sleep -Seconds 1; Write-Output second' }))
  317. const first = await readUntil(proc, 'first\n')
  318. expect(lf(first)).toBe('first\n')
  319. await proc.done
  320. // Read-after-exit returns the remaining buffered output — once.
  321. const second = proc.readOutput()
  322. expect(lf(second.delta)).toBe('second\n')
  323. expect(second.lossy).toBe(false)
  324. expect(proc.readOutput().delta).toBe('')
  325. })
  326. it('readOutput marks stderr sections', async () => {
  327. const { bash } = await setup()
  328. const proc = bash.start(bash.resolve({ command: 'Write-Output out; [Console]::Error.WriteLine("err")' }))
  329. await proc.done
  330. expect(lf(proc.readOutput().delta)).toBe('out\n[stderr]\nerr\n')
  331. })
  332. it('readOutput reports stderr-only deltas without a leading newline', async () => {
  333. const { bash } = await setup()
  334. const proc = bash.start(bash.resolve({ command: '[Console]::Error.WriteLine("err")' }))
  335. await proc.done
  336. expect(lf(proc.readOutput().delta)).toBe('[stderr]\nerr\n')
  337. })
  338. it('readOutput adds a separator only when stdout lacks a trailing newline', async () => {
  339. const { bash } = await setup()
  340. const proc = bash.start(bash.resolve({ command: '[Console]::Out.Write("out"); [Console]::Error.WriteLine("err")' }))
  341. await proc.done
  342. expect(lf(proc.readOutput().delta)).toBe('out\n[stderr]\nerr\n')
  343. })
  344. it('readOutput flags lossy reads and reports stdout spill paths', async () => {
  345. const { bash } = await setup({ maxOutputBytes: 100 })
  346. const proc = bash.start(bash.resolve({ command: '1..100 | ForEach-Object { "line-$_" }' }))
  347. await proc.done
  348. const read = proc.readOutput()
  349. // Window slid past offset 0 → lossy, spill path points at the full stream.
  350. expect(read.lossy).toBe(true)
  351. expect(read.stdoutSpillPath).toBeDefined()
  352. })
  353. it('readOutput reports stderr spill paths', async () => {
  354. const { bash } = await setup({ maxOutputBytes: 100 })
  355. const proc = bash.start(bash.resolve({ command: '1..100 | ForEach-Object { [Console]::Error.WriteLine("line-$_") }' }))
  356. await proc.done
  357. const read = proc.readOutput()
  358. expect(read.lossy).toBe(true)
  359. expect(read.stderrSpillPath).toBeDefined()
  360. expect(lf(read.delta)).toContain('[stderr]')
  361. })
  362. it('kill() terminates the process tree: true once, false after settlement', async () => {
  363. const { bash } = await setup()
  364. const proc = bash.start(bash.resolve({ command: 'Start-Sleep -Seconds 60' }))
  365. expect(proc.kill()).toBe(true)
  366. await proc.done
  367. expect(proc.status).toBe('killed')
  368. expect(proc.kill()).toBe(false)
  369. })
  370. it('kill() returns false for a naturally completed process', async () => {
  371. const { bash } = await setup()
  372. const proc = bash.start(bash.resolve({ command: 'Write-Output ok' }))
  373. await proc.done
  374. expect(proc.status).toBe('completed')
  375. expect(proc.kill()).toBe(false)
  376. })
  377. it('a spec.signal abort settles the handle as killed, not completed', async () => {
  378. const { bash } = await setup()
  379. const controller = new AbortController()
  380. const proc = bash.start(bash.resolve({ command: 'Start-Sleep -Seconds 60', signal: controller.signal }))
  381. controller.abort()
  382. await proc.done
  383. expect(proc.status).toBe('killed')
  384. })
  385. it.skipIf(process.platform === 'win32')('a self-signal exit settles the handle as killed, not completed (POSIX)', async () => {
  386. const { bash } = await setup()
  387. const proc = bash.start(bash.resolve({ command: 'Stop-Process -Id $PID' }))
  388. await proc.done
  389. expect(proc.status).toBe('killed')
  390. expect(proc.exitCode).toBeNull()
  391. // PowerShell picks SIGTERM for Stop-Process, SIGKILL for the hard kill.
  392. expect(['SIGTERM', 'SIGKILL']).toContain(proc.signal)
  393. })
  394. it('a background spawn failure settles as killed with the error readable on stderr', async () => {
  395. const { bash } = await setup()
  396. const proc = bash.start(bash.resolve({ command: 'Write-Output ok', workdir: '/nonexistent-dsh' }))
  397. // done resolves (never rejects) even though the process never ran.
  398. await expect(proc.done).resolves.toBeUndefined()
  399. expect(proc.status).toBe('killed')
  400. expect(proc.readOutput().delta).toContain('spawn failed:')
  401. })
  402. })
  403. describe.skipIf(!hasPwsh)('process lifecycle ownership (the subprocess service, not the executor)', () => {
  404. it('a background process survives executor-fiber disposal and dies with the subprocess service', async () => {
  405. const ctx = new Context()
  406. const managerFiber = await ctx.plugin(LocalSubprocessRuntime)
  407. ;(ctx.subprocess as LocalSubprocessRuntime).internals = { spillDir }
  408. const executorFiber = await ctx.plugin(PwshLocalExecutor, { graceMs: 200 })
  409. const bash = ctx.shell as PwshLocalExecutor
  410. // The child prints its own pid so the test can probe liveness through the
  411. // public read surface alone.
  412. const proc = bash.start(bash.resolve({ command: 'Write-Output $PID; Start-Sleep -Seconds 60' }))
  413. const pid = Number((await readUntil(proc, '\n')).trim())
  414. expect(Number.isInteger(pid) && pid > 0).toBe(true)
  415. // Executor reload/disposal leaves background work running — the
  416. // handle stays live and readable, mirroring the job runtime's
  417. // registrations-outlive-producer-fibers contract.
  418. await executorFiber.dispose()
  419. expect(proc.status).toBe('running')
  420. expect(() => process.kill(pid, 0)).not.toThrow()
  421. // Service disposal kills the group and AWAITS its exit (no orphans).
  422. await managerFiber.dispose()
  423. expect(() => process.kill(pid, 0)).toThrow()
  424. await proc.done
  425. // POSIX reports the kill as a signal; Windows reports a forced
  426. // termination as exit 1 with no signal (indistinguishable from a crash),
  427. // so the status stamp follows the platform's exit facts.
  428. expect(proc.status).toBe(process.platform === 'win32' ? 'completed' : 'killed')
  429. })
  430. it('service disposal settles running handles and leaves settled ones untouched', async () => {
  431. const ctx = new Context()
  432. const managerFiber = await ctx.plugin(LocalSubprocessRuntime)
  433. ;(ctx.subprocess as LocalSubprocessRuntime).internals = { spillDir }
  434. await ctx.plugin(PwshLocalExecutor, { graceMs: 200 })
  435. const bash = ctx.shell as PwshLocalExecutor
  436. const finished = bash.start(bash.resolve({ command: 'Write-Output done' }))
  437. await finished.done
  438. expect(finished.status).toBe('completed')
  439. const running = bash.start(bash.resolve({ command: 'Start-Sleep -Seconds 60' }))
  440. await managerFiber.dispose()
  441. // A settled process was untouched; the live one was terminated and joined.
  442. expect(finished.status).toBe('completed')
  443. await running.done
  444. expect(running.status).toBe(process.platform === 'win32' ? 'completed' : 'killed')
  445. })
  446. })