Skip to content

[P2] perf(windows): stop the capability poll respawning blocking wsl.exe probes - #11698

Merged
OrcaWin merged 5 commits into
mainfrom
nwparker/p2-windows-capability-poll
Aug 8, 2026
Merged

OrcaWin merged 5 commits into
mainfrom
nwparker/p2-windows-capability-poll

Conversation

@nwparker

@nwparker nwparker commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

ELI5 Orca was repeatedly asking Windows “is WSL/PowerShell installed yet?” from the same Electron process that handles terminal input and IPC. On machines without WSL, mounted UI surfaces could trigger this every 30 seconds for the entire session. The checks used synchronous child processes, so a slow or hooked wsl.exe/pwsh.exe paused Orca while each command ran; the production timeout permits a pause of up to 5 seconds. This PR keeps later-install discovery without keeping the old spawn rate: - capability reads use async child processes across desktop IPC, paired-client RPC, and relay preflight; - consumers of one local host share a single 30s → 60s → 120s backoff, then one ceiling check every 5 minutes; - window focus can bring only a ceiling check forward, never postpone a pending check, and never probe less than 30 seconds after the last one; - a usable WSL stops the watcher, and the last consumer unmounting removes it; - stable “no WSL” sessions fall from 60 checks/30 minutes per consumer to at most 9 shared reads, while WSL installed in a continuously focused Orca session is still discovered. ## What changed - Added async WSL and PowerShell availability probes that share the existing caches and in-flight work. - Routed renderer IPC, host RPC, relay preflight, distro listing, LocalPtyProvider.getProfiles(), and automatic local shell selection through async paths. - Added generation-ordered cache writes so an older async failure cannot overwrite a newer success, and distro discovery invalidates an in-flight stale availability failure. - Added windowsHide: true to the new Windows child processes. - Replaced per-consumer fixed intervals with the shared bounded watcher above. - Preserved local, SSH, paired-client, and folder-workspace behavior; there is no remote wire change. ## Deterministic reproduction Before the hardening commit, six new fake-clock/deferred-callback tests failed deterministically while 58 neighboring tests passed: 1. older WSL async failure overwrote a newer synchronous success; 2. successful distro discovery was overwritten by an already-running availability failure; 3. older PowerShell async failure overwrote a newer synchronous success; 4. a second consumer reset the shared watcher’s earned backoff; 5. 25-second focus churn could defer the next probe forever; 6. a demand signal just after parking could be dropped forever. The same tests pass after the fix. The scheduler tests also pin the exact 30/60/120-second ladder, five-minute ceiling, 30-second focus floor, shared-consumer behavior, teardown, and stop-on-usable-WSL behavior. ## Native Windows benchmark Environment: native Windows, wsl.exe present but no installed distro. Six-block ABBA run, 12 sync and 12 async samples per exact command. “Gap” is event-loop delay; the async baseline is approximately one 16 ms timer tick. | Command | Sync median / p95 gap | Async median / p95 gap | | --- | ---: | ---: | | wsl.exe --status | 34.1 / 63.5 ms | 16.1 / 16.4 ms | | wsl.exe --list --quiet | 35.1 / 37.3 ms | 16.0 / 25.5 ms | | pwsh.exe -Version | 103.0 / 312.9 ms | 18.9 / 25.8 ms | This shows the synchronous path delays the event loop for the command’s duration, while the async path stays near the timer baseline. Machines with slow security hooks or wedged WSL can amplify the old pause up to the 5-second timeout. ## Verification Green locally: - 188/188 focused WSL, PowerShell, watcher, capability-hook, and local-PTY tests - 99/99 IPC, host-RPC, relay-preflight, local/SSH ownership, settings, and Windows tab-launch tests - 624/627 broader direct-consumer tests; the three failures reproduce in files identical to origin/main and are existing native-Windows PTY fixture assumptions (POSIX path expectations and unrelated Codex resume provenance) - pnpm typecheck - pnpm exec oxlint --format github - native and type-aware code-quality audits - reliability-gate and max-lines ratchets - changed-file formatting and git diff --check A repository-wide pnpm test run was inconclusive: it produced no test output before the explicit 10-minute local timeout. PR CI remains the authoritative full-shard run. ## Tradeoffs - A stable unavailable host still performs a shared async ceiling read every five minutes. This is deliberate: permanent parking would miss wsl --install completed while Orca remains focused. - Focus can accelerate ceiling reads, but the 30-second floor bounds churn. - Async WSL availability and distro reads may overlap instead of serially blocking the main loop. - getProfiles() may await a slow WSL result for up to the existing timeout, but it no longer freezes Electron while waiting. Regression source: #11295 changed absent-WSL detection from a process-lifetime latch to a 30-second renderer poll without first moving the underlying Windows probes off the main event loop.

@greptile-apps

