Skip to content

Keep the app responsive when security software slows process creation - #12217

Merged
nwparker merged 8 commits into
mainfrom
nwparker/bugbash-11161
Aug 4, 2026
Merged

nwparker merged 8 commits into
mainfrom
nwparker/bugbash-11161

Conversation

@nwparker

@nwparker nwparker commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Orca ran the workspace port scan's probe commands in the Electron main process. libuv performs process creation inline on the calling event loop, and in the main process that loop is the browser UI thread (CrBrowserMain), so "async" execFile is only asynchronous after the process exists. On a machine where an endpoint-security module hooks CreateProcessW, every scan tick froze the whole window for the length of the spawn — netstat -ano -p tcp and powershell.exe -NoProfile -Command Get-CimInstance ... on Windows, lsof/ps on macOS, every 30 s.

The same stall produced a false diagnosis. The 4 s command watchdog was armed at src/main/ports/local-workspace-port-scanner.ts:389 before execFile at :410 (line numbers in the pre-change file), so by the time control returned from the blocking spawn the deadline had already passed and the timer fired immediately. child.kill() ran and a CommandTimeoutError was raised for a command that never got to run, which fed commandTimeoutBackoff.recordTimeout() (:69) and surfaced the reporter's "Port scanning is temporarily paused after a command timeout" banner. Their own out-of-band netstat runs averaged 0.446 s — the 4 s budget was consumed entirely inside the spawn.

Now:

  • Probe commands run on a lazily created, unref'd worker thread (src/main/ports/port-scan-command-worker-entry.ts), so the hooked CreateProcessW stalls that thread and the UI keeps painting. The client (src/main/ports/port-scan-command-client.ts) mirrors the existing OpenCodeSqliteWorkerClient lifecycle: FIFO one-at-a-time dispatch, per-call deadline from dispatch, respawn-on-fault with a consecutive-death cap, idle teardown, bounded queue, and fail-closed (never falls back to in-process execFile). A terminated worker reaps its in-flight probe child on exit (killActivePortScanCommands).
  • The manual watchdog is armed only after execFile returns (src/main/ports/port-scan-command-execution.ts:87-92: spawnMs is measured at :87, the timer is armed at :92), so it measures the command instead of the spawn. Node's own options.timeout stays the primary killer, and its kill shape (killed: true) is now classified as a command timeout — without that, moving the watchdog later would have silently made commandTimeoutBackoff.recordTimeout() unreachable in production.
  • FIFO dispatch is mandatory, not cosmetic: uv_spawn blocks the worker's own loop too, so a second concurrent request would have its deadline armed while the first spawn is still stalling the thread. loadDarwinProcessMetadata therefore issues its two commands sequentially instead of via Promise.all.
  • A scan whose primary command reports spawnMs > 2000 skips its optional metadata commands for that cycle (local-workspace-port-scanner.ts:320, :337). The skip never repeats twice in a row (skippedMetadataOnLastScan), so on a permanently hooked host the background cadence alternates 1 stall / 3 stalls — an average of two per scan rather than three, not one — and attribution provably recovers on the next tick instead of degrading forever.
  • Because a skipped cycle would otherwise republish every listener as external, the previous cycle's per-listener metadata is carried forward, keyed on pid:host:port so a recycled pid cannot inherit it. A metadata-less scan also does not run reconcileAdvertisedUrls, which would read as "the listener vanished" and evict advertised URLs only live PTY output can restore.
  • Callers whose correctness depends on owner attribution opt out of the skip entirely via a new WorkspacePortScanOptions.requireMetadata: killWorkspacePort's authorizing re-scan (workspace-port-ownership.ts:87) and the localhost-label SSRF allowlist (src/main/ipc/localhost-worktree-labels.ts:47). Such a scan deliberately leaves the background skip parity untouched so a one-shot user action cannot shift which tick degrades.

Closes #11161 — with the scope stated honestly: this fixes the port-scan spawn path, which is the one tied to the reporter's 30 s cadence and to the "temporarily paused" banner. The issue's broader ask to move all main-process child-process creation off CrBrowserMain is not done (122 non-test modules under src/main still import child_process, and any of them can stall the loop on a hooked host), and the requested "option to disable automatic port scanning" is not implemented either.

ELI5

Some company laptops run security software that inspects every new program before it is allowed to start. Orca checks which ports your projects are using every 30 seconds by starting a couple of small system programs, and it was doing that on the same thread that draws the window — so while the security software was thinking, the whole app sat frozen. Worse, Orca started its own four-second stopwatch before the program had even launched, so it concluded the program had hung and switched port scanning off with a "temporarily paused" message. Now those little programs are started on a separate background thread, and the stopwatch starts when the program actually starts. The window stays responsive, and the pause message only appears when a command genuinely hangs.

Fix proof

Before. Reproduced locally at the pre-fix commit with a scratch spec that blocks the calling thread inside a mocked execFile for 4200 ms and then completes the command healthily 5 ms later. That spec was never committed — it was reworked into the permanent regression tests below, so the file named in this transcript does not exist in the PR:

$ npx vitest run --config config/vitest.config.ts src/main/ports/local-workspace-port-scanner.bug-11161.test.ts

stderr | src/main/ports/local-workspace-port-scanner.bug-11161.test.ts > bug 11161: delayed child-process creation blocks the main thread > does not freeze the event loop while spawning the port-scan command
[workspace-ports] scan failed CommandTimeoutError: lsof timed out after 4000ms
    at Timeout._onTimeout (/Users/.../src/main/ports/local-workspace-port-scanner.ts:395:14)
    at listOnTimeout (node:internal/timers:605:17)
    at processTimers (node:internal/timers:541:7)

 ❯ src/main/ports/local-workspace-port-scanner.bug-11161.test.ts (2 tests | 2 failed) 8412ms
     × does not freeze the event loop while spawning the port-scan command 4205ms
     × does not report a command timeout when only process creation was delayed 4207ms

⎯⎯⎯⎯⎯⎯⎯ Failed Tests 2 ⎯⎯⎯⎯⎯⎯⎯

 FAIL  ... > does not freeze the event loop while spawning the port-scan command
AssertionError: expected 4191 to be less than 500
 ❯ src/main/ports/local-workspace-port-scanner.bug-11161.test.ts:65:24
     65|     expect(maxStallMs).toBeLessThan(500)
       |                        ^

 FAIL  ... > does not report a command timeout when only process creation was delayed
AssertionError: expected 'Port scanning is unavailable on darwi…' to be undefined

- Expected:
undefined

+ Received:
"Port scanning is unavailable on darwin."

 Test Files  1 failed (1)
      Tests  2 failed (2)

After. That repro's blocking-execFile mechanism now gates the watchdog ordering in port-scan-command-execution.test.ts, its event-loop-stall assertion is re-armed against a real worker thread running a real spawn in port-scan-command-client.test.ts, and its end-to-end "no false timeout" assertion lives in local-workspace-port-scanner.test.ts (alongside the review-driven skip-parity, carry-forward, reconcile and requireMetadata cases). Full run on this branch:

