Skip to content

fix(wsl): skip stopped distros during background CLI/quota checks - #21013

Closed
RoxasZohbi wants to merge 3 commits into
stablyai:mainfrom
RoxasZohbi:fix/20184-wsl-autolaunch-no-workspace
Closed

RoxasZohbi wants to merge 3 commits into
stablyai:mainfrom
RoxasZohbi:fix/20184-wsl-autolaunch-no-workspace

Conversation

@RoxasZohbi

Copy link
Copy Markdown
Contributor

Author (X/Twitter): SyedZohaib2623

ELI5

Just opening Orca (with no workspace open at all) was quietly booting up
a stopped WSL virtual machine in the background. This fixes two separate
places in the code that were each capable of causing that on their own.

What Changed

Two independent code paths were booting a stopped WSL distro just from launching Orca, with no workspace open (#20184):

  • Startup CLI-bridge registration reconciliation execs into any distro that hasn't been inspected for the current app version yet, with no check for whether it's already running.
  • The background usage/rate-limit refresh (~1s after every window creation) resolves a WSL-hosted account's home path unconditionally, even when that account's distro is stopped.

Both now check listRunningWslDistrosAsync() first and skip the distro entirely if it isn't already running, instead of waking it. This is the same reusable guard the codebase already uses elsewhere for this exact purpose.

prepareForRateLimitFetch (Codex) and its resolver type are now async to support the running-distro check; threaded the await through every call site in the rate-limit service and the reset-credit coordinator. Updated affected tests to the new async contract, and added dedicated regression tests for both triggers.

Why

Booting a stopped WSL distro is a multi-second, resource-heavy operation the user never asked for and has no way to opt out of — it happened purely as a side effect of passive background housekeeping (a version-bump check, a status-bar quota refresh), with no workspace open and no WSL feature actually in use.

Linked Issue

This addresses two of the mechanisms behind #20184; not marked as Fixes #20184 since another contributor may be independently working the first one (see the issue thread for the shared root-cause writeup).

Visual Proof

https://www.loom.com/share/5b0c9e4d80ab433cbd5095641ebf5fc9

Testing

  • I manually tested these changes locally
  • Automated tests added/updated

Manual verification (Windows, WSL2):

  • Trigger 1: reset the CLI-registration state file so a distro looked un-reconciled again, built via pnpm build:unpack (packaged build required, since this path only runs when app.isPackaged), shut down WSL, launched with no workspace — distro stayed stopped.
  • Trigger 2: added a WSL-hosted Codex account, shut down WSL, launched via pnpm dev with no workspace — distro stayed stopped (previously reproduced the bug reliably before this fix).

Automated: added regression tests for both triggers, verified each fails against the pre-fix code and passes against the fix.

Platforms tested: Windows only (this bug is Windows/WSL-specific by nature).

AI Disclosure

Claude (Sonnet 5, via Claude Code) was used throughout: reproducing the bug, tracing both root causes, implementing the fix, and writing the regression tests, all reviewed and directed by me at each step.

Review

  • Cross-platform: both changes are gated to win32/WSL-specific code paths already; no effect on macOS or Linux behavior.
  • SSH/remote: not applicable, this is local-machine WSL detection only.
  • Agent/integration compatibility: Codex-specific for Trigger 2; Claude's equivalent rate-limit-fetch path likely has the same shape of issue, flagged as a follow-up, not fixed here to keep this PR focused.
  • Performance: adds one lightweight listRunningWslDistrosAsync() call (a wsl.exe --list --running probe, not a distro boot) before each affected path.
  • Security: no new external input handling or IPC/network surface changes.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Found and fixed two independent triggers for the same reported symptom; documented both on the issue thread before implementing. A third, related gap (Claude's WSL-hosted account rate-limit fetch likely has the same unconditional-resolve issue) was identified but intentionally left out of scope for this PR.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • 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)

Two independent code paths were booting a stopped WSL distro just from
launching Orca, with no workspace open (stablyai#20184):

- Startup CLI-bridge registration reconciliation execs into any distro
  that hasn't been inspected for the current app version yet, with no
  check for whether it's already running.
- The background usage/rate-limit refresh (~1s after every window
  creation) resolves a WSL-hosted account's home path unconditionally,
  even when that account's distro is stopped.

Both now check listRunningWslDistrosAsync() first and skip the distro
entirely if it isn't already running, instead of waking it. This is
the same reusable guard the codebase already uses elsewhere for this
exact purpose.

prepareForRateLimitFetch (Codex) and its resolver type are now async
to support the running-distro check; threaded the await through every
call site in the rate-limit service and the reset-credit coordinator.
Updated affected tests to the new async contract, and added dedicated
regression tests for both triggers.

This addresses two of the mechanisms behind stablyai#20184; not marked as
Fixes since another contributor may be independently working the
first one.
@coderabbitai

coderabbitai Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: da1d4087-18cd-4e5a-a951-ce107b1a2a2d

📥 Commits

Reviewing files that changed from the base of the PR and between 21d82f2 and 647f65d.

📒 Files selected for processing (3)
  • src/main/cli/wsl-cli-installer.test.ts
  • src/main/rate-limits/service-refresh-orchestration.test.ts
  • src/main/rate-limits/service-window-activation.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.


📝 Walkthrough

Walkthrough

The change restricts WSL registration repair and rate-limit home preparation to distros that are already running. WSL distro names are normalized before matching. Home-path resolution becomes asynchronous, and rate-limit cycle callers now await it. Reset-credit consumption rejects target changes detected during home preparation. Tests add running-distro mocks, await the updated APIs, and cover stopped-distro and stale-result behavior.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 647f6

The change avoids starting stopped WSL distributions and rejects stale asynchronous reset requests, with no concrete merge-blocking risk remaining.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 3 functions across 25 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary change: skipping stopped WSL distributions during background CLI and quota checks.
Description check ✅ Passed The description is complete and relevant. It includes the ELI5 summary, changed behavior, rationale, issue reference, visual proof, testing details, AI disclosure, compatibility review, scope notes, a…
Linked Issues check ✅ Passed Issue #20184 requires Orca to avoid starting stopped WSL distributions during startup when no WSL feature is in use. reconcileManagedWslCliRegistrations now filters registration candidates against `…
Out of Scope Changes check ✅ Passed The changes stay within issue #20184. The asynchronous Codex home-resolution updates support the running-distro check and update its call sites and tests. The target and generation rechecks prevent st…
  • Fix all pre-merge checks with AI

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: 2322933d-7792-47f6-917f-b23ee78efd4c

📥 Commits

Reviewing files that changed from the base of the PR and between 291b4dd and 5dfb8ea.

📒 Files selected for processing (20)
  • src/main/cli/wsl-cli-registration-reconciliation.test.ts
  • src/main/cli/wsl-cli-registration-reconciliation.ts
  • src/main/codex-accounts/codex-reset-credit-coordinator.ts
  • src/main/codex-accounts/runtime-home-managed-auth-recovery.test.ts
  • src/main/codex-accounts/runtime-home-per-account-homes.test.ts
  • src/main/codex-accounts/runtime-home-real-home-lane-routing.test.ts
  • src/main/codex-accounts/runtime-home-retained-auth-provenance.test.ts
  • src/main/codex-accounts/runtime-home-service-home-routing.ts
  • src/main/codex-accounts/runtime-home-service-per-account-migration.test.ts
  • src/main/codex-accounts/runtime-home-service-state.ts
  • src/main/codex-accounts/runtime-home-wsl-managed-accounts.test.ts
  • src/main/codex-accounts/runtime-home-wsl-system-default.test.ts
  • src/main/codex-accounts/sta-4422-transient-ownership-error.test.ts
  • src/main/rate-limits/service-account-target-selection.test.ts
  • src/main/rate-limits/service-inactive-account-previews.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

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

throw new Error('A previous reset attempt for this target still has an unknown outcome.')
}
const homeResolution = this.dependencies.runtimeHome.prepareForRateLimitFetch(target)
const homeResolution = await this.dependencies.runtimeHome.prepareForRateLimitFetch(target)

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Revalidate target after home preparation.

The checks before this await do not protect the provider mutation after it. If the user changes the Codex target while home preparation lists WSL distros, this call still spends reset credit against the old target. This conflicts with the existing changed-target rejection contract.

Re-read the active target and selected account after the await. Reject the operation if either value no longer matches the initial state.

@pullfrog pullfrog 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

This PR leaves the test suite red. Three tests fail on Linux CI (all pass at base caa465d, verified in a clean worktree). Unit tests run on ubuntu-latest, so at least one is a guaranteed CI failure. Inline comments carry the exact failures and the minimal fixes.

Reviewed changes

  • CLI-bridge reconciliation skips stopped distros — wsl-cli-registration-reconciliation.ts gains a listRunningDistros option and filters candidates through listRunningWslDistrosAsync before repairManagedRegistration() execes into them.
  • Codex quota poll skips stopped distros — prepareForRateLimitFetch becomes async and returns { kind: 'skip' } for a WSL target whose distro is not running, via a new isWslDistroRunningForRateLimitFetch gate.
  • Async plumbing — CodexHomePathResolver now returns a Promise; resolveCodexHome is async and awaited at four rate-limit call sites; the reset-credit coordinator awaits prepareForRateLimitFetch; the abstract signature in runtime-home-service-state.ts changes.
  • Tests — regression tests added for both triggers; WSL account/rate-limit tests migrated to the async contract.

ℹ️ Stopped distros no longer get their CLI bridge reconciled automatically

Reconciliation runs only once, at startup (main-process-ready-foundation.ts:105), and is now filtered to distros that are already running. A distro that is stopped on every launch therefore never has its managed orca bridge repaired until the user runs the Settings install/repair action — previously the startup pass would boot it and repair. The new comment documents this tradeoff, so flagging it only to confirm the follow-up path is real (e.g. an on-demand reconcile when a WSL workspace is first opened) rather than relying solely on Settings.

Technical details
# CLI-bridge reconciliation no longer self-heals on later distro start

## Affected sites
- `src/main/startup/main-process-ready-foundation.ts:105` — the only production trigger of `reconcileManagedWslCliRegistrations`.
- `src/main/cli/wsl-cli-registration-reconciliation.ts:117-122` — candidates are filtered to currently-running distros.

## Required outcome
- Confirm the intended recovery path for a bridge that goes stale while every relevant distro is stopped at startup, so it cannot silently persist across app updates.

## Open questions for the human
- Is a stale managed launcher acceptable until the user opens a WSL workspace, or should reconciliation re-run once a distro starts?

ℹ️ Nitpicks

  • src/main/codex-accounts/service-test-harness.ts:82,89 still types RuntimeHomeStub.prepareForRateLimitFetch as returning CodexRateLimitHomeResolution synchronously, and service-reset-credit-target-routing.test.ts:171 still uses mockReturnValue. It compiles only because callers cast as never; tightening the stub to Promise<...> would keep it honest against the new abstract contract.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment on lines +267 to +269
if (wslTarget.wslDistro && !(await this.isWslDistroRunningForRateLimitFetch(wslTarget))) {
return { kind: 'skip' }
}

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.

This skip is on the user-initiated reset-credit path too, not just passive background polls: codex-reset-credit-coordinator.ts:160 awaits prepareForRateLimitFetch(target) and rejects with ManagedCodexHomeTemporarilyUnavailableError on skip. So a reset requested for a WSL-hosted account whose distro is stopped now surfaces "Codex account files are temporarily locked. Retry in a moment." instead of booting the distro — worth confirming that's the intended behavior for an explicit user action, since the PR scope is described as background checks.

Technical details
# Skip guard also covers the user-initiated reset-credit consume path

## Affected sites
- `src/main/codex-accounts/runtime-home-service-home-routing.ts:267-269` — returns `{ kind: 'skip' }` for a stopped WSL distro.
- `src/main/codex-accounts/codex-reset-credit-coordinator.ts:160-165` — awaited by `serializeMutation`; `skip` throws `ManagedCodexHomeTemporarilyUnavailableError`.
- `src/main/startup/main-process-account-services.ts:70-72` — the same resolver feeds the passive `RateLimitService` poll.

## Required outcome
- Decide whether an explicit reset should be allowed to wake the target distro, or whether the UI should suppress/reset that affordance while the distro is stopped (and the error message should describe the stopped distro rather than locked files).

## Open questions for the human
- Can the reset-credit UI be reached for a WSL account while its distro is stopped, or is the offer refreshed away by the skipped poll?

Fix a race introduced when prepareForRateLimitFetch became async (it now lists WSL distros). Re-check the active Codex target and selected account around the await in codex-reset-credit-coordinator so a changed selection cannot be spent against. Make the runtimeHome test stub return a Promise and add regression tests that simulate the target/account changing while home resolution is pending. Also capture codexFetchGeneration earlier in the full-cycle preparation so a stale full-refresh result cannot overwrite a newer reset outcome.

@pullfrog pullfrog 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.

ℹ️ No new issues in this delta — the new commit is a clean race fix. This is not an approval because the previously reported test failures are still open.

Reviewed changes

Since the prior pullfrog review (5dfb8ea), one commit landed (21d82f2):

  • Reset-credit race closed — consumeCurrent() re-reads the active target and selected account after awaiting prepareForRateLimitFetch(), rejecting if either changed during the WSL-distro listing gap.
  • Stale Codex generation captured earlier — codexGeneration now snapshots before resolveCodexHome() awaits, so a concurrent reset that bumps the generation can no longer let a stale full-refresh result overwrite the newer selection.
  • Test harness matched to the async contract — RuntimeHomeStub.prepareForRateLimitFetch is now typed to return a Promise, and the reset-routing test uses mockResolvedValue (the prior nitpick).
  • Regression tests added — cover the target changing while home resolution is pending, and a stale cycle result landing over a newer reset. I confirmed the latter fails against the pre-fix code (usedPercent stays 100) and passes with it, so it is real coverage.

Note: the three tests flagged in the prior review still fail at this head (verified locally; only the two rate-limit ones fall under src/main/rate-limits, the third is src/main/cli/wsl-cli-installer.test.ts). The open review threads carry the exact failures and fixes, so I have not repeated them inline. pnpm tc:node passes and no other test regressions were introduced by the race fixes.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Stabilize tests affected by async resolveCodexHome and WSL behavior. In wsl-cli-installer.test.ts add listRunningDistros to include running Ubuntu. In service-refresh-orchestration.test.ts increase flushMicrotasks to 8 and add a comment explaining resolveCodexHome is now async (pushing settlement past the default flush). In service-window-activation.test.ts add an extra microtask await and comment to ensure the fetch cycle runs after the async resolve. These changes make timing deterministic and prevent intermittent test flakes.

@pullfrog pullfrog 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.

ℹ️ No new issues in this delta — the new commit resolves the two prior test failures, so the suite is green again. Approval is withheld only because the one remaining open design-question thread on the reset-credit path is still unaddressed.

Reviewed changes

Since the prior pullfrog review (21d82f2), one commit landed (647f65d), touching only the tests that were red:

  • WSL installer test taught the running-distro filter — wsl-cli-installer.test.ts:440 now injects listRunningDistros: async () => ['Ubuntu'], so the reconciliation call under test still repairs instead of returning [].
  • Rate-limit microtask flushes widened — service-refresh-orchestration.test.ts:287 flushes 8 microtasks and service-window-activation.test.ts:136-138 awaits one extra Promise.resolve(), covering the microtask that the now-async resolveCodexHome inserts even with no resolver registered.

Verified locally: all three previously failing tests pass and the full src/main/rate-limits, src/main/codex-accounts, and src/main/cli suites are green (118 files, 1044 tests). Both prior threads anchored to those failures have been resolved.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@RoxasZohbi

Copy link
Copy Markdown
Contributor Author

Hi @AmethystLiang, just checking in on this one since it's been open a couple of weeks. Happy to make any changes if something needs adjusting.

daltonxiong added a commit to daltonxiong/orca that referenced this pull request Oct 8, 2026
Records the official issue check behind the WSL switch: stablyai#20184 is still open and its fix PR stablyai#21013 is unmerged, so the patch stays. Also documents the build procedure, the pnpm shim workaround, the max-lines overage, and the esbuild temp-dir workaround.
@nwparker

Copy link
Copy Markdown
Contributor

Hi @AmethystLiang, just checking in on this one since it's been open a couple of weeks. Happy to make any changes if something needs adjusting.

sorry this got lost for a bit, please ping me in the future. Working on it

@nwparker

Copy link
Copy Markdown
Contributor

Thank you @RoxasZohbi for digging into #20184 and for the clear root-cause write-up here. We're closing this in favor of #27684, which takes a broader approach: one shared gate that defers background work until a distro is running (so CLI registration still completes in the same session instead of waiting for the next launch), and it covers a few more triggers (fish-history cleanup, the Claude/Kimi usage polls, and the pre-update Codex login sync).

Your Codex home-resolution race fix and its regression test applied to our branch too. They're ported into #27684 as a separate commit with you as co-author, and the PR description credits this PR. Thanks again!

@nwparker nwparker closed this Oct 12, 2026
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