greptile-apps Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a session-long wsl.exe/pwsh.exe spawn storm on Windows hosts without WSL by replacing the unconditional per-consumer setInterval with a shared, demand-driven watcher that backs off exponentially (30 s → 60 s → 120 s), parks after three consecutive identical answers, and re-arms only on window focus or a newly mounted consumer. In parallel, the three main-process IPC handlers (wsl:isAvailable, wsl:listDistros, pwsh:isAvailable) and their web-client RPC equivalents are switched from blocking execFileSync to async execFile twins that share caches and deduplicate concurrent callers onto a single spawn.

  • Renderer watcher (windows-terminal-capability-reprobe.ts): replaces three separate 30 s setInterval instances (TabBar + two StatusBar mounts) with a single backoff schedule per owner key; parks permanently after a settled answer, revived by focus or a new consumer mount.
  • Main-process async probes (wsl-availability.ts, pwsh.ts): isWslAvailableAsync deduplicates concurrent callers via wslAvailabilityProbeInFlight; isTimeoutError handles both execFileSync ETIMEDOUT and execFile SIGTERM-kill shapes; isRetryableWslProbeFailure now recognises numeric error.code from the execFile callback so a definitive non-zero exit earns the 10-minute cache window instead of the 45-second retryable one.
  • Cache extraction (wsl-availability.ts): WSL availability state moved verbatim from wsl.ts to stay under the 300-line max-lines rule; re-exported from wsl.ts so all callers are unchanged.

Confidence Score: 5/5

Safe to merge; the async probe twins correctly share caches and backoff with their sync counterparts, the renderer watcher parks cleanly, and the full test suite covers the key regression paths.

All functional changes — async probe deduplication, failure classifier fixes for both execFileSync and execFile error shapes, the backoff/park watcher — are well-covered by the new test suite. The only gaps are cosmetic: the windowsHide option claimed in the description is missing from two spawns, and the attempt field is redundant with unchangedStreak. Neither affects correctness.

Files Needing Attention: src/main/wsl-availability.ts and src/main/pwsh.ts — the two async spawn sites that are missing windowsHide: true.

Important Files Changed

Filename Overview
src/renderer/src/lib/windows-terminal-capability-reprobe.ts New shared backoff/park watcher replacing the per-consumer setInterval; logic is sound — both attempt and unchangedStreak are always incremented/reset together (effectively redundant), and the focus-guard correctly drops signals within 30s of the last probe to prevent churn.
src/main/wsl-availability.ts New async twin of isWslAvailable; deduplication via wslAvailabilityProbeInFlight is correct; isRetryableWslProbeFailure correctly handles both execFileSync (numeric status) and execFile callback (numeric code) shapes; windowsHide option absent from probeWslStatus.
src/main/pwsh.ts isTimeoutError correctly handles both execFileSync ETIMEDOUT and execFile SIGTERM kill shapes; isPwshAvailableAsync deduplicates via pwshProbeInFlight; warmPwshAvailabilityCache uses a separate in-flight to avoid mixing 5s/30s timeout semantics; windowsHide option absent from the async spawn.
src/renderer/src/lib/windows-terminal-capabilities.ts reprobe.stop null-safety on fast unmount is correctly handled via the cancelled flag; startWindowsTerminalCapabilityReprobe is only called after the first load resolves and only for local non-SSH targets.
src/main/wsl.ts Availability cache and async twin cleanly extracted to wsl-availability.ts; re-exports preserve all existing callers; listWslDistrosAsync lacks in-flight deduplication (acknowledged as an accepted trade-off).
src/main/ipc/app.ts wsl:isAvailable, wsl:listDistros, and pwsh:isAvailable IPC handlers correctly switched from sync to async variants; gitBash:isAvailable correctly stays synchronous.
src/main/runtime/rpc/methods/host-capabilities.ts RPC methods for web/mobile clients now route through async probes, matching the IPC path; isGitBashAvailable correctly stays synchronous.
src/relay/preflight-handler.ts detectWindowsTerminalCapabilities now uses async probe twins; wslDistros correctly gated on wslAvailable to avoid a redundant spawn when WSL is absent.

Sequence Diagram

sequenceDiagram
    participant R as Renderer (TabBar/StatusBar)
    participant W as windows-terminal-capabilities.ts
    participant Reprobe as capability-reprobe.ts
    participant IPC as Electron IPC
    participant Main as Main Process (ipc/app.ts)
    participant WSL as wsl-availability.ts
    participant Pwsh as pwsh.ts

    R->>W: useWindowsTerminalCapabilities()
    W->>IPC: loadWindowsTerminalCapabilities()
    IPC->>Main: wsl:isAvailable / wsl:listDistros / pwsh:isAvailable
    Main->>WSL: isWslAvailableAsync() [deduped in-flight]
    Main->>Pwsh: isPwshAvailableAsync() [deduped in-flight]
    WSL-->>Main: result (cached or from wsl.exe spawn)
    Pwsh-->>Main: result (cached or from pwsh.exe spawn)
    Main-->>IPC: "Promise<boolean/string[]>"
    IPC-->>W: WindowsTerminalCapabilities
    W->>Reprobe: startWindowsTerminalCapabilityReprobe()
    Note over Reprobe: arm(attempt=0) -> 30s timer
    Reprobe->>Reprobe: "runProbe() at +30s (unchanged, streak=1, next=60s)"
    Reprobe->>Reprobe: "runProbe() at +90s (unchanged, streak=2, next=120s)"
    Reprobe->>Reprobe: "runProbe() at +210s (unchanged, streak=3 >= SETTLE, park)"
    Note over Reprobe: Parked. Re-armed by window focus or new consumer mount.
    R->>Reprobe: "window focus event (>30s after last probe)"
    Reprobe->>Reprobe: "armRunner() -> reset streak/attempt -> 30s timer"
Loading

Reviews (8): Last reviewed commit: "perf(windows): route relay host-capabili..." | Re-trigger Greptile