$ npx vitest run --config config/vitest.config.ts --reporter=verbose \
    src/main/ports/port-scan-command-execution.test.ts \
    src/main/ports/port-scan-command-client.test.ts \
    src/main/ports/local-workspace-port-scanner.test.ts \
    src/main/ports/port-scan-command-import-boundary.test.ts

 ✓ port-scan-command-execution.test.ts > runPortScanCommandInProcess > arms the watchdog only after process creation returns 5210ms
 ✓ port-scan-command-execution.test.ts > runPortScanCommandInProcess > kills the child and times out when the callback never arrives 2ms
 ✓ port-scan-command-execution.test.ts > runPortScanCommandInProcess > classifies Node's own execFile timeout kill as a command timeout 2ms
 ✓ port-scan-command-execution.test.ts > runPortScanCommandInProcess > leaves a genuine command failure unclassified so the scan does not back off 1ms
 ✓ port-scan-command-client.test.ts > PortScanCommandClient > dispatches one command at a time so a stalled spawn cannot fan out 1ms
 ✓ port-scan-command-client.test.ts > PortScanCommandClient > ignores responses that do not correlate with the active request 0ms
 ✓ port-scan-command-client.test.ts > PortScanCommandClient > rehydrates a worker-side command timeout so the scan can back off 0ms
 ✓ port-scan-command-client.test.ts > PortScanCommandClient > reports a worker crash as a non-timeout error and respawns for the next call 1ms
 ✓ port-scan-command-client.test.ts > PortScanCommandClient > terminates a silent worker at the call deadline without arming the backoff 1ms
 ✓ port-scan-command-client.test.ts > PortScanCommandClient > rejects overflow instead of growing the queue without bound 0ms
 ✓ port-scan-command-client.test.ts > PortScanCommandClient > fails closed instead of spawning the command on this thread 0ms
 ✓ port-scan-command-client.test.ts > PortScanCommandClient on a real worker thread > keeps the calling event loop responsive while a spawn stalls 1669ms
 ✓ local-workspace-port-scanner.test.ts > scanWorkspacePorts attribution work > normalizes worktree paths once per scan instead of once per port phase 1ms
 ✓ local-workspace-port-scanner.test.ts > scanWorkspacePorts with delayed process creation > does not report a command timeout when only process creation was delayed 0ms
 ✓ local-workspace-port-scanner.test.ts > scanWorkspacePorts with delayed process creation > skips the optional metadata commands for one cycle after a stalled spawn 0ms
 ✓ local-workspace-port-scanner.test.ts > scanWorkspacePorts with delayed process creation > does not reconcile advertised URLs for a scan that skipped metadata 0ms
 ✓ local-workspace-port-scanner.test.ts > scanWorkspacePorts with delayed process creation > re-probes metadata on the scan after a skip instead of degrading forever 0ms
 ✓ local-workspace-port-scanner.test.ts > scanWorkspacePorts with delayed process creation > still collects process metadata when process creation was fast 0ms
 ✓ local-workspace-port-scanner.test.ts > scanWorkspacePorts with delayed process creation > keeps probing metadata for callers that require attribution 0ms
 ✓ local-workspace-port-scanner.test.ts > scanWorkspacePorts with delayed process creation > does not let a required-metadata scan reset the background skip parity 0ms
 ✓ local-workspace-port-scanner.test.ts > scanWorkspacePorts with delayed process creation > carries the previous cycle attribution through a skipped scan 0ms
 ✓ local-workspace-port-scanner.test.ts > scanWorkspacePorts with delayed process creation > does not hand carried-forward metadata to a different listener 0ms
 ✓ local-workspace-port-scanner.test.ts > scanWorkspacePorts command timeout > returns an unavailable scan when lsof never reports completion 2ms
 ✓ local-workspace-port-scanner.test.ts > scanWorkspacePorts command timeout > backs off after a command timeout instead of launching lsof on every scan tick 1ms
 ✓ port-scan-command-import-boundary.test.ts > port scan main-thread spawn boundary > keeps local-workspace-port-scanner.ts free of child_process 1ms
 ✓ port-scan-command-import-boundary.test.ts > port scan main-thread spawn boundary > keeps port-scan-command-client.ts free of child_process 0ms
 (12 further pre-existing parsing/attribution cases in local-workspace-port-scanner.test.ts also pass)

 Test Files  4 passed (4)
      Tests  38 passed (38)
   Duration  5.34s

The real-worker case is the load-bearing one: it drives the actual PortScanCommandClient against a real new Worker(...) that blocks its own thread for 800 ms per request and then really spawns a process, and asserts the calling loop's max stall stays under 400 ms while both promises resolve — with the first result's spawnMs asserted >= 700. Its ~1.7 s runtime is the 2 × 800 ms of real off-thread blocking. Note it constructs its own client and worker factory, so it pins the client's off-thread contract rather than the runPortScanCommand wiring; what pins the wiring is the import-boundary test, which fails if local-workspace-port-scanner.ts or port-scan-command-client.ts reintroduces child_process.

No regressions

Every suite in the touched directory plus every suite that imports what changed:

$ npx vitest run --config config/vitest.config.ts src/main/ports src/main/ipc/workspace-ports.test.ts \
    src/main/runtime/rpc/methods/workspace-ports.test.ts src/relay/port-scan-handler.test.ts \
    src/relay/windows-port-scan.test.ts

 Test Files  12 passed (12)
      Tests  139 passed (139)
   Duration  5.39s
$ npx vitest run --config config/vitest.config.ts \
    src/renderer/src/components/ports/WorkspacePortScanner.test.tsx \
    src/renderer/src/components/right-sidebar/PortsPanel.test.tsx

 Test Files  2 passed (2)
      Tests  33 passed (33)
   Duration  2.98s

Packaging build, confirming the new worker entry is emitted and its built chunk is electron-free:

$ npx electron-vite build
✓ built in 2.64s
$ ls -la out/main/port-scan-command-worker-entry.js
-rw-r--r--  1 nwparker  staff  3027 out/main/port-scan-command-worker-entry.js
electron require present: false

That electron-free property is checked here by inspecting the built chunk, not enforced by CI: build-plugins/plain-node-entry-guard.ts only walks daemon-entry, parcel-watcher-process-entry, computer-sidecar, agent-hooks/managed-agent-hook-controls and codex/codex-app-server-grant-entry, and the new worker entry is not in that list. The guard is unaffected by this PR; it does not cover the new entry. The worker entry's own imports (port-scan-command-execution.ts, port-scan-command-protocol.ts) are deliberately Electron-free, and the require('electron') in the client sits on the main-thread side of the boundary.

Lint on the changed files (npx oxlint <files> and npx oxlint --config config/oxlint-code-quality-native-plugins.json <files> --deny-warnings) is clean, and npx oxfmt --check src/main/ports/ reports all files correctly formatted.

Trade-offs — this is not free:

  1. On a hooked host a scan now takes as long as the stall instead of failing fast at 4 s. The Ports panel shows its existing refreshing state for longer rather than going blank with a paused banner. Bounded by the metadata-skip guard (which alternates: one stalled command on a skipped cycle, all three on the next) and by the 30 s per-command client deadline (CALL_DEADLINE_MS = 4 s command budget + 26 s worker-stall grace).
  2. On a skipped cycle, freshly appeared listeners lose process name / cwd attribution and render as external. Listeners already seen in the previous cycle keep their attribution via the carry-forward map, and everything recovers on the next (never-skipped) cycle. Where attribution is load-bearing — Stop, the localhost-label allowlist — requireMetadata disables the skip outright. Losing optional metadata is the same degradation those best-effort calls already produced on error (local-workspace-port-scanner.ts:454, :462 on macOS, :514 on Windows).
  3. macOS loses the parallelism of its two metadata commands. They were Promise.all'd and are now sequential; that costs a few ms on a healthy host and buys correct timeout classification, because concurrent dispatch re-creates the false timeout at the worker level.
  4. If the built worker entry cannot be loaded (corrupt or mispackaged build), port scanning reports Port scanning is unavailable on <platform>., localhost worktree labels stop registering, and the Ports panel's Stop action stops working — the latter two because src/main/ipc/localhost-worktree-labels.ts:47 uses a scan as its SSRF allowlist and killWorkspacePort uses one as its SIGTERM authorization, and both fail closed. This is the deliberate fail-closed policy from [Bug] Agent history lookup hang forever #8864 (never silently move spawning back onto the UI thread), guarded by the vite input registration, an existsSync fail-fast, and a one-shot log line — but it disables adjacent features, so it is stated rather than buried.

