Repository navigation
fix(rate-limits): read Kimi usage credentials from the configured WSL runtime - #12475
Conversation
📝 WalkthroughWalkthroughAdded 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 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
… 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).
d51b233 to
ae9bd4d
Compare
There was a problem hiding this comment.
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
📒 Files selected for processing (8)
src/main/index.tssrc/main/kimi/kimi-runtime-home.test.tssrc/main/kimi/kimi-runtime-home.tssrc/main/rate-limits/kimi-fetcher-wsl-home.test.tssrc/main/rate-limits/kimi-fetcher.test.tssrc/main/rate-limits/kimi-fetcher.tssrc/main/rate-limits/service.test.tssrc/main/rate-limits/service.ts
| credentialsReadByPath.set(path, read) | ||
| const clearRead = (): void => { | ||
| if (credentialsReadByPath.get(path) === read) { | ||
| credentialsReadByPath.delete(path) | ||
| } | ||
| } | ||
| void read.result.then(clearRead, clearRead) |
There was a problem hiding this comment.
🩺 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.
… 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]>
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:fetchKimiRateLimits()(src/main/rate-limits/kimi-fetcher.ts:242) took no arguments, and the callersrc/main/rate-limits/service.ts:1664invoked it as a barefetchKimiRateLimits()— in contrast with the adjacentfetchCodexRateLimits({ codexHomePath, ... })atservice.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.jsonwhile Orca kept reading the abandoned Windows copy. That copy is always expired, so the fetcher returnedfailureKind: 'delegated-refresh-required', which maps to the status-bar string atsrc/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)(wrapsresolveLocalAccountRuntimeTargetand pins tohostwheneverplatform !== 'win32', because that resolver returnswslon any platform when the setting sayswsl— the same guardgetInitialCodexRateLimitTargetuses, so SSH/Linux/mac hosts never probewsl.exe), andresolveKimiHome(target)(distro from the target or the first installed distro, home from the cachedecho $HOMEprobe, joined with win32 semantics because the result is a UNC path).KIMI_CODE_HOMEstays host-only: it describes the Windows process, not the distro. An unprobeable distro yieldspath: nullso 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 throughcreateAuthFilesystemOperation— async, deduped per path, bounded by a 5sAbortSignal— so a stopped distro degrades to an error instead of parking Electron's main process on a UNC read.ENOENT/ENOTDIRkeep the oldexistsSync"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 akimiFetchTarget+account-runtime-target-syncentry 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 asyncwsl.exehelpers (listWslDistrosAsync/getWslHomeAsync) rather than the sync ones the Codex path still uses.Out of scope, deliberately:
src/main/kimi/hook-service.ts:38andsrc/main/ai-vault/session-scanner-kimi-paths.ts:21duplicate the same host-only.kimi-coderesolution, andsrc/main/rate-limits/grok-auth.ts:5-12has the identical host-only OAuth-home defect (Grok hits the samedelegated-refresh-requireddead 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 onlynode: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, electronnet.fetchmocked. Host home holds a token expired 3 days ago; awsl.localhost/Ubuntu/home/neilhome holds a token fresh for another 13 minutes — what a running WSL Kimi CLI would have just written.The fresh WSL token is never read and no usage request is even attempted.
C) Real-host corroboration on the
win-oldbox (Windows 11 + WSL), showing the two homes really do diverge there: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:
(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 nowsl.exemock — only electron'snet.fetchis stubbed, so the assertion is about which credential file Orca reads and which token it sends.First, the CLI's own contract, read out of the shipped bundle (
dist/main.mjs) rather than assumed:KIMI_CODE_HOME ?? ~/.kimi-codedefaultKimiHome():process.env["KIMI_CODE_HOME"]elsejoin(homedir(), ".kimi-code")<home>/credentials/kimi-code.jsoncredentialsDir = join(homeDir, "credentials");FileTokenStorage.pathFor→join(dir, "kimi-code.json")viaresolveKimiTokenStorageName("oauth/kimi-code"→"kimi-code")GET https://api.kimi.com/coding/v1/usagesmanagedUsageUrl()→`${baseUrl.replace(/\/+$/,"")}/usages`, default basehttps://api.kimi.com/coding/v1expires_atis Unix secondsnowAsSeconds() < expiresAt - 30Then 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:
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 realwsl.exeprobe, 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):execFileUtf8's 5s cap fires,resolveKimiHomereturnspath: 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→Runningafterwards), andgetWslHomeAsynccaches successes for the process lifetime, so the steady state spawns no furtherwsl.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 statusis 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+readFileSynctonode:fs/promisesbehindcreateAuthFilesystemOperation(per-path dedup,AbortSignalbound, 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:
src/main/kimi/and exportsgetHostKimiHome(), so the three other host-only.kimi-coderesolutions can adopt it later; his puts it underrate-limits/where only the fetcher can reach it.{ 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.getMissingWslKimiHomeResultbranch inservice.ts— same user-visible result, ~16 fewer lines of service state.wslDistro?.trim() || ...andKIMI_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 usedgetDefaultWslDistro()/getWslHome(), which shell out towsl.exewithexecFileSync— up to 5s of blocked main process per poll when the distro is stopped, since only successes are cached.ENOTDIRis also treated as "not signed in" alongsideENOENT, preservingexistsSyncsemantics his version narrowed toENOENTonly.Fixes #12370.
Testing
Rebased onto
2c865cda66(the branch was 223 commits behind) and re-verified there, on Windows:Those 10 failures are pre-existing on
origin/mainand Windows-only, not from this PR. Verified by reverting this branch's sources toorigin/mainin the same worktree and re-running: identical 10 failures (7 Claude cases inservice.test.ts, 2 incodex-fetcher.test.ts, 1 inkimi/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 Windowsjoinemits backslashes, so threekimi-fetcher.test.tscases mismatched and onekimi-fetcher-wsl-home.test.tsfixture key never matched the path the fetcher read. Expectations now go throughpath.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 --checkreports issues on all 8 files locally, but it does the same on untouchedmainfiles (src/main/wsl.ts,src/shared/local-account-runtime.ts) — this checkout hascore.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.mjscan't run here either (spawnSync pnpm.cmd EINVALon 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_HOMEignored for WSL, default-distro fallback, unprobeable home, nowsl.exeprobe 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 tocredentials/kimi-code-env-<sha256:16>.json(resolveKimiCodeOAuthKey) rather thankimi-code.json, so Orca reads the wrong file for self-hosted/staging configs. That predates this PR — the filename was already hardcoded onmain— and it is orthogonal to the WSL home resolution, so it is left alone here.Made with Orca 🐋