Skip to content

fix(rate-limits): read Kimi usage credentials from the configured WSL runtime - #12475

Merged
OrcaWin merged 3 commits into
mainfrom
nwparker/bugpr-12372
Aug 8, 2026
Merged

OrcaWin merged 3 commits into
mainfrom
nwparker/bugpr-12372

Conversation

@nwparker

@nwparker nwparker commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

What was broken (ELI5)

If you use Kimi Code on Windows and run it inside WSL (the Linux environment on your PC), Orca's usage meter for Kimi was permanently stuck on "Run Kimi to refresh" — even right after you used Kimi. Orca was looking for your Kimi login in the Windows side of the machine, while the copy that Kimi actually keeps up to date lives on the Linux side. Orca now reads the login from whichever runtime you configured Kimi to run in, so the Kimi usage numbers show up and stay current.

Root cause

getKimiHome() hardcoded the Windows host's resolution and the fetcher took no target at all:

src/main/rate-limits/kimi-fetcher.ts:21-29 (at base 29bfc1e22c)
function getKimiHome(): string {
  return process.env.KIMI_CODE_HOME ?? join(homedir(), '.kimi-code')
}
function getCredentialsPath(): string {
  return join(getKimiHome(), 'credentials', 'kimi-code.json')
}

fetchKimiRateLimits() (src/main/rate-limits/kimi-fetcher.ts:242) took no arguments, and the caller src/main/rate-limits/service.ts:1664 invoked it as a bare fetchKimiRateLimits() — in contrast with the adjacent fetchCodexRateLimits({ codexHomePath, ... }) at service.ts:1653-1657, which is fed a WSL-resolved home.

Kimi's CLI rotates its OAuth token roughly every 15 minutes and writes it into the home of whichever runtime it runs in. With localAccountRuntime: 'wsl', the CLI refreshes \\wsl.localhost\<distro>\home\<user>\.kimi-code\credentials\kimi-code.json while Orca kept reading the abandoned Windows copy. That copy is always expired, so the fetcher returned failureKind: 'delegated-refresh-required', which maps to the status-bar string at src/renderer/src/components/status-bar/usage-error-copy.ts:84 → "Run Kimi to refresh". Permanently.

The fix

  • src/main/kimi/kimi-runtime-home.ts (new): getHostKimiHome() (the CLI's host resolution, now in one place), getKimiRuntimeTarget(settings, platform) (wraps resolveLocalAccountRuntimeTarget and pins to host whenever platform !== 'win32', because that resolver returns wsl on any platform when the setting says wsl — the same guard getInitialCodexRateLimitTarget uses, so SSH/Linux/mac hosts never probe wsl.exe), and resolveKimiHome(target) (distro from the target or the first installed distro, home from the cached echo $HOME probe, joined with win32 semantics because the result is a UNC path). KIMI_CODE_HOME stays host-only: it describes the Windows process, not the distro. An unprobeable distro yields path: null so Orca never silently falls back to the stale host copy.
  • src/main/rate-limits/kimi-fetcher.ts: takes the resolved home (defaults to host, so nothing else changes), reads credentials through createAuthFilesystemOperation — async, deduped per path, bounded by a 5s AbortSignal — so a stopped distro degrades to an error instead of parking Electron's main process on a UNC read. ENOENT/ENOTDIR keep the old existsSync "not signed in" semantics. The expired-session copy now names the runtime ("run kimi inside WSL (Ubuntu)" vs "on the computer running Orca"), since that string is the entire user-visible symptom.
  • src/main/rate-limits/service.ts + src/main/index.ts: setKimiHomeResolver(), re-resolved every poll cycle so flipping the local-account runtime policy takes effect on the next poll. Kimi has no per-account switcher (unlike Codex/Claude), so a kimiFetchTarget + account-runtime-target-sync entry would be dead weight. The resolver is chained rather than awaited up front so resolving a WSL home never delays the other providers' fetches, and it uses the async wsl.exe helpers (listWslDistrosAsync / getWslHomeAsync) rather than the sync ones the Codex path still uses.

Out of scope, deliberately: src/main/kimi/hook-service.ts:38 and src/main/ai-vault/session-scanner-kimi-paths.ts:21 duplicate the same host-only .kimi-code resolution, and src/main/rate-limits/grok-auth.ts:5-12 has the identical host-only OAuth-home defect (Grok hits the same delegated-refresh-required dead end under WSL). Those mean installing hooks into / scanning sessions from the WSL filesystem — a feature change, not this credential-read bug. getHostKimiHome() is exported so they can adopt it when that work happens.

Reproduction

A) Code confirms the report at base 29bfc1e22c — see the root-cause section: the fetcher had zero WSL awareness (it imported only node:fs/node:os/node:path/electron).

