Skip to content

fix(ports): keep the UI responsive when process creation is delayed (#11161) - #12258

Closed
OrcaWin wants to merge 1 commit into
mainfrom
OrcaWin/bug-ui-hangs-when-child-process-creation-is-dela
Closed

OrcaWin wants to merge 1 commit into
mainfrom
OrcaWin/bug-ui-hangs-when-child-process-creation-is-dela

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

Summary

Orca ran the workspace port scan's probe commands on 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 an "async" execFile is only asynchronous after the child exists. On the reporter's machine an endpoint-security module hooks CreateProcessW, so every scan tick froze the whole window for the duration of the spawn: netstat -ano -p tcp plus powershell.exe -NoProfile -Command Get-CimInstance ... on Windows, lsof/ps on macOS, every 30 s. That is exactly the stack in the reporter's hang dump (CrBrowserMain → injected module → KERNELBASE!CreateProcessInternalW → Orca!uv_spawn).

The same stall also produced a false diagnosis. The 4 s command watchdog was armed at local-workspace-port-scanner.ts:389 before execFile at :410, 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() 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 entire 4 s budget was consumed inside the spawn.

Now:

  • Probe commands run on a lazily created, unref'd worker thread (port-scan-command-worker-entry.ts), so the hooked CreateProcessW stalls that thread and the UI keeps painting. The client (port-scan-command-client.ts) mirrors the OpenCodeSqliteWorkerClient lifecycle introduced for the same class of bug in [Bug] Agent history lookup hang forever #8864: FIFO one-at-a-time dispatch, per-call deadline armed at dispatch, respawn-on-fault with a consecutive-death cap, idle teardown, bounded queue, and fail-closed (it never falls back to in-process execFile).
  • The manual watchdog is armed only after execFile returns (port-scan-command-execution.ts), 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. A maxBuffer overflow kill is explicitly excluded, since that is too much output, not a hang.
  • A scan whose primary probe reports spawnMs >= 2000 skips its optional metadata commands for that cycle, capping a hooked host at roughly one stall per scan instead of two.

Closes #11161

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.

Reproduction

I could reproduce the field condition without any endpoint-security software by putting an unreachable UNC path first on PATH. Windows' SMB resolution then blocks inside process creation for ~21 s, which is the same shape as a hooked CreateProcessW — a delay in the spawn, not in the command.

Baseline, 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 that is a hard event-loop stall — the async API is synchronous through uv_spawn.

At the code level, a repro test driving scanWorkspacePorts with an execFile double that blocks the calling thread for 4200 ms and then completes the command healthily 5 ms later failed on main in both of the ways the reporter described:

AssertionError: expected 4190 to be less than 500          ← the UI freeze
AssertionError: expected 'Port scanning is unavailable on darwin.' to be undefined   ← the false timeout

Fix proof

The load-bearing check drives the built, shipped artifact — out/main/port-scan-command-worker-entry.js in a real Worker — against that real 21 s CreateProcessW delay, and measures the calling loop:

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

All three failure modes are gone 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) instead of being killed and reported as a timeout. spawnMs of 21037 also trips the metadata-skip guard, so the follow-up powershell.exe spawn is not issued that cycle.

The repro was converted into permanent regression tests rather than kept under a bug-numbered name: its blocking-execFile mechanism now gates 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 "no false timeout" assertion lives in local-workspace-port-scanner.test.ts.

$ npx vitest run --config config/vitest.config.ts src/main/ports
 Test Files  7 passed (7)
      Tests  101 passed (101)

I verified the real-worker assertion actually discriminates: running the identical workload (2 × 800 ms of blocking + a real spawn) on the calling thread instead measures a stall of > 400 ms and fails the same bound, while routing it through the client keeps it under. An import-boundary test additionally fails if local-workspace-port-scanner.ts or the client ever reaches for child_process again — the fix is a property of the import graph, and a behavioural test alone would not catch its removal.

No regressions

$ npx vitest run --config config/vitest.config.ts src/main/ports                    → 7 files, 101 tests passed
$ npx vitest run ... 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          → 4 files,  32 tests passed
$ npx vitest run ... WorkspacePortScanner.test.tsx PortsPanel.test.tsx              → 2 files,  33 tests passed

