Skip to content

fix(windows): one chokepoint for every child process - #15746

Merged
nwparker merged 9 commits into
mainfrom
nwparker/w2-process-spawn-chokepoint
Aug 22, 2026
Merged

nwparker merged 9 commits into
mainfrom
nwparker/w2-process-spawn-chokepoint

Conversation

@nwparker

@nwparker nwparker commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1252 $\color{#cf222e}{\Huge{\mathbf{−}}}$​508 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​744
Prod 13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​669 $\color{#cf222e}{\Huge{\mathbf{−}}}$​296 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​373

Why

There is no one place in Orca where "run a program on Windows" is defined. 179 child_process calls across 109 files each independently re-decide: hide the console or not, how to quote for cmd.exe, whether the target needs cmd.exe at all, how to resolve the binary, what timeout to use. POSIX forgives all six. Windows punishes each differently, so the same gap reaches users as several unrelated-looking bugs.

This PR adds the chokepoint and migrates the sites where the gap is most visible.

What the measurements showed

I derived the Windows argument encoding on a real Windows 11 box rather than from documentation, and the results changed the design:

Approach Result
spawn('foo.cmd', args, {shell:false}) EINVAL — Node blocks it outright (CVE-2024-27980 mitigation)
spawn('foo.cmd', args, {shell:true}) starts, but escapes nothing — 6 of 13 adversarial arguments corrupted
cmd.exe /d /v:off /s /c + the encoding here 20/20

shell: true is worse than mangling. Sent a&b, the child received "a" and b ran as a command. That is argument injection, and it is the shape agent prompts take (Fix "src/a b.ts" & run tests 100%). shell: true also silently makes windowsHide a no-op, which is the console flash in #14543.

The non-obvious part: the usual \" escaping is wrong here. CommandLineToArgvW understands \", but cmd.exe counts " naively — so \" flips cmd's quote parity and every later & | < > on the line stops being data. Writing "" instead keeps both parsers happy. Each % is additionally broken out of the quoted run as "^%", because %VAR% expands even inside quotes (x%ORCATEST%y arrived as xBOOMy).

Measured before/after on the composed case:

sent:   ["a b", 'c"d', "e%F%g", "h&i", "j^k"]
before: ["a b", 'c"d', "e^%F^%g", "h"]        <- & truncated the arg and ran the rest
after:  ["a b", 'c"d', "e%F%g", "h&i", "j^k"]

Node's own quoting is already correct for real .exe targets (19/19), so the chokepoint only special-cases .cmd/.bat. That keeps the surface small.

What changed

  • src/shared/child-process/ — runProcess, runProcessSync, spawnProcess. windowsHide unconditionally, shell: false unconditionally, one timeout policy, .cmd routed through a verbatim cmd.exe line.
  • resolveSpawn is pure and exported, so the Windows branch is testable from macOS/Linux. These decisions must not be observable only on the platform that breaks.
  • Migrated: the ssh -G probe, the ProxyJump tunnel, the ProxyCommand wrapper, font enumeration, the DPAPI cookie decrypt.
  • PowerShell is now spawned by absolute System32 path, not bare name.
  • Deleted system-fonts' 40-line bespoke execFileText.

Tests

  • 42 unit tests. The encoder is checked against a model of CommandLineToArgvW and against cmd's quote-parity rule — not against itself.
  • windows-command-line.win32.test.ts runs the same corpus through a real .cmd shim, with %F%/%VAR% set as live variables so the percent cases cannot pass by accident. Includes an explicit assertion that the tail of an & argument does not execute.
  • Three suites that mocked child_process directly now mock runProcess. That is the point: how a process starts is no longer each module's business.
  • child-process-import-boundary.test.ts is a ratchet seeded at today's count, currently 173 → 170. It only shrinks. It also fails on a stale entry, so a migrated file cannot stay listed and hide the next regression, and it asserts it scanned enough files so it can never go vacuous.

Issues

Closes #10488. Addresses the windowsHide half of #14543 and the bare-name half of #11771. Lays the groundwork for #8793, #11374, #6694 (the .cmd argv encoding they need is here; their call sites migrate next).

Follow-ups

  • Font enumeration still needs PowerShell, so a Group Policy block still degrades to the fallback list. Reading HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts via the registry dependency already in package.json would remove that; filed separately since deriving families from per-style registry names is a behaviour change.
  • 170 files remain on the ratchet.

Six decisions have to be made every time Orca starts a child process --
console visibility, argument quoting, .cmd interpretation, binary
resolution, timeout policy, and how the tree is later terminated. POSIX
forgives all six. Windows punishes each differently, and made per-call
site across 172 files they were right in some and wrong in others.

runProcess/spawnProcess make them once:
- windowsHide unconditionally, shell:false unconditionally (shell:true
  concatenates argv unescaped and silently disables windowsHide)
- .cmd/.bat routed through cmd.exe /d /v:off /s /c with a verbatim line,
  because Node refuses to spawn them otherwise (EINVAL)

The encoding was derived by measurement on Windows 11, not from the
docs. An embedded quote is written "" rather than \" so cmd's naive
quote count stays even -- with \" the parity flips and every later &
| < > on the line stops being data. Measured before the fix, argv
["a b", 'c"d', "e%F%g", "h&i", "j^k"] arrived as
["a b", 'c"d', "e^%F^%g", "h"]: the & truncated the argument and
ran its remainder as a command. Each % is broken out of the quoted run
as "^%" because %VAR% expands even inside quotes.

The import-boundary test is a ratchet seeded at today's 172 files; it
only shrinks.
…epoint

The ssh -G config probe fires on every connect and reconnect, and ssh.exe
is console-subsystem, so a GUI-subsystem parent gets a fresh visible
conhost that takes foreground -- keystrokes typed into an Orca terminal
at that moment go into the black box (#10488, #14543). Same for the
ProxyJump tunnel, the ProxyCommand cmd.exe wrapper, the font enumeration
and the DPAPI cookie decrypt.

Also stops spawning powershell by bare name: PATH under Electron is not
the user's, so where policy has pruned the System32 entry the spawn fails
and the font picker silently reports five hardcoded families rather than
an error (#11771).

Deletes system-fonts' 40-line bespoke execFileText -- timeout, output cap
and kill are the chokepoint's job now. Adds runProcessSync so the sync
callers have a compliant path; without one the ratchet could never
reach zero.

The three suites that mocked child_process directly now mock runProcess,
which is the point: how a process gets started is no longer each
module's business. Ratchet 173 -> 170.
@coderabbitai

coderabbitai Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8345233d-d00c-404d-a83d-19b665c48e9e

📥 Commits

Reviewing files that changed from the base of the PR and between 2d63a82 and 645fb37.

📒 Files selected for processing (5)
  • src/shared/child-process/__fixtures__/windows-argument-corpus.ts
  • src/shared/child-process/run-process.test.ts
  • src/shared/child-process/run-process.ts
  • src/shared/child-process/windows-command-line.test.ts
  • src/shared/child-process/windows-command-line.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

The change adds centralized asynchronous and synchronous child-process runners with structured results, bounded output capture, timeout handling, abort support, and Windows spawn resolution. It adds Windows command-line quoting and system-binary path utilities with corpus-based tests. Browser, SSH, font, emulator, filesystem, memory, PowerShell, and macOS login-shell process calls now use the shared helpers. Tests and an import-boundary guard validate the migration and process behavior.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 38.18% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 55 functions across 27 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description covers implementation, rationale, testing, issues, and follow-ups, but omits several required template sections. Add the missing ELI5, Visual Proof, AI Disclosure, Review, Agent skill boundary, Notes, and Checklist sections.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the centralized Windows child-process change.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Nitpick comments (3)
src/shared/child-process/child-process-import-allowlist.ts (1)

1-13: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reduce the policy comments to their local invariants.

  • src/shared/child-process/child-process-import-allowlist.ts#L1-L13: retain the allowlist purpose and migration instruction.
  • src/shared/child-process/child-process-import-boundary.test.ts#L6-L17: retain the boundary invariant and the required runner path.

As per coding guidelines, comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.

Source: Coding guidelines

src/shared/child-process/run-process.ts (1)

100-104: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Narrow the spawnProcess parameter type.

spawnProcess accepts a full ProcessSpec but honours only program, args, cwd, and env. A caller that passes timeoutMs, input, maxOutputBytes, or signal gets silent no-ops. Accept a launch-only type so the compiler rejects the ignored fields.

♻️ Proposed refactor
+export type ProcessLaunchSpec = Pick<ProcessSpec, 'program' | 'args' | 'cwd' | 'env'>
+
 /** Start a child process. Use for long-lived or streaming children. */
-export function spawnProcess(spec: ProcessSpec): ChildProcess {
+export function spawnProcess(spec: ProcessLaunchSpec): ChildProcess {
   const resolved = resolveSpawn(spec, process.platform)
   return nodeSpawn(resolved.file, [...resolved.args], resolved.options)
 }
src/shared/child-process/run-process.test.ts (1)

1-61: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add tests for the runProcess runtime paths.

This suite covers resolveSpawn only. The lifecycle policies that the module exists to centralize have no coverage: timeoutMs expiry and the timedOut flag, AbortSignal cancellation including an already-aborted signal, maxOutputBytes truncation, input delivery to a child that exits early, and rejection when the program cannot be started. These are the same paths I flagged in run-process.ts. Tests here can use a portable child such as process.execPath with -e, so they run on macOS, Linux, and Windows.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a1f518a3-5783-4566-b2f0-6522f6a8ae73

📥 Commits

Reviewing files that changed from the base of the PR and between 59892a2 and a80e597.

📒 Files selected for processing (15)
  • src/main/browser/browser-cookie-import.ts
  • src/main/ssh/ssh-config-resolver.test.ts
  • src/main/ssh/ssh-g-config-resolution.ts
  • src/main/ssh/ssh-proxy-command.ts
  • src/main/system-fonts.test.ts
  • src/main/system-fonts.ts
  • src/shared/child-process/child-process-import-allowlist.ts
  • src/shared/child-process/child-process-import-boundary.test.ts
  • src/shared/child-process/run-process.test.ts
  • src/shared/child-process/run-process.ts
  • src/shared/child-process/windows-command-line-corpus.ts
  • src/shared/child-process/windows-command-line.test.ts
  • src/shared/child-process/windows-command-line.ts
  • src/shared/child-process/windows-command-line.win32.test.ts
  • src/shared/child-process/windows-system-binary.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment on lines +18 to +22
const IMPORT_PATTERN =
/(?:from\s+['"]node:child_process['"]|from\s+['"]child_process['"]|require\(\s*['"]node:child_process['"]|require\(\s*['"]child_process['"])/

const OWNER_DIRECTORY = 'src/shared/child-process'
const SCANNED_EXTENSIONS = ['.ts', '.tsx']

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- tracked candidate files ---'
git ls-files | rg '(^|/)(child-process-import-boundary\.test\.ts|child-process-import-allowlist\.ts)$|child-process'

printf '%s\n' '--- file outline ---'
if command -v ast-grep >/dev/null 2>&1; then
  ast-grep outline src/shared/child-process/child-process-import-boundary.test.ts
  ast-grep outline src/shared/child-process/child-process-import-allowlist.ts
fi

printf '%s\n' '--- boundary test ---'
cat -n src/shared/child-process/child-process-import-boundary.test.ts

printf '%s\n' '--- allowlist ---'
cat -n src/shared/child-process/child-process-import-allowlist.ts

printf '%s\n' '--- related references ---'
rg -n --glob '*.{ts,tsx,js,jsx}' 'IMPORT_PATTERN|SCANNED_EXTENSIONS|child-process-import|node:child_process|from ['"'"'"]child_process|require\(' src package.json 2>/dev/null || true

Repository: stablyai/orca

Length of output: 50372


🏁 Script executed:

#!/bin/bash
set -eu

cat -n src/shared/child-process/child-process-import-boundary.test.ts
cat -n src/shared/child-process/child-process-import-allowlist.ts
rg -n --glob '*.{ts,tsx,js,jsx}' 'IMPORT_PATTERN|SCANNED_EXTENSIONS|child-process-import|node:child_process|from ["'"'"']child_process|require\(' src package.json 2>/dev/null || true

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -eu

python3 - <<'PY'
from pathlib import Path
import re

root = Path("src")
extensions = {".ts", ".tsx"}
all_source = []
scanned = []
js_like = []
direct_js_like = []

pattern = re.compile(
    r"""(?:from\s+['"]node:child_process['"]|from\s+['"]child_process['"]|require\(\s*['"]node:child_process['"]|require\(\s*['"]child_process['"])"""
)

samples = {
    "named import": "import { spawn } from 'node:child_process'",
    "side-effect import": "import 'node:child_process'",
    "dynamic import": "const cp = import('node:child_process')",
    "require": "const cp = require('node:child_process')",
    "bare child_process import": "import { spawn } from 'child_process'",
    "bare side-effect import": "import 'child_process'",
    "bare dynamic import": "const cp = import('child_process')",
}

print("--- pattern behavior ---")
for name, text in samples.items():
    print(f"{name}: {'MATCH' if pattern.search(text) else 'MISS'}")

for path in root.rglob("*"):
    if not path.is_file():
        continue
    all_source.append(path)
    if path.suffix in extensions:
        scanned.append(path)
    if path.suffix in {".js", ".jsx"}:
        js_like.append(path)
        text = path.read_text(encoding="utf-8", errors="replace")
        if "child_process" in text:
            direct_js_like.append(path)

print("--- source counts ---")
print(f"src files: {len(all_source)}")
print(f"scanned .ts/.tsx files: {len(scanned)}")
print(f".js/.jsx files: {len(js_like)}")
print(f".js/.jsx files containing child_process text: {len(direct_js_like)}")
for path in direct_js_like[:20]:
    print(path)

hypothetical = Path("src/example-production.ts")
text = "const cp = import('node:child_process')"
print("--- hypothetical production file ---")
print(f"extension scanned: {hypothetical.suffix in extensions}")
print(f"pattern matched: {bool(pattern.search(text))}")
print(f"would be an offender: {hypothetical.suffix in extensions and bool(pattern.search(text))}")
PY

Repository: stablyai/orca

Length of output: 593


🏁 Script executed:

#!/bin/bash
set -eu

python3 - <<'PY'
from pathlib import Path
import re

root = Path("src")
extensions = {".ts", ".tsx"}
pattern = re.compile(
    r"""(?:from\s+['"]node:child_process['"]|from\s+['"]child_process['"]|require\(\s*['"]node:child_process['"]|require\(\s*['"]child_process['"])"""
)

samples = {
    "named import": "import { spawn } from 'node:child_process'",
    "side-effect import": "import 'node:child_process'",
    "dynamic import": "const cp = import('node:child_process')",
    "require": "const cp = require('node:child_process')",
    "bare side-effect import": "import 'child_process'",
    "bare dynamic import": "const cp = import('child_process')",
}

print("--- pattern behavior ---")
for name, text in samples.items():
    print(f"{name}: {'MATCH' if pattern.search(text) else 'MISS'}")

all_files = [p for p in root.rglob("*") if p.is_file()]
js_like = [p for p in all_files if p.suffix in {".js", ".jsx"}]
direct_js_like = [
    p for p in js_like
    if "child_process" in p.read_text(encoding="utf-8", errors="replace")
]

print("--- source counts ---")
print(f"src files: {len(all_files)}")
print(f"scanned .ts/.tsx files: {sum(p.suffix in extensions for p in all_files)}")
print(f".js/.jsx files: {len(js_like)}")
print(f".js/.jsx files containing child_process text: {len(direct_js_like)}")
for path in direct_js_like[:20]:
    print(path)

text = "const cp = import('node:child_process')"
print("--- hypothetical production file ---")
print(f"extension scanned: {Path('src/example-production.ts').suffix in extensions}")
print(f"pattern matched: {bool(pattern.search(text))}")
PY

Repository: stablyai/orca

Length of output: 532


Cover dynamic and side-effect child_process imports.

IMPORT_PATTERN misses import('node:child_process') and import 'node:child_process', so a new .ts or .tsx production importer can bypass the boundary. Cover these forms and scan .js/.jsx when supported. Add regression cases.

Source: Coding guidelines

Comment thread src/shared/child-process/run-process.ts Outdated
Comment on lines +132 to +139
const collect = (chunks: Buffer[], chunk: Buffer, bytes: number): number => {
const remaining = maxOutputBytes - bytes
if (remaining <= 0) {
return bytes
}
chunks.push(chunk.length > remaining ? chunk.subarray(0, remaining) : chunk)
return bytes + chunk.length
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Align the maxOutputBytes contract across the async and sync runners.

The doc comment on lines 38-39 states the process is killed beyond the cap. The async path does not kill it: collect truncates and the child keeps running and writing. The sync path passes the value as maxBuffer on line 223, so Node aborts the child and reports ENOBUFS, which line 226 rethrows. A caller that moves between runProcess and runProcessSync therefore changes failure mode from silent truncation to a thrown error.

Pick one behaviour and document it. Truncation also cuts at an arbitrary byte offset, so a split multi-byte UTF-8 sequence decodes as U+FFFD; use a StringDecoder if the truncated tail must stay valid.

🐛 Proposed fix: make the async path fail the same way
     const collect = (chunks: Buffer[], chunk: Buffer, bytes: number): number => {
       const remaining = maxOutputBytes - bytes
       if (remaining <= 0) {
         return bytes
       }
       chunks.push(chunk.length > remaining ? chunk.subarray(0, remaining) : chunk)
+      if (bytes + chunk.length > maxOutputBytes) {
+        outputOverflowed = true
+        terminate(child)
+      }
       return bytes + chunk.length
     }

Then surface outputOverflowed on ProcessResult, or align the sync path to truncate instead of throwing.

🧰 Tools
🪛 ast-grep (0.45.1)

[warning] 5: Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import {
spawn as nodeSpawn,
spawnSync as nodeSpawnSync,
type ChildProcess,
type SpawnOptions as NodeSpawnOptions
} from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

Comment thread src/shared/child-process/run-process.ts Resolved
Comment thread src/shared/child-process/run-process.ts Resolved
@nwparker

Copy link
Copy Markdown
Contributor Author

Validated on real Windows 11 (build 26200, Node 24.18) rather than only in the model-based unit tests:

 ✓ src/shared/child-process/run-process.test.ts (5 tests)
 ✓ src/shared/child-process/windows-command-line.test.ts (33 tests)
 ✓ src/shared/child-process/windows-command-line.win32.test.ts (22 tests) 1679ms
 ✓ src/shared/child-process/child-process-import-boundary.test.ts (4 tests)

 Test Files  4 passed (4)
      Tests  64 passed (64)

The 22 win32 cases are the ones that matter — they push each adversarial argument through a real .cmd shim with %F%/%VAR% set as live environment variables, so the percent cases cannot pass by accident. That includes the assertion that the tail of an & argument does not execute.

runProcessSync inferred a timeout from signal === 'SIGTERM'. Measured:
a real timeout sets error.code ETIMEDOUT and kills with SIGTERM, but so
does anything else that terminates the child -- and those cases set no
error at all. Reading the signal alone reports a process someone stopped
on purpose as having timed out, which callers retry.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/shared/child-process/run-process.ts (1)

219-223: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Make the synchronous timeout terminal.

When a POSIX child handles SIGTERM, spawnSync can wait indefinitely after timeoutMs. Set killSignal to SIGKILL and add a POSIX regression test with a child that ignores SIGTERM.

Proposed fix
     input: spec.input,
     timeout: spec.timeoutMs ?? DEFAULT_PROCESS_TIMEOUT_MS,
+    killSignal: 'SIGKILL',
     maxBuffer: spec.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: fe2d166b-1778-412b-bb12-db7632a1b6db

📥 Commits

Reviewing files that changed from the base of the PR and between a80e597 and d4f852c.

📒 Files selected for processing (2)
  • src/shared/child-process/run-process.test.ts
  • src/shared/child-process/run-process.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

The allowlist and the adversarial argument corpus are read only by tests,
so they were production modules in name only; they move to __fixtures__.

pwsh.ts carried isTimeoutError() purely to reconcile two spellings of the
same event -- execFileSync reports a timeout as ETIMEDOUT, the execFile
callback as a SIGTERM kill with no code. runProcess reports one timedOut
flag, so the helper and the reasoning behind it both go.

Its sync probe also spawned without windowsHide, which flashes a console
and steals foreground on every cold cache read.
Each one deletes a hand-rolled promise/timeout/kill wrapper and stops
re-deciding console visibility for itself. Ratchet 170 -> 164.

Two things this surfaced, both kept:

runProcess now accepts string chunks as well as buffers. A stream someone
called setEncoding on emits strings, and concatenating those as buffers
throws inside a data handler -- where the rejection has nowhere to go and
the caller simply hangs rather than failing.

ProcessSpec keeps its AbortSignal. I had removed it as unused; the macOS
PAM preflight passes one through from its own caller.

ipc/app.ts is deliberately NOT migrated. Its probe spawns a three-stage
 pipeline detached so a timeout can reap the group with one
negative-pid SIGKILL; runProcess kills only the root, which would orphan
the plutil stages. Migrating it needs the chokepoint to own POSIX
process-group termination first -- the same guarantee job objects give on
Windows. Reverted and left on the ratchet.
@nwparker

Copy link
Copy Markdown
Contributor Author

Elegance pass

The stack was +735 net production lines; it is now +451. Where that came from, and where it didn't:

Test data was miscounted as production code (−227). The ratchet allowlist and the adversarial argument corpus are imported only by tests. They are now fixtures, which is also just what they are.

Six more call sites migrated (−107). Each deletes a hand-rolled promise/timeout/kill wrapper: pwsh.ts, local-worktree-filesystem.ts, host-memory.ts, macos-tcc-login-shell.ts, windows-process-resource-collector.ts, serve-sim-execution.ts. Ratchet 170 → 163.

pwsh.ts is the clearest case for why the chokepoint earns its size. It carried this:

// Why: execFileSync reports a timeout as ETIMEDOUT, but the execFile callback
// reports it as a SIGTERM kill with no code — both shapes must be recognised
// or the async probe caches a cold-start timeout as "pwsh missing".

That helper and the reasoning behind it are gone; timedOut is one shape. Its sync probe was also spawning without windowsHide.

Three defects the pass surfaced

  1. runProcessSync reported deliberate kills as timeouts. It inferred from signal === 'SIGTERM'; measured, only a real timeout also sets ETIMEDOUT. Callers that retry on timeout would have retried a process someone stopped on purpose.
  2. runProcess assumed Buffer chunks. A stream with setEncoding emits strings, Buffer.concat throws inside the data handler, and the caller hangs instead of failing. Now accepts both.
  3. I removed AbortSignal as unused and was wrong — the macOS PAM preflight threads one through. Restored.

One migration deliberately reverted

ipc/app.ts spawns a three-stage sh -c pipeline detached, so its timeout can reap the group with one negative-pid SIGKILL:

// Why: killing only the shell orphans pipeline stages; detached spawn lets one negative-pid SIGKILL reap the whole group.

runProcess kills only the root, so migrating it would orphan the plutil stages — reintroducing exactly the bug class this stack exists to remove. Reverted and left on the ratchet.

That is the most useful thing this pass found: the chokepoint has no POSIX process-group termination. It is the POSIX analogue of the job object in #15755, and it is what the next batch of migrations needs before they are safe.

On net-negative

Honest arithmetic: the new shared capability is ~660 lines; migrations have paid back ~270. Reaching net-negative needs roughly 15–20 more migrations at the observed rate, and the ratchet guarantees they only go one way. I could get there today by deleting the identity/taskkill fallback (~170 prod + ~250 test), but that fallback is load-bearing on hosts where job assignment is refused, and trading it for a line count is the wrong trade.

30,199 tests green, pnpm typecheck and oxlint clean across the stack.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
src/shared/child-process/__fixtures__/windows-argument-corpus.ts (1)

1-12: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Condense the new comments.

Keep one concise line for each non-obvious constraint.

  • src/shared/child-process/__fixtures__/windows-argument-corpus.ts#L1-L12: State only the corpus purpose.
  • src/shared/child-process/__fixtures__/windows-argument-corpus.ts#L36-L39: State only that the environment makes expansion cases deterministic.
  • src/shared/child-process/run-process.ts#L107-L113: State only that the sink accepts buffers and strings.
  • src/shared/child-process/run-process.ts#L186-L188: State only that stdin closes to deliver EOF.

As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line.”

Source: Coding guidelines

src/main/memory/collector.test.ts (1)

30-32: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Shorten this test comment.

Use one line for the mock rationale.

As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line.”

Proposed change
-// Why mock the chokepoint for the Windows sweep: maxBuffer, timeout and the
-// hidden console are its contract now, so the assertions below are about which
-// query runs, not how a process is started.
+// Mock the chokepoint so Windows tests verify query specifications.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9f1493f3-d998-4096-bf72-52a017ae2f3c

📥 Commits

Reviewing files that changed from the base of the PR and between d4f852c and 2d63a82.

📒 Files selected for processing (18)
  • src/main/emulator/serve-sim-execution.ts
  • src/main/local-worktree-filesystem.test.ts
  • src/main/local-worktree-filesystem.ts
  • src/main/memory/collector.test.ts
  • src/main/memory/host-memory.test.ts
  • src/main/memory/host-memory.ts
  • src/main/memory/windows-process-resource-collector.ts
  • src/main/providers/macos-tcc-login-shell.test.ts
  • src/main/providers/macos-tcc-login-shell.ts
  • src/main/pwsh.test.ts
  • src/main/pwsh.ts
  • src/shared/child-process/__fixtures__/child-process-import-allowlist.txt
  • src/shared/child-process/__fixtures__/windows-argument-corpus.ts
  • src/shared/child-process/child-process-import-boundary.test.ts
  • src/shared/child-process/run-process.test.ts
  • src/shared/child-process/run-process.ts
  • src/shared/child-process/windows-command-line.test.ts
  • src/shared/child-process/windows-command-line.win32.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.

Windows has no signals, so the same deliberate kill reports an exit code
there and a signal on POSIX. What has to hold on both is that neither
shape reads as a timeout. Caught by running the suite on Windows.

(cherry picked from commit 0a6e990)
…kill

close only fires once the child is actually gone, so a child that traps
SIGTERM never emits it and the promise outlives its own deadline
forever. That is the same wedge shape just fixed for the process table,
and it is worse here: pwsh.ts and the snapshot reader both cache an
in-flight probe, so one unkillable child hands every later caller the
same dead promise.

After the deadline it now escalates to SIGKILL and settles regardless,
reporting timedOut with whatever output arrived.

(cherry picked from commit 78ac169)
The grace escalation I added covered the timeout path and left abort on
the old one, so an aborted caller with an unkillable child still waited
forever -- the same defect, one path over. The macOS PAM preflight is a
real caller that passes an AbortSignal.

Both paths now share one stop-and-settle, and the result reports
timedOut honestly: false when the caller aborted.

(cherry picked from commit 7e9523a)
escapePercentForCmd ran as a post-pass over the quoted string, so it
inserted a quote wherever a percent was -- including straight after a
backslash. CommandLineToArgvW reads backslash-quote as an escaped quote,
so C:\Users\%USERNAME%\x arrived corrupted. That is about as common as
Windows paths get, and my 20-case corpus had no backslash-before-percent
entry to catch it.

Percent handling is now part of the quoting loop, where the backslash
run is known and can be doubled before the inserted quote. Two corpus
cases cover the shape.

The program path gets the same treatment. It was quoted but not
percent-escaped, so a launcher under C:\Users\%USERNAME%\ had its own
path expanded on the cmd hop.

quoteWindowsArgument no longer takes a boolean. Passing it to
values.map() handed map's index in as the flag -- which is how the first
version of this fix was written, and the corpus test caught it.

Separately: an AbortSignal that was already aborted never fires the
event, so runProcess ran the child to its full timeout for a caller who
had already given up.

(cherry picked from commit f7e2e56)
@nwparker

Copy link
Copy Markdown
Contributor Author

Merged to main.

Closed by this stack: #10488, #15209, #9045, #10475, #10897, #9195, #10415.

Commented, not closed — partially addressed or needing a reporter re-test: #14543, #11771, #15036, #10686, #10087, #8275, #10150, #10358, #10857.

Withdrawn: #15549 — I claimed it early and hardware testing disproved it. Job liveness reports null, not [], for a dead tree.

Windows CI now gates the argv encoder against real cmd.exe, per-pane tree kill, clean-exit preservation, breakaway, and host-death reaping.

paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 23, 2026
* feat(process): add the Windows-correct child-process chokepoint

Six decisions have to be made every time Orca starts a child process --
console visibility, argument quoting, .cmd interpretation, binary
resolution, timeout policy, and how the tree is later terminated. POSIX
forgives all six. Windows punishes each differently, and made per-call
site across 172 files they were right in some and wrong in others.

runProcess/spawnProcess make them once:
- windowsHide unconditionally, shell:false unconditionally (shell:true
  concatenates argv unescaped and silently disables windowsHide)
- .cmd/.bat routed through cmd.exe /d /v:off /s /c with a verbatim line,
  because Node refuses to spawn them otherwise (EINVAL)

The encoding was derived by measurement on Windows 11, not from the
docs. An embedded quote is written "" rather than \" so cmd's naive
quote count stays even -- with \" the parity flips and every later &
| < > on the line stops being data. Measured before the fix, argv
["a b", 'c"d', "e%F%g", "h&i", "j^k"] arrived as
["a b", 'c"d', "e^%F^%g", "h"]: the & truncated the argument and
ran its remainder as a command. Each % is broken out of the quoted run
as "^%" because %VAR% expands even inside quotes.

The import-boundary test is a ratchet seeded at today's 172 files; it
only shrinks.

* fix(process): route the console-flashing spawn sites through the chokepoint

The ssh -G config probe fires on every connect and reconnect, and ssh.exe
is console-subsystem, so a GUI-subsystem parent gets a fresh visible
conhost that takes foreground -- keystrokes typed into an Orca terminal
at that moment go into the black box (stablyai#10488, stablyai#14543). Same for the
ProxyJump tunnel, the ProxyCommand cmd.exe wrapper, the font enumeration
and the DPAPI cookie decrypt.

Also stops spawning powershell by bare name: PATH under Electron is not
the user's, so where policy has pruned the System32 entry the spawn fails
and the font picker silently reports five hardcoded families rather than
an error (stablyai#11771).

Deletes system-fonts' 40-line bespoke execFileText -- timeout, output cap
and kill are the chokepoint's job now. Adds runProcessSync so the sync
callers have a compliant path; without one the ratchet could never
reach zero.

The three suites that mocked child_process directly now mock runProcess,
which is the point: how a process gets started is no longer each
module's business. Ratchet 173 -> 170.

* fix(process): do not report a deliberately killed child as timed out

runProcessSync inferred a timeout from signal === 'SIGTERM'. Measured:
a real timeout sets error.code ETIMEDOUT and kills with SIGTERM, but so
does anything else that terminates the child -- and those cases set no
error at all. Reading the signal alone reports a process someone stopped
on purpose as having timed out, which callers retry.

* refactor(process): hold the ratchet as data and migrate the pwsh probes

The allowlist and the adversarial argument corpus are read only by tests,
so they were production modules in name only; they move to __fixtures__.

pwsh.ts carried isTimeoutError() purely to reconcile two spellings of the
same event -- execFileSync reports a timeout as ETIMEDOUT, the execFile
callback as a SIGTERM kill with no code. runProcess reports one timedOut
flag, so the helper and the reasoning behind it both go.

Its sync probe also spawned without windowsHide, which flashes a console
and steals foreground on every cold cache read.

* refactor(process): migrate five more spawn sites onto the chokepoint

Each one deletes a hand-rolled promise/timeout/kill wrapper and stops
re-deciding console visibility for itself. Ratchet 170 -> 164.

Two things this surfaced, both kept:

runProcess now accepts string chunks as well as buffers. A stream someone
called setEncoding on emits strings, and concatenating those as buffers
throws inside a data handler -- where the rejection has nowhere to go and
the caller simply hangs rather than failing.

ProcessSpec keeps its AbortSignal. I had removed it as unused; the macOS
PAM preflight passes one through from its own caller.

ipc/app.ts is deliberately NOT migrated. Its probe spawns a three-stage
 pipeline detached so a timeout can reap the group with one
negative-pid SIGKILL; runProcess kills only the root, which would orphan
the plutil stages. Migrating it needs the chokepoint to own POSIX
process-group termination first -- the same guarantee job objects give on
Windows. Reverted and left on the ratchet.

* test(process): do not assert a POSIX signal on Windows

Windows has no signals, so the same deliberate kill reports an exit code
there and a signal on POSIX. What has to hold on both is that neither
shape reads as a timeout. Caught by running the suite on Windows.

(cherry picked from commit 0a6e990)

* fix(process): settle a timed-out run even when the child ignores the kill

close only fires once the child is actually gone, so a child that traps
SIGTERM never emits it and the promise outlives its own deadline
forever. That is the same wedge shape just fixed for the process table,
and it is worse here: pwsh.ts and the snapshot reader both cache an
in-flight probe, so one unkillable child hands every later caller the
same dead promise.

After the deadline it now escalates to SIGKILL and settles regardless,
reporting timedOut with whatever output arrived.

(cherry picked from commit 78ac169)

* fix(process): escalate an aborted child too, not just a timed-out one

The grace escalation I added covered the timeout path and left abort on
the old one, so an aborted caller with an unkillable child still waited
forever -- the same defect, one path over. The macOS PAM preflight is a
real caller that passes an AbortSignal.

Both paths now share one stop-and-settle, and the result reports
timedOut honestly: false when the caller aborted.

(cherry picked from commit 7e9523a)

* fix(windows): stop percent escaping from forging an escaped quote

escapePercentForCmd ran as a post-pass over the quoted string, so it
inserted a quote wherever a percent was -- including straight after a
backslash. CommandLineToArgvW reads backslash-quote as an escaped quote,
so C:\Users\%USERNAME%\x arrived corrupted. That is about as common as
Windows paths get, and my 20-case corpus had no backslash-before-percent
entry to catch it.

Percent handling is now part of the quoting loop, where the backslash
run is known and can be doubled before the inserted quote. Two corpus
cases cover the shape.

The program path gets the same treatment. It was quoted but not
percent-escaped, so a launcher under C:\Users\%USERNAME%\ had its own
path expanded on the cmd hop.

quoteWindowsArgument no longer takes a boolean. Passing it to
values.map() handed map's index in as the flag -- which is how the first
version of this fix was written, and the corpus test caught it.

Separately: an AbortSignal that was already aborted never fires the
event, so runProcess ran the child to its full timeout for a caller who
had already given up.

(cherry picked from commit f7e2e56)
(cherry picked from commit b7e79b7)
zpyoung added a commit to zpyoung/orca that referenced this pull request Aug 26, 2026
v1.4.190 makes runWslProcess the one chokepoint for wsl.exe (stablyai#15903, stablyai#15923)
and runProcess the one chokepoint for child processes (stablyai#15746), and both are
now ratcheted. The fork's live-plugin-marketplace WSL source still called
execFile('wsl.exe', buildWslExecArgs(...)) directly, which broke five checks
from one cause:

- child-process-import-boundary: a direct node:child_process import, and the
  offender count 153 over its 152 ceiling
- wsl-invocation-boundary (unit and package (windows)): a direct wsl.exe spawn
- skill-discovery-wsl-plugins: upstream's test mocks runWslProcess and expects
  two calls; the fork's execFile bypassed the mock, so the scan consumed the
  metadata frames and parseWslSkillDiscoveryOutput rejected record kind F
- the feature's own WSL tests, which mocked child_process

Adopt the sibling reader's migrated shape (loginPath 'none', shell 'bash',
maxOutputBytes, throw on non-zero or timeout) — the payload is that reader's
and stays bash. The runner takes the script unencoded, so the test's base64
decode is gone; the --exec assertion is replaced by one on the spec the fork
now owns, since --exec and payload transport moved into the runner.
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
* feat(process): add the Windows-correct child-process chokepoint

Six decisions have to be made every time Orca starts a child process --
console visibility, argument quoting, .cmd interpretation, binary
resolution, timeout policy, and how the tree is later terminated. POSIX
forgives all six. Windows punishes each differently, and made per-call
site across 172 files they were right in some and wrong in others.

runProcess/spawnProcess make them once:
- windowsHide unconditionally, shell:false unconditionally (shell:true
  concatenates argv unescaped and silently disables windowsHide)
- .cmd/.bat routed through cmd.exe /d /v:off /s /c with a verbatim line,
  because Node refuses to spawn them otherwise (EINVAL)

The encoding was derived by measurement on Windows 11, not from the
docs. An embedded quote is written "" rather than \" so cmd's naive
quote count stays even -- with \" the parity flips and every later &
| < > on the line stops being data. Measured before the fix, argv
["a b", 'c"d', "e%F%g", "h&i", "j^k"] arrived as
["a b", 'c"d', "e^%F^%g", "h"]: the & truncated the argument and
ran its remainder as a command. Each % is broken out of the quoted run
as "^%" because %VAR% expands even inside quotes.

The import-boundary test is a ratchet seeded at today's 172 files; it
only shrinks.

* fix(process): route the console-flashing spawn sites through the chokepoint

The ssh -G config probe fires on every connect and reconnect, and ssh.exe
is console-subsystem, so a GUI-subsystem parent gets a fresh visible
conhost that takes foreground -- keystrokes typed into an Orca terminal
at that moment go into the black box (stablyai#10488, stablyai#14543). Same for the
ProxyJump tunnel, the ProxyCommand cmd.exe wrapper, the font enumeration
and the DPAPI cookie decrypt.

Also stops spawning powershell by bare name: PATH under Electron is not
the user's, so where policy has pruned the System32 entry the spawn fails
and the font picker silently reports five hardcoded families rather than
an error (stablyai#11771).

Deletes system-fonts' 40-line bespoke execFileText -- timeout, output cap
and kill are the chokepoint's job now. Adds runProcessSync so the sync
callers have a compliant path; without one the ratchet could never
reach zero.

The three suites that mocked child_process directly now mock runProcess,
which is the point: how a process gets started is no longer each
module's business. Ratchet 173 -> 170.

* fix(process): do not report a deliberately killed child as timed out

runProcessSync inferred a timeout from signal === 'SIGTERM'. Measured:
a real timeout sets error.code ETIMEDOUT and kills with SIGTERM, but so
does anything else that terminates the child -- and those cases set no
error at all. Reading the signal alone reports a process someone stopped
on purpose as having timed out, which callers retry.

* refactor(process): hold the ratchet as data and migrate the pwsh probes

The allowlist and the adversarial argument corpus are read only by tests,
so they were production modules in name only; they move to __fixtures__.

pwsh.ts carried isTimeoutError() purely to reconcile two spellings of the
same event -- execFileSync reports a timeout as ETIMEDOUT, the execFile
callback as a SIGTERM kill with no code. runProcess reports one timedOut
flag, so the helper and the reasoning behind it both go.

Its sync probe also spawned without windowsHide, which flashes a console
and steals foreground on every cold cache read.

* refactor(process): migrate five more spawn sites onto the chokepoint

Each one deletes a hand-rolled promise/timeout/kill wrapper and stops
re-deciding console visibility for itself. Ratchet 170 -> 164.

Two things this surfaced, both kept:

runProcess now accepts string chunks as well as buffers. A stream someone
called setEncoding on emits strings, and concatenating those as buffers
throws inside a data handler -- where the rejection has nowhere to go and
the caller simply hangs rather than failing.

ProcessSpec keeps its AbortSignal. I had removed it as unused; the macOS
PAM preflight passes one through from its own caller.

ipc/app.ts is deliberately NOT migrated. Its probe spawns a three-stage
 pipeline detached so a timeout can reap the group with one
negative-pid SIGKILL; runProcess kills only the root, which would orphan
the plutil stages. Migrating it needs the chokepoint to own POSIX
process-group termination first -- the same guarantee job objects give on
Windows. Reverted and left on the ratchet.

* test(process): do not assert a POSIX signal on Windows

Windows has no signals, so the same deliberate kill reports an exit code
there and a signal on POSIX. What has to hold on both is that neither
shape reads as a timeout. Caught by running the suite on Windows.

(cherry picked from commit 0a6e990)

* fix(process): settle a timed-out run even when the child ignores the kill

close only fires once the child is actually gone, so a child that traps
SIGTERM never emits it and the promise outlives its own deadline
forever. That is the same wedge shape just fixed for the process table,
and it is worse here: pwsh.ts and the snapshot reader both cache an
in-flight probe, so one unkillable child hands every later caller the
same dead promise.

After the deadline it now escalates to SIGKILL and settles regardless,
reporting timedOut with whatever output arrived.

(cherry picked from commit 78ac169)

* fix(process): escalate an aborted child too, not just a timed-out one

The grace escalation I added covered the timeout path and left abort on
the old one, so an aborted caller with an unkillable child still waited
forever -- the same defect, one path over. The macOS PAM preflight is a
real caller that passes an AbortSignal.

Both paths now share one stop-and-settle, and the result reports
timedOut honestly: false when the caller aborted.

(cherry picked from commit 7e9523a)

* fix(windows): stop percent escaping from forging an escaped quote

escapePercentForCmd ran as a post-pass over the quoted string, so it
inserted a quote wherever a percent was -- including straight after a
backslash. CommandLineToArgvW reads backslash-quote as an escaped quote,
so C:\Users\%USERNAME%\x arrived corrupted. That is about as common as
Windows paths get, and my 20-case corpus had no backslash-before-percent
entry to catch it.

Percent handling is now part of the quoting loop, where the backslash
run is known and can be doubled before the inserted quote. Two corpus
cases cover the shape.

The program path gets the same treatment. It was quoted but not
percent-escaped, so a launcher under C:\Users\%USERNAME%\ had its own
path expanded on the cmd hop.

quoteWindowsArgument no longer takes a boolean. Passing it to
values.map() handed map's index in as the flag -- which is how the first
version of this fix was written, and the corpus test caught it.

Separately: an AbortSignal that was already aborted never fires the
event, so runProcess ran the child to its full timeout for a caller who
had already given up.

(cherry picked from commit f7e2e56)
yoyoys added a commit to yoyoys/orca that referenced this pull request Aug 31, 2026
The child_process chokepoint landed in stablyai#15746 after this branch was
written; rebasing onto it made the direct node:child_process import a
ratchet violation. runProcess also encapsulates the Windows .cmd
argument encoding this file was doing by hand, so getSpawnArgsForWindows
is no longer needed here — only the absolute-path resolution is, since
runProcess spawns without a shell.

runProcess reports failure in its result rather than throwing, so
non-zero exits and timeouts are converted to a thrown error to preserve
the token cache's failure-cooldown behavior.

Claude-Session: https://claude.ai/code/session_01CR2s8B3hk7fUHZTe58zdzy
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* feat(process): add the Windows-correct child-process chokepoint

Six decisions have to be made every time Orca starts a child process --
console visibility, argument quoting, .cmd interpretation, binary
resolution, timeout policy, and how the tree is later terminated. POSIX
forgives all six. Windows punishes each differently, and made per-call
site across 172 files they were right in some and wrong in others.

runProcess/spawnProcess make them once:
- windowsHide unconditionally, shell:false unconditionally (shell:true
  concatenates argv unescaped and silently disables windowsHide)
- .cmd/.bat routed through cmd.exe /d /v:off /s /c with a verbatim line,
  because Node refuses to spawn them otherwise (EINVAL)

The encoding was derived by measurement on Windows 11, not from the
docs. An embedded quote is written "" rather than \" so cmd's naive
quote count stays even -- with \" the parity flips and every later &
| < > on the line stops being data. Measured before the fix, argv
["a b", 'c"d', "e%F%g", "h&i", "j^k"] arrived as
["a b", 'c"d', "e^%F^%g", "h"]: the & truncated the argument and
ran its remainder as a command. Each % is broken out of the quoted run
as "^%" because %VAR% expands even inside quotes.

The import-boundary test is a ratchet seeded at today's 172 files; it
only shrinks.

* fix(process): route the console-flashing spawn sites through the chokepoint

The ssh -G config probe fires on every connect and reconnect, and ssh.exe
is console-subsystem, so a GUI-subsystem parent gets a fresh visible
conhost that takes foreground -- keystrokes typed into an Orca terminal
at that moment go into the black box (stablyai#10488, stablyai#14543). Same for the
ProxyJump tunnel, the ProxyCommand cmd.exe wrapper, the font enumeration
and the DPAPI cookie decrypt.

Also stops spawning powershell by bare name: PATH under Electron is not
the user's, so where policy has pruned the System32 entry the spawn fails
and the font picker silently reports five hardcoded families rather than
an error (stablyai#11771).

Deletes system-fonts' 40-line bespoke execFileText -- timeout, output cap
and kill are the chokepoint's job now. Adds runProcessSync so the sync
callers have a compliant path; without one the ratchet could never
reach zero.

The three suites that mocked child_process directly now mock runProcess,
which is the point: how a process gets started is no longer each
module's business. Ratchet 173 -> 170.

* fix(process): do not report a deliberately killed child as timed out

runProcessSync inferred a timeout from signal === 'SIGTERM'. Measured:
a real timeout sets error.code ETIMEDOUT and kills with SIGTERM, but so
does anything else that terminates the child -- and those cases set no
error at all. Reading the signal alone reports a process someone stopped
on purpose as having timed out, which callers retry.

* refactor(process): hold the ratchet as data and migrate the pwsh probes

The allowlist and the adversarial argument corpus are read only by tests,
so they were production modules in name only; they move to __fixtures__.

pwsh.ts carried isTimeoutError() purely to reconcile two spellings of the
same event -- execFileSync reports a timeout as ETIMEDOUT, the execFile
callback as a SIGTERM kill with no code. runProcess reports one timedOut
flag, so the helper and the reasoning behind it both go.

Its sync probe also spawned without windowsHide, which flashes a console
and steals foreground on every cold cache read.

* refactor(process): migrate five more spawn sites onto the chokepoint

Each one deletes a hand-rolled promise/timeout/kill wrapper and stops
re-deciding console visibility for itself. Ratchet 170 -> 164.

Two things this surfaced, both kept:

runProcess now accepts string chunks as well as buffers. A stream someone
called setEncoding on emits strings, and concatenating those as buffers
throws inside a data handler -- where the rejection has nowhere to go and
the caller simply hangs rather than failing.

ProcessSpec keeps its AbortSignal. I had removed it as unused; the macOS
PAM preflight passes one through from its own caller.

ipc/app.ts is deliberately NOT migrated. Its probe spawns a three-stage
 pipeline detached so a timeout can reap the group with one
negative-pid SIGKILL; runProcess kills only the root, which would orphan
the plutil stages. Migrating it needs the chokepoint to own POSIX
process-group termination first -- the same guarantee job objects give on
Windows. Reverted and left on the ratchet.

* test(process): do not assert a POSIX signal on Windows

Windows has no signals, so the same deliberate kill reports an exit code
there and a signal on POSIX. What has to hold on both is that neither
shape reads as a timeout. Caught by running the suite on Windows.

(cherry picked from commit 0a6e990)

* fix(process): settle a timed-out run even when the child ignores the kill

close only fires once the child is actually gone, so a child that traps
SIGTERM never emits it and the promise outlives its own deadline
forever. That is the same wedge shape just fixed for the process table,
and it is worse here: pwsh.ts and the snapshot reader both cache an
in-flight probe, so one unkillable child hands every later caller the
same dead promise.

After the deadline it now escalates to SIGKILL and settles regardless,
reporting timedOut with whatever output arrived.

(cherry picked from commit 78ac169)

* fix(process): escalate an aborted child too, not just a timed-out one

The grace escalation I added covered the timeout path and left abort on
the old one, so an aborted caller with an unkillable child still waited
forever -- the same defect, one path over. The macOS PAM preflight is a
real caller that passes an AbortSignal.

Both paths now share one stop-and-settle, and the result reports
timedOut honestly: false when the caller aborted.

(cherry picked from commit 7e9523a)

* fix(windows): stop percent escaping from forging an escaped quote

escapePercentForCmd ran as a post-pass over the quoted string, so it
inserted a quote wherever a percent was -- including straight after a
backslash. CommandLineToArgvW reads backslash-quote as an escaped quote,
so C:\Users\%USERNAME%\x arrived corrupted. That is about as common as
Windows paths get, and my 20-case corpus had no backslash-before-percent
entry to catch it.

Percent handling is now part of the quoting loop, where the backslash
run is known and can be doubled before the inserted quote. Two corpus
cases cover the shape.

The program path gets the same treatment. It was quoted but not
percent-escaped, so a launcher under C:\Users\%USERNAME%\ had its own
path expanded on the cmd hop.

quoteWindowsArgument no longer takes a boolean. Passing it to
values.map() handed map's index in as the flag -- which is how the first
version of this fix was written, and the corpus test caught it.

Separately: an AbortSignal that was already aborted never fires the
event, so runProcess ran the child to its full timeout for a caller who
had already given up.

(cherry picked from commit f7e2e56)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Windows: SSH workspace connect/reconnect flashes a console window and steals keyboard focus (spawn sites missing windowsHide)

1 participant