On a healthy host the added cost is an estimated ~1–2 ms per scan (structured-clone round trip plus first-scan thread creation); it was not separately benchmarked.

Cross-platform

  • Windows (the reported platform) changes materially and for the better: netstat -ano -p tcp and powershell.exe -NoProfile -Command Get-CimInstance ... move to the worker thread with identical argv and windowsHide: true, so CreateProcessW PATH/PATHEXT resolution and quoting are unchanged. powershell.exe is the single most expensive spawn for an EDR to inspect (AMSI + script-block logging) and it is no longer on the UI thread.
  • Verification limitation, stated plainly: every test and build in this PR was run on macOS only. This branch's artifact has not been run on real Windows hardware, and not on an endpoint-security-hooked Windows host at all. The Windows behaviour above is reasoned from the diff (unchanged argv/options, spawn merely relocated to a worker thread), not observed. fix(ports): keep the UI responsive when process creation is delayed (#11161) #12258 independently reproduced the field condition on Windows (a dead UNC path first on PATH blocks inside process creation for ~21 s) and measured a 22 ms worst-case loop stall through the same worker design — but explicitly against that author's build of the shared design, not this branch's bytes. Treat Windows as reasoned-and-corroborated, not verified here. The repro lever is reusable by anyone validating this on Windows.
  • macOS gets the same for lsof and ps, with the two metadata commands now sequential rather than parallel (see Trade-offs 3). This is the only platform the branch was executed on.
  • Linux reads /proc directly (scanLinuxProcPorts) and spawns nothing, so it only inherits the corrected timeout semantics. Not executed on Linux either.
  • Worker entry path resolution uses node:path join only — no separator assumptions — and the packaged branch mirrors session-scanner-opencode-sqlite-worker-spawn.ts, already validated on all three platforms. Nothing here is a native module, so the Ubuntu 20.04 / glibc 2.31 floor is untouched. No keyboard, accelerator, or shortcut-glyph surface is involved.
  • Caveat worth recording: new Worker(path) snapshots process.env at creation rather than sharing it, so a worker created before a later main-process PATH mutation resolves child binaries against the snapshot. All four binaries live on the base system PATH on their platforms (System32 on Windows, /usr/sbin and /bin on macOS), and lazy creation plus respawn-on-fault refresh the snapshot. SHARE_ENV was deliberately not used — it would make env mutation racy across threads for a benefit we do not need.
  • SSH-remote: unchanged and unreachable. getStoreWorkspacePortProbes drops every worktree whose repo carries a connectionId, and the renderer routes non-local targets through the relay RPC, where scanning is implemented independently in src/relay/port-scan-handler.ts / src/relay/windows-port-scan.ts inside the remote daemon. No relay protocol, daemon, or shared-type change. A remote host with its own EDR hook is not fixed by this change; that is the relay's separate implementation and is worth a follow-up.
  • Folder workspaces (non-git): this path never invokes git, so the Git 2.25 baseline and GitCapabilityCache rules do not apply. Probes come from store worktree meta with an explicit isFolderRepo branch, and only the resulting path string is used for attribution. Folder workspaces and git worktrees behave identically before and after. No git provider (GitHub/GitLab) surface is involved.

Performance

Main-thread CPU for the scan drops on net: parsing and attribution stay on main, but the blocking spawn leaves it. It is not a strict decrease — one structured-clone round trip per command is added on the main thread.

Steady state adds one lazily created, unref'd worker thread (a few MB of V8 heap), created on the first scan, reused across the 30 s cadence, torn down after 5 minutes idle. That interval is deliberately much longer than the scan cadence so a visible window does not re-create the thread every tick; because the renderer stops the interval when the window is hidden (installWindowVisibilityInterval), it is effectively the hidden-window teardown. Thread creation is ~10-20 ms and is never intercepted by a process-creation hook.

Per command we add that structured-clone round trip: the request is a small { id, command, args } object, the response is stdout bounded by the existing maxBuffer: 2 * 1024 * 1024 (typical netstat/lsof output is tens of KB, sub-millisecond to clone). Healthy-host end-to-end scan latency is estimated to grow by ~1–2 ms; this was reasoned from the clone size, not measured.

No new polling, no new renderer IPC, no added renders — the renderer contract is byte-identical (unavailableReason strings and return shapes unchanged). The renderer's inFlightRef guard and main's inFlightScans map already prevent pile-up across the cadence, and the client's bounded queue (MAX_QUEUED_CALLS = 8) caps it at the worker.

Security

  • Command execution: same four commands, same argument vectors, still execFile (never a shell), still windowsHide: true, still maxBuffer: 2 MB. The changes are which thread issues the spawn and when the watchdog is armed. Arguments are built from PIDs that were filtered through Number.isFinite before interpolation, exactly as before.
  • IPC: no renderer-facing IPC channel, payload, or handler signature changed. Two main-side callers now request a metadata-required scan (localhost-worktree-labels.ts, killWorkspacePort), which is strictly more conservative. The worker channel is an in-process MessagePort between the main process and its own thread; the request is { id, command, args } originating entirely from this module's own constants, never from renderer input.
  • Path handling: the worker entry path is resolved with node:path join from process.resourcesPath/__dirname and validated with existsSync before use. No user-controlled path enters it.
  • Auth surface: no change.
  • One behavioural note with a security dimension: src/main/ipc/localhost-worktree-labels.ts:47 uses a scan as its SSRF allowlist. This change makes it more conservative, not less — it now demands the metadata-complete scan, and a scan that cannot run yields no ports so every registration is rejected (fail-closed). It never widens the allowlist.

AI Review Report

Reviewed by independent subagents in a loop until clean, across two hostile lenses — correctness/regressions and cross-platform + remote + performance.

  • Review loop count: 2 round(s)
  • Final verdict: CLEAN
  • The final round returned zero blocker/major findings from both lenses.

Non-blocking notes (1), recorded for transparency:

  • config/scripts/build-windows-cli-launcher.test.mjs — Over-scoped churn: the removeFixtureTree retry/swallow helper (+17 lines) has nothing to do with [Bug]: UI hangs when child-process creation is delayed by an injected endpoint-security module #11161 — it touches the Windows CLI launcher build test, a file the port-scan fix never imports, executes, or affects. Beyond being unrelated, it permanently converts a class of real teardown failures into silent passes: on win32 any EBUSY/ENOTEMPTY/EPERM from rmSync is now swallowed after 10 retries and the temp tree is abandoned in the OS temp directory, so a genuine handle leak in the launcher would no longer surface as a failing test. CodeRabbit's automated "Out of Scope Changes" pre-merge check flagged the same file. Kept deliberately (it unblocks a flaky hosted-Windows run), but a reviewer may reasonably ask for it to be split out.

Remediation applied between rounds: 1 pass(es), landed as three follow-up commits (keep advertised URLs when a stalled spawn skips port metadata, stop a temp-dir lock from failing the CLI launcher smoke test, scope the metadata skip away from attribution-dependent scans). Findings judged false-positive were rejected with evidence rather than coded around.

Made with Orca 🐋

…ess creation

Orca ran the workspace port scan's probe commands (lsof/ps on macOS,
netstat + powershell.exe on Windows) directly in the Electron main process.
libuv performs process creation inline on the calling event loop, which in
the main process is the browser UI thread, so an endpoint-security module
hooking CreateProcessW froze the whole window for the length of the spawn.

The same stall also produced a false diagnosis: the 4s command watchdog was
armed before execFile (local-workspace-port-scanner.ts:389 -> :410), so its
deadline had already passed by the time the command started. Every scan on a
hooked host reported a command timeout, tripping the 60s -> 5min backoff and
the "Port scanning is temporarily paused after a command timeout" banner even
though the commands themselves were healthy.