$ npx tsc --noEmit -p config/tsconfig.node.json                                      → clean
$ npx oxlint src/main/ports/                                                         → clean
$ npx oxlint --config config/oxlint-code-quality-native-plugins.json src/main/ports --deny-warnings   → clean
$ npx oxlint --type-aware --config config/oxlint-code-quality-type-aware.json src/main/ports --deny-warnings → clean
$ npx oxfmt --check src/main/ports/ electron.vite.config.ts                          → all formatted
$ node config/scripts/check-reliability-gates.mjs                                    → 62 gates passed
$ node config/scripts/check-max-lines-ratchet.mjs                                    → OK, no new bypasses
$ npx electron-vite build                                                            → built; worker entry emitted, 0 electron requires

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 and by a 30 s per-command client deadline.
  2. On a hooked host, process name / cwd attribution is dropped for that cycle, so some workspace ports render as external for one scan. This is the same degradation those best-effort calls already produced on error, and it recovers on the next healthy scan.
  3. If the built worker entry cannot be loaded (corrupt or mispackaged build), port scanning reports unavailable AND localhost worktree labels stop registering, because src/main/ipc/localhost-worktree-labels.ts:45 uses a scan as its SSRF allowlist and fails 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 a second feature, so it is stated rather than buried.
  4. A host whose spawn exceeds the 30 s client deadline loses that scan and respawns the worker. It is reported as a worker fault, not a command timeout, so it does not arm the backoff; the next tick retries.

On a healthy host the added cost is ~1–2 ms per scan.

Screenshots

No visual change. The renderer contract is byte-identical — unavailableReason strings and scan return shapes are unchanged.

Testing

  • pnpm lint (oxlint native + type-aware, oxfmt, reliability gates, max-lines ratchet — all run on the changed surface)
  • pnpm typecheck (tsconfig.node.json)
  • pnpm test (every suite in the touched directory plus every suite importing what changed)
  • pnpm build (electron-vite build; new worker entry emitted and verified electron-free)
  • Added regression tests that would catch this specific regression, including one that drives a real worker thread with a real spawn, and an import-boundary test that fails if spawning moves back to the main thread

AI Review Report

Reviewed for correctness, lifecycle, and platform risk. What it checked and what changed as a result:

  • The watchdog reorder silently disabling backoff. Moving the manual timer after execFile means Node's own options.timeout usually wins the race. Node surfaces that as a plain error with killed: true, which the old code did not classify — so recordTimeout() would have become unreachable in production while tests still passed. Fixed by classifying the kill shape, and covered by a dedicated test. maxBuffer overflow (also a kill) is excluded so a chatty command is not mistaken for a hang.
  • Concurrent dispatch re-creating the same bug one level down. uv_spawn blocks the worker's loop too, so a second in-flight request would have its deadline armed while the first spawn is still stalling the thread. The client dispatches strictly FIFO and arms each deadline at dispatch, not at enqueue.
  • Worker lifecycle faults: crash mid-request, silent worker, clean self-exit leaving a stale handle, crash-loop, and queue overflow are each covered by a test. A crash is deliberately not reported as a command timeout — backing off would blame the command for the worker's failure.
  • Cross-platform, explicitly checked for macOS, Linux, and Windows. 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 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. macOS gets the same for lsof and ps. Linux reads /proc directly and spawns nothing, so it only inherits the corrected timeout semantics. Worker path resolution uses node:path join only — no separator assumptions — and mirrors session-scanner-opencode-sqlite-worker-spawn.ts, already validated on all three platforms. No native module, so the Ubuntu 20.04 / glibc 2.31 floor is untouched. No keyboard, accelerator, or shortcut-glyph surface is involved.
  • Env snapshot caveat, recorded deliberately: new Worker(path) snapshots process.env at creation rather than sharing it, so a worker created before a later main-process PATH mutation resolves 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), the worker is created lazily on first scan (well after startup PATH hydration), and respawn-on-fault refreshes it. 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 from this path. 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 strictly decreases — parsing and attribution stay on main, but the spawn syscall leaves it. 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 cadence so a visible window does not re-create the thread every tick; because the renderer stops the interval when the window is hidden, 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 one structured-clone round trip: the request is two short strings, the response is stdout bounded by the existing maxBuffer: 2 MB (typical netstat/lsof output is tens of KB, sub-millisecond to clone). No new polling, no new renderer IPC, no added renders.

