Repository navigation
fix(wsl): stop booting stopped distros for background work - #27684
Conversation
📝 Walkthrough
Priority: ➖ Normal Severity of issue fixed: Medium Merge Risk: 🟡 Moderate · up to A Codex reset can lose its completed state, background reconciliation can restart a stopped distro in a race, and deferred WSL history cleanup can remain pending. These issues should be addressed before merging. Pre-merge checks |
|
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
- Configuration used: Repository UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
f7c3b7be-31b9-4010-93ff-b5100d8f846e
📥 Commits
Reviewing files that changed from the base of the PR and between cfb63dc and eac0d3da689420805dbb5ed543ccfdf9039179ee.
📒 Files selected for processing (30)
src/main/agent-hooks/wsl-hook-relay-deps.tssrc/main/agent-hooks/wsl-hook-relay-launch.tssrc/main/claude-accounts/runtime-auth-service.test.tssrc/main/claude-accounts/runtime-auth-service.tssrc/main/cli/wsl-cli-installer.test.tssrc/main/cli/wsl-cli-registration-reconciliation.test.tssrc/main/cli/wsl-cli-registration-reconciliation.tssrc/main/codex-accounts/runtime-home-restart-stopped-distro.test.tssrc/main/codex-accounts/runtime-home-service-home-routing.tssrc/main/ipc/pty/ipc/spawn-execute.tssrc/main/ipc/pty/runtime/spawn-execute.tssrc/main/kimi/kimi-runtime-home.test.tssrc/main/kimi/kimi-runtime-home.tssrc/main/rate-limits/service-account-target-selection.test.tssrc/main/rate-limits/service-refresh-orchestration.test.tssrc/main/rate-limits/service-window-activation.test.tssrc/main/rate-limits/service/service-fetch-targets.tssrc/main/rate-limits/service/service-full-cycle-application.tssrc/main/rate-limits/service/service-full-cycle-preparation.tssrc/main/rate-limits/service/service-provider-cycles.tssrc/main/rate-limits/service/service-types.tssrc/main/startup/main-process-account-services.tssrc/main/startup/main-process-ready-foundation.tssrc/main/terminal-history-deletion.tssrc/main/terminal-history-tombstone-retry.test.tssrc/main/wsl-background-distro-gate.test.tssrc/main/wsl-background-distro-gate.tssrc/main/wsl-fish-history-cleanup.test.tssrc/main/wsl-fish-history-cleanup.tssrc/main/wsl-running-distro-cache.ts
💤 Files with no reviewable changes (1)
- src/main/agent-hooks/wsl-hook-relay-launch.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.
| staleHome.resolve({ kind: 'ready', codexHomePath: '/tmp/approved-selection' }) | ||
| await staleRefresh | ||
|
|
||
| expect(service.getState().codex?.session?.usedPercent).not.toBe(100) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Assert that the reset result survives the older refresh.
This assertion also passes when codex has no session after the older refresh changes it to fetching. Assert the expected 0% usage and settled status. The test will then detect a lost reset result.
| const previousState = this.state | ||
| // Why: a skipped Codex poll must not stop the other providers' cycle, so gate | ||
| // only the Codex slot instead of returning early (#STA-4422). | ||
| const codexHome = this.resolveCodexHome(codexTarget) | ||
| const codexHome = await this.resolveCodexHome(codexTarget) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Preserve reset state when Codex home resolution outlives a reset. Both cycles capture the Codex generation before an await, then mark Codex fetching without checking whether a reset completed. A later generation check rejects the older fetch result but cannot restore the reset value.
src/main/rate-limits/service/service-full-cycle-preparation.ts#L80-L80: check the captured generation after resolution and preserve the current Codex state if it changed.src/main/rate-limits/service/service-provider-cycles.ts#L15-L15: check the captured generation before marking Codex fetching or starting its fetch.
Based on learnings, re-check a captured generation after an await before writing results from an asynchronous poll.
📍 Affects 2 files
src/main/rate-limits/service/service-full-cycle-preparation.ts#L80-L80(this comment)src/main/rate-limits/service/service-provider-cycles.ts#L15-L15
Source: Learnings
eac0d3d to
c6f989c
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
- Configuration used: Repository UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
18c9e9e3-9bad-49ab-bac5-395e3f6c7cd9
📥 Commits
Reviewing files that changed from the base of the PR and between eac0d3da689420805dbb5ed543ccfdf9039179ee and c6f989c.
📒 Files selected for processing (3)
src/main/cli/wsl-cli-registration-reconciliation.tssrc/main/wsl-background-distro-gate.test.tssrc/main/wsl-background-distro-gate.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.
| distro.toLowerCase() | ||
| ) | ||
| ) | ||
| const distros = candidates.filter((distro) => running.has(distro.toLowerCase())) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Recheck each distro before its repair starts.
If more than two candidates are running, a later candidate can stop while the first two repairs run. The later worker still uses this earlier running-list result and calls repairManagedRegistration(), which can boot the stopped distro. Check the distro again inside its serialized repair operation. If it has stopped, defer that repair instead.
| if (process.platform !== 'win32') { | ||
| return false | ||
| } | ||
| const target = distro?.trim() || (await listWslDistrosAsync())[0] |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Check the current default distro, not the cached first distro.
If the user changes the WSL default while Orca remains open, listWslDistrosAsync() can still return its earlier first entry. This gate can then approve background work because the old distro is running, while an undirected wsl.exe command starts the new, stopped default distro. Resolve the current default for this check, or require callers to name the distro that their command will use. WSL’s quiet list contains names, while --set-default changes the distro used by undirected commands. (learn.microsoft.com)
Any `wsl.exe -d` (or \\wsl.localhost access) boots a stopped distro: 1-2s of VM boot, and on WSL < 3.0.1 its later idle-stop wipes the VM-wide WSLInterop binfmt entry for every other running distro (microsoft/WSL#13885). Add one gate (wsl-background-distro-gate.ts): background work checks `wsl --list --running` (never boots), and stopped-distro work can be deferred until the distro is next seen running (a confirmed running probe or a local WSL terminal spawn). - Startup CLI registration reconciliation: only running candidates; stopped ones are deferred per distro and stay registry candidates for later starts. - Fish history GC: keeps the tombstone (and its meta.json) while the distro is stopped and finishes the cleanup once it runs; no admission slot is held. - Codex/Claude/Kimi quota polls for WSL targets: skip while stopped (Codex keeps its last value). User-driven resets still boot. - Codex WSL auth drain before an update restart: skip stopped distros (no live legacy pane there; the next launch prep drains anyway).
…lution The Codex home resolver is now async (it checks whether the WSL distro is running), so a reset that lands during that await bumped the generation the full-refresh cycle then read as its own, letting a stale result overwrite it. Co-authored-by: Syed Zohaib Hussain <[email protected]>
c6f989c to
7b9e32b
Compare
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟡 Minor · Recheck the confirmed WSL state when registering deferred… · wsl-background-distro-gate.ts:48-77
src/main/wsl-background-distro-gate.ts:48-77
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winRecheck the confirmed WSL state when registering deferred work.
deferUntilWslDistroRunningcan run after an asynchronous caller has observed a running distro and the cache has synchronously notified existing listeners. The gate does not replay that notification or recheck the confirmed state after registration. The deferred task can therefore remain pending while its distro is already running.Move the current confirmed-state check into this shared registration boundary so asynchronous callers receive the same behavior as callers that explicitly call
noteWslDistrosRunning.
🟡 Minor · Re-derive WSL tombstones before returning for an empty worktree… · terminal-history-gc.ts:151-173
src/main/terminal-history-gc.ts:151-173
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winRe-derive WSL tombstones before returning for an empty worktree set.
Desktop GC schedules only the native tombstone root before returning when
liveWorktreeIdsis empty. It therefore skips persisted WSL tombstones. After a restart,noteWslDistrosRunningcan replay only in-memory deferred tasks, so starting the distro later does not queue the tombstone. The guest history cleanup can remain pending until another qualifying GC or headless startup.Suggested fix
if (liveWorktreeIds.size === 0) { + await Promise.all( + listWslHistoryRoots().map((distroRoot) => schedulePendingHistoryTreeRemovals(distroRoot)) + ) console.log('[pty:history:gc] Skipped: live worktree set is empty') return }
ℹ️ Review info
⚙️ Run configuration
- Configuration used: Repository UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
744cbfe9-3309-4756-bed1-7aea1c1a6c80
📒 Files selected for processing (2)
src/main/wsl-running-distro-cache.tssrc/main/wsl-running-distros.test.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.
ELI5
On Windows, Orca was quietly starting up Linux environments (WSL distros) that the user had stopped, just to do housekeeping. Now that housekeeping waits until the user is already using that distro.
What Changed
Before: with a WSL distro stopped, Orca would start it anyway for background work: re-registering the
orcacommand after every app update (every registered distro, at launch), cleaning up deleted terminals' fish history, polling Codex/Claude/Kimi usage for WSL accounts, and syncing a Codex WSL login before an update restart.After: a stopped distro stays stopped. That work is put on hold and runs as soon as Orca next sees the distro running (a running-distro check succeeds, or the user opens a WSL terminal). Usage polls for a stopped distro are skipped, not queued.
Mechanism: one shared gate,
src/main/wsl-background-distro-gate.ts. It askswsl --list --running(which never starts anything) and keeps a per-distro queue of deferred tasks, keyed so a rescan cannot queue duplicates. Every trigger above goes through it. Things the user explicitly asks for (agent detection, skills, picking a worktree folder) still start the distro as before.If the running-distro check itself fails (e.g.
wsl.execannot be spawned), the gate reads every distro as stopped rather than trusting the last successful answer, so a distro that idled out since cannot be booted off a stale list; deferred work waits for the next successful check.A second commit captures the Codex usage "generation" before the now-async home lookup, so a reset that lands during the lookup cannot be overwritten by an older poll's result.
Why
Starting a cold distro costs about 1.2-1.6 s of VM boot each time. Worse, on WSL older than 3.0.1, when a systemd distro that Orca started later idles out, its shutdown removes Windows-program support for every running distro (microsoft/WSL#13885), so
.exelaunches in the user's other distros start failing with "Exec format error".Builds on the investigation in #21013 by @RoxasZohbi, which skips stopped distros for two of these triggers; the generation fix and its regression test come from that PR. This branch defers instead of skipping, so the
orcacommand gets repaired in the same session once the distro runs rather than waiting for the next app launch, and it covers every background trigger through one gate.Out of scope: the issue commenter's periodic
glabcall through WSL, which is a separate trigger.Linked Issue
Fixes #20184
Visual Proof
N/A. Nothing in the UI changes; the only difference is that a stopped distro stays stopped.
Testing
Real Windows host (Windows 11 26200, WSL 2.7.11, distros
Ubuntu-24.04(default) and a second one already running). A Node harness bundled from this branch's realwsl.ts,wsl-running-distro-cache.tsandwsl-background-distro-gate.ts(esbuild, not reimplemented) was run with Orca's own Electron as Node, against a throwaway non-systemd Alpine distro imported for the test and unregistered afterwards:wsl --list --running --quietis UTF-16LE withoutWSL_UTF8and UTF-8 with it; the parser returns["Ubuntu-24.04", "<second distro>"]either way, the default distro comes first in--list --quiet, a no-name lookup resolves to the default, and matching is case-insensitive.wsl -l --runningbefore and after; no task ran.wsl -d <probe> --exec sleepstarted it, the first running check ran each task once (same timestamp); 7 more checks and a simulated WSL-terminal spawn ran nothing more; a task re-queued while running ran once on the next check.wsl.exemade unspawnable, the previous gate answered "running" from the stale cached list (would have booted it); the fixed gate answers "stopped". A unit test now covers this.No distros running (second Windows host, WSL 2.7, en-US, single systemd
Ubuntustopped; read-only, nothing started):wsl --list --running --quietexits 0 with empty stdout both with and withoutWSL_UTF8. Only the non-quiet form prints "There are no running distributions." and exits -1, and Orca never uses that form, so the check does not depend on the message text or its language. The same bundled gate and parser returned[]as a confirmed answer (no failure warning), and the running check, the default-distro check and the named-distro check all returned "stopped".wsl -l -vshowed Ubuntu stopped before and after. A unit test pins this captured output.Automated (macOS):
pnpm tcpasses.Targeted
pnpm test(WSL gate/CLI registration/fish/running cache/wsl.ts, rate limits, Codex/Claude accounts, Kimi, terminal history): 863 files after rebasing onto main (including the WSL interop-repair change it now sits on); all pass except 2 native-chat tests this PR does not touch, which pass when re-run alone.oxlinton changed files andpnpm run check:code-quality:changed: clean.New tests cover deferral and later replay, the running-list check, the failed-check-reads-as-stopped rule, skipped polls, and the stale-generation race (which fails without the fix).
I manually tested these changes locally
Automated tests added/updated, or explained why not below
AI Disclosure
Review
Agent skill upstream boundary
Notes
Ensure no issues in: Security, Cross-platoform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance
Windows-only paths; on macOS and Linux the gate reports "not running" and the gated callers are already WSL-only. SSH and mobile are unaffected. Deferred work lives only in memory, so on the next launch the startup check finds it again.
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)