Skip to content

fix(wsl): stop booting stopped distros for background work - #27684

Merged
nwparker merged 4 commits into
mainfrom
nwparker/wsl-a1-no-background-distro-boot
Oct 12, 2026
Merged

nwparker merged 4 commits into
mainfrom
nwparker/wsl-a1-no-background-distro-boot

Conversation

@nwparker

@nwparker nwparker commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 12 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​431 $\color{#cf222e}{\Huge{\mathbf{−}}}$​21 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​410
Prod 19 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​289 $\color{#cf222e}{\Huge{\mathbf{−}}}$​67 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​222

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 orca command 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 asks wsl --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.exe cannot 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 .exe launches 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 orca command 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 glab call 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 real wsl.ts, wsl-running-distro-cache.ts and wsl-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:

  • Parsing: raw wsl --list --running --quiet is UTF-16LE without WSL_UTF8 and 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.
  • Stopped distro is not booted: 5 rounds of the running check plus deferring two tasks (one keyed with an upper-cased distro name) left the probe distro absent from wsl -l --running before and after; no task ran.
  • Deferred work runs exactly once: after a separate wsl -d <probe> --exec sleep started 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.
  • Bug found and fixed here: with the probe distro primed as running, then terminated, then wsl.exe made 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 Ubuntu stopped; read-only, nothing started): wsl --list --running --quiet exits 0 with empty stdout both with and without WSL_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 -v showed Ubuntu stopped before and after. A unit test pins this captured output.

Automated (macOS):

  • pnpm tc passes.

  • 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.

  • oxlint on changed files and pnpm 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

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

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

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@coderabbitai

coderabbitai Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes add shared WSL running-state checks and deferred tasks. CLI reconciliation and fish-history cleanup defer work for stopped distros. WSL-dependent auth preparation, runtime-home lookup, and pre-restart auth draining check distro state. PTY spawn paths report resolved distros as running. Codex home resolution is asynchronous in rate-limit refresh paths, with generation checks covering resets during resolution.



Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🟡 Moderate · up to 7b9e3

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 | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 32 functions across 30 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check Passed Issue #20184 requires Orca startup to leave stopped WSL distributions stopped when no WSL feature is in use. Startup reconciliation now processes only confirmed running distros and defers stopped dist…
Out of Scope Changes check Passed The changes remain connected to issue #20184. The shared gate and caller updates prevent unintended WSL startup across the identified background triggers. The Codex generation change protects the asyn…
Title check Passed The title clearly and concisely describes the main change: preventing background work from starting stopped WSL distributions.
Description check Passed The description is complete and matches the template. It explains the user impact, implementation, rationale, linked issue, testing, platform considerations, and visual-proof exception. The detailed t…

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR




  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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: 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.ts
  • src/main/agent-hooks/wsl-hook-relay-launch.ts
  • src/main/claude-accounts/runtime-auth-service.test.ts
  • src/main/claude-accounts/runtime-auth-service.ts
  • src/main/cli/wsl-cli-installer.test.ts
  • src/main/cli/wsl-cli-registration-reconciliation.test.ts
  • src/main/cli/wsl-cli-registration-reconciliation.ts
  • src/main/codex-accounts/runtime-home-restart-stopped-distro.test.ts
  • src/main/codex-accounts/runtime-home-service-home-routing.ts
  • src/main/ipc/pty/ipc/spawn-execute.ts
  • src/main/ipc/pty/runtime/spawn-execute.ts
  • src/main/kimi/kimi-runtime-home.test.ts
  • src/main/kimi/kimi-runtime-home.ts
  • src/main/rate-limits/service-account-target-selection.test.ts
  • src/main/rate-limits/service-refresh-orchestration.test.ts
  • src/main/rate-limits/service-window-activation.test.ts
  • src/main/rate-limits/service/service-fetch-targets.ts
  • src/main/rate-limits/service/service-full-cycle-application.ts
  • src/main/rate-limits/service/service-full-cycle-preparation.ts
  • src/main/rate-limits/service/service-provider-cycles.ts
  • src/main/rate-limits/service/service-types.ts
  • src/main/startup/main-process-account-services.ts
  • src/main/startup/main-process-ready-foundation.ts
  • src/main/terminal-history-deletion.ts
  • src/main/terminal-history-tombstone-retry.test.ts
  • src/main/wsl-background-distro-gate.test.ts
  • src/main/wsl-background-distro-gate.ts
  • src/main/wsl-fish-history-cleanup.test.ts
  • src/main/wsl-fish-history-cleanup.ts
  • src/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)

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.

🎯 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)

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.

🎯 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

@nwparker
nwparker force-pushed the nwparker/wsl-a1-no-background-distro-boot branch from eac0d3d to c6f989c Compare October 12, 2026 01:55

@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: 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.ts
  • src/main/wsl-background-distro-gate.test.ts
  • src/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()))

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.

🎯 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]

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.

🎯 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)

nwparker and others added 4 commits October 11, 2026 19:33
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]>
@nwparker
nwparker force-pushed the nwparker/wsl-a1-no-background-distro-boot branch from c6f989c to 7b9e32b Compare October 12, 2026 02:38

@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 GitHub limitations.

⚠️ Outside diff range comments (2)

🟡 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 win

Recheck the confirmed WSL state when registering deferred work.

deferUntilWslDistroRunning can 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 win

Re-derive WSL tombstones before returning for an empty worktree set.

Desktop GC schedules only the native tombstone root before returning when liveWorktreeIds is empty. It therefore skips persisted WSL tombstones. After a restart, noteWslDistrosRunning can 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
📥 Commits

Reviewing files that changed from the base of the PR and between c6f989c and 7b9e32b.

📒 Files selected for processing (2)
  • src/main/wsl-running-distro-cache.ts
  • src/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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Orca 1.4.200 launches WSL automatically on startup even with no workspace open

1 participant