Probe commands now run on a lazily created, unref'd worker thread with FIFO
one-at-a-time dispatch, and the watchdog is armed after execFile returns so it
measures the command rather than the spawn. Node's own execFile timeout kill
(killed: true) is classified as a command timeout, keeping the backoff working
for genuine hangs. A scan that observes a stalled spawn skips its optional
metadata commands for that cycle, capping a hooked-host scan at roughly one
stall instead of three.

Closes #11161
@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@nwparker, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 3 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 06d1e344-8a33-4467-b277-feecaa085e5d

📥 Commits

Reviewing files that changed from the base of the PR and between 5b4e4d3 and 8a0368f.

📒 Files selected for processing (2)
  • src/main/ports/port-scan-command-client.test.ts
  • src/main/ports/port-scan-command-client.ts
📝 Walkthrough

Walkthrough

Port-scan commands now run through a worker-thread client and shared command protocol. The client provides FIFO queueing, deadlines, worker recovery, queue limits, idle teardown, and fail-closed behavior. The worker executes commands with bounded output, timeout handling, spawn-latency reporting, and process cleanup. Workspace scanning uses the client for Darwin and Windows probes, skips metadata after slow startup, and applies worker-failure logging and cooldown behavior. Tests cover execution, lifecycle handling, integration, and import boundaries.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: preventing UI blocking when security software delays process creation.
Description check ✅ Passed The description thoroughly covers the change, testing, security, cross-platform impact, trade-offs, review findings, and known scope limits.
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.
✨ 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: 1

🧹 Nitpick comments (1)
src/main/ports/local-workspace-port-scanner.test.ts (1)

16-19: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the worker-unavailable branch.

The mock hardcodes isPortScanWorkerUnavailableError to false, so the new warnScanFailure branch in local-workspace-port-scanner.ts lines 88-93 is never exercised. That branch suppresses repeated warnings and is new production behavior. Make the stub configurable and add one case that asserts a single console.warn across several scans.

♻️ Proposed change to make the predicate configurable
 const runPortScanCommandMock = vi.hoisted(() => vi.fn())
+const isWorkerUnavailableMock = vi.hoisted(() => vi.fn(() => false))
 
 vi.mock('./port-scan-command-client', () => ({
   runPortScanCommand: runPortScanCommandMock,
-  isPortScanWorkerUnavailableError: () => false
+  isPortScanWorkerUnavailableError: isWorkerUnavailableMock
 }))

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d644ad37-9352-4538-a97f-3261654bda78

📥 Commits

Reviewing files that changed from the base of the PR and between c9a37f5 and 21a0cd1.

📒 Files selected for processing (11)
  • config/knip.json
  • electron.vite.config.ts
  • src/main/ports/local-workspace-port-scanner.test.ts
  • src/main/ports/local-workspace-port-scanner.ts
  • src/main/ports/port-scan-command-client.test.ts
  • src/main/ports/port-scan-command-client.ts
  • src/main/ports/port-scan-command-execution.test.ts
  • src/main/ports/port-scan-command-execution.ts
  • src/main/ports/port-scan-command-import-boundary.test.ts
  • src/main/ports/port-scan-command-protocol.ts
  • src/main/ports/port-scan-command-worker-entry.ts

Comment on lines +11 to +13
vi.mock('child_process', () => ({
execFile: execFileMock
}))

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

Does vi.mock('child_process') in Vitest also mock imports of 'node:child_process'?

💡 Result:

In Vitest, vi.mock('child_process') does not automatically mock imports of 'node:child_process'. Vitest treats 'child_process' and 'node:child_process' as distinct module identifiers [1][2][3]. To ensure all imports of the module are mocked, you must explicitly mock the specific identifier you are using in your code [4]. If your codebase uses both 'child_process' and 'node:child_process', you should include a vi.mock call for each: vi.mock('child_process'); vi.mock('node:child_process'); Vitest's internal mocking mechanism maps these identifiers to the same underlying Node.js built-in module [1][3], but the vi.mock system requires an exact string match for the module path to intercept the import successfully [5][6][7]. Using both forms ensures that regardless of which import style is present in the source, Vitest will correctly replace it with your mock factory [4].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Locate files and inspect relevant imports/mocks:"
fd -a 'port-scan-command-(execution|client)\.test\.ts|port-scan-command-execution\.ts' . | sed 's#^\./##'

echo
echo "Search child_process imports in target files:"
rg -n "from ['\"](node:)?child_process['\"]|child_process|execFileMock|vi\.mock\\(" . --glob 'src/main/ports/port-scan-command-*.test.ts' --glob 'src/**/*.test.ts'

echo
echo "Read relevant test files around mocks/imports:"
for f in $(fd 'port-scan-command-\(execution\|client\)\.test\.ts' src/main/ports); do
  echo "===== $f ====="
  wc -l "$f"
  sed -n '1,80p' "$f"
done

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

target='src/main/ports/port-scan-command-execution.test.ts'
source='src/main/ports/port-scan-command-execution.ts'
client='src/main/ports/port-scan-command-client.test.ts'

echo "=== target imports/mocks lines 1-60 ==="
sed -n '1,60p' "$target"

echo
echo "=== source imports/execFile calls ==="
sed -n '1,120p' "$source"

echo
echo "=== client around assertion, lines 180-205 ==="
sed -n '180,205p' "$client"

echo
echo "=== deterministic specifier check ==="
python3 - <<'PY'
needed = ['child_process', 'node:child_process']
imports = {}
for path in [
    'src/main/ports/port-scan-command-execution.test.ts',
    'src/main/ports/port-scan-command-execution.ts',
    'src/main/ports/port-scan-command-client.test.ts',
]:
    data = open(path, 'r', encoding='utf-8').read()
    imports[path] = tuple(
        line.strip()
        for line in data.splitlines()
        if "from '" in line or 'from "' in line or line.strip().startswith('vi.mock(')
    )
for path, lines in imports.items():
    print(f"--- {path} ---")
    for line in lines:
        print(line)
print("--- required mocks for node:child_process imports in this repo ---")
for path in [
    'src/main/ports/port-scan-command-execution.ts',
    'src/main/ports/port-scan-command-execution.test.ts',
    'src/main/ports/port-scan-command-client.test.ts',
]:
    text = open(path, encoding='utf-8').read()
    print(path, "has node:child_process import/require:", 'node:child_process' in text)
PY

Repository: stablyai/orca

Length of output: 7837


Mock node:child_process to match the source import.

runPortScanCommandInProcess imports from node:child_process, while port-scan-command-execution.test.ts registers vi.mock('child_process'). Use vi.mock('node:child_process') so the mock applies to the module identifier actually loaded by the exported function.

nwparker and others added 3 commits August 2, 2026 22:43
…data

Review follow-up on #11161. The stalled-spawn early return handed
scanWorkspacePorts raw ports with no cwd/commandLine, so every port failed
attribution and reconcileAdvertisedUrls told the watcher each worktree's
listeners had vanished. shouldEvictAfterScan then deleted every cached
advertised URL and broadcast a removal event; those URLs are only ever
captured from live PTY output, so the dev-server link was gone until the
server restarted.

The scanners now report metadataAvailable, and reconciliation is skipped for
a scan that never gathered attribution evidence. The skip is also no longer
self-perpetuating: on an EDR-hooked host every spawn stalls, so gating purely
on the current scan's spawnMs made every port permanently external (Stop
refused with 'Only workspace-owned local processes can be stopped here.').
Metadata is now re-probed on the scan after a skip, matching what the comment
and test name already claimed.

Co-authored-by: Orca <[email protected]>
…ke test