Comment thread src/main/wsl-availability.ts Resolved
@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The main process now performs WSL and PowerShell availability checks asynchronously. Shared caches, retry backoff, timeout handling, generation tracking, and in-flight deduplication manage probe results. IPC, RPC, preflight, and profile handlers use asynchronous probes. The renderer replaces fixed capability polling with cancellable, shared reprobe runners that support backoff, focus-triggered rearming, cached results, and consumer lifecycle cleanup. Tests cover probe behavior, handler usage, cache behavior, reprobe scheduling, recovery, and shutdown.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.91% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the change and testing in detail but omits the required Screenshots, AI Review Report, and Security Audit sections. Add the required Screenshots, AI Review Report, and Security Audit sections, and complete the Testing checklist with explicit results for each command.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the Windows performance change: replacing recurring blocking WSL probes in the capability poll.
✨ 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: 4


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1bdb4c47-bc75-4c65-b32f-9edf321c04ed

📥 Commits

Reviewing files that changed from the base of the PR and between a2d0e77 and 6533811.

📒 Files selected for processing (12)
  • config/tsconfig.tc.web.json
  • src/main/ipc/app.test.ts
  • src/main/ipc/app.ts
  • src/main/pwsh.test.ts
  • src/main/pwsh.ts
  • src/main/wsl-availability.ts
  • src/main/wsl.test.ts
  • src/main/wsl.ts
  • src/renderer/src/lib/windows-terminal-capabilities.test.ts
  • src/renderer/src/lib/windows-terminal-capabilities.ts
  • src/renderer/src/lib/windows-terminal-capability-reprobe.test.ts
  • src/renderer/src/lib/windows-terminal-capability-reprobe.ts

Comment thread src/main/pwsh.ts Resolved
Comment thread src/main/wsl-availability.ts Resolved

@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

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 4


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1bdb4c47-bc75-4c65-b32f-9edf321c04ed

📥 Commits

Reviewing files that changed from the base of the PR and between a2d0e77 and 6533811.

📒 Files selected for processing (12)
  • config/tsconfig.tc.web.json
  • src/main/ipc/app.test.ts
  • src/main/ipc/app.ts
  • src/main/pwsh.test.ts
  • src/main/pwsh.ts
  • src/main/wsl-availability.ts
  • src/main/wsl.test.ts
  • src/main/wsl.ts
  • src/renderer/src/lib/windows-terminal-capabilities.test.ts
  • src/renderer/src/lib/windows-terminal-capabilities.ts
  • src/renderer/src/lib/windows-terminal-capability-reprobe.test.ts
  • src/renderer/src/lib/windows-terminal-capability-reprobe.ts
🛑 Comments failed to post (1)
src/renderer/src/lib/windows-terminal-capability-reprobe.ts (1)

125-141: 🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Unconditional armRunner call resets an active backoff schedule whenever a new consumer joins.

startWindowsTerminalCapabilityReprobe calls armRunner(runner) every time, including when a second consumer joins a runner that is already mid-backoff (runner.timer is not null). This restarts attempt/unchangedStreak at zero and reschedules at the 30-second base delay, discarding any backoff progress the shared schedule had made.

This is not a rare edge case. The comment on loadWindowsTerminalCapabilities states that Settings, status bar, and paired web tab bars intentionally share one owner key. If the status bar stays mounted while the user repeatedly opens and closes Settings, each open resets the shared runner to the base delay, keeping the "local" owner key probing every 30 seconds indefinitely instead of backing off. This directly undermines the PR's goal of avoiding frequent wsl.exe/pwsh.exe spawns on the main process.

Only restart the backoff when there is no active schedule (new runner or previously parked), not on every join.

Consider adding a regression test that starts a first consumer, advances past the base delay so attempt grows, then starts a second consumer on the same owner key and asserts the following probe still uses the backed-off delay rather than 30 seconds. Do you want me to draft this test?

🔧 Proposed fix to avoid discarding an active backoff schedule
   runner.probe = options.probe
   runner.readCached = options.readCached
   runner.consumers += 1
   runnersByOwnerKey.set(options.ownerKey, runner)
-  // A newly mounted surface is a demand signal, so restart the backoff window.
-  armRunner(runner)
+  // Restart the backoff only when no schedule is currently running (brand-new
+  // runner or previously parked); joining an active schedule must not discard
+  // its progress.
+  if (runner.timer === null) {
+    armRunner(runner)
+  }
   attachFocusListener()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

  const runner: CapabilityReprobeRunner = runnersByOwnerKey.get(options.ownerKey) ?? {
    consumers: 0,
    timer: null,
    attempt: 0,
    unchangedStreak: 0,
    signature: capabilitySignature(options.readCached()),
    lastProbeAt: 0,
    probe: options.probe,
    readCached: options.readCached
  }
  runner.probe = options.probe
  runner.readCached = options.readCached
  runner.consumers += 1
  runnersByOwnerKey.set(options.ownerKey, runner)
  // Restart the backoff only when no schedule is currently running (brand-new
  // runner or previously parked); joining an active schedule must not discard
  // its progress.
  if (runner.timer === null) {
    armRunner(runner)
  }
  attachFocusListener()

@nwparker

Copy link
Copy Markdown
Contributor Author

Review follow-up (c4e45b4)

Fixed

1. Sync/async probe races (wsl-availability.ts, pwsh.ts) — valid, and the harm was worse than the stale failure count: the older probe's result could land last and overwrite a newer answer. A sync probe that just saw wsl.exe --status exit 0 could be overwritten by an async ENOENT/exit-1 that started earlier, caching "WSL missing" for the full 10-minute definitive window and dropping WSL from the picker; the same shape in pwsh.ts cached "pwsh missing" for 30s over a successful probe and silently disabled the user's PowerShell 7 preference.

