executor.spec.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  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. async terminalEnvironment() { return { platform: 'posix' as const } }
  172. specs: SubprocessSpawnSpec[] = []
  173. done: Promise<SubprocessOutcome> = Promise.resolve({ exitCode: 0, signal: null })
  174. stderrText = ''
  175. override async resolveExecutable(command: string): Promise<string> { return command }
  176. override spawnTerminal(): Promise<never> { throw new Error('pwsh spawns pipes, never terminals') }
  177. private readonly stdoutReader: SubprocessOutputReader = {
  178. readFrom: () => ({ text: '', lossy: false, nextOffset: 0 }),
  179. }
  180. private readonly stderrReader: SubprocessOutputReader = {
  181. readFrom: offset => ({
  182. text: this.stderrText.slice(offset),
  183. lossy: false,
  184. nextOffset: this.stderrText.length,
  185. }),
  186. }
  187. override spawn(spec: SubprocessSpawnSpec): SubprocessHandle {
  188. this.specs.push(spec)
  189. return {
  190. control: undefined,
  191. stdin: undefined,
  192. stdout: undefined,
  193. stderr: undefined,
  194. collected: { stdout: this.stdoutReader, stderr: this.stderrReader },
  195. done: this.done,
  196. terminate: () => {},
  197. waitForExit: async () => true,
  198. }
  199. }
  200. }
  201. it('runs every command as ONE argv element under the UTF-8 encoding preamble', async () => {
  202. const ctx = createContext()
  203. const subprocess = new CapturingSubprocessRuntime(ctx)
  204. await ctx.plugin(PwshLocalExecutor)
  205. await ctx.shell.run(ctx.shell.resolve({ command: 'Write-Output 你好' }))
  206. expect(subprocess.specs).toHaveLength(1)
  207. const { argv } = subprocess.specs[0]!
  208. expect(argv.slice(0, 5)).toEqual([expect.any(String), '-NoLogo', '-NoProfile', '-NonInteractive', '-Command'])
  209. expect(argv[5]).toBe(`${ENCODING_PREAMBLE}Write-Output 你好`)
  210. expect(ENCODING_PREAMBLE).toContain('[Console]::OutputEncoding')
  211. expect(ENCODING_PREAMBLE).toContain('$OutputEncoding')
  212. })
  213. it('reports both unread stderr and an asynchronous provider rejection exactly once', async () => {
  214. const ctx = createContext()
  215. const subprocess = new CapturingSubprocessRuntime(ctx)
  216. await ctx.plugin(PwshLocalExecutor)
  217. subprocess.stderrText = 'target stderr'
  218. subprocess.done = Promise.reject(new Error('provider lost the direct outcome'))
  219. const proc = await ctx.shell.start(ctx.shell.resolve({ command: 'Write-Output maybe-ran' }))
  220. await expect(proc.done).resolves.toBeUndefined()
  221. expect(proc.status).toBe('killed')
  222. const output = proc.readOutput().delta
  223. expect(output).toContain('target stderr')
  224. expect(output).toContain('subprocess failed before reporting an outcome:')
  225. expect(output).not.toContain('spawn failed:')
  226. expect(proc.readOutput().delta).toBe('')
  227. })
  228. it('settles an unprintable provider rejection instead of rejecting done', async () => {
  229. const ctx = createContext()
  230. const subprocess = new CapturingSubprocessRuntime(ctx)
  231. await ctx.plugin(PwshLocalExecutor)
  232. const providerError = new Error('unprintable provider error')
  233. Object.defineProperty(providerError, Symbol.toPrimitive, {
  234. value: () => { throw new Error('provider formatting must not escape') },
  235. })
  236. subprocess.done = Promise.reject(providerError)
  237. const proc = await ctx.shell.start(ctx.shell.resolve({ command: 'Write-Output maybe-ran' }))
  238. await expect(proc.done).resolves.toBeUndefined()
  239. expect(proc.status).toBe('killed')
  240. expect(proc.readOutput().delta).toContain('unprintable provider failure')
  241. expect(proc.readOutput().delta).toBe('')
  242. })
  243. it('preserves an explicit kill stamp and maps an aborted direct outcome to killed', async () => {
  244. const ctx = createContext()
  245. const subprocess = new CapturingSubprocessRuntime(ctx)
  246. await ctx.plugin(PwshLocalExecutor)
  247. const killedOutcome = Promise.withResolvers<SubprocessOutcome>()
  248. subprocess.done = killedOutcome.promise
  249. const killed = await ctx.shell.start(ctx.shell.resolve({ command: 'Write-Output maybe-ran' }))
  250. expect(killed.kill()).toBe(true)
  251. killedOutcome.resolve({ exitCode: 0, signal: null })
  252. await killed.done
  253. expect(killed.status).toBe('killed')
  254. expect(killed.exitCode).toBe(0)
  255. const abortedOutcome = Promise.withResolvers<SubprocessOutcome>()
  256. subprocess.done = abortedOutcome.promise
  257. const controller = new AbortController()
  258. const aborted = await ctx.shell.start(ctx.shell.resolve({
  259. command: 'Write-Output maybe-ran',
  260. signal: controller.signal,
  261. }))
  262. controller.abort()
  263. abortedOutcome.resolve({ exitCode: 0, signal: null })
  264. await aborted.done
  265. expect(aborted.status).toBe('killed')
  266. })
  267. })
  268. describe.skipIf(!hasPwsh)('PwshLocalExecutor.run', () => {
  269. it('resolves with output and the effective timeout', { timeout: 15_000 }, async () => {
  270. const { bash } = await setup({ timeoutMs: 10_000 })
  271. const result = await bash.run(bash.resolve({ command: 'Write-Output hi' }))
  272. expect(result.exitCode).toBe(0)
  273. expect(lf(result.stdout.text)).toBe('hi\n')
  274. expect(result.timeoutMs).toBe(10_000)
  275. })
  276. it('uses config cwd, overridable per call', async () => {
  277. const first = mkdtempSync(join(tmpdir(), 'dsh-pwsh-cwd-a-'))
  278. const second = mkdtempSync(join(tmpdir(), 'dsh-pwsh-cwd-b-'))
  279. tempDirs.push(first, second)
  280. const { bash } = await setup({ cwd: first })
  281. const fromConfig = await bash.run(bash.resolve({ command: '(Get-Location).Path' }))
  282. expect(samePath(fromConfig.stdout.text.trim(), first)).toBe(true)
  283. const fromCall = await bash.run(bash.resolve({ command: '(Get-Location).Path', workdir: second }))
  284. expect(samePath(fromCall.stdout.text.trim(), second)).toBe(true)
  285. })
  286. it('defaults cwd to process.cwd()', async () => {
  287. const { bash } = await setup()
  288. const result = await bash.run(bash.resolve({ command: '(Get-Location).Path' }))
  289. expect(samePath(result.stdout.text.trim(), process.cwd())).toBe(true)
  290. })
  291. it('caps per-call timeouts at maxTimeoutMs', async () => {
  292. const { bash } = await setup({ timeoutMs: 1_000, maxTimeoutMs: 2_000 })
  293. const result = await bash.run(bash.resolve({ command: 'Write-Output ok', timeoutMs: 99_999 }))
  294. expect(result.timeoutMs).toBe(2_000)
  295. })
  296. it('rejects invalid numeric config and timeout overrides', async () => {
  297. await expect(setup({ timeoutMs: Number.NaN })).rejects.toThrow(/timeoutMs/)
  298. await expect(setup({ maxTimeoutMs: 0 })).rejects.toThrow(/maxTimeoutMs/)
  299. await expect(setup({ maxOutputBytes: -1 })).rejects.toThrow(/maxOutputBytes/)
  300. await expect(setup({ maxSpillBytes: 0 })).rejects.toThrow(/maxSpillBytes/)
  301. await expect(setup({ graceMs: 0 })).rejects.toThrow(/graceMs/)
  302. await expect(setup({ graceMs: MAX_TIMER_DELAY_MS + 1 }))
  303. .rejects.toThrow(`graceMs must be no greater than ${MAX_TIMER_DELAY_MS}`)
  304. const { bash } = await setup()
  305. expect(() => bash.resolve({ command: 'Write-Output ok', timeoutMs: Number.NaN })).toThrow(/request\.timeoutMs/)
  306. expect(() => bash.resolve({ command: 'Write-Output ok', timeoutMs: -1 })).toThrow(/request\.timeoutMs/)
  307. expect(() => bash.resolve({ command: 'Write-Output ok', stdoutMaxBytes: Number.NaN })).toThrow(/request\.stdoutMaxBytes/)
  308. expect(() => bash.resolve({ command: 'Write-Output ok', stdoutMaxBytes: -1 })).toThrow(/request\.stdoutMaxBytes/)
  309. })
  310. it('defaults stdoutMaxBytes to maxOutputBytes and lets foreground callers raise stdout only', async () => {
  311. const { bash } = await setup({ maxOutputBytes: 100 })
  312. expect(bash.resolve({ command: 'Write-Output ok' }).stdoutMaxBytes).toBe(100)
  313. // Raw Console writes avoid PowerShell's own line-ending and formatting
  314. // layers, so the byte counts are exact on every platform.
  315. const result = await bash.run(bash.resolve({
  316. command: '[Console]::Out.Write("x" * 500); [Console]::Error.WriteLine("e" * 500)',
  317. stdoutMaxBytes: 500,
  318. }))
  319. expect(result.stdout.text).toBe('x'.repeat(500))
  320. expect(result.stdout.truncated).toBe(false)
  321. expect(result.stderr.truncated).toBe(true)
  322. expect(result.stderr.text.length).toBeLessThanOrEqual(100)
  323. })
  324. it('per-call timeout takes precedence under the cap and kills on expiry', async () => {
  325. const { bash } = await setup({ timeoutMs: 60_000 })
  326. const result = await bash.run(bash.resolve({ command: 'Start-Sleep -Seconds 60', timeoutMs: 100 }))
  327. expect(result.timedOut).toBe(true)
  328. // Mutually exclusive: a timeout classifies as timedOut, never also aborted.
  329. expect(result.aborted).toBe(false)
  330. expect(result.timeoutMs).toBe(100)
  331. })
  332. it('propagates abort signals', async () => {
  333. const { bash } = await setup()
  334. const controller = new AbortController()
  335. const pending = bash.run(bash.resolve({ command: 'Start-Sleep -Seconds 60', signal: controller.signal }))
  336. setTimeout(() => { controller.abort() }, 50)
  337. const result = await pending
  338. expect(result.aborted).toBe(true)
  339. // Mutually exclusive: an upstream cancel classifies as aborted, never also timedOut.
  340. expect(result.timedOut).toBe(false)
  341. })
  342. it('classifies a self-killed command as neither timed out nor aborted', async () => {
  343. const { bash } = await setup({ timeoutMs: 60_000 })
  344. const result = await bash.run(bash.resolve({ command: 'Stop-Process -Id $PID' }))
  345. expect(result.timedOut).toBe(false)
  346. expect(result.aborted).toBe(false)
  347. // Windows reports a forced termination without a signal; POSIX reports the
  348. // terminating signal PowerShell chose (SIGTERM, or SIGKILL for the hard kill).
  349. if (process.platform === 'win32') {
  350. expect(result.signal).toBeNull()
  351. } else {
  352. expect(['SIGTERM', 'SIGKILL']).toContain(result.signal)
  353. }
  354. })
  355. it('rejects on spawn failure (bad workdir)', async () => {
  356. const { bash } = await setup()
  357. await expect(bash.run(bash.resolve({ command: 'Write-Output ok', workdir: '/nonexistent-dsh' }))).rejects.toThrow(/ENOENT/)
  358. })
  359. it('resolve() carries stdin/env/dshEnv onto the spec, and run() threads them to the command', async () => {
  360. const { bash } = await setup()
  361. const spec = bash.resolve({
  362. command: '$s = ([Console]::In.ReadToEnd()).TrimEnd(); Write-Output $s; Write-Output "[$env:SEAM_VAR][$env:DSH_SEAM_VAR]"',
  363. stdin: 'piped\n',
  364. env: { SEAM_VAR: 'env-ok' },
  365. dshEnv: { DSH_SEAM_VAR: 'dsh-ok' },
  366. })
  367. // resolve() keeps the optional input/environment fields verbatim.
  368. expect(spec.stdin).toBe('piped\n')
  369. expect(spec.env).toEqual({ SEAM_VAR: 'env-ok' })
  370. expect(spec.dshEnv).toEqual({ DSH_SEAM_VAR: 'dsh-ok' })
  371. const result = await bash.run(spec)
  372. expect(lf(result.stdout.text)).toBe('piped\n[env-ok][dsh-ok]\n')
  373. })
  374. it('resolve() omits stdin/env/dshEnv when the request supplies none', async () => {
  375. const { bash } = await setup()
  376. const spec = bash.resolve({ command: 'Write-Output ok' })
  377. expect('stdin' in spec).toBe(false)
  378. expect('env' in spec).toBe(false)
  379. expect('dshEnv' in spec).toBe(false)
  380. })
  381. })
  382. describe.skipIf(!hasPwsh)('PwshLocalExecutor.start (background process handles)', () => {
  383. it('start returns immediately with a running handle that settles as completed', async ({ task }) => {
  384. const { bash } = await setup()
  385. const barrier = commandBarrier()
  386. const proc = await bash.start(bash.resolve({
  387. command: `Write-Output ready; [Console]::Out.Flush(); ${barrier.command}; Write-Output done`,
  388. env: barrier.env,
  389. }))
  390. expect(proc.status).toBe('running')
  391. expect(await readUntil(proc, 'ready\n', task.timeout)).toBe('ready\n')
  392. expect(proc.status).toBe('running')
  393. barrier.release()
  394. await proc.done
  395. expect(proc.status).toBe('completed')
  396. expect(proc.signal).toBeNull()
  397. expect(proc.exitCode).toBe(0)
  398. expect(lf(proc.readOutput().delta)).toBe('done\n')
  399. })
  400. it('threads stdin and extra env into a background process', async () => {
  401. const { bash } = await setup()
  402. const proc = await bash.start(bash.resolve({
  403. command: '$s = ([Console]::In.ReadToEnd()).TrimEnd(); Write-Output $s; Write-Output "[$env:BG_VAR][$env:DSH_BG_VAR]"',
  404. stdin: 'bg-stdin\n',
  405. env: { BG_VAR: 'bg-env' },
  406. dshEnv: { DSH_BG_VAR: 'bg-dsh-env' },
  407. }))
  408. await proc.done
  409. expect(proc.status).toBe('completed')
  410. expect(proc.signal).toBeNull()
  411. expect(proc.exitCode).toBe(0)
  412. expect(lf(proc.readOutput().delta)).toBe('bg-stdin\n[bg-env][bg-dsh-env]\n')
  413. })
  414. it('readOutput is consuming: increments are never re-delivered, and reads stay valid after exit', async ({ task }) => {
  415. const { bash } = await setup()
  416. const barrier = commandBarrier()
  417. const proc = await bash.start(bash.resolve({
  418. command: `Write-Output first; [Console]::Out.Flush(); ${barrier.command}; Write-Output second`,
  419. env: barrier.env,
  420. }))
  421. const first = await readUntil(proc, 'first\n', task.timeout)
  422. expect(first).toBe('first\n')
  423. expect(proc.status).toBe('running')
  424. expect(proc.readOutput().delta).toBe('')
  425. barrier.release()
  426. await proc.done
  427. expect(proc.status).toBe('completed')
  428. expect(proc.exitCode).toBe(0)
  429. // Read-after-exit returns the remaining buffered output — once.
  430. const second = proc.readOutput()
  431. expect(lf(second.delta)).toBe('second\n')
  432. expect(second.lossy).toBe(false)
  433. expect(proc.readOutput().delta).toBe('')
  434. })
  435. it('readOutput marks stderr sections', async () => {
  436. const { bash } = await setup()
  437. const proc = await bash.start(bash.resolve({ command: 'Write-Output out; [Console]::Error.WriteLine("err")' }))
  438. await proc.done
  439. expect(lf(proc.readOutput().delta)).toBe('out\n[stderr]\nerr\n')
  440. })
  441. it('readOutput reports stderr-only deltas without a leading newline', async () => {
  442. const { bash } = await setup()
  443. const proc = await bash.start(bash.resolve({ command: '[Console]::Error.WriteLine("err")' }))
  444. await proc.done
  445. expect(lf(proc.readOutput().delta)).toBe('[stderr]\nerr\n')
  446. })
  447. it('readOutput adds a separator only when stdout lacks a trailing newline', async () => {
  448. const { bash } = await setup()
  449. const proc = await bash.start(bash.resolve({ command: '[Console]::Out.Write("out"); [Console]::Error.WriteLine("err")' }))
  450. await proc.done
  451. expect(lf(proc.readOutput().delta)).toBe('out\n[stderr]\nerr\n')
  452. })
  453. it('readOutput flags lossy reads and reports stdout spill paths', async () => {
  454. const { bash } = await setup({ maxOutputBytes: 100 })
  455. const proc = await bash.start(bash.resolve({ command: '1..100 | ForEach-Object { "line-$_" }' }))
  456. await proc.done
  457. const read = proc.readOutput()
  458. // Window slid past offset 0 → lossy, spill path points at the full stream.
  459. expect(read.lossy).toBe(true)
  460. expect(read.stdoutSpillPath).toBeDefined()
  461. })
  462. it('readOutput reports stderr spill paths', async () => {
  463. const { bash } = await setup({ maxOutputBytes: 100 })
  464. const proc = await bash.start(bash.resolve({ command: '1..100 | ForEach-Object { [Console]::Error.WriteLine("line-$_") }' }))
  465. await proc.done
  466. const read = proc.readOutput()
  467. expect(read.lossy).toBe(true)
  468. expect(read.stderrSpillPath).toBeDefined()
  469. expect(lf(read.delta)).toContain('[stderr]')
  470. })
  471. it('kill() requests managed-range termination: true once, false after settlement', async () => {
  472. const { bash } = await setup()
  473. const proc = await bash.start(bash.resolve({ command: 'Start-Sleep -Seconds 60' }))
  474. expect(proc.kill()).toBe(true)
  475. await proc.done
  476. expect(proc.status).toBe('killed')
  477. expect(proc.kill()).toBe(false)
  478. })
  479. it('kill() returns false for a naturally completed process', async () => {
  480. const { bash } = await setup()
  481. const proc = await bash.start(bash.resolve({ command: 'Write-Output ok' }))
  482. await proc.done
  483. expect(proc.status).toBe('completed')
  484. expect(proc.kill()).toBe(false)
  485. })
  486. it('a spec.signal abort settles the handle as killed, not completed', async () => {
  487. const { bash } = await setup()
  488. const controller = new AbortController()
  489. const proc = await bash.start(bash.resolve({ command: 'Start-Sleep -Seconds 60', signal: controller.signal }))
  490. controller.abort()
  491. await proc.done
  492. expect(proc.status).toBe('killed')
  493. })
  494. it.skipIf(process.platform === 'win32')('a self-signal exit settles the handle as killed, not completed (POSIX)', async () => {
  495. const { bash } = await setup()
  496. const proc = await bash.start(bash.resolve({ command: 'Stop-Process -Id $PID' }))
  497. await proc.done
  498. expect(proc.status).toBe('killed')
  499. expect(proc.exitCode).toBeNull()
  500. // PowerShell picks SIGTERM for Stop-Process, SIGKILL for the hard kill.
  501. expect(['SIGTERM', 'SIGKILL']).toContain(proc.signal)
  502. })
  503. it('an asynchronous creation failure settles as killed with a stage-neutral note', async () => {
  504. const { bash } = await setup()
  505. const proc = await bash.start(bash.resolve({ command: 'Write-Output ok', workdir: '/nonexistent-dsh' }))
  506. // done resolves (never rejects) even though the process never ran.
  507. await expect(proc.done).resolves.toBeUndefined()
  508. expect(proc.status).toBe('killed')
  509. expect(proc.readOutput().delta).toContain('subprocess failed before reporting an outcome:')
  510. })
  511. })
  512. describe.skipIf(!hasPwsh)('process lifecycle ownership (the subprocess service, not the executor)', () => {
  513. it('a background process survives executor-fiber disposal and dies with the subprocess service', async ({ task }) => {
  514. const ctx = createContext()
  515. const managerFiber = await ctx.plugin(LocalSubprocessRuntime)
  516. ;(ctx.subprocess as LocalSubprocessRuntime).internals = { spillDir }
  517. const executorFiber = await ctx.plugin(PwshLocalExecutor, { graceMs: 200 })
  518. const bash = ctx.shell as PwshLocalExecutor
  519. // The child prints its own pid so the test can probe liveness through the
  520. // public read surface alone.
  521. const proc = await bash.start(bash.resolve({ command: 'Write-Output $PID; Start-Sleep -Seconds 60' }))
  522. const pid = Number((await readUntil(proc, '\n', task.timeout)).trim())
  523. expect(Number.isInteger(pid) && pid > 0).toBe(true)
  524. // Executor reload/disposal leaves background work running — the
  525. // handle stays live and readable, mirroring the job runtime's
  526. // registrations-outlive-producer-fibers contract.
  527. await executorFiber.dispose()
  528. expect(proc.status).toBe('running')
  529. expect(() => process.kill(pid, 0)).not.toThrow()
  530. // Service disposal kills the group and AWAITS its exit (no orphans).
  531. await managerFiber.dispose()
  532. expect(() => process.kill(pid, 0)).toThrow()
  533. await proc.done
  534. // Service disposal confirmed the tree is gone (kill(pid,0) throws above).
  535. // On POSIX the stamp depends on whether the shell traps SIGTERM and exits
  536. // cleanly (completed) or is killed by the signal (killed); Windows forced
  537. // termination (taskkill, no signals) also stamps completed. Both mean the
  538. // process no longer survives the service.
  539. expect(['killed', 'completed']).toContain(proc.status)
  540. })
  541. it('service disposal settles running handles and leaves settled ones untouched', async () => {
  542. const ctx = createContext()
  543. const managerFiber = await ctx.plugin(LocalSubprocessRuntime)
  544. ;(ctx.subprocess as LocalSubprocessRuntime).internals = { spillDir }
  545. await ctx.plugin(PwshLocalExecutor, { graceMs: 200 })
  546. const bash = ctx.shell as PwshLocalExecutor
  547. const finished = await bash.start(bash.resolve({ command: 'Write-Output done' }))
  548. await finished.done
  549. expect(finished.status).toBe('completed')
  550. const running = await bash.start(bash.resolve({ command: 'Start-Sleep -Seconds 60' }))
  551. await managerFiber.dispose()
  552. // A settled process was untouched; the live one was terminated and joined.
  553. expect(finished.status).toBe('completed')
  554. await running.done
  555. // The live handle was terminated and joined; on POSIX the stamp depends
  556. // on whether the shell traps SIGTERM and exits cleanly (completed) or is
  557. // killed by the signal (killed); Windows forced termination (taskkill, no
  558. // signals) also stamps completed. Both mean the process no longer
  559. // survives the service.
  560. expect(['killed', 'completed']).toContain(running.status)
  561. })
  562. })