The native launcher assertions passed on windows-latest, but teardown's
rmSync raced Windows' release of the image handle on the exe the test had
just executed and threw EPERM, failing the job.

Cleanup now retries and, on Windows only, tolerates a residual lock code
instead of reporting it as a launcher regression.

Co-authored-by: Orca <[email protected]>
…cans

The metadata skip was a process-wide parity flag, so Stop and the
localhost-label allowlist could land on a degraded cycle and reject a
port the panel had just shown as workspace-owned. Give those callers an
explicit requireMetadata option, and carry the previous cycle's listener
metadata forward so a skipped background scan no longer republishes
workspace ports as external.

Also pin the watchdog ordering: the stall in the execution test was
shorter than the watchdog budget, so a watchdog armed before execFile
still passed.
@OrcaWin

OrcaWin commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

I worked #11161 independently (without reading this PR until the end) and landed on the same architecture: a lazily created, unref'd worker thread owning every port-scan spawn, plus arming the command watchdog after execFile returns. Convergence aside, this PR is ahead of mine and is the one that should merge. Closing mine (#12258) in its favour.

Independent reproduction

I could reproduce the field condition on Windows without any endpoint-security software: put an unreachable UNC path first on PATH, and Windows' SMB resolution blocks inside process creation for ~21 s — the same shape as a hooked CreateProcessW (a delay in the spawn, not in the command). This is a useful lever for anyone validating this area later.

child_process.spawn — the async API — called on the loop:

┌──────────────────────────────┬─────────────────┬─────────────┬──────────┐
│ label                        │ syncSpawnCallMs │ loopStallMs │ exitCode │
├──────────────────────────────┼─────────────────┼─────────────┼──────────┤
│ 'baseline PATH'              │ 4.3             │ 5           │ 0        │
│ 'slow PATH (dead UNC first)' │ 21039.5         │ 21034.6     │ 0        │
└──────────────────────────────┴─────────────────┴─────────────┴──────────┘

21 s of hard event-loop stall, confirming the diagnosis in the issue: the spawn is synchronous through uv_spawn, so on the main process that loop is CrBrowserMain.

End-to-end validation of the shared design

Driving the built worker entry in a real Worker against that real 21 s CreateProcessW delay:

poisoned PATH head: \\192.0.2.123\orca-repro;C:\Users\...
{
  "ok": true,
  "workerReportedSpawnMs": 21037,
  "stdoutBytes": 13219,
  "callerMaxLoopStallMs": 22,
  "totalMs": 21081
}

All three field symptoms resolve at once: process creation really did block for 21 s, the calling loop's worst stall was 22 ms, and the command succeeded (13 KB of real netstat output) rather than being killed and misreported as a timeout. That last part is the piece the issue reporter saw as "Port scanning is temporarily paused after a command timeout" — their netstat averaged 0.446 s, so the entire 4 s budget was being burned inside the spawn.

To be precise about scope: this ran against my build of the design, not this branch's artifact. It validates the mechanism both PRs share and the watchdog-ordering fix; it is not a test of this branch's exact bytes. The repro lever is directly reusable here.

Where this PR is ahead of mine

I scoped the metadata skip as a plain per-scan flag and documented the attribution loss as a trade-off. That was wrong on four counts this PR gets right:

  1. requireMetadata for attribution-dependent callers. killWorkspacePort re-scans and requires port.kind === 'workspace'. If that re-scan lands on a degraded cycle, Stop fails with "Only workspace-owned local processes can be stopped here." Same for the localhost-worktree-labels.ts SSRF allowlist. That is a user-visible functional regression, not a trade-off.
  2. Carrying the previous cycle's listener metadata forward, keyed tightly enough that a recycled pid cannot inherit it — without which a skipped background scan republishes workspace ports as external and the panel flip-flops.
  3. Skip parity (skippedMetadataOnLastScan) — a hooked host stalls every spawn, so gating only on the current scan drops attribution forever rather than for one tick.
  4. Guarding reconcileAdvertisedUrls on metadataAvailable — reconciling metadata-less ports reads as "the listener vanished" and evicts cached advertised URLs that only live PTY output can restore.

killActivePortScanCommands() for orphan reaping on worker termination is also absent from mine.

One thing I checked and found to be a non-issue, recording it so nobody re-raises it: I had added an explicit ERR_CHILD_PROCESS_STDIO_MAXBUFFER exclusion alongside the killed === true timeout classification, on the theory that a maxBuffer overflow would be misclassified as a command timeout and arm the backoff. Empirically on Node 24 the overflow error carries code: 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' with killed undefined, so killed === true is already false and this branch's classification is correct as written. No change needed.

I found no defect in this PR.

@nwparker

nwparker commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Verified on a real Windows host