Security Audit

  • Command execution: same four commands, same argument vectors, still execFile (never a shell), still windowsHide: true, still maxBuffer: 2 MB. The only change is which thread issues the spawn. Arguments are built from PIDs already filtered through Number.isFinite before interpolation, exactly as before.
  • IPC: no renderer-facing IPC channel, payload, or handler changed. 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 / secrets / dependencies: no change. No new dependencies.
  • One behavioural note with a security dimension: src/main/ipc/localhost-worktree-labels.ts:45 uses a scan as its SSRF allowlist. This change makes it more conservative, not less — a scan that cannot run yields no ports and every registration is rejected (fail-closed). It never widens the allowlist.
  • Follow-up: the relay's own port-scan implementation has the same in-loop spawn shape on a remote host. It does not affect the Orca UI, but it is worth the same treatment.

Notes

  • Platform-specific behaviour, env-snapshot semantics, the fail-closed consequence for localhost worktree labels, and the relay follow-up are all called out above.

Made with Orca 🐋

@OrcaWin

OrcaWin commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded by #12217, which reaches the same architecture (worker-thread-owned port-scan spawns + watchdog armed after execFile returns) and is ahead of this PR on scanner semantics: requireMetadata for attribution-dependent callers (Stop, the localhost-label SSRF allowlist), metadata carry-forward across a skipped cycle, skip parity so a hooked host does not lose attribution forever, a metadataAvailable guard on reconcileAdvertisedUrls, and killActivePortScanCommands() orphan reaping. Full comparison and my independent reproduction evidence are in #12217 (comment). Credit for the merged fix belongs to @nwparker as its author; this branch stays available only as the independent cross-check.

@OrcaWin OrcaWin closed this Aug 3, 2026
@coderabbitai

coderabbitai Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds an Electron-free port-scan command protocol and in-process execution with timeout and spawn-duration reporting. Adds a worker-thread client with queued dispatch, deadlines, crash recovery, and teardown. Adds worker bundling and runtime resolution for development and packaged builds. Updates local workspace scanning to use worker commands and skip optional metadata after stalled process creation. Expands unit, integration, boundary, and scanner tests.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 55.56% 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 and concisely describes the main fix: preserving UI responsiveness when process creation is delayed.
Description check ✅ Passed The description completes all required sections and provides detailed scope, testing, platform review, security audit, and follow-up notes.
Linked Issues check ✅ Passed The changes address issue #11161 by moving spawning off the UI thread, improving timeout handling, and adding recovery and regression coverage.
Out of Scope Changes check ✅ Passed The code, configuration, and tests remain focused on the workspace port-scan responsiveness and reliability objectives.
✨ 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.

🧹 Nitpick comments (2)
src/main/ports/port-scan-command-client.ts (1)

47-68: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider exposing a dispose method.

The class owns a worker thread but exposes only run. Callers cannot release the thread deterministically. The downstream effect appears in src/main/ports/port-scan-command-client.test.ts lines 166-188: that test creates a real Worker and leaves it alive until the unref'd 5-minute idle timer, because no teardown API exists. A small dispose closes that gap and lets the test terminate the thread in a finally block.

♻️ Proposed addition
   private destroyWorker(): void {

Add a public method before pump:

  /** Release the worker thread and reject anything still pending. */
  dispose(): void {
    const pending = this.active ? [this.active, ...this.queue] : [...this.queue]
    this.queue = []
    const error = new PortScanWorkerUnavailableError('port scan command client disposed')
    for (const call of pending) {
      this.settle(call, () => call.reject(error))
    }
    this.destroyWorker()
  }
src/main/ports/local-workspace-port-scanner.ts (1)

406-408: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider suppressing the repeated warning for an unavailable worker.

Restricting backoff to PortScanCommandTimeout is correct. A PortScanWorkerUnavailableError is not a command timeout. One side effect remains: while the worker cannot start, every scan tick reaches console.warn('[workspace-ports] scan failed', error) on line 79. The client already logs that condition once, in src/main/ports/port-scan-command-client.ts lines 146-153. Skipping the scanner-side warning for this error type keeps the log readable.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0a0de719-dc46-43ff-b1e1-d578c783aa17

📥 Commits

Reviewing files that changed from the base of the PR and between 1dbf55e and 0516546.

📒 Files selected for processing (12)
  • 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
  • src/main/ports/port-scan-command-worker-spawn.ts

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

1 participant