B) Harness repro (scratch vitest file, created in-repo, run, then deleted; tree verified clean). Real fs + real temp dirs, node:os.homedir() mocked to a fake Windows host home, electron net.fetch mocked. Host home holds a token expired 3 days ago; a wsl.localhost/Ubuntu/home/neil home holds a token fresh for another 13 minutes — what a running WSL Kimi CLI would have just written.

$ npx vitest run src/main/rate-limits/kimi-wsl-scratch-repro.test.ts --reporter=verbose --disable-console-intercept
host creds   : /var/folders/.../kimi-wsl-repro-2uIbQz/C_Users_neil/.kimi-code/credentials/kimi-code.json
wsl creds    : /var/folders/.../kimi-wsl-repro-2uIbQz/wsl.localhost/Ubuntu/home/neil/.kimi-code/credentials/kimi-code.json
net.fetch calls: 0
result: {
  "provider": "kimi",
  "session": null,
  "weekly": null,
  "updatedAt": 1785828245660,
  "error": "Kimi session expired — run kimi on the computer running Orca, then retry usage.",
  "status": "error",
  "usageMetadata": {
    "failureKind": "delegated-refresh-required",
    "source": "oauth"
  }
}
 ✓ SCRATCH: kimi fetcher on a Windows host whose Kimi CLI runs in WSL > ignores the fresh WSL-side credentials and reports delegated-refresh-required
 Test Files  1 passed (1)

The fresh WSL token is never read and no usage request is even attempted.

C) Real-host corroboration on the win-old box (Windows 11 + WSL), showing the two homes really do diverge there:

PS C:\Users\neil\...> if (Test-Path "$env:USERPROFILE\.kimi-code\credentials\kimi-code.json") { echo HOSTCRED_EXISTS } else { echo HOSTCRED_MISSING }; wsl.exe -l -q
HOSTCRED_MISSING
Ubuntu

Kimi Code was not installed inside that distro at the time. It is now — see E) below for the live run.

D) Regression proof — the new tests fail against the base sources:

$ git show 29bfc1e22c:src/main/rate-limits/kimi-fetcher.ts > src/main/rate-limits/kimi-fetcher.ts
$ npx vitest run src/main/rate-limits/kimi-fetcher-wsl-home.test.ts
     × reads the WSL token instead of the stale host one 19ms
     × still reads the host home by default 17ms
     × points an expired WSL session at the distro to rerun kimi in 15ms
     × reports an unresolvable WSL home instead of falling back to host credentials 15ms
     × bounds a stalled UNC read instead of parking the poll cycle 12ms
 Test Files  1 failed (1)
      Tests  5 failed | 1 passed (6)

$ git show 29bfc1e22c:src/main/rate-limits/service.ts > src/main/rate-limits/service.ts
$ npx vitest run src/main/rate-limits/service.test.ts -t 'Kimi home'
     × passes the resolved Kimi home into each fetch cycle 3ms
     × reads the host Kimi home when no resolver is wired 3ms
AssertionError: expected "vi.fn()" to be called with arguments: [ { home: undefined } ]
 Test Files  1 failed (1)
      Tests  2 failed | 73 skipped (75)

(Both files restored afterwards; the only passing case in the first run is the host-default control.)

E) Live end-to-end verification against the real Kimi Code CLI (added on re-verification, after rebasing onto 2c865cda66). The real CLI is now installed inside the distro, and the whole path was exercised on a real Windows 11 + WSL2 box with no fs mocks and no wsl.exe mock — only electron's net.fetch is stubbed, so the assertion is about which credential file Orca reads and which token it sends.

$ wsl.exe -- bash -c 'npm install -g @moonshot-ai/kimi-code'   # added 6 packages
$ wsl.exe -- bash -c 'kimi --version'
0.34.0

First, the CLI's own contract, read out of the shipped bundle (dist/main.mjs) rather than assumed:

What the fetcher assumes What the shipped CLI does
KIMI_CODE_HOME ?? ~/.kimi-code defaultKimiHome(): process.env["KIMI_CODE_HOME"] else join(homedir(), ".kimi-code") ✅
<home>/credentials/kimi-code.json credentialsDir = join(homeDir, "credentials"); FileTokenStorage.pathFor → join(dir, "kimi-code.json") via resolveKimiTokenStorageName ("oauth/kimi-code" → "kimi-code") ✅
GET https://api.kimi.com/coding/v1/usages managedUsageUrl() → `${baseUrl.replace(/\/+$/,"")}/usages`, default base https://api.kimi.com/coding/v1 ✅
expires_at is Unix seconds token freshness compares nowAsSeconds() < expiresAt - 30 ✅

Then the live run. The WSL home holds a token valid for another 13 min (what a running WSL CLI would have just written); the Windows host home holds one expired 3 days ago:

$ npx vitest run <live harness> --disable-console-intercept
resolved target : {"runtime":"wsl","wslDistro":null}
resolved home   : \\wsl.localhost\Ubuntu\root\.kimi-code     <- from a real wsl.exe probe
probe ms        : 1517
fetch url       : https://api.kimi.com/coding/v1/usages
auth header     : Bearer orca-e2e-probe-token                <- the WSL token, read over real UNC
result          : { "session": { "usedPercent": 65, ... }, "weekly": { "usedPercent": 9, ... },
                    "error": null, "status": "ok" }
 ✓ resolves the WSL home off a real wsl.exe probe and reads the real UNC token

host-only result: { "error": "Kimi session expired — run kimi on the computer running Orca,
                    then retry usage.", "status": "error",
                    "usageMetadata": { "failureKind": "delegated-refresh-required" } }
 ✓ CONTROL: the pre-fix host-only read hits the stale Windows copy and dead-ends

The control is the bug as reported: the host-only read finds the abandoned Windows copy, returns delegated-refresh-required, and the status bar renders "Run Kimi to refresh" forever. The fixed path resolves the distro home from a real wsl.exe probe, reads the real UNC file, and produces live quota windows.

Cold-distro degradation, measured rather than argued. With the distro stopped (wsl.exe --terminate Ubuntu):

resolved home   : null
probe ms        : 5135

execFileUtf8's 5s cap fires, resolveKimiHome returns path: null, and the cycle surfaces "WSL Kimi home unavailable for Ubuntu" instead of blocking — the intended degradation. It self-heals: the probe boots the distro (wsl -l -v → Running afterwards), and getWslHomeAsync caches successes for the process lifetime, so the steady state spawns no further wsl.exe. Worst case is one async 5s probe per 15-minute poll — the sync helpers this PR deliberately avoids would have parked Electron's main process for that 5s.

The harness was scratch-only and deleted; git status is clean and the synthetic credentials were removed from both homes afterwards.

Relationship to #12372