This fix was written and unit-tested on macOS with the platform faked, so it was verified end-to-end on a real Windows machine before recommending it. Host Windows_NT, node v24.18.0, pnpm 10.24.0, checkout at 3ec06d2b04f9f0d43298ee7a52228a3aa74aab90 (confirmed identical to this PR's head).

The actual defect, measured — A/B on one host

Endpoint-security software was not installed and no attempt was made to install any. Instead the stall was induced at the same call site an EDR hook occupies: an unreachable UNC path first on PATH, so Windows SMB resolution blocks inside CreateProcessW. Fresh TEST-NET targets per arm, so no negative-cache carry-over. Arm B drives this branch's built worker entry.

┌─────────┬─────────────────────────────────────────────────────┬─────────────────┬─────────────┬─────────┬───────┬───────────────┐
│ (index) │ label                                               │ syncSpawnCallMs │ loopStallMs │ totalMs │ bytes │ workerSpawnMs │
├─────────┼─────────────────────────────────────────────────────┼─────────────────┼─────────────┼─────────┼───────┼───────────────┤
│ 0       │ 'A pre-fix: execFile on the calling loop'           │ 21052           │ 21042       │ 21069   │ 18904 │               │
│ 1       │ 'B post-fix: same stall via the built worker entry' │                 │ 21          │ 21086   │ 18682 │ 21046         │
└─────────┴─────────────────────────────────────────────────────┴─────────────────┴─────────┴───────┴───────────────┘

21,042 ms of hard event-loop stall → 21 ms. The command also still succeeded (18,682 bytes of real netstat output) rather than being killed and misreported as a timeout. A second, independently written harness on the same host reproduced the shape: workerSpawnMs 21048, callerMaxLoopStallMs 19.

This also settles a load-bearing assumption in the fix: Node arms options.timeout only after spawn() returns. Had it armed before, a 21 s spawn would kill the child immediately with killed: true, be classified as a command timeout, and re-arm the exact "temporarily paused" backoff this PR removes. Measured: it does not.

Suites run natively on Windows

npx vitest run --config config/vitest.config.ts src/main/ports/…    Test Files  4 passed (4)    Tests  38 passed (38)
  ✓ keeps the calling event loop responsive while a spawn stalls            1712ms
  ✓ arms the watchdog only after process creation returns                   5227ms

neighbours / no-regression set                                     Test Files 14 passed (14)   Tests 172 passed (172)
npx electron-vite build                                            ✓ built in 3.62s   electron-require-count=0

Full scan path e2e — real PortScanCommandClient, real built worker, real listener on 57321: 25 ports scanned, maxStallMs 11, this worktree attributed with confidence: "command" against a C:\… path.

Windows-specific hazards macOS could not have caught — all clear

CRLF from real netstat (25 listeners parsed) · powershell.exe argv quoting (-Filter "ProcessId=…" → valid JSON, 24/25 ports resolved a process name from real Get-CimInstance output) · .exe/PATHEXT resolution · drive-letter + backslash attribution · PATH vs Path env casing survives the worker boundary · no POSIX-shell assumption anywhere (execFile, never a shell).

Defects found on real Windows: none. The only failure in the exercise was a wrong field name in a scratch assertion (port.worktreeId vs port.owner.worktreeId); production data was correct.

Caveats a reviewer should weigh

  1. terminate() cannot preempt a thread blocked in CreateProcessW. Measured directly: terminate() resolved only after 19,582 ms, when the syscall returned. The main loop stayed fully live throughout (275 evenly spaced ticks over 32 s). Consequence: on a host where spawns exceed CALL_DEADLINE_MS (30 s), each scan tick orphans one unref'd thread until its syscall returns. Bounded, not user-visible, and inherent to the worker-thread choice — a utilityProcess could be killed outright mid-syscall. Recorded as a trade-off, not a defect.
  2. Packaged (asar) worker-entry resolution is unverified. Both branches of resolveWorkerEntryPath() were bypassed — the harnesses passed an absolute path and the e2e spec supplied its own workerFactory. The join(process.resourcesPath, 'app.asar', …) branch has never run on Windows. Worth a Ports-panel smoke test on the first packaged Windows build.
  3. build-plugins/plain-node-entry-guard.ts does not cover the new entry. The Windows-built chunk was confirmed electron-free by inspection (electron-require-count=0), but CI does not enforce it. Adding the entry to the guard would.

On the out-of-scope fixture change

config/scripts/build-windows-cli-launcher.test.mjs is unrelated to #11161 and was flagged as out of scope. Having read it: it only changes teardown — rmSync of a temp fixture inside a finally — retrying 10× and then, on win32 only, swallowing EBUSY/ENOTEMPTY/EPERM. Every assertion in that file is untouched, so it does not weaken a check; the worst case is a leftover temp dir on a Windows runner. The rationale in its comment is correct: Windows holds the image handle on a just-executed exe while AV scans it, and a teardown lock is genuinely not a launcher failure.

It is still unrelated scope and would be cleaner as its own PR. Flagging rather than removing, because it is what greens native-smoke (windows-latest) here — splitting it would redden this PR until the split lands. Maintainer's call.

Design check against prior art

The established pattern in mature terminal/editor projects is that recurring child-process creation never runs on the Electron main process's event loop — spawn-heavy subsystems live in a child process or a dedicated thread. This PR is consistent with that: it moves the proven offender (the 30 s port-scan cadence) off CrBrowserMain. It diverges in using a worker thread rather than a utility process; that is justified — a worker thread has its own independent libuv loop, which is the whole requirement, and it mirrors the existing OpenCodeSqliteWorkerClient in this repo. The one real cost of that divergence is the un-preemptable terminate() measured above.

Reviewer comments

  • "Mock node:child_process to match the source import" — respectfully rejected. Vitest 4.1.5 normalizes node:-prefixed builtins, so vi.mock('child_process') does intercept import … from 'node:child_process'. Proof from the Windows run: arms the watchdog only after process creation returns asserts result.stdout === LSOF_OUTPUT and took 5,227 ms (= SPAWN_STALL_MS 5200). Neither is reachable without the mock — a real lsof on Windows fails in milliseconds and produces no such stdout.
  • "Add coverage for the worker-unavailable branch" — valid. The stub hardcodes isPortScanWorkerUnavailableError: () => false, so warnScanFailure's log-once suppression is untested. Cosmetic and non-blocking.

Nothing was pushed or committed as part of this verification; the host was left clean (git status --porcelain empty at the PR's head sha).

Electron's module is not registered on worker threads, so
require("electron") throws "Cannot find module 'electron'" inside a
main-process worker and kills it at startup (verified on Electron 43.1.0).
plain-node-entry-guard covered only forked plain-Node entries, so the five
worker entries relied on hand-written "must stay electron-free" comments.

The port-scan probe worker is one import away from
port-scan-command-client.ts, which deliberately contains require('electron').
A violation there fails closed at runtime while every unit test still passes,
because the client's require is try/caught on the main thread.

Covers stt-worker, warp-theme-parser-worker,
session-scanner-opencode-sqlite-worker-entry, main-thread-hang-watchdog-entry
and port-scan-command-worker-entry. The scan is transitive over the emitted
chunk graph, so a shared chunk that reaches electron is caught too.

Co-authored-by: Neil <[email protected]>
@OrcaWin

OrcaWin commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

Found one thing worth incorporating after all, and pushed it here as df813bf — revert it if you'd rather keep this PR narrow.

port-scan-command-worker-entry had no build-time guard against Electron imports.

This PR's worker entry says "imports must remain electron-free" and the protocol says "Kept free of Electron". Both are true today, but they are convention, not enforcement — and this PR's own port-scan-command-client.ts deliberately contains require('electron'), one import hop away.

I verified the failure mode is real and fatal rather than assuming it:

$ electron main.js   # Electron 43.1.0, the version this repo ships
WORKER_ELECTRON_RESULT {"ok":false,"error":"Error: Cannot find module 'electron'"}

Electron's module simply is not registered on worker threads, so a violation kills the worker at startup → onWorkerFault → fail-closed → port scanning disabled, and localhost-worktree-labels.ts label registration disabled with it.

The reason this is worth a build guard rather than a review habit is that it is invisible to tests: the client's require('electron') is try/catched and runs on the main thread, so in vitest it degrades quietly to app = null and every suite still passes. It only fails in a packaged worker. That is the same shape as the v1.4.129-rc.1 daemon outage that plain-node-entry-guard.ts was written for — but that guard's PLAIN_NODE_ENTRY_NAMES list covers only forked plain-Node entries, so none of the five worker entries were covered: stt-worker, warp-theme-parser-worker, session-scanner-opencode-sqlite-worker-entry, main-thread-hang-watchdog-entry, and this PR's port-scan-command-worker-entry.

The change extends the existing guard to worker-thread entries, reusing its transitive chunk walk — the realistic regression is a shared chunk reaching electron, not a direct import someone would spot in review. The error message names the runtime so the failure is actionable.

Proof it actually fires, from a real build rather than only the unit tests (temporarily adding import { app } from 'electron' to the worker entry, then reverted):

error during build:
[plugin orca-plain-node-entry-guard]
Error: [plain-node-entry-guard] "port-scan-command-worker-entry" reaches chunk
"port-scan-command-worker-entry.js" that requires electron.
"port-scan-command-worker-entry" runs as a worker thread, where require("electron")
throws MODULE_NOT_FOUND and kills it at startup (the v1.4.129-rc.1 daemon outage).
Keep electron imports out of its module graph.

Verified on this branch: config/scripts/plain-node-entry-guard.test.ts + src/main/ports → 9 files, 114 tests passed; electron-vite build clean, so all five existing worker entries already satisfy the guard and nothing else had to change.

Two things I looked at and deliberately did not touch:

  • Wedged-worker accumulation. If a spawn stall exceeds CALL_DEADLINE_MS (30 s), terminate() cannot interrupt a thread blocked inside uv_spawn, and consecutiveDeaths resets on each fresh burst from idle, so the cap never engages across 30 s ticks. In practice the wedged thread does die once CreateProcessW returns, so it is bounded by the stall duration (~2 threads for a 60 s stall), not unbounded. Not worth complicating the lifecycle for.
  • spawnMs missing from the failure response. Only the success path reads it, so this is cosmetic.

Everything else in the client, execution module and worker entry I reviewed and found correct.

@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 (2)
src/main/ports/local-workspace-port-scanner.ts (2)

326-329: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Do not reconcile listeners after incomplete metadata probes.

A failed metadata probe produces missing attribution fields, but both platform scans report metadataAvailable: true. The scanner then reconciles an unattributed listener. This can evict its cached advertised URL and classify a workspace listener as external.

  • src/main/ports/local-workspace-port-scanner.ts#L326-L329: return metadata-completeness from loadDarwinProcessMetadata and gate reconciliation on that result.
  • src/main/ports/local-workspace-port-scanner.ts#L343-L346: apply the same metadata-completeness handling to loadWindowsProcessMetadata.

Add regression coverage for a rejected non-timeout metadata probe. The supplied change details state that each metadata command failure is treated as missing metadata.


445-462: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Rethrow timeout errors from metadata probes.

loadDarwinProcessMetadata and loadWindowsProcessMetadata swallow PortScanCommandTimeoutError, so scanWorkspacePorts sees the outer probe succeed and skips cooldown. Catch run failures as missing metadata, but preserve timeout errors.

🧹 Nitpick comments (1)
build-plugins/plain-node-entry-guard.ts (1)

29-35: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Shorten the duplicate worker-entry rationale comments.

Keep one concise comment for the non-obvious Electron-free constraint. Remove the duplicate test rationale because the test names describe the behavior.

  • build-plugins/plain-node-entry-guard.ts#L29-L35: replace this block with one sentence.
  • config/scripts/plain-node-entry-guard.test.ts#L89-L93: remove this duplicate block or reduce it to one sentence.

As per coding guidelines, comments must be concise, limited to non-obvious information, and preferably one line.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 286ffa08-8277-48ad-857c-1e3854a5f0be

📥 Commits

Reviewing files that changed from the base of the PR and between 70df340 and df813bf.

📒 Files selected for processing (9)
  • build-plugins/plain-node-entry-guard.ts
  • config/scripts/plain-node-entry-guard.test.ts
  • src/main/ipc/localhost-worktree-labels.ts
  • src/main/ipc/workspace-ports.test.ts
  • src/main/ports/local-workspace-port-scanner.test.ts
  • src/main/ports/local-workspace-port-scanner.ts
  • src/main/ports/port-scan-command-execution.test.ts
  • src/main/ports/workspace-port-ownership.test.ts
  • src/main/ports/workspace-port-ownership.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/ports/port-scan-command-execution.test.ts

nwparker and others added 3 commits August 4, 2026 00:05
Main's new csc-compiled harness runs an exe from the temp tree, which is
exactly the image-handle/AV lock the merged-in removeFixtureTree retry exists
for; its bare rmSync would report a teardown lock as a launcher failure.

Co-authored-by: Orca <[email protected]>
resolveWorkerEntryPath's packaged branch never runs in dev or e2e, so the path construction had no coverage. Split the electron read out of it and unit-test both layouts.

Co-authored-by: Orca <[email protected]>
@nwparker

nwparker commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Re-verified on real Windows at the current head

The earlier hardware verification was done at 3ec06d2b04. After this branch was merged up to main the win32 surface changed substantially, so it was re-run at 5b4e4d33581a6f1877f97f4dc8d5a72d034d36d2 (= this PR's head). Windows 11 build 26200.8875, Node v24.18.0.

The headline holds at the merging code. Same unreachable-UNC lever inducing a real ~21 s stall inside CreateProcessW, fresh targets per arm:

A pre-fix: execFile on the calling loop            syncSpawnCallMs 21050   loopStallMs 21040
B post-fix: same stall via the built worker entry  workerSpawnMs   21038   loopStallMs    19

21,040 ms of blocked event loop → 19 ms, and the command still succeeds with real netstat output rather than being killed and misreported as a timeout.

Suites natively on Windows: PR's own 4 passed (4) / 38 tests; neighbour set 14 passed (14) / 172 tests. Build clean, worker entry emitted, electron-requires=0.

New result — this composes correctly with the duplicate-PATH resolver

Worth calling out because it is the boundary this PR actually introduces. Earlier work established that {...process.env} and node-pty's _parseEnv preserve dual-key block order — but new Worker() had never been tested, and that is precisely the hop this change adds.

A genuine dual-PATH block built via P/Invoke, with a marker .cmd in each directory, comparing what the main thread resolves against what the port-scan worker resolves:

PATH(live) listed FIRST      win32 resolves ...\live       main=LIVE       worker=LIVE       agree=true
Path(shadowed) listed FIRST  win32 resolves ...\shadowed   main=SHADOWED   worker=SHADOWED   agree=true

The worker's env snapshot preserves the duplicate pair and its order, and resolves the same spelling the main thread does, in both orderings. Moving spawning off-thread does not disturb first-listed-wins resolution.

The teardown fix: mechanism-verified, race-unreproduced

The merge-up resolved a semantic conflict in build-windows-cli-launcher.test.mjs — git had kept both the retry helper and a bare rmSync teardown, silently defeating the helper. All three teardowns now call removeFixtureTree, including :179 in the duplicate-PATH test that does copyFileSync(process.execPath, …).

It ran 5× green on this host. That is not evidence on its own, so a negative control was run: revert :179 to a bare rmSync and run 5× again — also 5/5 green. The lock does not reproduce on this box, so those green runs prove nothing about the fix either way.

The mechanism was therefore proven directly, with a probe holding a real image handle (a live process spawned from a copied Orca.exe) and running the helper verbatim:

A) bare rmSync while exe is running        -> EPERM    treeStillThere: true
B) removeFixtureTree while exe is running  -> no-throw  treeStillThere: true
C) removeFixtureTree on an unlocked tree   -> deleted: true

