executor.spec.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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, rmSync, 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 { afterAll, afterEach, 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, SubprocessOutcome, 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. afterAll(() => {
  25. rmSync(spillDir, { recursive: true, force: true })
  26. })
  27. /** Per-test temp dirs, removed after each test. */
  28. const tempDirs: string[] = []
  29. const contexts: Context[] = []
  30. afterEach(async () => {
  31. const ownedContexts = contexts.splice(0)
  32. const directories = tempDirs.splice(0)
  33. const results = await Promise.allSettled(ownedContexts.map(ctx => ctx.fiber.dispose()))
  34. for (const dir of directories) rmSync(dir, { recursive: true, force: true })
  35. const failures: unknown[] = results.flatMap((result): unknown[] => result.status === 'rejected' ? [result.reason] : [])
  36. if (failures.length > 0) throw new AggregateError(failures, 'PowerShell fixture cleanup failed')
  37. })
  38. function createContext(): Context {
  39. const ctx = new Context()
  40. contexts.push(ctx)
  41. return ctx
  42. }
  43. /** A private file barrier keeps the command alive until the test releases it. */
  44. function commandBarrier() {
  45. const dir = mkdtempSync(join(tmpdir(), 'dsh-pwsh-barrier-'))
  46. tempDirs.push(dir)
  47. const path = join(dir, 'release')
  48. return {
  49. command: 'while (-not (Test-Path -LiteralPath $env:DSH_TEST_RELEASE)) { Start-Sleep -Milliseconds 20 }',
  50. env: { DSH_TEST_RELEASE: path },
  51. release: () => { writeFileSync(path, '') },
  52. }
  53. }
  54. // The probe follows the executor's own resolution (Program Files installs on
  55. // Windows are found even when bare `pwsh` is not on PATH).
  56. const hasPwsh = spawnSync(resolvePwshPath(), ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '$true'], { encoding: 'utf8' }).status === 0
  57. /** Normalize PowerShell's platform line endings (CRLF on Windows, LF elsewhere). */
  58. const lf = (text: string): string => text.replace(/\r\n/g, '\n')
  59. /** Filesystem path equality across macOS temp symlinks and Windows drive-letter casing. */
  60. function samePath(actual: string, expected: string): boolean {
  61. const norm = (value: string) => (
  62. process.platform === 'win32' ? realpathSync.native(value).toLowerCase() : realpathSync.native(value)
  63. )
  64. return norm(actual) === norm(expected)
  65. }
  66. async function setup(config: ConstructorParameters<typeof PwshLocalExecutor>[1] = {}) {
  67. const ctx = createContext()
  68. await ctx.plugin(LocalSubprocessRuntime)
  69. ;(ctx.subprocess as LocalSubprocessRuntime).internals = { spillDir }
  70. // A short kill grace via the REAL config path, so escalation tests stay fast.
  71. await ctx.plugin(PwshLocalExecutor, { graceMs: 200, ...config })
  72. const bash = ctx.shell as PwshLocalExecutor
  73. return { ctx, bash }
  74. }
  75. /**
  76. * Accumulate consuming reads until the marker arrives, using the current test's
  77. * budget. Callers keep the child at a barrier when later output must remain unread.
  78. */
  79. async function readUntil(proc: ShellProcess, expected: string, timeoutMs: number): Promise<string> {
  80. let all = ''
  81. await expect.poll(() => {
  82. all += proc.readOutput().delta
  83. return lf(all)
  84. }, { timeout: timeoutMs }).toContain(expected)
  85. return lf(all)
  86. }
  87. describe('resolvePwshPath and candidatePwshPaths (pure, every platform)', () => {
  88. it('trusts an explicit configured path verbatim', () => {
  89. expect(resolvePwshPath('C:\\custom\\pwsh.exe')).toBe('C:\\custom\\pwsh.exe')
  90. expect(resolvePwshPath('pwsh')).toBe('pwsh')
  91. })
  92. it('falls through an empty configured path to platform resolution', () => {
  93. // SystemRoot points at a non-existent tree so the Windows PowerShell 5.1
  94. // fallback candidate cannot exist either.
  95. expect(resolvePwshPath('', {
  96. PATH: 'P:\\Store',
  97. ProgramFiles: 'P:\\no-program-files',
  98. SystemRoot: 'S:\\no-windows',
  99. }, 'win32')).toBe('pwsh')
  100. })
  101. it('returns pwsh on non-Windows platforms regardless of the environment', () => {
  102. expect(resolvePwshPath(undefined, { ProgramFiles: 'P:\\Program Files' }, 'linux')).toBe('pwsh')
  103. expect(resolvePwshPath(undefined, { PATH: 'P:\\Store' }, 'darwin')).toBe('pwsh')
  104. })
  105. it('uses stable Windows roots when the environment omits both overrides', () => {
  106. expect(candidatePwshPaths({})).toEqual([
  107. join('C:\\Program Files', 'PowerShell', '7', 'pwsh.exe'),
  108. join('C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
  109. ])
  110. })
  111. it('lists PowerShell 7, PATH entries (quotes stripped), then Windows PowerShell 5.1 on win32', () => {
  112. const candidates = candidatePwshPaths({
  113. ProgramFiles: 'P:\\Program Files',
  114. SystemRoot: 'S:\\Windows',
  115. PATH: ';"Q:\\quoted store";' + ';',
  116. })
  117. expect(candidates).toEqual([
  118. join('P:\\Program Files', 'PowerShell', '7', 'pwsh.exe'),
  119. join('Q:\\quoted store', 'pwsh.exe'),
  120. join('S:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
  121. ])
  122. // A missing PATH contributes no entries (the empty-string fallback).
  123. expect(candidatePwshPaths({ ProgramFiles: 'P:\\Program Files', SystemRoot: 'S:\\Windows' }))
  124. .toEqual([
  125. join('P:\\Program Files', 'PowerShell', '7', 'pwsh.exe'),
  126. join('S:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
  127. ])
  128. })
  129. it('returns the first EXISTING win32 candidate, else pwsh', () => {
  130. const dir = mkdtempSync(join(tmpdir(), 'dsh-pwsh-resolve-'))
  131. tempDirs.push(dir)
  132. const store = join(dir, 'store')
  133. mkdirSync(store, { recursive: true })
  134. writeFileSync(join(store, 'pwsh.exe'), '')
  135. // The existing PATH entry wins over the non-existent Program Files install.
  136. expect(resolvePwshPath(undefined, { ProgramFiles: join(dir, 'missing'), PATH: store }, 'win32'))
  137. .toBe(join(store, 'pwsh.exe'))
  138. // No candidate exists anywhere (SystemRoot points at a non-existent tree,
  139. // so even the Windows PowerShell 5.1 fallback cannot exist) → the
  140. // PATH-resolution fallback.
  141. expect(resolvePwshPath(undefined, { ProgramFiles: join(dir, 'missing'), PATH: join(dir, 'empty'), SystemRoot: join(dir, 'no-windows') }, 'win32'))
  142. .toBe('pwsh')
  143. })
  144. it('accepts a link-shaped PATH candidate whose target cannot be stat-ed', () => {
  145. // Store app execution aliases stat as EACCES but lstat as a link; a
  146. // dangling symlink reproduces that split on every platform.
  147. const dir = mkdtempSync(join(tmpdir(), 'dsh-pwsh-resolve-link-'))
  148. tempDirs.push(dir)
  149. const store = join(dir, 'store')
  150. mkdirSync(store, { recursive: true })
  151. const link = join(store, 'pwsh.exe')
  152. symlinkSync(join(dir, 'no-such-target.exe'), link)
  153. expect(resolvePwshPath(undefined, { ProgramFiles: join(dir, 'missing'), PATH: store }, 'win32'))
  154. .toBe(link)
  155. })
  156. it('skips a directory candidate and falls through to the PATH-resolution default', () => {
  157. const dir = mkdtempSync(join(tmpdir(), 'dsh-pwsh-resolve-dir-'))
  158. tempDirs.push(dir)
  159. const store = join(dir, 'store')
  160. mkdirSync(join(store, 'pwsh.exe'), { recursive: true })
  161. expect(resolvePwshPath(undefined, {
  162. ProgramFiles: join(dir, 'missing'),
  163. PATH: store,
  164. SystemRoot: join(dir, 'no-windows'),
  165. }, 'win32')).toBe('pwsh')
  166. })
  167. })
  168. describe('spawn construction (pure, every platform)', () => {
  169. /** A subprocess service that records spawn specs and settles instantly. */
  170. class CapturingSubprocessRuntime extends SubprocessRuntime {
  171. specs: SubprocessSpawnSpec[] = []
  172. done: Promise<SubprocessOutcome> = Promise.resolve({ exitCode: 0, signal: null })
  173. stderrText = ''
  174. override async resolveExecutable(command: string): Promise<string> { return command }
  175. override spawnTerminal(): Promise<never> { throw new Error('pwsh spawns pipes, never terminals') }
  176. private readonly stdoutReader: SubprocessOutputReader = {
  177. readFrom: () => ({ text: '', lossy: false, nextOffset: 0 }),
  178. }
  179. private readonly stderrReader: SubprocessOutputReader = {
  180. readFrom: offset => ({
  181. text: this.stderrText.slice(offset),
  182. lossy: false,
  183. nextOffset: this.stderrText.length,
  184. }),
  185. }
  186. override spawn(spec: SubprocessSpawnSpec): SubprocessHandle {
  187. this.specs.push(spec)
  188. return {
  189. stdin: undefined,
  190. stdout: undefined,
  191. stderr: undefined,
  192. collected: { stdout: this.stdoutReader, stderr: this.stderrReader },
  193. done: this.done,
  194. terminate: () => {},
  195. waitForExit: async () => true,
  196. }
  197. }
  198. }
  199. it('runs every command as ONE argv element under the UTF-8 encoding preamble', async () => {
  200. const ctx = createContext()
  201. const subprocess = new CapturingSubprocessRuntime(ctx)
  202. await ctx.plugin(PwshLocalExecutor)
  203. await ctx.shell.run(ctx.shell.resolve({ command: 'Write-Output 你好' }))
  204. expect(subprocess.specs).toHaveLength(1)
  205. const { argv } = subprocess.specs[0]!
  206. expect(argv.slice(0, 5)).toEqual([expect.any(String), '-NoLogo', '-NoProfile', '-NonInteractive', '-Command'])
  207. expect(argv[5]).toBe(`${ENCODING_PREAMBLE}Write-Output 你好`)
  208. expect(ENCODING_PREAMBLE).toContain('[Console]::OutputEncoding')
  209. expect(ENCODING_PREAMBLE).toContain('$OutputEncoding')
  210. })
  211. it('reports both unread stderr and an asynchronous provider rejection exactly once', async () => {
  212. const ctx = createContext()
  213. const subprocess = new CapturingSubprocessRuntime(ctx)
  214. await ctx.plugin(PwshLocalExecutor)
  215. subprocess.stderrText = 'target stderr'
  216. subprocess.done = Promise.reject(new Error('provider lost the direct outcome'))
  217. const proc = ctx.shell.start(ctx.shell.resolve({ command: 'Write-Output maybe-ran' }))
  218. await expect(proc.done).resolves.toBeUndefined()
  219. expect(proc.status).toBe('killed')
  220. const output = proc.readOutput().delta
  221. expect(output).toContain('target stderr')
  222. expect(output).toContain('subprocess failed before reporting an outcome:')
  223. expect(output).not.toContain('spawn failed:')
  224. expect(proc.readOutput().delta).toBe('')
  225. })
  226. it('settles an unprintable provider rejection instead of rejecting done', async () => {
  227. const ctx = createContext()
  228. const subprocess = new CapturingSubprocessRuntime(ctx)
  229. await ctx.plugin(PwshLocalExecutor)
  230. const providerError = new Error('unprintable provider error')
  231. Object.defineProperty(providerError, Symbol.toPrimitive, {
  232. value: () => { throw new Error('provider formatting must not escape') },
  233. })
  234. subprocess.done = Promise.reject(providerError)
  235. const proc = ctx.shell.start(ctx.shell.resolve({ command: 'Write-Output maybe-ran' }))
  236. await expect(proc.done).resolves.toBeUndefined()
  237. expect(proc.status).toBe('killed')
  238. expect(proc.readOutput().delta).toContain('unprintable provider failure')
  239. expect(proc.readOutput().delta).toBe('')
  240. })
  241. it('preserves an explicit kill stamp and maps an aborted direct outcome to killed', async () => {
  242. const ctx = createContext()
  243. const subprocess = new CapturingSubprocessRuntime(ctx)
  244. await ctx.plugin(PwshLocalExecutor)
  245. const killedOutcome = Promise.withResolvers<SubprocessOutcome>()
  246. subprocess.done = killedOutcome.promise
  247. const killed = ctx.shell.start(ctx.shell.resolve({ command: 'Write-Output maybe-ran' }))
  248. expect(killed.kill()).toBe(true)
  249. killedOutcome.resolve({ exitCode: 0, signal: null })
  250. await killed.done
  251. expect(killed.status).toBe('killed')
  252. expect(killed.exitCode).toBe(0)
  253. const abortedOutcome = Promise.withResolvers<SubprocessOutcome>()
  254. subprocess.done = abortedOutcome.promise
  255. const controller = new AbortController()
  256. const aborted = ctx.shell.start(ctx.shell.resolve({
  257. command: 'Write-Output maybe-ran',
  258. signal: controller.signal,
  259. }))
  260. controller.abort()
  261. abortedOutcome.resolve({ exitCode: 0, signal: null })
  262. await aborted.done
  263. expect(aborted.status).toBe('killed')
  264. })
  265. })
  266. describe.skipIf(!hasPwsh)('PwshLocalExecutor.run', () => {
  267. it('resolves with output and the effective timeout', { timeout: 15_000 }, async () => {
  268. const { bash } = await setup({ timeoutMs: 10_000 })
  269. const result = await bash.run(bash.resolve({ command: 'Write-Output hi' }))
  270. expect(result.exitCode).toBe(0)
  271. expect(lf(result.stdout.text)).toBe('hi\n')
  272. expect(result.timeoutMs).toBe(10_000)
  273. })
  274. it('uses config cwd, overridable per call', async () => {
  275. const first = mkdtempSync(join(tmpdir(), 'dsh-pwsh-cwd-a-'))
  276. const second = mkdtempSync(join(tmpdir(), 'dsh-pwsh-cwd-b-'))
  277. tempDirs.push(first, second)
  278. const { bash } = await setup({ cwd: first })
  279. const fromConfig = await bash.run(bash.resolve({ command: '(Get-Location).Path' }))
  280. expect(samePath(fromConfig.stdout.text.trim(), first)).toBe(true)
  281. const fromCall = await bash.run(bash.resolve({ command: '(Get-Location).Path', workdir: second }))
  282. expect(samePath(fromCall.stdout.text.trim(), second)).toBe(true)
  283. })
  284. it('defaults cwd to process.cwd()', async () => {
  285. const { bash } = await setup()
  286. const result = await bash.run(bash.resolve({ command: '(Get-Location).Path' }))
  287. expect(samePath(result.stdout.text.trim(), process.cwd())).toBe(true)
  288. })
  289. it('caps per-call timeouts at maxTimeoutMs', async () => {
  290. const { bash } = await setup({ timeoutMs: 1_000, maxTimeoutMs: 2_000 })
  291. const result = await bash.run(bash.resolve({ command: 'Write-Output ok', timeoutMs: 99_999 }))
  292. expect(result.timeoutMs).toBe(2_000)
  293. })
  294. it('rejects invalid numeric config and timeout overrides', async () => {
  295. await expect(setup({ timeoutMs: Number.NaN })).rejects.toThrow(/timeoutMs/)
  296. await expect(setup({ maxTimeoutMs: 0 })).rejects.toThrow(/maxTimeoutMs/)
  297. await expect(setup({ maxOutputBytes: -1 })).rejects.toThrow(/maxOutputBytes/)
  298. await expect(setup({ maxSpillBytes: 0 })).rejects.toThrow(/maxSpillBytes/)
  299. await expect(setup({ graceMs: 0 })).rejects.toThrow(/graceMs/)
  300. await expect(setup({ graceMs: MAX_TIMER_DELAY_MS + 1 }))
  301. .rejects.toThrow(`graceMs must be no greater than ${MAX_TIMER_DELAY_MS}`)
  302. const { bash } = await setup()
  303. expect(() => bash.resolve({ command: 'Write-Output ok', timeoutMs: Number.NaN })).toThrow(/request\.timeoutMs/)
  304. expect(() => bash.resolve({ command: 'Write-Output ok', timeoutMs: -1 })).toThrow(/request\.timeoutMs/)
  305. expect(() => bash.resolve({ command: 'Write-Output ok', stdoutMaxBytes: Number.NaN })).toThrow(/request\.stdoutMaxBytes/)
  306. expect(() => bash.resolve({ command: 'Write-Output ok', stdoutMaxBytes: -1 })).toThrow(/request\.stdoutMaxBytes/)
  307. })
  308. it('defaults stdoutMaxBytes to maxOutputBytes and lets foreground callers raise stdout only', async () => {
  309. const { bash } = await setup({ maxOutputBytes: 100 })
  310. expect(bash.resolve({ command: 'Write-Output ok' }).stdoutMaxBytes).toBe(100)
  311. // Raw Console writes avoid PowerShell's own line-ending and formatting
  312. // layers, so the byte counts are exact on every platform.
  313. const result = await bash.run(bash.resolve({
  314. command: '[Console]::Out.Write("x" * 500); [Console]::Error.WriteLine("e" * 500)',
  315. stdoutMaxBytes: 500,
  316. }))
  317. expect(result.stdout.text).toBe('x'.repeat(500))
  318. expect(result.stdout.truncated).toBe(false)
  319. expect(result.stderr.truncated).toBe(true)
  320. expect(result.stderr.text.length).toBeLessThanOrEqual(100)
  321. })
  322. it('per-call timeout takes precedence under the cap and kills on expiry', async () => {
  323. const { bash } = await setup({ timeoutMs: 60_000 })
  324. const result = await bash.run(bash.resolve({ command: 'Start-Sleep -Seconds 60', timeoutMs: 100 }))
  325. expect(result.timedOut).toBe(true)
  326. // Mutually exclusive: a timeout classifies as timedOut, never also aborted.
  327. expect(result.aborted).toBe(false)
  328. expect(result.timeoutMs).toBe(100)
  329. })
  330. it('propagates abort signals', async () => {
  331. const { bash } = await setup()
  332. const controller = new AbortController()
  333. const pending = bash.run(bash.resolve({ command: 'Start-Sleep -Seconds 60', signal: controller.signal }))
  334. setTimeout(() => { controller.abort() }, 50)
  335. const result = await pending
  336. expect(result.aborted).toBe(true)
  337. // Mutually exclusive: an upstream cancel classifies as aborted, never also timedOut.
  338. expect(result.timedOut).toBe(false)
  339. })
  340. it('classifies a self-killed command as neither timed out nor aborted', async () => {
  341. const { bash } = await setup({ timeoutMs: 60_000 })
  342. const result = await bash.run(bash.resolve({ command: 'Stop-Process -Id $PID' }))
  343. expect(result.timedOut).toBe(false)
  344. expect(result.aborted).toBe(false)
  345. // Windows reports a forced termination without a signal; POSIX reports the
  346. // terminating signal PowerShell chose (SIGTERM, or SIGKILL for the hard kill).
  347. if (process.platform === 'win32') {
  348. expect(result.signal).toBeNull()
  349. } else {
  350. expect(['SIGTERM', 'SIGKILL']).toContain(result.signal)
  351. }
  352. })
  353. it('rejects on spawn failure (bad workdir)', async () => {
  354. const { bash } = await setup()
  355. await expect(bash.run(bash.resolve({ command: 'Write-Output ok', workdir: '/nonexistent-dsh' }))).rejects.toThrow(/ENOENT/)
  356. })
  357. it('resolve() carries stdin/env/dshEnv onto the spec, and run() threads them to the command', async () => {
  358. const { bash } = await setup()
  359. const spec = bash.resolve({
  360. command: '$s = ([Console]::In.ReadToEnd()).TrimEnd(); Write-Output $s; Write-Output "[$env:SEAM_VAR][$env:DSH_SEAM_VAR]"',
  361. stdin: 'piped\n',
  362. env: { SEAM_VAR: 'env-ok' },
  363. dshEnv: { DSH_SEAM_VAR: 'dsh-ok' },
  364. })
  365. // resolve() keeps the optional input/environment fields verbatim.
  366. expect(spec.stdin).toBe('piped\n')
  367. expect(spec.env).toEqual({ SEAM_VAR: 'env-ok' })
  368. expect(spec.dshEnv).toEqual({ DSH_SEAM_VAR: 'dsh-ok' })
  369. const result = await bash.run(spec)
  370. expect(lf(result.stdout.text)).toBe('piped\n[env-ok][dsh-ok]\n')
  371. })
  372. it('resolve() omits stdin/env/dshEnv when the request supplies none', async () => {
  373. const { bash } = await setup()
  374. const spec = bash.resolve({ command: 'Write-Output ok' })
  375. expect('stdin' in spec).toBe(false)
  376. expect('env' in spec).toBe(false)
  377. expect('dshEnv' in spec).toBe(false)
  378. })
  379. })
  380. describe.skipIf(!hasPwsh)('PwshLocalExecutor.start (background process handles)', () => {
  381. it('start returns immediately with a running handle that settles as completed', async ({ task }) => {
  382. const { bash } = await setup()
  383. const barrier = commandBarrier()
  384. const proc = bash.start(bash.resolve({
  385. command: `Write-Output ready; [Console]::Out.Flush(); ${barrier.command}; Write-Output done`,
  386. env: barrier.env,
  387. }))
  388. expect(proc.status).toBe('running')
  389. expect(await readUntil(proc, 'ready\n', task.timeout)).toBe('ready\n')
  390. expect(proc.status).toBe('running')
  391. barrier.release()
  392. await proc.done
  393. expect(proc.status).toBe('completed')
  394. expect(proc.signal).toBeNull()
  395. expect(proc.exitCode).toBe(0)
  396. expect(lf(proc.readOutput().delta)).toBe('done\n')
  397. })
  398. it('threads stdin and extra env into a background process', async () => {
  399. const { bash } = await setup()
  400. const proc = bash.start(bash.resolve({
  401. command: '$s = ([Console]::In.ReadToEnd()).TrimEnd(); Write-Output $s; Write-Output "[$env:BG_VAR][$env:DSH_BG_VAR]"',
  402. stdin: 'bg-stdin\n',
  403. env: { BG_VAR: 'bg-env' },
  404. dshEnv: { DSH_BG_VAR: 'bg-dsh-env' },
  405. }))
  406. await proc.done
  407. expect(proc.status).toBe('completed')
  408. expect(proc.signal).toBeNull()
  409. expect(proc.exitCode).toBe(0)
  410. expect(lf(proc.readOutput().delta)).toBe('bg-stdin\n[bg-env][bg-dsh-env]\n')
  411. })
  412. it('readOutput is consuming: increments are never re-delivered, and reads stay valid after exit', async ({ task }) => {
  413. const { bash } = await setup()
  414. const barrier = commandBarrier()
  415. const proc = bash.start(bash.resolve({
  416. command: `Write-Output first; [Console]::Out.Flush(); ${barrier.command}; Write-Output second`,
  417. env: barrier.env,
  418. }))
  419. const first = await readUntil(proc, 'first\n', task.timeout)
  420. expect(first).toBe('first\n')
  421. expect(proc.status).toBe('running')
  422. expect(proc.readOutput().delta).toBe('')
  423. barrier.release()
  424. await proc.done
  425. expect(proc.status).toBe('completed')
  426. expect(proc.exitCode).toBe(0)
  427. // Read-after-exit returns the remaining buffered output — once.
  428. const second = proc.readOutput()
  429. expect(lf(second.delta)).toBe('second\n')
  430. expect(second.lossy).toBe(false)
  431. expect(proc.readOutput().delta).toBe('')
  432. })
  433. it('readOutput marks stderr sections', async () => {
  434. const { bash } = await setup()
  435. const proc = bash.start(bash.resolve({ command: 'Write-Output out; [Console]::Error.WriteLine("err")' }))
  436. await proc.done
  437. expect(lf(proc.readOutput().delta)).toBe('out\n[stderr]\nerr\n')
  438. })
  439. it('readOutput reports stderr-only deltas without a leading newline', async () => {
  440. const { bash } = await setup()
  441. const proc = bash.start(bash.resolve({ command: '[Console]::Error.WriteLine("err")' }))
  442. await proc.done
  443. expect(lf(proc.readOutput().delta)).toBe('[stderr]\nerr\n')
  444. })
  445. it('readOutput adds a separator only when stdout lacks a trailing newline', async () => {
  446. const { bash } = await setup()
  447. const proc = bash.start(bash.resolve({ command: '[Console]::Out.Write("out"); [Console]::Error.WriteLine("err")' }))
  448. await proc.done
  449. expect(lf(proc.readOutput().delta)).toBe('out\n[stderr]\nerr\n')
  450. })
  451. it('readOutput flags lossy reads and reports stdout spill paths', async () => {
  452. const { bash } = await setup({ maxOutputBytes: 100 })
  453. const proc = bash.start(bash.resolve({ command: '1..100 | ForEach-Object { "line-$_" }' }))
  454. await proc.done
  455. const read = proc.readOutput()
  456. // Window slid past offset 0 → lossy, spill path points at the full stream.
  457. expect(read.lossy).toBe(true)
  458. expect(read.stdoutSpillPath).toBeDefined()
  459. })
  460. it('readOutput reports stderr spill paths', async () => {
  461. const { bash } = await setup({ maxOutputBytes: 100 })
  462. const proc = bash.start(bash.resolve({ command: '1..100 | ForEach-Object { [Console]::Error.WriteLine("line-$_") }' }))
  463. await proc.done
  464. const read = proc.readOutput()
  465. expect(read.lossy).toBe(true)
  466. expect(read.stderrSpillPath).toBeDefined()
  467. expect(lf(read.delta)).toContain('[stderr]')
  468. })
  469. it('kill() requests managed-range termination: true once, false after settlement', async () => {
  470. const { bash } = await setup()
  471. const proc = bash.start(bash.resolve({ command: 'Start-Sleep -Seconds 60' }))
  472. expect(proc.kill()).toBe(true)
  473. await proc.done
  474. expect(proc.status).toBe('killed')
  475. expect(proc.kill()).toBe(false)
  476. })
  477. it('kill() returns false for a naturally completed process', async () => {
  478. const { bash } = await setup()
  479. const proc = bash.start(bash.resolve({ command: 'Write-Output ok' }))
  480. await proc.done
  481. expect(proc.status).toBe('completed')
  482. expect(proc.kill()).toBe(false)
  483. })
  484. it('a spec.signal abort settles the handle as killed, not completed', async () => {
  485. const { bash } = await setup()
  486. const controller = new AbortController()
  487. const proc = bash.start(bash.resolve({ command: 'Start-Sleep -Seconds 60', signal: controller.signal }))
  488. controller.abort()
  489. await proc.done
  490. expect(proc.status).toBe('killed')
  491. })
  492. it.skipIf(process.platform === 'win32')('a self-signal exit settles the handle as killed, not completed (POSIX)', async () => {
  493. const { bash } = await setup()
  494. const proc = bash.start(bash.resolve({ command: 'Stop-Process -Id $PID' }))
  495. await proc.done
  496. expect(proc.status).toBe('killed')
  497. expect(proc.exitCode).toBeNull()
  498. // PowerShell picks SIGTERM for Stop-Process, SIGKILL for the hard kill.
  499. expect(['SIGTERM', 'SIGKILL']).toContain(proc.signal)
  500. })
  501. it('an asynchronous creation failure settles as killed with a stage-neutral note', async () => {
  502. const { bash } = await setup()
  503. const proc = bash.start(bash.resolve({ command: 'Write-Output ok', workdir: '/nonexistent-dsh' }))
  504. // done resolves (never rejects) even though the process never ran.
  505. await expect(proc.done).resolves.toBeUndefined()
  506. expect(proc.status).toBe('killed')
  507. expect(proc.readOutput().delta).toContain('subprocess failed before reporting an outcome:')
  508. })
  509. })
  510. describe.skipIf(!hasPwsh)('process lifecycle ownership (the subprocess service, not the executor)', () => {
  511. it('a background process survives executor-fiber disposal and dies with the subprocess service', async ({ task }) => {
  512. const ctx = createContext()
  513. const managerFiber = await ctx.plugin(LocalSubprocessRuntime)
  514. ;(ctx.subprocess as LocalSubprocessRuntime).internals = { spillDir }
  515. const executorFiber = await ctx.plugin(PwshLocalExecutor, { graceMs: 200 })
  516. const bash = ctx.shell as PwshLocalExecutor
  517. // The child prints its own pid so the test can probe liveness through the
  518. // public read surface alone.
  519. const proc = bash.start(bash.resolve({ command: 'Write-Output $PID; Start-Sleep -Seconds 60' }))
  520. const pid = Number((await readUntil(proc, '\n', task.timeout)).trim())
  521. expect(Number.isInteger(pid) && pid > 0).toBe(true)
  522. // Executor reload/disposal leaves background work running — the
  523. // handle stays live and readable, mirroring the job runtime's
  524. // registrations-outlive-producer-fibers contract.
  525. await executorFiber.dispose()
  526. expect(proc.status).toBe('running')
  527. expect(() => process.kill(pid, 0)).not.toThrow()
  528. // Service disposal kills the group and AWAITS its exit (no orphans).
  529. await managerFiber.dispose()
  530. expect(() => process.kill(pid, 0)).toThrow()
  531. await proc.done
  532. // Service disposal confirmed the tree is gone (kill(pid,0) throws above).
  533. // On POSIX the stamp depends on whether the shell traps SIGTERM and exits
  534. // cleanly (completed) or is killed by the signal (killed); Windows forced
  535. // termination (taskkill, no signals) also stamps completed. Both mean the
  536. // process no longer survives the service.
  537. expect(['killed', 'completed']).toContain(proc.status)
  538. })
  539. it('service disposal settles running handles and leaves settled ones untouched', async () => {
  540. const ctx = createContext()
  541. const managerFiber = await ctx.plugin(LocalSubprocessRuntime)
  542. ;(ctx.subprocess as LocalSubprocessRuntime).internals = { spillDir }
  543. await ctx.plugin(PwshLocalExecutor, { graceMs: 200 })
  544. const bash = ctx.shell as PwshLocalExecutor
  545. const finished = bash.start(bash.resolve({ command: 'Write-Output done' }))
  546. await finished.done
  547. expect(finished.status).toBe('completed')
  548. const running = bash.start(bash.resolve({ command: 'Start-Sleep -Seconds 60' }))
  549. await managerFiber.dispose()
  550. // A settled process was untouched; the live one was terminated and joined.
  551. expect(finished.status).toBe('completed')
  552. await running.done
  553. // The live handle was terminated and joined; on POSIX the stamp depends
  554. // on whether the shell traps SIGTERM and exits cleanly (completed) or is
  555. // killed by the signal (killed); Windows forced termination (taskkill, no
  556. // signals) also stamps completed. Both mean the process no longer
  557. // survives the service.
  558. expect(['killed', 'completed']).toContain(running.status)
  559. })
  560. })