Both caches now carry a generation counter that every write bumps. A probe captures the generation when it spawns and only writes a failure if nothing has been written since; a success always wins (a zero exit is proof, and #11295 says absent must never latch). The WSL failure count is now read at write time instead of from a snapshot taken at call time.

The double spawn itself is gone for WSL: LocalPtyProvider.getProfiles() was the only remaining main-process caller of the sync twin, and it is already an async method, so it now awaits isWslAvailableAsync() — one shared probe, and no 5s main-thread block when listing profiles. isPwshAvailable() still has a genuinely synchronous caller (ipc/pty.ts:1784 → the PTY spawn path), so its sync twin can still spawn alongside an in-flight async probe; making that path async would reach into PTY spawn and is not worth the regression risk. With the generation guard the outcome is correct either way — it is at most one extra short-lived pwsh.exe in a narrow overlap.

Regression tests (both fail on the pre-fix code): wsl.test.ts "does not let an older in-flight probe overwrite a newer answer", pwsh.test.ts same name.

2. Stale probe restoring an invalidated failure (wsl-availability.ts:151-154) — valid. dropStaleWslAvailabilityFailure() now bumps the same generation unconditionally, so an availability probe already in flight cannot land its failure after a non-empty distro list proved wsl.exe runs. Regression test: wsl.test.ts "does not restore an availability failure a distro list disproved mid-probe" (fails pre-fix).

3. armRunner resetting a shared backoff on every join (windows-terminal-capability-reprobe.ts:125-141) — valid, thanks. Joining a runner that already has a live schedule no longer resets attempt/unchangedStreak. A parked runner still re-arms (a new surface is a demand signal), but through the same recency guard the focus handler uses, so repeated Settings opens can't pin the shared local owner key at a 30s spawn. The newly mounted surface is not left waiting: its own mount still reads through loadWindowsTerminalCapabilities. Regression test: "keeps the earned backoff when a second consumer joins a running schedule" (fails pre-fix), plus "re-arms a parked watcher when a new consumer joins" to pin the behaviour that is kept.

Refuted

"Make the reprobe callback bypass the capability cache" (windows-terminal-capabilities.ts:268) — replied in-thread. Short version: the TTL check at :143 is strict (<) and measures from the start of the previous read (loadedAt = now captured at :133), while the re-probe's shortest delay equals the TTL and its timer is only armed after the previous load resolved — so the elapsed time is always ≥ TTL and the re-probe always reads through. force: true would additionally bypass the in-flight dedup at :147 and reintroduce duplicate wsl.exe/pwsh.exe spawns. Added a boundary test at exactly the TTL so this cannot regress silently.

Verification

src/main (17 587 tests), src/relay, src/renderer/src/lib (3 450 tests) and the capability-consuming renderer components all pass; oxlint clean; tsc -p config/tsconfig.node.json and config/tsconfig.tc.web.json clean. The one full-suite failure (src/main/pty/omp-shell-wrapper.node-pty.test.ts) spawns real PTYs, passes in isolation and on src/main/pty, and is untouched by this change.

@nwparker

Copy link
Copy Markdown
Contributor Author

Both blocking items verified against the branch and fixed in ade28dea4b.

1. Focus churn starved the re-probe — valid, fixed.

Reproduced exactly as described. rearmOnDemandSignal guarded only on runner.lastProbeAt, while armRunner → scheduleNextProbe clears the pending timer and reschedules from now at the base delay, and lastProbeAt is only written inside runProbe. So every focus landing more than 30s after the last completed probe pushed the next probe out by another 30s, and because no probe completed the guard never re-engaged. Regression test added to windows-terminal-capability-reprobe.test.ts ("keeps probing while the window is focused more often than the base delay"): first probe at 30s, then 10 minutes of focus at a 25s cadence. On the pre-fix code it fails with expected 1 to be greater than 1 — one probe in 10.5 minutes; after the fix it is 8.

Fix is the suggested early return: rearmOnDemandSignal now no-ops when runner.timer !== null, so a demand signal only revives a parked runner. The lastProbeAt guard is kept — it is still what stops rapid focus churn from re-arming a parked runner every few seconds. The mount-join path now calls rearmOnDemandSignal unconditionally, since the existing.timer === null check it used to do inline is exactly the new guard; that removes the asymmetry the earlier commit left behind. The test asserts an upper bound too (< 12 probes), so the fix cannot degrade into 25s polling.

2. The TTL boundary test was inert — valid, fixed.

Confirmed by the same mutation: with windows-terminal-capabilities.ts:143 changed from < to <=, the old test passed (1 passed, isolated). Root cause is as diagnosed — no subscriber for the local owner key, so pruneExpiredCapabilityOwners deleted the entry at the boundary and the second load was a prune-driven miss, not a strict-< fall-through.

The test now mounts a consumer (the only state a re-probe actually runs in, so prune never fires) and derives the second timestamp from REPROBE_BASE_DELAY_MS, which is now exported. Both failure modes are covered:

  • < → <= mutation: fails (wslAvailable: true → false, 1 call instead of 2).
  • REPROBE_BASE_DELAY_MS lowered to 20s (below the 30s TTL): fails.

windows-terminal-capabilities.test.ts crossed the 800-line max-lines ceiling with the larger test, so the repeated 4-line createRoot boilerplate in five tests is now a mountHookRoot helper. No max-lines disable, no assertion weakened or removed.

Deliberately left

  • pwsh.ts:105-116 (pwshProbeInFlight assigned around a callback that nulls it) — agreed it is a latent hazard only. Node never invokes the execFile callback synchronously, and this shape predates the PR on main in warmPwshAvailabilityCache. Mirroring the WSL .finally shape is churn in probe plumbing for a case that cannot occur today, so I left it rather than take the regression risk on a P2 fix branch.
  • Clearing wslAvailabilityProbeInFlight alongside the generation bump in dropStaleWslAvailabilityFailure — the wrong answer is transient and self-corrects on the next call, as noted. Clearing the handle lets a concurrent caller spawn a second wsl.exe while the first is still running, which is a real behavioural change to the dedup the PR is about; not worth it here.
  • isWslAvailable having no production callers, and listWslDistrosAsync lacking in-flight dedup — both out of scope for this branch; happy to take either as a follow-up.

Suites run green: windows-terminal-capability-reprobe, windows-terminal-capabilities, TabBar.windows-shell-launch, AgentSettingsDialog, WindowsTerminalStep, windows-terminal-onboarding-telemetry, useSettingsNavigationMetadata.capability-owner, useWindowsTerminalCapabilityOwnerKey, windows-terminal-shell, preflight-handler, runtime/rpc/methods/preflight, ipc/preflight, wsl, pwsh, local-pty-provider, host-capabilities — 12 files / 129 tests plus the 11-file / 225-test sweep. oxlint clean on the changed files, typecheck:web clean.

@nwparker

Copy link
Copy Markdown
Contributor Author

Thanks — the blocking finding was correct and reproduced exactly as described. Pushed f178e5d810.

Fixed: parked runner silently discarded a demand signal inside the base delay

rearmOnDemandSignal checked runner.timer !== null and then Date.now() - runner.lastProbeAt < REPROBE_BASE_DELAY_MS. The recency guard exists to stop a signal from pushing out a pending probe; a parked runner has no pending probe, so the guard had nothing to protect and the signal was dropped instead of deferred. Your Settings-at-t=220s path is real, and origin/main did not have it (every mount installed its own unconditional setInterval(…, 30_000)).

The signal is now scheduled at lastProbeAt + REPROBE_BASE_DELAY_MS rather than returning. That deadline is absolute, so repeated signals inside the window cannot walk it forward — the starvation ade28dea4b fixed stays fixed (its two tests are unchanged and green).

Regression tests added at your suggested offsets, plus the starvation direction:

  • re-arms a parked watcher for a consumer joining {1000,10000,29999}ms after the last probe — asserts the probe lands at the 30s deadline and not one tick earlier
  • does not let repeated signals defer a parked watcher past the base delay — 25s of focus churn after the parking probe still fires at 30s

All four fail on ade28dea4b with expected "vi.fn()" to be called 4 times, but got 3 times (verified by reverting the production file only) and pass on the fix. No existing assertion was changed or removed.

Fixed: attempt / unchangedStreak lockstep, REPROBE_MAX_DELAY_MS dead

Correct — the two counters were incremented and reset together on every path, so they always held the same value, attempt never exceeded 2, and the Math.min(…, REPROBE_MAX_DELAY_MS) cap was unreachable. Dropped attempt and the constant; the step is now Math.min(unchangedStreak, REPROBE_SETTLE_STREAK - 1), which is bounded by construction and yields the identical 30s/60s/120s ladder.

Fixed: windowsHide: true

Added to probeWslStatus and isPwshAvailableAsync. wsl.test.ts's expect.anything() for the options arg is now expect.objectContaining({ timeout: 5000, windowsHide: true }) — a strengthening, not a relaxation.

Deliberately not done: ceiling probe instead of a permanent park

Your analysis is right, and I've written it into the PR body under Open decision rather than silently keeping it. Parking after ~210s does drop a behaviour origin/main had: a user running wsl --install inside an Orca terminal never blurs the window and mounts nothing new, so nothing re-checks.

I did not fold the fix into this commit because it is not a safe drive-by:

  • Settling onto REPROBE_MAX_DELAY_MS means the timer is never null, so rearmOnDemandSignal would swallow every demand signal — a focus that today yields a probe in 30s would yield one in up to 5 minutes. Making both work needs the runner to distinguish a ceiling timer from a ladder timer, which is new state on the exact guard this PR is already fixing twice.
  • It inverts the park semantics five existing tests encode, including backs off and parks on a stable answer instead of probing forever, and I'm not willing to rewrite that assertion as part of a review-fix pass.
  • It is a product tradeoff (a permanent 1-spawn-per-5-min on every WSL-less Windows box) that belongs in a deliberate decision, not a fixup.

Happy to do it as a follow-up if you want the un-latching guarantee back; the shape above is what it would take.

Handoff report staleness

Acknowledged, and the PR body is now re-stated against the real head. For the record: head is f178e5d810 (was ade28dea4b, not c4e45b4af0), and all 43 checks were green on ade28dea4b including crash-survival (packaged build) and Greptile Review. The body now carries per-commit follow-up entries for both ade28dea4b (the starvation regression c4e45b4af0 introduced) and f178e5d810.

Verification run

windows-terminal-capability-reprobe, windows-terminal-capabilities, wsl, wsl-availability, pwsh, ipc/app, runtime/rpc/methods/host-capabilities, providers/local-pty-provider, relay/preflight-handler, TabBar.windows-shell-launch, useWindowsTerminalCapabilityOwnerKey, useSettingsNavigationMetadata.capability-owner — all green. npx tsc --noEmit for config/tsconfig.node.json and config/tsconfig.tc.web.json, npx oxlint on every changed file.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

⚠️ Outside diff range comments (1)
src/main/pwsh.ts (1)

121-147: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Add windowsHide to the warm-up probe's execFile call.

Line 135 spawns pwsh.exe without windowsHide. The sibling probe in isPwshAvailableAsync (line 107) sets windowsHide: true specifically to prevent a background probe from flashing a console window. warmPwshAvailabilityCache runs the same background probe and still can flash a console window on Windows.

🩹 Proposed fix
   const generation = pwshCacheGeneration
   pwshWarmupInFlight = new Promise((resolve) => {
-    execFile('pwsh.exe', ['-Version'], { timeout: PWSH_WARMUP_PROBE_TIMEOUT_MS }, (error) => {
-      pwshWarmupInFlight = null
-      if (!error) {
-        setPwshAvailabilityCache({ available: true })
-        resolve(true)
-        return
-      }
-      cachePwshProbeFailure(error, generation)
-      resolve(false)
-    })
+    execFile(
+      'pwsh.exe',
+      ['-Version'],
+      { timeout: PWSH_WARMUP_PROBE_TIMEOUT_MS, windowsHide: true },
+      (error) => {
+        pwshWarmupInFlight = null
+        if (!error) {
+          setPwshAvailabilityCache({ available: true })
+          resolve(true)
+          return
+        }
+        cachePwshProbeFailure(error, generation)
+        resolve(false)
+      }
+    )
   })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 563e1370-3b80-4363-b4cf-1feb3e075fdd

📥 Commits

Reviewing files that changed from the base of the PR and between 6533811 and f178e5d81007062250a8459a441087958f125ef4.

📒 Files selected for processing (13)
  • src/main/providers/local-pty-provider.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/pwsh.test.ts
  • src/main/pwsh.ts
  • src/main/runtime/rpc/methods/host-capabilities.test.ts
  • src/main/runtime/rpc/methods/host-capabilities.ts
  • src/main/wsl-availability.ts
  • src/main/wsl.test.ts
  • src/relay/preflight-handler.test.ts
  • src/relay/preflight-handler.ts
  • src/renderer/src/lib/windows-terminal-capabilities.test.ts
  • src/renderer/src/lib/windows-terminal-capability-reprobe.test.ts
  • src/renderer/src/lib/windows-terminal-capability-reprobe.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/lib/windows-terminal-capability-reprobe.ts

@nwparker
nwparker force-pushed the nwparker/p2-windows-capability-poll branch from f178e5d to 6533811 Compare July 31, 2026 10:11
@nwparker

Copy link
Copy Markdown
Contributor Author

Remediation backed out — branch reset to 653381143f

I attempted to address the review feedback with an automated multi-agent pass. It introduced regressions, so I have reset this branch to its last independently-reviewed-clean commit (653381143f) rather than ship them. Known, documented gaps are safer than unknown new ones.

What went wrong

The thread that was refuted became valid again at the new head (the re-probe does land on a capability cache hit), Item 3 was not fixed at the root — a demand signal landing during an in-flight probe still resets the shared backoff — and Item 1's getProfiles change had no test that fails on pre-fix code.

Still outstanding: both WSL/PowerShell cache races (wsl-availability.ts:111,151-154) and the shared-backoff reset (windows-terminal-capability-reprobe.ts:136-140). Your note that the force-cache-bypass comment is invalid still stands and needs no action.

Recovery

The backed-out work is not lost — it is reachable by SHA at f178e5d81007062250a8459a441087958f125ef4, should any individual piece be worth salvaging.

The reviewer feedback on this PR remains valid and unaddressed. Flagging rather than silently leaving it.

@nwparker
nwparker force-pushed the nwparker/p2-windows-capability-poll branch from 3dd67a1 to f7bea17 Compare July 31, 2026 10:44
@nwparker

Copy link
Copy Markdown
Contributor Author

Correction: my earlier reset was too aggressive

The reset I posted earlier reset this branch to its first commit, not its last reviewed-clean one. The original fix round ran 07-30 21:55–23:41; the failed remediation began 07-31 01:18. I used the wrong boundary and dropped 1–2 legitimate commits that were part of the reviewed-clean PR.

The branch is now at the correct boundary — the last commit before remediation started. Apologies for the churn; the force-pushes were mine, not a tooling issue.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

⚠️ Outside diff range comments (1)
src/main/wsl-availability.ts (1)

122-145: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Add windowsHide to the Windows capability probes.

src/main/wsl-availability.ts and src/main/pwsh.ts run execFileSync for Windows probers without hiding the console child. Add windowsHide: true to both sync probes so wsl.exe and pwsh.exe do not flash a terminal window on Windows.

🧹 Nitpick comments (1)
src/renderer/src/lib/windows-terminal-capability-reprobe.ts (1)

6-9: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Merge attempt and unchangedStreak; the 5-minute cap is unreachable.

attempt and unchangedStreak change together on every path: both increment in the "unchanged" branch (Lines 71-72), both reset in the "changed" branch (Lines 75-77), and both reset in armRunner (Lines 108-109). No code path ever sets one without the other, so the two fields always hold the same value. Keep one counter to avoid a future edit desynchronizing them.

This coupling also makes REPROBE_MAX_DELAY_MS dead. Scheduling only continues while unchangedStreak < REPROBE_SETTLE_STREAK (3), so scheduleNextProbe never sees attempt above 2, giving a maximum delay of 30000 * 2^2 = 120000 ms. The documented 5-minute cap (Line 7) never engages under any signature-change pattern. Confirm whether the intended maximum backoff is 2 minutes (current behavior) or 5 minutes (as the constant suggests), and adjust either REPROBE_SETTLE_STREAK or REPROBE_MAX_DELAY_MS to match the intended cap.

♻️ Proposed fix: merge the two counters
 type CapabilityReprobeRunner = {
   consumers: number
   timer: ReturnType<typeof globalThis.setTimeout> | null
   attempt: number
-  unchangedStreak: number
   signature: string
   lastProbeAt: number
   probing: boolean
   rearmAfterProbe: boolean
   probe: () => Promise<WindowsTerminalCapabilities>
   readCached: () => WindowsTerminalCapabilities
 }
   if (capabilitySignature(capabilities) === runner.signature) {
-    runner.unchangedStreak += 1
     runner.attempt += 1
   } else {
     // A moving answer means the host is still changing; watch it closely again.
     runner.signature = capabilitySignature(capabilities)
-    runner.unchangedStreak = 0
     runner.attempt = 0
   }
   if (isSettled(capabilities)) {
     runner.rearmAfterProbe = false
     return
   }
   if (runner.rearmAfterProbe) {
     armRunner(runner)
     return
   }
-  if (runner.unchangedStreak >= REPROBE_SETTLE_STREAK) {
+  if (runner.attempt >= REPROBE_SETTLE_STREAK) {
     return
   }
   scheduleNextProbe(runner)

Also applies to: 11-23, 70-92


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 892072a1-43fc-494a-a62e-b77832fe06ad

📥 Commits

Reviewing files that changed from the base of the PR and between f178e5d81007062250a8459a441087958f125ef4 and 3dd67a1.

📒 Files selected for processing (4)
  • src/main/wsl-availability.ts
  • src/main/wsl.test.ts
  • src/renderer/src/lib/windows-terminal-capability-reprobe.test.ts
  • src/renderer/src/lib/windows-terminal-capability-reprobe.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/wsl.test.ts

@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/pwsh.ts (2)

70-103: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Hide the pwsh.exe probe windows.

windowsHide defaults to false for child_process.execFile, so Windows PowerShell probes can create visible child-console windows. Add windowsHide: true to the async probe and the warm-up probe. Also add it to the sync probe options since it is available on the Node target.


13-20: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Guard the shared PowerShell cache against stale completions.

isPwshAvailable(), isPwshAvailableAsync(), and warmPwshAvailabilityCache() each write pwshAvailableCache independently, while pwshProbeInFlight and pwshWarmupInFlight protect only shared spawns, not cache ordering. A later async completion can overwrite a newer cache entry and keep subsequent checks false until the negative-cache TTL; it can also leave stale false entries after a later valid probe completed in another writer.

Use one shared in-flight operation or a monotonic generation guard for every cache writer, and cover both completion orders.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4276c0d8-f966-4bed-a4c0-9d5c130fe2de

📥 Commits

Reviewing files that changed from the base of the PR and between 3dd67a1 and f7bea17.

📒 Files selected for processing (10)
  • src/main/pwsh.test.ts
  • src/main/pwsh.ts
  • src/main/runtime/rpc/methods/host-capabilities.test.ts
  • src/main/runtime/rpc/methods/host-capabilities.ts
  • src/main/wsl-availability.ts
  • src/main/wsl.test.ts
  • src/relay/preflight-handler.test.ts
  • src/relay/preflight-handler.ts
  • src/renderer/src/lib/windows-terminal-capability-reprobe.test.ts
  • src/renderer/src/lib/windows-terminal-capability-reprobe.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/main/pwsh.test.ts
  • src/renderer/src/lib/windows-terminal-capability-reprobe.test.ts
  • src/main/wsl.test.ts
  • src/renderer/src/lib/windows-terminal-capability-reprobe.ts

nwparker and others added 4 commits August 7, 2026 13:16
…robes

#11295 added a 30s renderer interval to `useWindowsTerminalCapabilities` whose
early-return only fires when WSL is available with at least one distro, so on the
common Windows host (no WSL) it re-ran a full capability read forever. Each read
IPCs four probes whose main-process handlers were synchronous `execFileSync` calls
to wsl.exe/pwsh.exe, blocking the Electron main event loop for up to 5s a time.

The un-latching intent is kept: a host that answers "no WSL" is still re-checked,
now on an exponential backoff (30s, +60s, +120s) that parks once the answer stops
moving, re-arms on window focus, is shared by all consumers of an owner key, and
stops entirely when the last consumer unmounts. The wsl/pwsh IPC handlers now use
async twins that share the existing caches and back off identically.
…e error shape

The async twins feed `execFile` callback errors into classifiers written for
`execFileSync`: a non-zero exit lands on `error.code` as a number rather than
`error.status`, and a timeout is a SIGTERM kill rather than ETIMEDOUT.

So a Windows host without WSL (wsl.exe ships in System32, so it exits non-zero
instead of ENOENT) was cached as retryable, shrinking the shared window from
10min to 45s and making the still-sync callers re-pay their blocking spawn ~13x
more often; and a pwsh cold start past 5s cached "pwsh missing" for 30s,
demoting the user's PowerShell 7 preference — the exact case the ETIMEDOUT
branch exists to prevent.

Also drops a literal NUL byte from the new re-probe module's signature
separator, which made the file binary to git, and seeds `lastProbeAt` at
registration so focus churn right after mount cannot defer the first re-probe
indefinitely.

Co-authored-by: Orca <[email protected]>
…sl/pwsh twins

A paired web/mobile client resolves `useWindowsTerminalCapabilities` to a local
target (TabBar's `isWebClient` gate, and `useSettingsNavigationMetadata` forces
`{kind:'local'}`), so the new re-probe arms there too. But `window.api.wsl/pwsh`
on a web client is not the ipc/app.ts channel — it is `host.wsl.*`/`host.pwsh.*`
over the runtime RPC, which still ran the sync probes and blocked the desktop
main event loop on `execFileSync('wsl.exe' | 'pwsh.exe')` for up to 5s per call.

Switch those handlers and the relay preflight capability probe to the async
twins added here; they share the same caches, dedupe and backoff, so remote
callers see no behavior change.
@OrcaWin
OrcaWin force-pushed the nwparker/p2-windows-capability-poll branch from f7bea17 to f07f85e Compare August 7, 2026 20:41
@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b68e8946-e483-4e12-939c-68380be8448f

📥 Commits

Reviewing files that changed from the base of the PR and between 8c3e953 and f07f85e.

📒 Files selected for processing (18)
  • config/tsconfig.tc.web.json
  • src/main/ipc/app.test.ts
  • src/main/ipc/app.ts
  • src/main/providers/local-pty-provider.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/pwsh.test.ts
  • src/main/pwsh.ts
  • src/main/runtime/rpc/methods/host-capabilities.test.ts
  • src/main/runtime/rpc/methods/host-capabilities.ts
  • src/main/wsl-availability.ts
  • src/main/wsl.test.ts
  • src/main/wsl.ts
  • src/relay/preflight-handler.test.ts
  • src/relay/preflight-handler.ts
  • src/renderer/src/lib/windows-terminal-capabilities.test.ts
  • src/renderer/src/lib/windows-terminal-capabilities.ts
  • src/renderer/src/lib/windows-terminal-capability-reprobe.test.ts
  • src/renderer/src/lib/windows-terminal-capability-reprobe.ts
🚧 Files skipped from review as they are similar to previous changes (10)
  • config/tsconfig.tc.web.json
  • src/main/ipc/app.test.ts
  • src/relay/preflight-handler.test.ts
  • src/renderer/src/lib/windows-terminal-capabilities.test.ts
  • src/main/runtime/rpc/methods/host-capabilities.test.ts
  • src/renderer/src/lib/windows-terminal-capabilities.ts
  • src/renderer/src/lib/windows-terminal-capability-reprobe.test.ts
  • src/main/runtime/rpc/methods/host-capabilities.ts
  • src/main/pwsh.test.ts
  • src/renderer/src/lib/windows-terminal-capability-reprobe.ts

Comment thread src/main/wsl-availability.ts Resolved
@OrcaWin
OrcaWin merged commit c3bf22b into main Aug 8, 2026
43 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…exe probes (stablyai#11698)

* perf(windows): stop the capability poll respawning blocking wsl.exe probes

stablyai#11295 added a 30s renderer interval to `useWindowsTerminalCapabilities` whose
early-return only fires when WSL is available with at least one distro, so on the
common Windows host (no WSL) it re-ran a full capability read forever. Each read
IPCs four probes whose main-process handlers were synchronous `execFileSync` calls
to wsl.exe/pwsh.exe, blocking the Electron main event loop for up to 5s a time.

The un-latching intent is kept: a host that answers "no WSL" is still re-checked,
now on an exponential backoff (30s, +60s, +120s) that parks once the answer stops
moving, re-arms on window focus, is shared by all consumers of an owner key, and
stops entirely when the last consumer unmounts. The wsl/pwsh IPC handlers now use
async twins that share the existing caches and back off identically.

* fix(windows): classify async wsl/pwsh probe failures with the execFile error shape

The async twins feed `execFile` callback errors into classifiers written for
`execFileSync`: a non-zero exit lands on `error.code` as a number rather than
`error.status`, and a timeout is a SIGTERM kill rather than ETIMEDOUT.

So a Windows host without WSL (wsl.exe ships in System32, so it exits non-zero
instead of ENOENT) was cached as retryable, shrinking the shared window from
10min to 45s and making the still-sync callers re-pay their blocking spawn ~13x
more often; and a pwsh cold start past 5s cached "pwsh missing" for 30s,
demoting the user's PowerShell 7 preference — the exact case the ETIMEDOUT
branch exists to prevent.

Also drops a literal NUL byte from the new re-probe module's signature
separator, which made the file binary to git, and seeds `lastProbeAt` at
registration so focus churn right after mount cannot defer the first re-probe
indefinitely.

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

* perf(windows): route relay host-capability probes through the async wsl/pwsh twins

A paired web/mobile client resolves `useWindowsTerminalCapabilities` to a local
target (TabBar's `isWebClient` gate, and `useSettingsNavigationMetadata` forces
`{kind:'local'}`), so the new re-probe arms there too. But `window.api.wsl/pwsh`
on a web client is not the ipc/app.ts channel — it is `host.wsl.*`/`host.pwsh.*`
over the runtime RPC, which still ran the sync probes and blocked the desktop
main event loop on `execFileSync('wsl.exe' | 'pwsh.exe')` for up to 5s per call.

Switch those handlers and the relay preflight capability probe to the async
twins added here; they share the same caches, dedupe and backoff, so remote
callers see no behavior change.

* fix(windows): harden async capability reprobes

* fix(windows): dedupe PowerShell shell probes

---------

Co-authored-by: Orca <[email protected]>
Co-authored-by: OrcaWin <[email protected]>
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.

2 participants