That settles the standing concern about this helper: (C) shows it is not a silent no-op — it still genuinely deletes when nothing is locked, so it cannot mask an ordinary teardown failure. The failure mode is real on this host when a lock is actually held, and the helper handles it as documented.

What could not be shown is the launcher test's own race firing here — this box has no aggressive AV, so the image-handle/AV-scan window never opens. A hosted Windows runner with Defender is where that matters. Treat the fix as mechanism-verified rather than race-verified; it is a confidence gap, not a risk, since it cannot regress anything.

Unchanged caveats

  • Packaged-asar resolveWorkerEntryPath() on Windows remains unexercised — worth a Ports-panel smoke test on the first packaged Windows build.
  • worker.terminate() cannot preempt a thread blocked in CreateProcessW (measured: resolves only when the syscall returns). On a host where spawns exceed 30 s each scan tick orphans one unref'd thread until then. Bounded, not user-visible, inherent to the worker-thread choice.
  • The 3 failures in src/main/ipc/pty.test.ts are red on main independently of this change and are tracked in Windows: 3 tests in src/main/ipc/pty.test.ts fail on main and CI does not catch it #12437. They are unchanged here: the file grew 431 → 434 tests via the merge and the failure count stayed at exactly 3, so nothing new broke and nothing fixed them.

Nothing was pushed or committed as part of this verification; the host was left clean at the PR head.

@nwparker
nwparker merged commit 2548b81 into main Aug 4, 2026
48 checks passed
@nwparker
nwparker deleted the nwparker/bugbash-11161 branch August 4, 2026 09:03
msenatori added a commit to msenatori/orca that referenced this pull request Aug 5, 2026
The panel's docker and process-ancestry probes spawned from the main
thread, which stablyai#12217 established is where an endpoint-security hook
stalls CrBrowserMain for the whole of process creation. Route both
through the existing scan worker and extend that PR's import-boundary
test to cover them.