Credit to @cengiz-io, who found, reported (#12370) and fixed (#12372) this. I wrote this fix independently before reading his PR, then cross-referenced. We landed on the same root cause and the same shape (resolve the Kimi home from the local-account runtime target, mirror the Codex pattern, pin to host off Windows, never fall back to the stale host copy) — which is a good sign the diagnosis is right.

Taken from his PR: the credentials read itself. His version converts the sync existsSync + readFileSync to node:fs/promises behind createAuthFilesystemOperation (per-path dedup, AbortSignal bound, per-distro serialization). Mine kept the sync read, which is a real defect: a sync stat/read against \\wsl.localhost\<distro> on a stopped distro blocks Electron's main process — i.e. freezes the whole app — every poll cycle. His approach is strictly better and is what this PR ships.

Kept from mine:

  • The resolution module lives in src/main/kimi/ and exports getHostKimiHome(), so the three other host-only .kimi-code resolutions can adopt it later; his puts it under rate-limits/ where only the fetcher can reach it.
  • The fetcher receives the whole { runtime, wslDistro, path } resolution, so the "run kimi inside WSL (Ubuntu)" message comes from the declared target rather than from re-parsing the credentials path as a UNC string.
  • The unresolvable-home error lives in the fetcher instead of a second getMissingWslKimiHomeResult branch in service.ts — same user-visible result, ~16 fewer lines of service state.
  • wslDistro?.trim() || ... and KIMI_CODE_HOME?.trim() || ..., so a blank setting or blank env var falls back instead of resolving to a relative path.

Beyond both: the runtime probe is async (listWslDistrosAsync / getWslHomeAsync). Both PRs originally used getDefaultWslDistro() / getWslHome(), which shell out to wsl.exe with execFileSync — up to 5s of blocked main process per poll when the distro is stopped, since only successes are cached. ENOTDIR is also treated as "not signed in" alongside ENOENT, preserving existsSync semantics his version narrowed to ENOENT only.

Fixes #12370.

Testing

Rebased onto 2c865cda66 (the branch was 223 commits behind) and re-verified there, on Windows:

$ npx vitest run src/main/kimi/kimi-runtime-home.test.ts src/main/rate-limits/kimi-fetcher.test.ts src/main/rate-limits/kimi-fetcher-wsl-home.test.ts
 Test Files  3 passed (3)
      Tests   26 passed (26)

$ npx vitest run src/main/rate-limits src/main/kimi
 Test Files  3 failed | 30 passed (33)
      Tests  10 failed | 423 passed (433)

$ npx tsc --noEmit -p config/tsconfig.node.json
(clean)

$ npx oxlint src/main/kimi/ src/main/rate-limits/ src/main/index.ts
(no findings)

$ oxlint --config config/oxlint-code-quality-native-plugins.json --deny-warnings <8 changed files>
$ oxlint --type-aware --config config/oxlint-code-quality-type-aware.json --deny-warnings <8 changed files>
(no findings)

$ npm run check:max-lines-ratchet
max-lines ratchet OK — 352 grandfathered suppression(s), no new bypasses.

Those 10 failures are pre-existing on origin/main and Windows-only, not from this PR. Verified by reverting this branch's sources to origin/main in the same worktree and re-running: identical 10 failures (7 Claude cases in service.test.ts, 2 in codex-fetcher.test.ts, 1 in kimi/hook-service.test.ts), none of which this PR touches.

Re-verification did find and fix 4 real failures of this PR's own tests (commit ae9bd4d): the host-home assertions hardcoded POSIX separators, so they only passed on a POSIX runner. On Windows join emits backslashes, so three kimi-fetcher.test.ts cases mismatched and one kimi-fetcher-wsl-home.test.ts fixture key never matched the path the fetcher read. Expectations now go through path.join, so they assert path components on every platform. This is why the green CI on the previous push was not sufficient evidence — the whole PR is about a Windows-only code path, and CI only runs Linux.

oxfmt --check reports issues on all 8 files locally, but it does the same on untouched main files (src/main/wsl.ts, src/shared/local-account-runtime.ts) — this checkout has core.autocrlf=true, so the working tree is CRLF. A checkout artifact, not a formatting defect; CI's LF checkout passes. config/scripts/check-changed-code-quality.mjs can't run here either (spawnSync pnpm.cmd EINVAL on Windows Node 24), so the two oxlint quality configs it wraps were run directly instead, as shown above.

New coverage: kimi-runtime-home.test.ts (10 — WSL/host target resolution incl. the off-Windows pin, auto policy, UNC home join, KIMI_CODE_HOME ignored for WSL, default-distro fallback, unprobeable home, no wsl.exe probe off Windows), kimi-fetcher-wsl-home.test.ts (6, path-aware fs mock — reads the fresh WSL token while the host copy is 3 days expired, host default unchanged, WSL-specific expired copy, unresolvable WSL home does not fall back to host, missing WSL creds → unavailable, stalled UNC read is bounded), kimi-fetcher.test.ts (+3 exact-read-path vectors adapted from #12372), service.test.ts (+2 — resolver result forwarded and re-resolved every cycle, host default when no resolver wired).

No visual proof: this bug is not observable in the UI beyond the status-bar string, so the terminal/test evidence above carries the proof.

Known follow-ups (not regressions from this PR): the Grok fetcher has the identical host-only OAuth-home defect, and Kimi's hook install / session scanning still resolve host-only. One more surfaced while reading the shipped CLI in E): when a user overrides KIMI_CODE_BASE_URL/KIMI_CODE_OAUTH_HOST, the CLI scopes the credential slot to credentials/kimi-code-env-<sha256:16>.json (resolveKimiCodeOAuthKey) rather than kimi-code.json, so Orca reads the wrong file for self-hosted/staging configs. That predates this PR — the filename was already hardcoded on main — and it is orthogonal to the WSL home resolution, so it is left alone here.

Made with Orca 🐋

@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Added Kimi host and WSL runtime-home resolution with environment-variable overrides, distro discovery, and platform-specific paths. Updated Kimi credential handling to use asynchronous, deduplicated, timeout-bounded reads and runtime-specific errors. Integrated resolved homes into RateLimitService refresh cycles. Added tests for runtime selection, credential paths, WSL failures, stalled reads, environment overrides, and resolver wiring.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.18% 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 thoroughly explains the fix and testing, but it omits the required AI Review Report, Security Audit, Notes, and dedicated Screenshots sections. Add the required AI Review Report, Security Audit, Notes, and Screenshots sections, stating “No visual change” where applicable.
✅ 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 summarizes the main change: reading Kimi credentials from the configured WSL runtime.
✨ 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.

nwparker and others added 3 commits August 7, 2026 18:35
… runtime

Kimi's usage fetch always read the Windows host's ~/.kimi-code, so a Kimi CLI running inside WSL rotated only the WSL-side token and the status bar was stuck on 'Run Kimi to refresh'.

Resolve the Kimi home from the local-account runtime target (mirroring Codex's getDefaultWslDistro()/getWslHome() UNC pattern), pinned to host off Windows, and keep KIMI_CODE_HOME host-only.

Fixes #12370

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

Adopted from @cengiz-io's #12372: read credentials through
createAuthFilesystemOperation (async, per-path dedup, AbortSignal bound) so a
stopped distro degrades to an error instead of parking Electron main on a UNC
read. ENOTDIR joins ENOENT as "not signed in" to keep existsSync parity, and the
WSL runtime target is now probed with the async wsl.exe helpers.

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

The host-home assertions hardcoded POSIX separators, so they only passed on
a POSIX runner — on a Windows dev machine `join` emits backslashes and all
four cases failed (three assertion mismatches plus a WSL-suite fixture whose
map key never matched the path the fetcher read).
@OrcaWin
OrcaWin force-pushed the nwparker/bugpr-12372 branch from d51b233 to ae9bd4d Compare August 8, 2026 01:54

@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: 70378871-e2f4-436d-a26c-34be10f7a830

📥 Commits

Reviewing files that changed from the base of the PR and between 2c865cd and ae9bd4d.

📒 Files selected for processing (8)
  • src/main/index.ts
  • src/main/kimi/kimi-runtime-home.test.ts
  • src/main/kimi/kimi-runtime-home.ts
  • src/main/rate-limits/kimi-fetcher-wsl-home.test.ts
  • src/main/rate-limits/kimi-fetcher.test.ts
  • src/main/rate-limits/kimi-fetcher.ts
  • src/main/rate-limits/service.test.ts
  • src/main/rate-limits/service.ts

Comment on lines +99 to +105
credentialsReadByPath.set(path, read)
const clearRead = (): void => {
if (credentialsReadByPath.get(path) === read) {
credentialsReadByPath.delete(path)
}
}
void read.result.then(clearRead, clearRead)

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.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Allow recovery after a stalled UNC read.

Line 105 removes the cached operation only after the raw readFile() promise settles. A timeout rejects wait(), but the raw UNC read can remain pending. Later polls for the same WSL home then reuse the stuck operation and time out again, even after the distro recovers.

Evict or replace timed-out operations with a bounded retry policy. Add a test that stalls one read, restores the same home, and verifies that a later poll reads fresh credentials.

@OrcaWin
OrcaWin merged commit 597c84f 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
… runtime (stablyai#12475)

* fix(rate-limits): read Kimi usage credentials from the configured WSL runtime

Kimi's usage fetch always read the Windows host's ~/.kimi-code, so a Kimi CLI running inside WSL rotated only the WSL-side token and the status bar was stuck on 'Run Kimi to refresh'.

Resolve the Kimi home from the local-account runtime target (mirroring Codex's getDefaultWslDistro()/getWslHome() UNC pattern), pinned to host off Windows, and keep KIMI_CODE_HOME host-only.

Fixes stablyai#12370

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

* fix(rate-limits): bound and offload the Kimi credentials read for WSL homes

Adopted from @cengiz-io's stablyai#12372: read credentials through
createAuthFilesystemOperation (async, per-path dedup, AbortSignal bound) so a
stopped distro degrades to an error instead of parking Electron main on a UNC
read. ENOTDIR joins ENOENT as "not signed in" to keep existsSync parity, and the
WSL runtime target is now probed with the async wsl.exe helpers.

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

* test(rate-limits): build Kimi credential-path expectations with path.join

The host-home assertions hardcoded POSIX separators, so they only passed on
a POSIX runner — on a Windows dev machine `join` emits backslashes and all
four cases failed (three assertion mismatches plus a WSL-suite fixture whose
map key never matched the path the fetcher read).

---------

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.

[Bug]: Kimi usage fetcher ignores WSL runtime — reads stale Windows credentials, status stuck on "Run Kimi to refresh"

2 participants