Repository navigation
Keep the app responsive when security software slows process creation - #12217
Conversation
…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
|
Warning Review limit reached
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 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 configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughPort-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)
✅ 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.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/main/ports/local-workspace-port-scanner.test.ts (1)
16-19: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd coverage for the worker-unavailable branch.
The mock hardcodes
isPortScanWorkerUnavailableErrortofalse, so the newwarnScanFailurebranch inlocal-workspace-port-scanner.tslines 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 singleconsole.warnacross 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
📒 Files selected for processing (11)
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.ts
| vi.mock('child_process', () => ({ | ||
| execFile: execFileMock | ||
| })) |
There was a problem hiding this comment.
📐 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:
- 1: vitest-dev/vitest@06208d3
- 2: https://github.com/vitest-dev/vitest/blob/9423dc08/test/cli/test/mocking.test.ts
- 3: https://tangled.org/vitest.dev/vitest/blob/896645b089e092f7aee0ebd7db805ac22d82078c/packages/mocker/src/node/redirect.ts
- 4: https://github.com/heinkokothet4-byte/Openclaw_JI/blob/main/src/plugin-sdk/test-helpers/node-builtin-mocks.child-process.test.ts
- 5: https://vitest.dev/api/vi
- 6: https://vitest.dev/guide/mocking/modules
- 7: https://github.com/vitest-dev/vitest/blob/1a4705da/docs/guide/mocking/modules.md
🏁 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"
doneRepository: 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)
PYRepository: 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.
…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.
|
I worked #11161 independently (without reading this PR until the end) and landed on the same architecture: a lazily created, Independent reproductionI could reproduce the field condition on Windows without any endpoint-security software: put an unreachable UNC path first on
21 s of hard event-loop stall, confirming the diagnosis in the issue: the spawn is synchronous through End-to-end validation of the shared designDriving the built worker entry in a real 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 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 mineI 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:
One thing I checked and found to be a non-issue, recording it so nobody re-raises it: I had added an explicit I found no defect in this PR. |
Verified on a real Windows hostThis 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 The actual defect, measured — A/B on one hostEndpoint-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 21,042 ms of hard event-loop stall → 21 ms. The command also still succeeded (18,682 bytes of real This also settles a load-bearing assumption in the fix: Node arms Suites run natively on WindowsFull scan path e2e — real Windows-specific hazards macOS could not have caught — all clearCRLF from real Defects found on real Windows: none. The only failure in the exercise was a wrong field name in a scratch assertion ( Caveats a reviewer should weigh
On the out-of-scope fixture change
It is still unrelated scope and would be cleaner as its own PR. Flagging rather than removing, because it is what greens Design check against prior artThe 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 Reviewer comments
Nothing was pushed or committed as part of this verification; the host was left clean ( |
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]>
|
Found one thing worth incorporating after all, and pushed it here as
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 I verified the failure mode is real and fatal rather than assuming it: Electron's module simply is not registered on worker threads, so a violation kills the worker at startup → The reason this is worth a build guard rather than a review habit is that it is invisible to tests: the client's 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 Verified on this branch: Two things I looked at and deliberately did not touch:
Everything else in the client, execution module and worker entry I reviewed and found correct. |
There was a problem hiding this comment.
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 winDo 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 fromloadDarwinProcessMetadataand gate reconciliation on that result.src/main/ports/local-workspace-port-scanner.ts#L343-L346: apply the same metadata-completeness handling toloadWindowsProcessMetadata.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 winRethrow timeout errors from metadata probes.
loadDarwinProcessMetadataandloadWindowsProcessMetadataswallowPortScanCommandTimeoutError, soscanWorkspacePortssees 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 valueShorten 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
📒 Files selected for processing (9)
build-plugins/plain-node-entry-guard.tsconfig/scripts/plain-node-entry-guard.test.tssrc/main/ipc/localhost-worktree-labels.tssrc/main/ipc/workspace-ports.test.tssrc/main/ports/local-workspace-port-scanner.test.tssrc/main/ports/local-workspace-port-scanner.tssrc/main/ports/port-scan-command-execution.test.tssrc/main/ports/workspace-port-ownership.test.tssrc/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
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]>
Re-verified on real Windows at the current headThe earlier hardware verification was done at The headline holds at the merging code. Same unreachable-UNC lever inducing a real ~21 s stall inside 21,040 ms of blocked event loop → 19 ms, and the command still succeeds with real Suites natively on Windows: PR's own New result — this composes correctly with the duplicate-
|
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.
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.
…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.
…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)
…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.
…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]>
…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.
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"execFileis only asynchronous after the process exists. On a machine where an endpoint-security module hooksCreateProcessW, every scan tick froze the whole window for the length of the spawn —netstat -ano -p tcpandpowershell.exe -NoProfile -Command Get-CimInstance ...on Windows,lsof/pson 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:389beforeexecFileat: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 aCommandTimeoutErrorwas raised for a command that never got to run, which fedcommandTimeoutBackoff.recordTimeout()(:69) 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 4 s budget was consumed entirely inside the spawn.Now:
unref'd worker thread (src/main/ports/port-scan-command-worker-entry.ts), so the hookedCreateProcessWstalls that thread and the UI keeps painting. The client (src/main/ports/port-scan-command-client.ts) mirrors the existingOpenCodeSqliteWorkerClientlifecycle: 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-processexecFile). A terminated worker reaps its in-flight probe child on exit (killActivePortScanCommands).execFilereturns (src/main/ports/port-scan-command-execution.ts:87-92:spawnMsis measured at:87, the timer is armed at:92), 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.uv_spawnblocks 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.loadDarwinProcessMetadatatherefore issues its two commands sequentially instead of viaPromise.all.spawnMs > 2000skips 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.external, the previous cycle's per-listener metadata is carried forward, keyed onpid:host:portso a recycled pid cannot inherit it. A metadata-less scan also does not runreconcileAdvertisedUrls, which would read as "the listener vanished" and evict advertised URLs only live PTY output can restore.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
CrBrowserMainis not done (122 non-test modules undersrc/mainstill importchild_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
execFilefor 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:After. That repro's blocking-
execFilemechanism now gates the 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 end-to-end "no false timeout" assertion lives inlocal-workspace-port-scanner.test.ts(alongside the review-driven skip-parity, carry-forward, reconcile andrequireMetadatacases). Full run on this branch:The real-worker case is the load-bearing one: it drives the actual
PortScanCommandClientagainst a realnew 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'sspawnMsasserted>= 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 therunPortScanCommandwiring; what pins the wiring is the import-boundary test, which fails iflocal-workspace-port-scanner.tsorport-scan-command-client.tsreintroduceschild_process.No regressions
Every suite in the touched directory plus every suite that imports what changed:
Packaging build, confirming the new worker entry is emitted and its built chunk is electron-free:
That electron-free property is checked here by inspecting the built chunk, not enforced by CI:
build-plugins/plain-node-entry-guard.tsonly walksdaemon-entry,parcel-watcher-process-entry,computer-sidecar,agent-hooks/managed-agent-hook-controlsandcodex/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 therequire('electron')in the client sits on the main-thread side of the boundary.Lint on the changed files (
npx oxlint <files>andnpx oxlint --config config/oxlint-code-quality-native-plugins.json <files> --deny-warnings) is clean, andnpx oxfmt --check src/main/ports/reports all files correctly formatted.Trade-offs — this is not free:
CALL_DEADLINE_MS= 4 s command budget + 26 s worker-stall grace).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 —requireMetadatadisables the skip outright. Losing optional metadata is the same degradation those best-effort calls already produced on error (local-workspace-port-scanner.ts:454,:462on macOS,:514on Windows).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.Port scanning is unavailable on <platform>., localhost worktree labels stop registering, and the Ports panel's Stop action stops working — the latter two becausesrc/main/ipc/localhost-worktree-labels.ts:47uses a scan as its SSRF allowlist andkillWorkspacePortuses 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, anexistsSyncfail-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
netstat -ano -p tcpandpowershell.exe -NoProfile -Command Get-CimInstance ...move to the worker thread 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.PATHblocks 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.lsofandps, with the two metadata commands now sequential rather than parallel (see Trade-offs 3). This is the only platform the branch was executed on./procdirectly (scanLinuxProcPorts) and spawns nothing, so it only inherits the corrected timeout semantics. Not executed on Linux either.node:pathjoinonly — no separator assumptions — and the packaged branch mirrorssession-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.new Worker(path)snapshotsprocess.envat 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/sbinand/binon macOS), and lazy creation plus respawn-on-fault refresh the snapshot.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.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 existingmaxBuffer: 2 * 1024 * 1024(typicalnetstat/lsofoutput 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 (
unavailableReasonstrings and return shapes unchanged). The renderer'sinFlightRefguard and main'sinFlightScansmap already prevent pile-up across the cadence, and the client's bounded queue (MAX_QUEUED_CALLS = 8) caps it at the worker.Security
execFile(never a shell), stillwindowsHide: true, stillmaxBuffer: 2 MB. The changes are which thread issues the spawn and when the watchdog is armed. Arguments are built from PIDs that were filtered throughNumber.isFinitebefore interpolation, exactly as before.localhost-worktree-labels.ts,killWorkspacePort), which is strictly more conservative. The worker channel is an in-processMessagePortbetween 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:47uses 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.
Non-blocking notes (1), recorded for transparency:
config/scripts/build-windows-cli-launcher.test.mjs— Over-scoped churn: theremoveFixtureTreeretry/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 anyEBUSY/ENOTEMPTY/EPERMfromrmSyncis 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 🐋