Repository navigation
Conversation
|
Superseded by #12217, which reaches the same architecture (worker-thread-owned port-scan spawns + watchdog armed after |
📝 WalkthroughWalkthroughAdds 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)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/main/ports/port-scan-command-client.ts (1)
47-68: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider exposing a
disposemethod.The class owns a worker thread but exposes only
run. Callers cannot release the thread deterministically. The downstream effect appears insrc/main/ports/port-scan-command-client.test.tslines 166-188: that test creates a realWorkerand leaves it alive until the unref'd 5-minute idle timer, because no teardown API exists. A smalldisposecloses that gap and lets the test terminate the thread in afinallyblock.♻️ 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 valueConsider suppressing the repeated warning for an unavailable worker.
Restricting backoff to
PortScanCommandTimeoutis correct. APortScanWorkerUnavailableErroris not a command timeout. One side effect remains: while the worker cannot start, every scan tick reachesconsole.warn('[workspace-ports] scan failed', error)on line 79. The client already logs that condition once, insrc/main/ports/port-scan-command-client.tslines 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
📒 Files selected for processing (12)
config/knip.jsonelectron.vite.config.tssrc/main/ports/local-workspace-port-scanner.test.tssrc/main/ports/local-workspace-port-scanner.tssrc/main/ports/port-scan-command-client.test.tssrc/main/ports/port-scan-command-client.tssrc/main/ports/port-scan-command-execution.test.tssrc/main/ports/port-scan-command-execution.tssrc/main/ports/port-scan-command-import-boundary.test.tssrc/main/ports/port-scan-command-protocol.tssrc/main/ports/port-scan-command-worker-entry.tssrc/main/ports/port-scan-command-worker-spawn.ts
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"execFileis only asynchronous after the child exists. On the reporter's machine an endpoint-security module hooksCreateProcessW, so every scan tick froze the whole window for the duration of the spawn:netstat -ano -p tcppluspowershell.exe -NoProfile -Command Get-CimInstance ...on Windows,lsof/pson 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:389beforeexecFileat: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 aCommandTimeoutErrorwas raised for a command that never got to run, which fedcommandTimeoutBackoff.recordTimeout()and surfaced the reporter's "Port scanning is temporarily paused after a command timeout" banner. Their own out-of-bandnetstatruns averaged 0.446 s — the entire 4 s budget was consumed inside the spawn.Now:
unref'd worker thread (port-scan-command-worker-entry.ts), so the hookedCreateProcessWstalls that thread and the UI keeps painting. The client (port-scan-command-client.ts) mirrors theOpenCodeSqliteWorkerClientlifecycle 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-processexecFile).execFilereturns (port-scan-command-execution.ts), so it measures the command instead of the spawn. Node's ownoptions.timeoutstays 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 madecommandTimeoutBackoff.recordTimeout()unreachable in production. AmaxBufferoverflow kill is explicitly excluded, since that is too much output, not a hang.spawnMs >= 2000skips 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 hookedCreateProcessW— a delay in the spawn, not in the command.Baseline,
child_process.spawn(the async API) called on the loop: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
scanWorkspacePortswith anexecFiledouble that blocks the calling thread for 4200 ms and then completes the command healthily 5 ms later failed onmainin both of the ways the reporter described:Fix proof
The load-bearing check drives the built, shipped artifact —
out/main/port-scan-command-worker-entry.jsin a realWorker— against that real 21 sCreateProcessWdelay, and measures the calling loop: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
netstatoutput) instead of being killed and reported as a timeout.spawnMsof 21037 also trips the metadata-skip guard, so the follow-uppowershell.exespawn is not issued that cycle.The repro was converted into permanent regression tests rather than kept under a bug-numbered name: its blocking-
execFilemechanism now gates watchdog ordering inport-scan-command-execution.test.ts, its event-loop-stall assertion is re-armed against a real worker thread running a real spawn inport-scan-command-client.test.ts, and its "no false timeout" assertion lives inlocal-workspace-port-scanner.test.ts.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 msand fails the same bound, while routing it through the client keeps it under. An import-boundary test additionally fails iflocal-workspace-port-scanner.tsor the client ever reaches forchild_processagain — the fix is a property of the import graph, and a behavioural test alone would not catch its removal.No regressions
Trade-offs — this is not free:
externalfor one scan. This is the same degradation those best-effort calls already produced on error, and it recovers on the next healthy scan.src/main/ipc/localhost-worktree-labels.ts:45uses 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, anexistsSyncfail-fast, and a one-shot log line — but it disables a second feature, so it is stated rather than buried.On a healthy host the added cost is ~1–2 ms per scan.
Screenshots
No visual change. The renderer contract is byte-identical —
unavailableReasonstrings 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)AI Review Report
Reviewed for correctness, lifecycle, and platform risk. What it checked and what changed as a result:
execFilemeans Node's ownoptions.timeoutusually wins the race. Node surfaces that as a plain error withkilled: true, which the old code did not classify — sorecordTimeout()would have become unreachable in production while tests still passed. Fixed by classifying the kill shape, and covered by a dedicated test.maxBufferoverflow (also a kill) is excluded so a chatty command is not mistaken for a hang.uv_spawnblocks 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.netstat -ano -p tcpandpowershell.exe -NoProfile -Command Get-CimInstance ...move to the worker with identical argv andwindowsHide: true, soCreateProcessWPATH/PATHEXT resolution and quoting are unchanged;powershell.exeis 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 forlsofandps. Linux reads/procdirectly and spawns nothing, so it only inherits the corrected timeout semantics. Worker path resolution usesnode:pathjoinonly — no separator assumptions — and mirrorssession-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.new Worker(path)snapshotsprocess.envat creation rather than sharing it, so a worker created before a later main-processPATHmutation resolves binaries against the snapshot. All four binaries live on the base systemPATHon their platforms (System32 on Windows,/usr/sbinand/binon macOS), the worker is created lazily on first scan (well after startupPATHhydration), and respawn-on-fault refreshes it.SHARE_ENVwas deliberately not used — it would make env mutation racy across threads for a benefit we do not need.getStoreWorkspacePortProbesdrops every worktree whose repo carries aconnectionId, and the renderer routes non-local targets through the relay RPC, where scanning is implemented independently insrc/relay/port-scan-handler.ts/src/relay/windows-port-scan.tsinside 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.GitCapabilityCacherules do not apply. Probes come from store worktree meta with an explicitisFolderRepobranch, 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.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 existingmaxBuffer: 2 MB(typicalnetstat/lsofoutput is tens of KB, sub-millisecond to clone). No new polling, no new renderer IPC, no added renders.Security Audit
execFile(never a shell), stillwindowsHide: true, stillmaxBuffer: 2 MB. The only change is which thread issues the spawn. Arguments are built from PIDs already filtered throughNumber.isFinitebefore interpolation, exactly as before.MessagePortbetween 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.node:pathjoinfromprocess.resourcesPath/__dirnameand validated withexistsSyncbefore use. No user-controlled path enters it.src/main/ipc/localhost-worktree-labels.ts:45uses 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.Notes
Made with Orca 🐋