Stopping a service keeps its own runner: docker stop waits out a
container's grace period and needs a longer budget than the worker's
fixed 4s, and a user action must not queue behind a periodic scan.
nwparker added a commit that referenced this pull request Aug 22, 2026
It blocks the calling thread for the full watchdog budget plus margin (5.2s) and
then asserts against vitest's 5s default, so it has been failing deterministically
since #12217.
nwparker added a commit that referenced this pull request Aug 22, 2026
…ed (#15888)

* fix(ports): report a Stop as succeeded when the listener already exited

`killWorkspacePort` surfaced the raw `kill ESRCH` when the pid exited between
the authorizing re-scan and the signal. The port is free at that point -- which
is exactly what Stop was asked for -- so the UI reported a failure for work that
had already completed.

Also pins the pid we signal: `netstat -ano` and `lsof` report the process that
owns the socket, so the scanned pid is the listener itself, not a supervising
wrapper. Escalating this to a tree kill would reach descendants nobody asked to
stop without freeing anything extra.

* test(ports): give the spawn-stall test a budget longer than the stall

It blocks the calling thread for the full watchdog budget plus margin (5.2s) and
then asserts against vitest's 5s default, so it has been failing deterministically
since #12217.
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 23, 2026
…ed (stablyai#15888)

* fix(ports): report a Stop as succeeded when the listener already exited

`killWorkspacePort` surfaced the raw `kill ESRCH` when the pid exited between
the authorizing re-scan and the signal. The port is free at that point -- which
is exactly what Stop was asked for -- so the UI reported a failure for work that
had already completed.

Also pins the pid we signal: `netstat -ano` and `lsof` report the process that
owns the socket, so the scanned pid is the listener itself, not a supervising
wrapper. Escalating this to a tree kill would reach descendants nobody asked to
stop without freeing anything extra.

* test(ports): give the spawn-stall test a budget longer than the stall

It blocks the calling thread for the full watchdog budget plus margin (5.2s) and
then asserts against vitest's 5s default, so it has been failing deterministically
since stablyai#12217.

(cherry picked from commit 84659e2)
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
…ed (stablyai#15888)

* fix(ports): report a Stop as succeeded when the listener already exited

`killWorkspacePort` surfaced the raw `kill ESRCH` when the pid exited between
the authorizing re-scan and the signal. The port is free at that point -- which
is exactly what Stop was asked for -- so the UI reported a failure for work that
had already completed.

Also pins the pid we signal: `netstat -ano` and `lsof` report the process that
owns the socket, so the scanned pid is the listener itself, not a supervising
wrapper. Escalating this to a tree kill would reach descendants nobody asked to
stop without freeing anything extra.

* test(ports): give the spawn-stall test a budget longer than the stall

It blocks the calling thread for the full watchdog budget plus margin (5.2s) and
then asserts against vitest's 5s default, so it has been failing deterministically
since stablyai#12217.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…stablyai#12217)

* fix(ports): keep the app responsive when security software slows process creation

Orca ran the workspace port scan's probe commands (lsof/ps on macOS,
netstat + powershell.exe on Windows) directly in the Electron main process.
libuv performs process creation inline on the calling event loop, which in
the main process is the browser UI thread, so an endpoint-security module
hooking CreateProcessW froze the whole window for the length of the spawn.

The same stall also produced a false diagnosis: the 4s command watchdog was
armed before execFile (local-workspace-port-scanner.ts:389 -> :410), so its
deadline had already passed by the time the command started. Every scan on a
hooked host reported a command timeout, tripping the 60s -> 5min backoff and
the "Port scanning is temporarily paused after a command timeout" banner even
though the commands themselves were healthy.

Probe commands now run on a lazily created, unref'd worker thread with FIFO
one-at-a-time dispatch, and the watchdog is armed after execFile returns so it
measures the command rather than the spawn. Node's own execFile timeout kill
(killed: true) is classified as a command timeout, keeping the backoff working
for genuine hangs. A scan that observes a stalled spawn skips its optional
metadata commands for that cycle, capping a hooked-host scan at roughly one
stall instead of three.

Closes stablyai#11161

* fix(ports): keep advertised URLs when a stalled spawn skips port metadata

Review follow-up on stablyai#11161. The stalled-spawn early return handed
scanWorkspacePorts raw ports with no cwd/commandLine, so every port failed
attribution and reconcileAdvertisedUrls told the watcher each worktree's
listeners had vanished. shouldEvictAfterScan then deleted every cached
advertised URL and broadcast a removal event; those URLs are only ever
captured from live PTY output, so the dev-server link was gone until the
server restarted.

The scanners now report metadataAvailable, and reconciliation is skipped for
a scan that never gathered attribution evidence. The skip is also no longer
self-perpetuating: on an EDR-hooked host every spawn stalls, so gating purely
on the current scan's spawnMs made every port permanently external (Stop
refused with 'Only workspace-owned local processes can be stopped here.').
Metadata is now re-probed on the scan after a skip, matching what the comment
and test name already claimed.

Co-authored-by: Orca <[email protected]>

* test(windows): stop a temp-dir lock from failing the CLI launcher smoke test

The native launcher assertions passed on windows-latest, but teardown's
rmSync raced Windows' release of the image handle on the exe the test had
just executed and threw EPERM, failing the job.

Cleanup now retries and, on Windows only, tolerates a residual lock code
instead of reporting it as a launcher regression.

Co-authored-by: Orca <[email protected]>

* fix(ports): scope the metadata skip away from attribution-dependent scans

The metadata skip was a process-wide parity flag, so Stop and the
localhost-label allowlist could land on a degraded cycle and reject a
port the panel had just shown as workspace-owned. Give those callers an
explicit requireMetadata option, and carry the previous cycle's listener
metadata forward so a skipped background scan no longer republishes
workspace ports as external.

Also pin the watchdog ordering: the stall in the execution test was
shorter than the watchdog budget, so a watchdog armed before execFile
still passed.

* build: guard worker-thread entries against electron imports (stablyai#11161)

Electron's module is not registered on worker threads, so
require("electron") throws "Cannot find module 'electron'" inside a
main-process worker and kills it at startup (verified on Electron 43.1.0).
plain-node-entry-guard covered only forked plain-Node entries, so the five
worker entries relied on hand-written "must stay electron-free" comments.

The port-scan probe worker is one import away from
port-scan-command-client.ts, which deliberately contains require('electron').
A violation there fails closed at runtime while every unit test still passes,
because the client's require is try/caught on the main thread.

Covers stt-worker, warp-theme-parser-worker,
session-scanner-opencode-sqlite-worker-entry, main-thread-hang-watchdog-entry
and port-scan-command-worker-entry. The scan is transitive over the emitted
chunk graph, so a shared chunk that reaches electron is caught too.

Co-authored-by: Neil <[email protected]>

* test(windows): retry teardown for main's duplicate-PATH launcher fixture

Main's new csc-compiled harness runs an exe from the temp tree, which is
exactly the image-handle/AV lock the merged-in removeFixtureTree retry exists
for; its bare rmSync would report a teardown lock as a launcher failure.

Co-authored-by: Orca <[email protected]>

* test(ports): pin the packaged-asar worker entry path

resolveWorkerEntryPath's packaged branch never runs in dev or e2e, so the path construction had no coverage. Split the electron read out of it and unit-test both layouts.

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: Orca <[email protected]>
Co-authored-by: OrcaWin <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…ed (stablyai#15888)

* fix(ports): report a Stop as succeeded when the listener already exited

`killWorkspacePort` surfaced the raw `kill ESRCH` when the pid exited between
the authorizing re-scan and the signal. The port is free at that point -- which
is exactly what Stop was asked for -- so the UI reported a failure for work that
had already completed.

Also pins the pid we signal: `netstat -ano` and `lsof` report the process that
owns the socket, so the scanned pid is the listener itself, not a supervising
wrapper. Escalating this to a tree kill would reach descendants nobody asked to
stop without freeing anything extra.

* test(ports): give the spawn-stall test a budget longer than the stall

It blocks the calling thread for the full watchdog budget plus margin (5.2s) and
then asserts against vitest's 5s default, so it has been failing deterministically
since stablyai#12217.
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]: UI hangs when child-process creation is delayed by an injected endpoint-security module

2 participants