Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(heterogeneous-agent): add Kimi Code subscription quota across local and remote paths (#19765)

Arvin Xu425fa64add7a
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.md
index 7732c8a4ce6..05330efbb9c 100644
--- a/.agents/acceptance/probe-mock-patterns.md
+++ b/.agents/acceptance/probe-mock-patterns.md
@@ -20,90 +20,91 @@ rg -n '^#{2,4} ' "$P" # every heading, to find the next bound
gateway / hetero / any (the agent runtime the recipe depends on); **phase** = env / auth / fixture /
drive / probe / capture / publish. Skip a row only when its surface AND runtime both miss yours.
-| id | surface | runtime | phase | situation |
-| --- | ------------- | --------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
-| P01 | any | any | probe | `window.__LOBE_STORES.<name>()` returns state only; add a dev action instead of HMR `setState` patches |
-| P02 | web, electron | any | probe | `goto` / `location.assign` full-reload wipes fetch wrappers; change route via `history.pushState` + `popstate` |
-| P03 | any | client, gateway | probe | Prove which runtime ran with a server-only artifact (operation row, queue step, server log) |
-| P04 | web, electron | any | probe | A top-level `const` in a second `agent-browser eval` collides; wrap payloads in an IIFE |
-| P05 | web | any | drive | `lobehub-dev` is shared across runs; use a run-specific session and check `location.origin` / script src first |
-| P06 | electron | any | probe | After adding or moving a module the renderer may keep the old graph; `goto`, then confirm a structural signal |
-| P07 | web | any | env | `_dangerous_local_dev_proxy` in a signed-out automation context sits on the loading shell; use the isolated local stack |
-| P08 | web | any | env | Workspace `packages/*` dynamic imports fail cross-origin through the proxy; A/B at HEAD, use Electron for settled state |
-| P09 | any | client, gateway | fixture | The stub must answer `stream:false` chat/completions with a plain JSON completion, never SSE |
-| P10 | web | gateway | fixture | `review_predict` is pinned to Gemini; pin the constants, allow private IPs, return schema JSON from the stub |
-| P11 | any | gateway | fixture | `generateObject` via the deepseek stub crashes; route through the openai `/v1/responses` stub |
-| P12 | web | gateway | fixture | Backdate node and op rows past the client's 15-minute lease, not the server's 5 |
-| P13 | web, cli | any | fixture | `lh topic create` rows have NULL trigger/status and drop out of the paged view; set both, then `goto` |
-| P14 | web, electron | hetero | fixture | Seed `agency_config.heterogeneousProvider` with SQL, then cold-load; the store write drops it |
-| P15 | web | any | fixture | Derive day boundaries from the browser's `resolvedOptions().timeZone`, never an assumed zone |
-| P16 | web, electron | any | fixture | Clear cache tiers in the NEW document via `addScriptToEvaluateOnNewDocument`; the outgoing page re-flushes on reload |
-| P17 | web | any | drive | Goals live at `/agent/:aid/goals` behind the Labs toggle `enableTopicAcceptance` |
-| P18 | electron | hetero | fixture | Local-execution CC agent plus a four-table ledger fixture keyed to the live CLI identity |
-| P19 | web | any | auth | Seed a second user and sign in from inside a run-specific session; a signed-out context hits `/signin` |
-| P20 | cli | any | fixture | Strip ambient topic/agent/operation ids for a LOCAL ingest; keep them for the production publish |
-| P21 | web | any | drive | Upload through the Add-menu input, poll `dockUploadFileList`, A/B the hashing worker with `window.Worker = undefined` |
-| P22 | web, electron | any | drive | `keyboard type` emits no keydown; fire `/` (and any menu trigger) with `press` |
-| P23 | web, electron | any | drive | Tag `svg.lucide-<rendered-name>` and click through agent-browser; `el.click()` on the wrapper does nothing |
-| P24 | web, electron | any | drive | Re-query elements after every re-render; one assertion per eval |
-| P25 | web, electron | any | capture | Anchor on `#nav-panel-drawer`'s aside sibling; tell skeleton states apart by testid, not row count |
-| P26 | web | any | capture | Park the route's own tRPC call with `park-request.cjs`; a broad `*trpc*` pattern stalls the shell |
-| P27 | web | any | drive | `SWRConfig` only affects hooks below it; move the hooks into a child component |
-| P28 | electron | any | capture | Raw CDP `Fetch.enable` on the layout chunk holds the sidebar fallback; name the layout module only |
-| P29 | web, electron | any | fixture, drive | Seed via `mkdirDocumentByPath` / `writeDocumentByPath`; rows live in pierre's shadow DOM; hetero agents have no Documents tab |
-| P30 | web, electron | any | drive | pierre's focus-visible and truncation-mask contracts when restyling the tree |
-| P31 | web | any | drive | Row-shape bugs need the real account: foreground the MCP tab, zero-write clicks, in-page event ring buffer |
-| P32 | web, electron | hetero | fixture | Dispatch a temp assistant message and attach an `AgentRuntimeError` guide code |
-| P33 | web, electron | any | fixture | Backfill `pluginState` from each tool message's result after Agent Mock playback |
-| P34 | web, electron | any | fixture | Dispatch an assistant+tool pair into an empty conversation; truncate args to reach the Streaming render |
-| P35 | web | gateway | probe | Step-boundary `uiMessages` snapshots overwrite the bucket; record `replaceMessages` stacks, A/B with `disableGatewayMode` |
-| P36 | web | gateway | env | Run the JWT handshake probe after every gateway restart; `/health` 200 proves nothing |
-| P37 | any | gateway | env | QStash / s3rver on fixed ports may belong to a sibling session; read the start log before stopping anything |
-| P38 | web | any | fixture | Call the real load-more store action when the fixture is too short for the observer |
-| P39 | web, electron | any | fixture | Replace the react-query `mutationFn` with a rejection via HMR so no network call ever fires |
-| P40 | web, electron | any | drive | Remount the DevDock panel after a reload; pre-seed `LOBE_DEV_DOCK_UI` to land on it |
-| P41 | web | client | fixture, drive | openai speaks `/v1/responses`; the model must be in `enabledAiModels`; set approval `auto-run` |
-| P42 | web | hetero | fixture, drive | In-page IPC mock feeding stream-json through the real `ClaudeCodeAdapter`, no Electron needed |
-| P43 | web, electron | any | capture | Focus and read in one eval, wait past the transition, assert an untransitioned property too |
-| P44 | web, electron | any | capture | Inject `html > canvas { display: none }` at capture time and disclose it |
-| P45 | web | any | capture | Gate on `checkVisibility`, match own text nodes, assert both columns in one pass |
-| P46 | web, electron | any | capture | Sample in-page (`addScriptToEvaluateOnNewDocument` or an entry injection), record the max tick gap, mirror the timer |
-| P47 | web, electron | any | capture | Sample opacity in-page at 8 ms and use `Page.startScreencast`; `data-ending-style` is never set |
-| P48 | web | any | capture | `localStorage.theme` + reload; assert `dataset.theme`; restore before stopping the server |
-| P49 | electron | any | capture | Prove the hosted URL (curl + open it), not the in-app preview |
-| P50 | any | any | publish | Re-running `ingest` mints a duplicate round; re-read with `run list` / `run get` / `view` |
-| P51 | electron | any | probe | Read the loaded entry script per run; never assume `entry.desktop.tsx` |
-| P52 | electron | any | capture | `DESKTOP_RENDERER_STATIC=1` pool instance; prove the build via modulepreload hashes |
-| P53 | electron | any | drive | Open via `openTopicInNewWindow` and attach raw CDP to the popup target |
-| P54 | electron | any | drive | `activateTab` alone is a no-op on the single-router shell; click the TabItem element and assert the pathname |
-| P55 | electron | any | drive | `addTab` activates; enter the route with `goto` and assert tab / pathname / activeTopicId agree |
-| P56 | electron | any | capture | Classify hidden slots on both sides of the switch and use the intersection |
-| P57 | electron | any | capture | The renderer tracks OS appearance; `themeMode` never applies; mark the dark case untested |
-| P58 | electron | any | probe | i18next stays English until `switchLocale`; decide language from the DOM, not `status.language` |
-| P59 | electron | any | drive | `addTab('/')` first; `goto /` alone keeps the restored tab |
-| P60 | electron | any | auth, env | Read `dataSyncConfig` first; `storageMode: cloud` means the run must stay read-only |
-| P61 | web, electron | any | capture | Stall `indexedDB.open` only on web; it kills the Electron renderer |
-| P62 | electron | any | env | Keep locale tests out of `packages/locales/src/default/` or the renderer imports vitest |
-| P63 | cli | gateway | auth | `lh task run --follow` needs OIDC; poll with `task view`; use internal ids for `--subject task:` |
-| P64 | web | any | auth | No seeded session for the debug proxy; drive the user's Chrome and add DOM measurements |
-| P65 | electron | any | auth, env | Start the server on the snapshot's port with `SERVER_PORT=`; inject a better-auth cookie over CDP |
-| P66 | electron | any | auth | `safeStorage` cannot decrypt the copied token; fall back to the legacy single instance |
-| P67 | electron | any | auth, env | Read the port from `/tmp/electron-dev.log`, mint a session, `Network.setCookie` |
-| P68 | electron | any | auth, env | Pool logs are `instance-<id>.log`; fix the port and start the server before Electron |
-| P69 | electron | any | fixture | Snapshot `dist/renderer` before building so the manifest differs from the local tree |
-| P70 | any | any | env | `.records/runtime/` holds the owned server's PID and ports; poll that port |
-| P71 | web | any | env | `lsof` the listener, kill only the run-owned tree, restart, reseed auth |
-| P72 | web, electron | any | env | Two copies of a dep produce context errors; `pnpm dedupe`; local-only, never a branch defect |
-| P73 | web | any | env | Install without `--ignore-scripts` and `rm -rf .next`; turbo-tasks panics are disposable cache |
-| P74 | electron | any | env | The desktop install duplicates `@types/react`; intersect errors with changed files, A/B after evidence |
-| P75 | electron | any | env | Run the Model B desktop command in a long-lived PTY |
-| P76 | any | any | env | Prefix git and check commands with `cd <worktree>`; read the diffstat before pushing |
-| P77 | web, cli | gateway | probe | Read `llm_generation_tracing.prompt_version` after one call; restart the server if stale |
-| P78 | web, cli | gateway | env | `SSRF_ALLOW_PRIVATE_IP_ADDRESS=1` so the server can read local s3rver URLs |
-| P79 | web, cli | client, gateway | env | Local SearXNG with `SEARCH_PROVIDERS=searxng`; the on-disk search1api keys are dead |
-| P84 | cli | any | auth | Drive `lh` against the local lobehub-cloud runtime by seeding an API key row into its main database |
-| P85 | cli | any | fixture | Simulate a publish whose response was lost by restoring `pendingCreateKey` in `.lobehub/artifacts.json` |
-| P82 | web | any | drive | Acceptance flow canvas through the production debug proxy: anonymous shared link, one uninterrupted script, canvas controls for clipped groups |
+| id | surface | runtime | phase | situation |
+| --- | ------------- | --------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| P01 | any | any | probe | `window.__LOBE_STORES.<name>()` returns state only; add a dev action instead of HMR `setState` patches |
+| P02 | web, electron | any | probe | `goto` / `location.assign` full-reload wipes fetch wrappers; change route via `history.pushState` + `popstate` |
+| P03 | any | client, gateway | probe | Prove which runtime ran with a server-only artifact (operation row, queue step, server log) |
+| P04 | web, electron | any | probe | A top-level `const` in a second `agent-browser eval` collides; wrap payloads in an IIFE |
+| P05 | web | any | drive | `lobehub-dev` is shared across runs; use a run-specific session and check `location.origin` / script src first |
+| P06 | electron | any | probe | After adding or moving a module the renderer may keep the old graph; `goto`, then confirm a structural signal |
+| P07 | web | any | env | `_dangerous_local_dev_proxy` in a signed-out automation context sits on the loading shell; use the isolated local stack |
+| P08 | web | any | env | Workspace `packages/*` dynamic imports fail cross-origin through the proxy; A/B at HEAD, use Electron for settled state |
+| P09 | any | client, gateway | fixture | The stub must answer `stream:false` chat/completions with a plain JSON completion, never SSE |
+| P10 | web | gateway | fixture | `review_predict` is pinned to Gemini; pin the constants, allow private IPs, return schema JSON from the stub |
+| P11 | any | gateway | fixture | `generateObject` via the deepseek stub crashes; route through the openai `/v1/responses` stub |
+| P12 | web | gateway | fixture | Backdate node and op rows past the client's 15-minute lease, not the server's 5 |
+| P13 | web, cli | any | fixture | `lh topic create` rows have NULL trigger/status and drop out of the paged view; set both, then `goto` |
+| P14 | web, electron | hetero | fixture | Seed `agency_config.heterogeneousProvider` with SQL, then cold-load; the store write drops it |
+| P15 | web | any | fixture | Derive day boundaries from the browser's `resolvedOptions().timeZone`, never an assumed zone |
+| P16 | web, electron | any | fixture | Clear cache tiers in the NEW document via `addScriptToEvaluateOnNewDocument`; the outgoing page re-flushes on reload |
+| P17 | web | any | drive | Goals live at `/agent/:aid/goals` behind the Labs toggle `enableTopicAcceptance` |
+| P18 | electron | hetero | fixture | Local-execution CC agent plus a four-table ledger fixture keyed to the live CLI identity |
+| P19 | web | any | auth | Seed a second user and sign in from inside a run-specific session; a signed-out context hits `/signin` |
+| P20 | cli | any | fixture | Strip ambient topic/agent/operation ids for a LOCAL ingest; keep them for the production publish |
+| P21 | web | any | drive | Upload through the Add-menu input, poll `dockUploadFileList`, A/B the hashing worker with `window.Worker = undefined` |
+| P22 | web, electron | any | drive | `keyboard type` emits no keydown; fire `/` (and any menu trigger) with `press` |
+| P23 | web, electron | any | drive | Tag `svg.lucide-<rendered-name>` and click through agent-browser; `el.click()` on the wrapper does nothing |
+| P24 | web, electron | any | drive | Re-query elements after every re-render; one assertion per eval |
+| P25 | web, electron | any | capture | Anchor on `#nav-panel-drawer`'s aside sibling; tell skeleton states apart by testid, not row count |
+| P26 | web | any | capture | Park the route's own tRPC call with `park-request.cjs`; a broad `*trpc*` pattern stalls the shell |
+| P27 | web | any | drive | `SWRConfig` only affects hooks below it; move the hooks into a child component |
+| P28 | electron | any | capture | Raw CDP `Fetch.enable` on the layout chunk holds the sidebar fallback; name the layout module only |
+| P29 | web, electron | any | fixture, drive | Seed via `mkdirDocumentByPath` / `writeDocumentByPath`; rows live in pierre's shadow DOM; hetero agents have no Documents tab |
+| P30 | web, electron | any | drive | pierre's focus-visible and truncation-mask contracts when restyling the tree |
+| P31 | web | any | drive | Row-shape bugs need the real account: foreground the MCP tab, zero-write clicks, in-page event ring buffer |
+| P32 | web, electron | hetero | fixture | Dispatch a temp assistant message and attach an `AgentRuntimeError` guide code |
+| P33 | web, electron | any | fixture | Backfill `pluginState` from each tool message's result after Agent Mock playback |
+| P34 | web, electron | any | fixture | Dispatch an assistant+tool pair into an empty conversation; truncate args to reach the Streaming render |
+| P35 | web | gateway | probe | Step-boundary `uiMessages` snapshots overwrite the bucket; record `replaceMessages` stacks, A/B with `disableGatewayMode` |
+| P36 | web | gateway | env | Run the JWT handshake probe after every gateway restart; `/health` 200 proves nothing |
+| P37 | any | gateway | env | QStash / s3rver on fixed ports may belong to a sibling session; read the start log before stopping anything |
+| P38 | web | any | fixture | Call the real load-more store action when the fixture is too short for the observer |
+| P39 | web, electron | any | fixture | Replace the react-query `mutationFn` with a rejection via HMR so no network call ever fires |
+| P40 | web, electron | any | drive | Remount the DevDock panel after a reload; pre-seed `LOBE_DEV_DOCK_UI` to land on it |
+| P41 | web | client | fixture, drive | openai speaks `/v1/responses`; the model must be in `enabledAiModels`; set approval `auto-run` |
+| P42 | web | hetero | fixture, drive | In-page IPC mock feeding stream-json through the real `ClaudeCodeAdapter`, no Electron needed |
+| P43 | web, electron | any | capture | Focus and read in one eval, wait past the transition, assert an untransitioned property too |
+| P44 | web, electron | any | capture | Inject `html > canvas { display: none }` at capture time and disclose it |
+| P45 | web | any | capture | Gate on `checkVisibility`, match own text nodes, assert both columns in one pass |
+| P46 | web, electron | any | capture | Sample in-page (`addScriptToEvaluateOnNewDocument` or an entry injection), record the max tick gap, mirror the timer |
+| P47 | web, electron | any | capture | Sample opacity in-page at 8 ms and use `Page.startScreencast`; `data-ending-style` is never set |
+| P48 | web | any | capture | `localStorage.theme` + reload; assert `dataset.theme`; restore before stopping the server |
+| P49 | electron | any | capture | Prove the hosted URL (curl + open it), not the in-app preview |
+| P50 | any | any | publish | Re-running `ingest` mints a duplicate round; re-read with `run list` / `run get` / `view` |
+| P51 | electron | any | probe | Read the loaded entry script per run; never assume `entry.desktop.tsx` |
+| P52 | electron | any | capture | `DESKTOP_RENDERER_STATIC=1` pool instance; prove the build via modulepreload hashes |
+| P53 | electron | any | drive | Open via `openTopicInNewWindow` and attach raw CDP to the popup target |
+| P54 | electron | any | drive | `activateTab` alone is a no-op on the single-router shell; click the TabItem element and assert the pathname |
+| P55 | electron | any | drive | `addTab` activates; enter the route with `goto` and assert tab / pathname / activeTopicId agree |
+| P56 | electron | any | capture | Classify hidden slots on both sides of the switch and use the intersection |
+| P57 | electron | any | capture | The renderer tracks OS appearance; `themeMode` never applies; mark the dark case untested |
+| P58 | electron | any | probe | i18next stays English until `switchLocale`; decide language from the DOM, not `status.language` |
+| P59 | electron | any | drive | `addTab('/')` first; `goto /` alone keeps the restored tab |
+| P60 | electron | any | auth, env | Read `dataSyncConfig` first; `storageMode: cloud` means the run must stay read-only |
+| P61 | web, electron | any | capture | Stall `indexedDB.open` only on web; it kills the Electron renderer |
+| P62 | electron | any | env | Keep locale tests out of `packages/locales/src/default/` or the renderer imports vitest |
+| P63 | cli | gateway | auth | `lh task run --follow` needs OIDC; poll with `task view`; use internal ids for `--subject task:` |
+| P64 | web | any | auth | No seeded session for the debug proxy; drive the user's Chrome and add DOM measurements |
+| P65 | electron | any | auth, env | Start the server on the snapshot's port with `SERVER_PORT=`; inject a better-auth cookie over CDP |
+| P66 | electron | any | auth | `safeStorage` cannot decrypt the copied token; fall back to the legacy single instance |
+| P67 | electron | any | auth, env | Read the port from `/tmp/electron-dev.log`, mint a session, `Network.setCookie` |
+| P68 | electron | any | auth, env | Pool logs are `instance-<id>.log`; fix the port and start the server before Electron |
+| P69 | electron | any | fixture | Snapshot `dist/renderer` before building so the manifest differs from the local tree |
+| P70 | any | any | env | `.records/runtime/` holds the owned server's PID and ports; poll that port |
+| P71 | web | any | env | `lsof` the listener, kill only the run-owned tree, restart, reseed auth |
+| P72 | web, electron | any | env | Two copies of a dep produce context errors; `pnpm dedupe`; local-only, never a branch defect |
+| P73 | web | any | env | Install without `--ignore-scripts` and `rm -rf .next`; turbo-tasks panics are disposable cache |
+| P74 | electron | any | env | The desktop install duplicates `@types/react`; intersect errors with changed files, A/B after evidence |
+| P75 | electron | any | env | Run the Model B desktop command in a long-lived PTY |
+| P76 | any | any | env | Prefix git and check commands with `cd <worktree>`; read the diffstat before pushing |
+| P77 | web, cli | gateway | probe | Read `llm_generation_tracing.prompt_version` after one call; restart the server if stale |
+| P78 | web, cli | gateway | env | `SSRF_ALLOW_PRIVATE_IP_ADDRESS=1` so the server can read local s3rver URLs |
+| P79 | web, cli | client, gateway | env | Local SearXNG with `SEARCH_PROVIDERS=searxng`; the on-disk search1api keys are dead |
+| P84 | cli | any | auth | Drive `lh` against the local lobehub-cloud runtime by seeding an API key row into its main database |
+| P85 | cli | any | fixture | Simulate a publish whose response was lost by restoring `pendingCreateKey` in `.lobehub/artifacts.json` |
+| P82 | web | any | drive | Acceptance flow canvas through the production debug proxy: anonymous shared link, one uninterrupted script, canvas controls for clipped groups |
+| P86 | electron, cli | any | env, auth | A session spawned by the desktop hetero runtime inherits `LOBEHUB_JWT` (production) and `ELECTRON_RUN_AS_NODE=1` — strip both before local Electron/CLI work |
## Choose the least invasive mechanism
@@ -1410,6 +1411,34 @@ Assert structure with `get count '.react-flow__node-flowGroup'` /
from the proxy in the same session and viewport, and rely on a top-bar string that exists
only in the worktree as the visible identity marker of every `after` screenshot.
+#### P86 · A session spawned by the desktop hetero runtime inherits production env — strip `LOBEHUB_JWT` and `ELECTRON_RUN_AS_NODE` before local work
+
+**applies-to:** surface=electron, cli · runtime=any · phase=env, auth
+
+**Situation:** running acceptance (Electron dev instance, `lh connect`, local CLI
+calls) from an agent session that is itself a heterogeneous-agent child of the
+LobeHub desktop app. The session shell carries `LOBEHUB_JWT` (the user's
+**production** token), `LOBEHUB_SERVER=https://lobehub.com`,
+`LOBEHUB_OPERATION_ID` / `LOBEHUB_TOPIC_ID`, and `ELECTRON_RUN_AS_NODE=1`.
+
+**Doesn't work:** using that env as-is. `ELECTRON_RUN_AS_NODE=1` makes the spawned
+Electron boot as plain Node — the main bundle dies at
+`TypeError: Cannot read properties of undefined (reading 'isPackaged')`.
+`pickAuthSource` gives `LOBEHUB_JWT` top precedence, so `lh connect` / `whoami`
+authenticate as the production account against production no matter what
+`LOBEHUB_CLI_HOME` says (an identical token `exp` across different CLI homes is
+the tell); against a local device-gateway that fails as
+`Authentication failed: signature verification failed`, and any successful write
+would have landed in the production account.
+
+**Works:** prefix local invocations with
+`env -u LOBEHUB_JWT -u LOBEHUB_SERVER -u LOBEHUB_OPERATION_ID -u LOBEHUB_TOPIC_ID -u LOBEHUB_ASSISTANT_MESSAGE_ID`,
+run `electron-dev.sh` as `env -u ELECTRON_RUN_AS_NODE .agents/acceptance/scripts/electron-dev.sh start`,
+then set the isolated home/server explicitly. Publish steps (ingest) strip
+`LOBEHUB_JWT` as well so the stored `~/.lobehub` login is used.
+
+`holds-while: pickAuthSource precedence LOBEHUB_JWT > flags > LOBEHUB_CLI_API_KEY > stored (apps/cli/src/auth/source.ts); Electron honors ELECTRON_RUN_AS_NODE.`
+
### Capturing and publishing evidence
#### P43 · Reading a transitioned CSS property immediately after focus/hover
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
index 9f142518d01..48b6513f590 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
@@ -91,6 +91,11 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
return (await this.getImplementation()).getClaudeCodeQuota(...args);
}
+ @IpcMethod()
+ async getKimiCodeQuota(...args: Parameters<Implementation['getKimiCodeQuota']>) {
+ return (await this.getImplementation()).getKimiCodeQuota(...args);
+ }
+
@IpcMethod()
async cancelSession(...args: Parameters<Implementation['cancelSession']>) {
return (await this.getImplementation()).cancelSession(...args);
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
index e12adba5f14..8c659fe2807 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -14,6 +14,7 @@ import type {
CodexRateLimitResetResult,
HeterogeneousAgentSessionError,
HeterogeneousCliAgentType,
+ KimiCodeQuotaSnapshot,
} from '@lobechat/electron-client-ipc';
import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc/types/heterogeneous-agent';
import type { HeterogeneousProviderBindingReference } from '@lobechat/heterogeneous-agents';
@@ -48,6 +49,7 @@ import {
CLAUDE_CODE_QUOTA_FRESH_MS,
createQuotaCacheKey,
fetchClaudeCodeQuota,
+ KIMI_CODE_QUOTA_FRESH_MS,
QuotaSnapshotCache,
readClaudeCodeIdentity,
} from '@lobechat/heterogeneous-agents/quota-sampler';
@@ -125,6 +127,7 @@ import {
createLambdaFileStorePort,
type RemoteServerAuth,
} from '@/modules/heterogeneousAgent/fileStorePort';
+import { fetchKimiCodeQuota } from '@/modules/heterogeneousAgent/kimiCodeQuota';
import { PiRpcPool } from '@/modules/heterogeneousAgent/piRpcPool';
import type { HostedProviderBinding } from '@/modules/heterogeneousAgent/providerBindingHost';
import {
@@ -380,6 +383,12 @@ interface GetClaudeCodeQuotaParams {
force?: boolean;
}
+interface GetKimiCodeQuotaParams {
+ env?: Record<string, string>;
+ force?: boolean;
+ kimiCodeHomePath?: string | null;
+}
+
export interface SessionInfo {
agentSessionId?: string;
}
@@ -632,6 +641,9 @@ export default class HeterogeneousAgentCtr {
freshMs: CLAUDE_CODE_QUOTA_FRESH_MS,
});
private readonly codexQuotaCache = new QuotaSnapshotCache<CodexQuotaSnapshot>();
+ private readonly kimiCodeQuotaCache = new QuotaSnapshotCache<KimiCodeQuotaSnapshot>({
+ freshMs: KIMI_CODE_QUOTA_FRESH_MS,
+ });
/**
* Typed as optional on purpose: a deferred chunk cannot assume the registry
@@ -3276,6 +3288,21 @@ export default class HeterogeneousAgentCtr {
);
}
+ /**
+ * Read the Kimi Code subscription quota. No CLI is spawned: the quota comes
+ * from the Kimi usage API using the local `kimi` login, and the request goes
+ * through the app's global proxy dispatcher.
+ */
+ async getKimiCodeQuota(params: GetKimiCodeQuotaParams = {}): Promise<KimiCodeQuotaSnapshot> {
+ const sourceKey = createQuotaCacheKey('kimi-code', params.env, params.kimiCodeHomePath);
+
+ return this.kimiCodeQuotaCache.get(
+ sourceKey,
+ () => fetchKimiCodeQuota({ env: params.env, kimiCodeHomePath: params.kimiCodeHomePath }),
+ { force: params.force },
+ );
+ }
+
/**
* Signal the whole process tree spawned by this session.
*
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index 96febe2e6cc..47fb8e01616 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -5,7 +5,7 @@ import * as os from 'node:os';
import path from 'node:path';
import { PassThrough } from 'node:stream';
-import type { CodexQuotaSnapshot } from '@lobechat/electron-client-ipc';
+import type { CodexQuotaSnapshot, KimiCodeQuotaSnapshot } from '@lobechat/electron-client-ipc';
import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';
import {
HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV,
@@ -620,6 +620,14 @@ vi.mock('@/modules/heterogeneousAgent/codexQuota', () => ({
fetchCodexQuota: fetchCodexQuotaMock,
}));
+const { fetchKimiCodeQuotaMock } = vi.hoisted(() => ({
+ fetchKimiCodeQuotaMock: vi.fn(),
+}));
+
+vi.mock('@/modules/heterogeneousAgent/kimiCodeQuota', () => ({
+ fetchKimiCodeQuota: fetchKimiCodeQuotaMock,
+}));
+
// Captures the most recent spawn() call so sendPrompt tests can assert on argv.
const spawnCalls: Array<{ args: string[]; command: string; options: any }> = [];
let nextFakeProc: any = null;
@@ -703,6 +711,7 @@ describe('HeterogeneousAgentCtr', () => {
appStoragePath = await mkdtemp(path.join(os.tmpdir(), 'lobehub-hetero-'));
consumeCodexRateLimitResetCreditMock.mockReset();
fetchCodexQuotaMock.mockReset();
+ fetchKimiCodeQuotaMock.mockReset();
claudeSdkSessionCloseMock.mockReset();
claudeSdkSessionConstructMock.mockReset();
codexAppServerCanReuse.value = true;
@@ -1214,6 +1223,66 @@ describe('HeterogeneousAgentCtr', () => {
});
});
+ describe('getKimiCodeQuota', () => {
+ it('passes env and kimiCodeHomePath through to the quota sampler', async () => {
+ const quota = {
+ error: null,
+ extraUsage: null,
+ monthly: null,
+ monthlyCode: null,
+ provider: 'kimi-code',
+ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
+ status: 'ok',
+ updatedAt: 1,
+ weekly: null,
+ } satisfies KimiCodeQuotaSnapshot;
+ fetchKimiCodeQuotaMock.mockResolvedValue(quota);
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const params = {
+ env: { KIMI_CODE_HOME: '/tmp/kimi-code-home' },
+ kimiCodeHomePath: '/tmp/kimi-code-home',
+ };
+
+ await expect(ctr.getKimiCodeQuota(params)).resolves.toEqual(quota);
+ expect(fetchKimiCodeQuotaMock).toHaveBeenCalledWith({
+ env: { KIMI_CODE_HOME: '/tmp/kimi-code-home' },
+ kimiCodeHomePath: '/tmp/kimi-code-home',
+ });
+ });
+
+ it('reuses automatic quota reads while explicit refresh bypasses the cache', async () => {
+ const quota = {
+ error: null,
+ extraUsage: null,
+ monthly: null,
+ monthlyCode: null,
+ provider: 'kimi-code',
+ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
+ status: 'ok',
+ updatedAt: Date.now(),
+ weekly: null,
+ } satisfies KimiCodeQuotaSnapshot;
+ fetchKimiCodeQuotaMock.mockResolvedValue(quota);
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const params = { env: { KIMI_CODE_HOME: '/tmp/kimi-code-home' } };
+
+ await ctr.getKimiCodeQuota(params);
+ await ctr.getKimiCodeQuota(params);
+
+ expect(fetchKimiCodeQuotaMock).toHaveBeenCalledTimes(1);
+
+ await ctr.getKimiCodeQuota({ ...params, force: true });
+
+ expect(fetchKimiCodeQuotaMock).toHaveBeenCalledTimes(2);
+ });
+ });
+
describe('sendPrompt (claude-code)', () => {
beforeEach(() => {
spawnCalls.length = 0;
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/kimiCodeQuota.ts b/apps/desktop/src/main/modules/heterogeneousAgent/kimiCodeQuota.ts
new file mode 100644
index 00000000000..c5734a2186a
--- /dev/null
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/kimiCodeQuota.ts
@@ -0,0 +1,2 @@
+export type { FetchKimiCodeQuotaOptions } from '@lobechat/heterogeneous-agents/quota-sampler';
+export { fetchKimiCodeQuota } from '@lobechat/heterogeneous-agents/quota-sampler';
diff --git a/apps/server/src/routers/lambda/__tests__/agentQuota.ingestSnapshot.test.ts b/apps/server/src/routers/lambda/__tests__/agentQuota.ingestSnapshot.test.ts
index 70a4eb2c86f..7b90db2aca2 100644
--- a/apps/server/src/routers/lambda/__tests__/agentQuota.ingestSnapshot.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agentQuota.ingestSnapshot.test.ts
@@ -16,11 +16,12 @@ vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({
}));
const mockCodexQuota = vi.fn();
+const mockKimiCodeQuota = vi.fn();
const mockFindAccount = vi.fn();
const mockLatestReadings = vi.fn();
const mockVisibleDevice = vi.fn();
vi.mock('@/server/services/deviceGateway', () => ({
- deviceGateway: { codexQuota: mockCodexQuota },
+ deviceGateway: { codexQuota: mockCodexQuota, kimiCodeQuota: mockKimiCodeQuota },
}));
vi.mock('../deviceWorkspaceGuard', () => ({ assertWorkspaceDeviceVisible: mockVisibleDevice }));
const mockFindByDeviceId = vi.fn();
@@ -202,3 +203,56 @@ describe('agentQuota.refreshCodexQuota', () => {
expect(mockIngestSnapshot).not.toHaveBeenCalled();
});
});
+
+describe('agentQuota.refreshKimiCodeQuota', () => {
+ const snapshot = {
+ error: null,
+ identity: { externalAccountId: 'kimi-account' },
+ provider: 'kimi-code',
+ readings: READINGS,
+ status: 'ok',
+ updatedAt: 1_700_000_000_000,
+ };
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockVisibleDevice.mockResolvedValue(undefined);
+ mockFindAccount.mockResolvedValue(undefined);
+ mockLatestReadings.mockResolvedValue([]);
+ mockFindByDeviceId.mockResolvedValue({ id: 'device-row' });
+ mockFindWorkspaceDeviceById.mockResolvedValue(undefined);
+ mockKimiCodeQuota.mockResolvedValue(snapshot);
+ });
+
+ it('refreshes and persists the remote account rather than returning an isolated device sample', async () => {
+ const result = await createCaller().refreshKimiCodeQuota({ deviceId: 'remote' });
+ expect(result).toEqual(snapshot);
+ expect(mockIngestSnapshot).toHaveBeenCalledWith({
+ deviceId: 'device-row',
+ identity: snapshot.identity,
+ provider: 'kimi-code',
+ readings: READINGS,
+ });
+ });
+
+ it('does not append the same cached readings twice', async () => {
+ mockFindAccount.mockResolvedValue({ id: 'account' });
+ mockLatestReadings.mockResolvedValue(READINGS);
+ await createCaller().refreshKimiCodeQuota({ deviceId: 'remote' });
+ expect(mockIngestSnapshot).not.toHaveBeenCalled();
+ });
+
+ it('does not persist an unidentified sample', async () => {
+ mockKimiCodeQuota.mockResolvedValue({ ...snapshot, identity: null });
+ await createCaller().refreshKimiCodeQuota({ deviceId: 'remote' });
+ expect(mockIngestSnapshot).not.toHaveBeenCalled();
+ });
+
+ it('checks workspace device visibility before sampling', async () => {
+ mockVisibleDevice.mockRejectedValue(new Error('hidden device'));
+ await expect(
+ createCaller('workspace').refreshKimiCodeQuota({ deviceId: 'remote' }),
+ ).rejects.toThrow('hidden device');
+ expect(mockKimiCodeQuota).not.toHaveBeenCalled();
+ expect(mockIngestSnapshot).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/agentQuota.ts b/apps/server/src/routers/lambda/agentQuota.ts
index a7b78122b30..71fdb68b7f8 100644
--- a/apps/server/src/routers/lambda/agentQuota.ts
+++ b/apps/server/src/routers/lambda/agentQuota.ts
@@ -28,7 +28,7 @@ const quotaProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
});
});
-const providerSchema = z.enum(['claude-code', 'codex']);
+const providerSchema = z.enum(['claude-code', 'codex', 'kimi-code']);
const readingSchema = z.object({
capturedAt: z.number(),
@@ -97,11 +97,73 @@ export const agentQuotaRouter = router({
return snapshot;
}),
+ /** Refresh on the execution device and publish its sample to the account quota layer. */
+ refreshKimiCodeQuota: quotaProcedure
+ .use(cloudWorkspaceAuth)
+ .input(
+ z.object({
+ deviceId: z.string(),
+ env: z.record(z.string(), z.string()).optional(),
+ force: z.boolean().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ if (ctx.workspaceId) await assertWorkspaceDeviceVisible(ctx.deviceModel, input.deviceId);
+ const snapshot = await deviceGateway.kimiCodeQuota({
+ ...input,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+ if (
+ snapshot?.status !== 'ok' ||
+ !snapshot.identity?.externalAccountId ||
+ !snapshot.readings?.length
+ )
+ return snapshot ?? null;
+ const account = await ctx.accountModel.findByExternalId(
+ 'kimi-code',
+ snapshot.identity.externalAccountId,
+ );
+ const latest = account ? await ctx.quotaService.listLatestReadings(account.id) : [];
+ const readings = snapshot.readings.filter(
+ (reading) =>
+ !latest.some(
+ (previous) =>
+ previous.limitType === reading.limitType &&
+ previous.scopeKey === reading.scopeKey &&
+ previous.capturedAt >= reading.capturedAt,
+ ),
+ );
+ if (readings.length) {
+ const device =
+ (ctx.workspaceId
+ ? await ctx.deviceModel.findWorkspaceDeviceById(input.deviceId)
+ : undefined) ?? (await ctx.deviceModel.findByDeviceId(input.deviceId));
+ await ctx.quotaService.ingestSnapshot({
+ deviceId: device?.id,
+ identity: snapshot.identity,
+ provider: 'kimi-code',
+ readings,
+ });
+ }
+ return snapshot;
+ }),
+
// ── ingestion (desktop sampler → DB) ──────────────────────────────────────
ingestSnapshot: quotaProcedure
.input(
z.object({
deviceId: z.string().optional(),
+ extraUsage: z
+ .object({
+ balanceCents: z.number(),
+ currency: z.string(),
+ monthlyChargeLimitCents: z.number(),
+ monthlyChargeLimitEnabled: z.boolean(),
+ monthlyUsedCents: z.number(),
+ totalCents: z.number(),
+ })
+ .nullish(),
identity: z.object({
displayName: z.string().optional(),
email: z.string().optional(),
@@ -138,6 +200,7 @@ export const agentQuotaRouter = router({
return ctx.quotaService.ingestSnapshot({
credentialRef: { origin: 'keychain' },
deviceId: deviceRow?.id,
+ extraUsage: input.extraUsage,
identity: input.identity,
provider: input.provider,
readings: input.readings,
diff --git a/apps/server/src/services/agentQuota/__tests__/index.test.ts b/apps/server/src/services/agentQuota/__tests__/index.test.ts
index f7b04c1335a..2487b31fdf4 100644
--- a/apps/server/src/services/agentQuota/__tests__/index.test.ts
+++ b/apps/server/src/services/agentQuota/__tests__/index.test.ts
@@ -4,6 +4,7 @@ import type { QuotaLimitReading } from '@lobechat/heterogeneous-agents/quota';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import {
+ AgentProviderAccountModel,
AgentQuotaCalibrationModel,
AgentQuotaUsageLedgerModel,
AgentQuotaWindowModel,
@@ -110,6 +111,35 @@ describe('AgentQuotaService.ingestSnapshot', () => {
expect(await windows.listByAccount(account.id)).toHaveLength(4);
expect(await calibrations.latest(account.id, 'session')).toBeNull();
});
+
+ it('persists the Extra Usage wallet on account metadata, and clears it on null', async () => {
+ // The wallet is not a limit reading — it rides the account row so the
+ // persisted panel keeps the Extra Usage section between live samples.
+ const accounts = new AgentProviderAccountModel(serverDB, userId);
+ const extraUsage = {
+ balanceCents: 1234,
+ currency: 'CNY',
+ monthlyChargeLimitCents: 5000,
+ monthlyChargeLimitEnabled: true,
+ monthlyUsedCents: 42,
+ totalCents: 2000,
+ };
+ const account = await service.ingestSnapshot({
+ extraUsage,
+ identity,
+ provider: 'kimi-code',
+ readings: [],
+ });
+ expect((await accounts.findById(account.id))?.metadata?.['extraUsage']).toEqual(extraUsage);
+
+ await service.ingestSnapshot({
+ extraUsage: null,
+ identity,
+ provider: 'kimi-code',
+ readings: [],
+ });
+ expect((await accounts.findById(account.id))?.metadata?.['extraUsage']).toBeNull();
+ });
});
describe('AgentQuotaService.listLatestReadings', () => {
diff --git a/apps/server/src/services/agentQuota/index.ts b/apps/server/src/services/agentQuota/index.ts
index f6ddf9221ee..2c28161bfa5 100644
--- a/apps/server/src/services/agentQuota/index.ts
+++ b/apps/server/src/services/agentQuota/index.ts
@@ -6,6 +6,7 @@ import {
isScopedWeeklyLimit,
isSessionLimit,
isWeeklyAllLimit,
+ type KimiCodeExtraUsage,
MIN_CALIBRATION_SAMPLES,
projectWindows,
type QuotaAccountIdentity,
@@ -92,6 +93,7 @@ export class AgentQuotaService {
ingestSnapshot = async (params: {
credentialRef?: QuotaAccountCredentialRef;
deviceId?: string;
+ extraUsage?: KimiCodeExtraUsage | null;
identity: QuotaAccountIdentity;
provider: string;
readings: QuotaLimitReading[];
@@ -101,6 +103,14 @@ export class AgentQuotaService {
params.identity as AccountIdentityInput,
params.credentialRef ? { credentialRef: params.credentialRef } : {},
);
+ // The wallet is not a limit reading, so it can't ride the snapshots table —
+ // keep the latest sample on the account row or the persisted view loses the
+ // Extra Usage section between live samples.
+ if (params.extraUsage !== undefined) {
+ await this.accounts.update(account.id, {
+ metadata: { ...account.metadata, extraUsage: params.extraUsage },
+ });
+ }
await this.ingestReadings(account.id, params.readings, params.deviceId);
// Ingestion is the only moment new evidence arrives, so it is also the only
// sensible calibration trigger. Cheap and self-guarding: without enough clean
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index 08cb0e5c95a..93516334738 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -12,6 +12,7 @@ import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
import type {
ClaudeCodeQuotaSnapshot,
CodexQuotaSnapshot,
+ KimiCodeQuotaSnapshot,
} from '@lobechat/heterogeneous-agents/quota';
import type {
DeviceCopyAssetForPublishResult,
@@ -580,6 +581,20 @@ export class DeviceGateway {
});
}
+ /** Kimi Code subscription quota sampled from the login on a remote device. */
+ kimiCodeQuota(params: {
+ deviceId: string;
+ env?: Record<string, string>;
+ force?: boolean;
+ userId: string;
+ workspaceId?: string;
+ }) {
+ return this.invokeDeviceRead<KimiCodeQuotaSnapshot>('getKimiCodeQuota', params, {
+ env: params.env,
+ force: params.force,
+ });
+ }
+
/** Git worktrees attached to the same repository as a directory on a remote device. */
listGitWorktrees(params: {
deviceId: string;
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index b94cabcd795..b8bb39c8666 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -997,6 +997,16 @@
"heteroAgent.executionTarget.workspaceGroup": "Workspace Devices",
"heteroAgent.fullAccess.label": "Full access",
"heteroAgent.fullAccess.tooltip": "The local coding agent runs with full read/write access to the working directory. Switching permission modes is not available yet.",
+ "heteroAgent.kimiCodeQuota.errorGeneric": "Couldn't load Kimi Code quota. Try again later.",
+ "heteroAgent.kimiCodeQuota.extraUsage": "Extra Usage",
+ "heteroAgent.kimiCodeQuota.fiveHour": "5-hour",
+ "heteroAgent.kimiCodeQuota.monthly": "Monthly",
+ "heteroAgent.kimiCodeQuota.monthlyCap": "{{used}} of {{limit}} used this month",
+ "heteroAgent.kimiCodeQuota.monthlyCode": "Monthly code",
+ "heteroAgent.kimiCodeQuota.title": "Kimi Code quota",
+ "heteroAgent.kimiCodeQuota.tooltip": "View Kimi Code quota",
+ "heteroAgent.kimiCodeQuota.unavailableExpired": "Kimi Code login has expired. Sign in with the kimi CLI again, then refresh.",
+ "heteroAgent.kimiCodeQuota.unavailableNotFound": "No Kimi Code login found. Run kimi in a terminal to sign in first.",
"heteroAgent.modelSelector.ariaLabel": "Model: {{model}}. Effort: {{reasoning}}",
"heteroAgent.modelSelector.default": "Default",
"heteroAgent.modelSelector.defaultConfig": "Default config",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 00dd7398676..81f50a7ea63 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -997,6 +997,16 @@
"heteroAgent.executionTarget.workspaceGroup": "工作区设备",
"heteroAgent.fullAccess.label": "完全访问权限",
"heteroAgent.fullAccess.tooltip": "本地编码 Agent 运行时对工作目录拥有完全的读写权限。当前暂不支持切换权限模式。",
+ "heteroAgent.kimiCodeQuota.errorGeneric": "无法获取 Kimi Code 额度,请稍后重试。",
+ "heteroAgent.kimiCodeQuota.extraUsage": "额外用量",
+ "heteroAgent.kimiCodeQuota.fiveHour": "5 小时",
+ "heteroAgent.kimiCodeQuota.monthly": "每月",
+ "heteroAgent.kimiCodeQuota.monthlyCap": "本月已用 {{used}} / {{limit}}",
+ "heteroAgent.kimiCodeQuota.monthlyCode": "每月代码",
+ "heteroAgent.kimiCodeQuota.title": "Kimi Code 额度",
+ "heteroAgent.kimiCodeQuota.tooltip": "查看 Kimi Code 额度",
+ "heteroAgent.kimiCodeQuota.unavailableExpired": "Kimi Code 登录已过期,请使用 kimi CLI 重新登录后再刷新。",
+ "heteroAgent.kimiCodeQuota.unavailableNotFound": "未找到 Kimi Code 登录凭证,请先在终端运行 kimi 完成登录。",
"heteroAgent.modelSelector.ariaLabel": "模型:{{model}}。思考强度:{{reasoning}}",
"heteroAgent.modelSelector.default": "默认",
"heteroAgent.modelSelector.defaultConfig": "默认配置",
diff --git a/packages/device-control/src/__tests__/kimiCodeQuota.test.ts b/packages/device-control/src/__tests__/kimiCodeQuota.test.ts
new file mode 100644
index 00000000000..2606dae7d99
--- /dev/null
+++ b/packages/device-control/src/__tests__/kimiCodeQuota.test.ts
@@ -0,0 +1,124 @@
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getKimiCodeQuota } from '../kimiCodeQuota';
+
+let fixtureDir: string;
+
+const okResponse = (payload: unknown) =>
+ ({ json: async () => payload, ok: true, status: 200 }) as Response;
+
+// Reset times must stay in the future relative to the test run — a fixed ISO
+// string goes stale and the window reads as rolled over (0%, no countdown).
+const RESET_5H = new Date(Date.now() + 2 * 3_600_000).toISOString();
+const RESET_7D = new Date(Date.now() + 5 * 86_400_000).toISOString();
+const RESET_MONTH = new Date(Date.now() + 10 * 86_400_000).toISOString();
+
+beforeAll(async () => {
+ fixtureDir = await mkdtemp(path.join(tmpdir(), 'kimi-code-quota-'));
+ await mkdir(path.join(fixtureDir, 'credentials'), { recursive: true });
+ await writeFile(
+ path.join(fixtureDir, 'credentials', 'kimi-code.json'),
+ JSON.stringify({
+ access_token: 'fixture-token',
+ expires_at: Math.floor(Date.now() / 1000) + 3600,
+ refresh_token: 'fixture-refresh',
+ }),
+ );
+});
+
+afterAll(async () => {
+ await rm(fixtureDir, { force: true, recursive: true });
+});
+
+beforeEach(() => {
+ vi.stubGlobal('fetch', vi.fn());
+ vi.mocked(fetch).mockImplementation(async (input) => {
+ const url = String(input);
+ if (url.endsWith('/me')) {
+ return okResponse({ email: '[email protected]', nickname: 'moonwalker', user_id: 'u_123' });
+ }
+ return okResponse({
+ boosterWallet: {
+ balance: { amount: 25_000_000_000, amountLeft: 10_000_000_000, type: 'BOOSTER' },
+ monthlyChargeLimit: { currency: 'CNY', priceInCents: 10_000_000_000 },
+ monthlyChargeLimitEnabled: true,
+ monthlyUsed: { currency: 'CNY', priceInCents: 0 },
+ },
+ usages: {
+ limit_5h: { reset_time: RESET_5H, used_ratio: 0.256 },
+ limit_7d: { reset_time: RESET_7D, used_ratio: 0.147 },
+ limit_month_code: { reset_time: RESET_MONTH, used_ratio: 0.333 },
+ limit_month_total: { reset_time: RESET_MONTH, used_ratio: 0.5 },
+ },
+ });
+ });
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('getKimiCodeQuota', () => {
+ it('reads and maps every usage window through the Kimi usage API', async () => {
+ const result = await getKimiCodeQuota({
+ env: { KIMI_CODE_HOME: fixtureDir },
+ force: true,
+ });
+
+ expect(result).toMatchObject({
+ error: null,
+ provider: 'kimi-code',
+ identity: { email: '[email protected]', externalAccountId: 'u_123' },
+ session: {
+ resetsAt: Date.parse(RESET_5H),
+ usedPercent: 26,
+ windowMinutes: 300,
+ },
+ status: 'ok',
+ weekly: {
+ resetsAt: Date.parse(RESET_7D),
+ usedPercent: 15,
+ windowMinutes: 10_080,
+ },
+ });
+ expect(result.extraUsage).toEqual({
+ balanceCents: 10_000,
+ currency: 'CNY',
+ monthlyChargeLimitCents: 10_000_000_000,
+ monthlyChargeLimitEnabled: true,
+ monthlyUsedCents: 0,
+ totalCents: 25_000,
+ });
+ expect(result.readings).toHaveLength(4);
+ expect(result.readings?.[0]).toMatchObject({
+ limitType: 'session',
+ scopeKey: '',
+ utilization: 26,
+ windowMinutes: 300,
+ });
+ expect(result.readings?.[3]).toMatchObject({
+ limitType: 'month_code',
+ utilization: 33,
+ windowMinutes: 43_200,
+ });
+ });
+
+ it('reports missing credentials without touching the network', async () => {
+ const result = await getKimiCodeQuota({
+ env: { KIMI_CODE_HOME: path.join(fixtureDir, 'missing') },
+ force: true,
+ });
+
+ expect(result).toMatchObject({
+ error: null,
+ provider: 'kimi-code',
+ reason: 'credentials-not-found',
+ status: 'unavailable',
+ });
+ expect(fetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.ts
index e2ea5b82e09..388a50fcd7e 100644
--- a/packages/device-control/src/dispatch.ts
+++ b/packages/device-control/src/dispatch.ts
@@ -28,6 +28,7 @@ import {
import { getClaudeCodeQuota, type GetClaudeCodeQuotaParams } from './claudeCodeQuota';
import { getCodexQuota, type GetCodexQuotaParams } from './codexQuota';
import { defaultCopyAssetForPublish, defaultReadExternalAssetForPublish } from './filePreview';
+import { getKimiCodeQuota, type GetKimiCodeQuotaParams } from './kimiCodeQuota';
import { defaultListProjectDirectory } from './projectFileIndex';
import { prepareSkillDirectory } from './skillDirectory';
import type {
@@ -61,6 +62,7 @@ export const DEVICE_RPC_METHODS = [
'listHeterogeneousAgentModels',
'getClaudeCodeQuota',
'getCodexQuota',
+ 'getKimiCodeQuota',
'listProjectSkills',
'prepareSkillDirectory',
'browseDirectory',
@@ -151,6 +153,10 @@ export const executeDeviceRpc = async (
return getCodexQuota(params as GetCodexQuotaParams);
}
+ case 'getKimiCodeQuota': {
+ return getKimiCodeQuota(params as GetKimiCodeQuotaParams);
+ }
+
case 'listProjectSkills': {
return listProjectSkills(params as ListProjectSkillsParams, deps);
}
diff --git a/packages/device-control/src/index.ts b/packages/device-control/src/index.ts
index 02b6dfa5555..622243cbc7c 100644
--- a/packages/device-control/src/index.ts
+++ b/packages/device-control/src/index.ts
@@ -6,6 +6,7 @@ export {
defaultReadExternalAssetForPublish,
EXTERNAL_PUBLISH_ASSET_MAX_BYTES,
} from './filePreview';
+export { getKimiCodeQuota, type GetKimiCodeQuotaParams } from './kimiCodeQuota';
export {
defaultGetProjectFileIndex,
defaultListProjectDirectory,
diff --git a/packages/device-control/src/kimiCodeQuota.ts b/packages/device-control/src/kimiCodeQuota.ts
new file mode 100644
index 00000000000..a0ccaf18b41
--- /dev/null
+++ b/packages/device-control/src/kimiCodeQuota.ts
@@ -0,0 +1,35 @@
+import type { KimiCodeQuotaSnapshot } from '@lobechat/heterogeneous-agents/quota';
+import {
+ createQuotaCacheKey,
+ fetchKimiCodeQuota,
+ KIMI_CODE_QUOTA_FRESH_MS,
+ QuotaSnapshotCache,
+} from '@lobechat/heterogeneous-agents/quota-sampler';
+
+export interface GetKimiCodeQuotaParams {
+ /** Agent-configured env overrides (KIMI_CODE_HOME / KIMI_CODE_BASE_URL). */
+ env?: Record<string, string>;
+ force?: boolean;
+}
+
+// One cache per device host process (`lh connect` daemon / desktop gateway
+// connection): every web client polling this device's quota coalesces into a
+// single usage-API request per fresh window.
+const quotaCache = new QuotaSnapshotCache<KimiCodeQuotaSnapshot>({
+ freshMs: KIMI_CODE_QUOTA_FRESH_MS,
+});
+
+/**
+ * Sample the Kimi Code subscription quota of the login on THIS device, for the
+ * `getKimiCodeQuota` device RPC. Same sampler as the desktop IPC path:
+ * credentials from the CLI's credential file, snapshot from the Kimi usage API
+ * — no CLI spawned.
+ */
+export const getKimiCodeQuota = (
+ params: GetKimiCodeQuotaParams = {},
+): Promise<KimiCodeQuotaSnapshot> =>
+ quotaCache.get(
+ createQuotaCacheKey('kimi-code', params.env),
+ () => fetchKimiCodeQuota({ env: params.env }),
+ { force: params.force },
+ );
diff --git a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
index 1909a3dc98d..01773f6d84b 100644
--- a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
+++ b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
@@ -76,6 +76,11 @@ export type {
CodexRateLimitResetOutcome,
CodexRateLimitSnapshot,
} from '@lobechat/heterogeneous-agents/quota';
+export type {
+ KimiCodeExtraUsage,
+ KimiCodeQuotaSnapshot,
+ KimiCodeQuotaUnavailableReason,
+} from '@lobechat/heterogeneous-agents/quota';
export interface CodexRateLimitResetResult {
outcome: CodexRateLimitResetOutcome;
diff --git a/packages/heterogeneous-agents/src/quota-sampler/index.ts b/packages/heterogeneous-agents/src/quota-sampler/index.ts
index eadecef19a7..416d71b206f 100644
--- a/packages/heterogeneous-agents/src/quota-sampler/index.ts
+++ b/packages/heterogeneous-agents/src/quota-sampler/index.ts
@@ -1,3 +1,4 @@
export * from './claudeCodeQuota';
export * from './codexQuota';
+export * from './kimiCodeQuota';
export * from './snapshotCache';
diff --git a/packages/heterogeneous-agents/src/quota-sampler/kimiCodeQuota.test.ts b/packages/heterogeneous-agents/src/quota-sampler/kimiCodeQuota.test.ts
new file mode 100644
index 00000000000..03a9a3e65fe
--- /dev/null
+++ b/packages/heterogeneous-agents/src/quota-sampler/kimiCodeQuota.test.ts
@@ -0,0 +1,399 @@
+import { readFile, writeFile } from 'node:fs/promises';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { fetchKimiCodeQuota } from './kimiCodeQuota';
+
+vi.mock('node:fs/promises', () => ({
+ readFile: vi.fn(),
+ writeFile: vi.fn(),
+}));
+
+vi.mock('node:os', () => ({
+ homedir: () => '/home/test',
+}));
+
+const CREDENTIALS_PATH = '/home/test/.kimi-code/credentials/kimi-code.json';
+
+const NOW = new Date('2026-09-20T12:00:00Z').getTime();
+const NOW_SECONDS = Math.floor(NOW / 1000);
+const FRESH_EXPIRES_AT = NOW_SECONDS + 3600;
+const STALE_EXPIRES_AT = NOW_SECONDS - 3600;
+
+const credentialsJson = (expiresAt: number, accessToken = 'file-token') =>
+ JSON.stringify({
+ access_token: accessToken,
+ expires_at: expiresAt,
+ expires_in: 3600,
+ refresh_token: 'refresh-token',
+ scope: 'openid',
+ token_type: 'Bearer',
+ });
+
+const okResponse = (payload: unknown) =>
+ ({ json: async () => payload, ok: true, status: 200 }) as Response;
+
+const fullUsagePayload = {
+ boosterWallet: {
+ balance: { amount: 25_000_000_000, amountLeft: 10_000_000_000, type: 'BOOSTER' },
+ monthlyChargeLimit: { currency: 'CNY', priceInCents: 10_000_000_000 },
+ monthlyChargeLimitEnabled: true,
+ monthlyUsed: { currency: 'CNY', priceInCents: 0 },
+ },
+ usages: {
+ limit_5h: { reset_time: '2026-09-20T14:42:21Z', used_ratio: 0.256 },
+ limit_7d: { reset_time: '2026-09-26T12:00:00Z', used_ratio: 0.147 },
+ limit_month_code: { reset_time: '2026-10-01T00:00:00Z', used_ratio: 0.333 },
+ limit_month_total: { reset_time: '2026-10-01T00:00:00Z', used_ratio: 0.5 },
+ },
+};
+
+const identityPayload = {
+ email: '[email protected]',
+ nickname: 'moonwalker',
+ user_id: 'u_123',
+};
+
+const mockKimiApi = (usagePayload: unknown, identity: unknown = null) => {
+ vi.mocked(fetch).mockImplementation(async (input) => {
+ const url = String(input);
+ if (url.endsWith('/me')) {
+ return identity === null ? ({ ok: false, status: 404 } as Response) : okResponse(identity);
+ }
+ return okResponse(usagePayload);
+ });
+};
+
+describe('fetchKimiCodeQuota', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(NOW);
+ vi.stubGlobal('fetch', vi.fn());
+ vi.stubEnv('KIMI_CODE_BASE_URL', '');
+ vi.stubEnv('KIMI_CODE_HOME', '');
+ vi.mocked(readFile).mockReset();
+ vi.mocked(readFile).mockRejectedValue(new Error('ENOENT'));
+ vi.mocked(writeFile).mockReset();
+ vi.mocked(writeFile).mockResolvedValue(undefined);
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ });
+
+ it('reports missing credentials without touching the network', async () => {
+ const result = await fetchKimiCodeQuota();
+
+ expect(result).toMatchObject({
+ error: null,
+ extraUsage: null,
+ monthly: null,
+ monthlyCode: null,
+ provider: 'kimi-code',
+ reason: 'credentials-not-found',
+ session: null,
+ status: 'unavailable',
+ updatedAt: NOW,
+ weekly: null,
+ });
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it('maps all four usage windows and the booster wallet from a fresh file login', async () => {
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));
+ mockKimiApi(fullUsagePayload, identityPayload);
+
+ const result = await fetchKimiCodeQuota();
+
+ expect(result).toMatchObject({
+ error: null,
+ extraUsage: {
+ balanceCents: 10_000,
+ currency: 'CNY',
+ monthlyChargeLimitCents: 10_000_000_000,
+ monthlyChargeLimitEnabled: true,
+ monthlyUsedCents: 0,
+ totalCents: 25_000,
+ },
+ identity: {
+ displayName: 'moonwalker',
+ email: '[email protected]',
+ externalAccountId: 'u_123',
+ },
+ monthly: {
+ resetsAt: Date.parse('2026-10-01T00:00:00Z'),
+ usedPercent: 50,
+ windowMinutes: 43_200,
+ },
+ monthlyCode: { usedPercent: 33, windowMinutes: 43_200 },
+ provider: 'kimi-code',
+ session: {
+ resetsAt: Date.parse('2026-09-20T14:42:21Z'),
+ usedPercent: 26,
+ windowMinutes: 300,
+ },
+ status: 'ok',
+ updatedAt: NOW,
+ weekly: {
+ resetsAt: Date.parse('2026-09-26T12:00:00Z'),
+ usedPercent: 15,
+ windowMinutes: 10_080,
+ },
+ });
+ expect(result.readings?.map((reading) => reading.limitType)).toEqual([
+ 'session',
+ 'weekly_all',
+ 'month_total',
+ 'month_code',
+ ]);
+ expect(fetch).toHaveBeenCalledWith(
+ 'https://api.kimi.com/coding/v1/usages',
+ expect.objectContaining({
+ headers: expect.objectContaining({ Authorization: 'Bearer file-token' }),
+ signal: expect.any(AbortSignal),
+ }),
+ );
+ // A fresh token is used as-is: no refresh round-trip.
+ expect(writeFile).not.toHaveBeenCalled();
+ });
+
+ it('keeps windows without a reset time and omits windows the payload lacks', async () => {
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));
+ mockKimiApi({ usages: { limit_5h: { used_ratio: 0.1 } } });
+
+ const result = await fetchKimiCodeQuota();
+
+ expect(result.status).toBe('ok');
+ expect(result.session).toEqual({ resetsAt: null, usedPercent: 10, windowMinutes: 300 });
+ expect(result.weekly).toBeNull();
+ expect(result.monthly).toBeNull();
+ expect(result.monthlyCode).toBeNull();
+ expect(result.extraUsage).toBeNull();
+ });
+
+ it('ignores a non-BOOSTER balance and defaults the currency to USD', async () => {
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));
+ mockKimiApi({
+ boosterWallet: { balance: { amount: 25_000_000_000, type: 'CREDIT' } },
+ usages: {},
+ });
+
+ const result = await fetchKimiCodeQuota();
+
+ expect(result.extraUsage).toBeNull();
+ });
+
+ it('rounds fixed-point money, rounding sub-cent remainders up', async () => {
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));
+ mockKimiApi({
+ boosterWallet: {
+ balance: { amount: 1_500_000, amountLeft: 500_000, type: 'BOOSTER' },
+ monthlyChargeLimitEnabled: false,
+ },
+ usages: {},
+ });
+
+ const result = await fetchKimiCodeQuota();
+
+ expect(result.extraUsage).toEqual({
+ balanceCents: 1,
+ currency: 'USD',
+ monthlyChargeLimitCents: 0,
+ monthlyChargeLimitEnabled: false,
+ monthlyUsedCents: 0,
+ totalCents: 2,
+ });
+ });
+
+ it('treats a missing amountLeft as a zero balance and a non-positive amount as no wallet', async () => {
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));
+ mockKimiApi({
+ boosterWallet: { balance: { amount: 25_000_000_000, type: 'BOOSTER' } },
+ usages: {},
+ });
+
+ const result = await fetchKimiCodeQuota();
+ expect(result.extraUsage).toMatchObject({ balanceCents: 0, totalCents: 25_000 });
+
+ mockKimiApi({
+ boosterWallet: { balance: { amount: 0, amountLeft: 0, type: 'BOOSTER' } },
+ usages: {},
+ });
+
+ const empty = await fetchKimiCodeQuota();
+ expect(empty.extraUsage).toBeNull();
+ });
+
+ it('refreshes a near-expiry token and persists the rotated credentials', async () => {
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(STALE_EXPIRES_AT, 'stale-token'));
+ vi.mocked(fetch).mockImplementation(async (input) => {
+ const url = String(input);
+ if (url === 'https://auth.kimi.com/api/oauth/token') {
+ return okResponse({ access_token: 'new-token', expires_in: 7200 });
+ }
+ if (url.endsWith('/me')) return { ok: false, status: 404 } as Response;
+ return okResponse({ usages: { limit_5h: { used_ratio: 0.5 } } });
+ });
+
+ const result = await fetchKimiCodeQuota();
+
+ expect(result.status).toBe('ok');
+ expect(fetch).toHaveBeenCalledWith(
+ 'https://auth.kimi.com/api/oauth/token',
+ expect.objectContaining({ method: 'POST' }),
+ );
+ const refreshInit = vi.mocked(fetch).mock.calls[0][1];
+ expect(String(refreshInit?.body)).toContain('grant_type=refresh_token');
+ expect(String(refreshInit?.body)).toContain('refresh_token=refresh-token');
+ expect(String(refreshInit?.body)).toContain('client_id=17e5f671-d194-4dfb-9706-5516cb48c098');
+ // The refreshed token authorizes the usage call.
+ expect(fetch).toHaveBeenCalledWith(
+ 'https://api.kimi.com/coding/v1/usages',
+ expect.objectContaining({
+ headers: expect.objectContaining({ Authorization: 'Bearer new-token' }),
+ }),
+ );
+ // The credential file is rewritten with the merged tokens and 0600 mode.
+ expect(writeFile).toHaveBeenCalledWith(
+ CREDENTIALS_PATH,
+ expect.any(String),
+ expect.objectContaining({ mode: 0o600 }),
+ );
+ const written = JSON.parse(vi.mocked(writeFile).mock.calls[0][1] as string);
+ expect(written).toMatchObject({
+ access_token: 'new-token',
+ expires_at: NOW_SECONDS + 7200,
+ // The old refresh token is kept when the response lacks one.
+ refresh_token: 'refresh-token',
+ });
+ });
+
+ it('reports credentials-expired when the refresh is rejected', async () => {
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(STALE_EXPIRES_AT));
+ vi.mocked(fetch).mockResolvedValue({
+ json: async () => ({ error: 'invalid_grant' }),
+ ok: false,
+ status: 400,
+ } as Response);
+
+ const result = await fetchKimiCodeQuota();
+
+ expect(result).toMatchObject({ reason: 'credentials-expired', status: 'unavailable' });
+ expect(writeFile).not.toHaveBeenCalled();
+ });
+
+ it('reports credentials-expired for an expired login without a refresh token', async () => {
+ vi.mocked(readFile).mockResolvedValue(
+ JSON.stringify({ access_token: 'stale-token', expires_at: STALE_EXPIRES_AT }),
+ );
+
+ const result = await fetchKimiCodeQuota();
+
+ expect(result).toMatchObject({ reason: 'credentials-expired', status: 'unavailable' });
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it('surfaces a refresh transport failure as an error', async () => {
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(STALE_EXPIRES_AT));
+ vi.mocked(fetch).mockRejectedValue(new Error('connect ECONNREFUSED'));
+
+ const result = await fetchKimiCodeQuota();
+
+ expect(result.status).toBe('error');
+ expect(result.error).toContain('ECONNREFUSED');
+ });
+
+ it('surfaces a usage API 500 as an error', async () => {
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));
+ vi.mocked(fetch).mockResolvedValue({ ok: false, status: 500 } as Response);
+
+ const result = await fetchKimiCodeQuota();
+
+ expect(result).toMatchObject({ status: 'error' });
+ expect(result.reason).toBeUndefined();
+ expect(result.error).toContain('500');
+ });
+
+ it('surfaces a usage API 401 as an error, not a credential state', async () => {
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));
+ vi.mocked(fetch).mockResolvedValue({ ok: false, status: 401 } as Response);
+
+ const result = await fetchKimiCodeQuota();
+
+ expect(result).toMatchObject({ status: 'error' });
+ expect(result.error).toContain('401');
+ });
+
+ it('honors KIMI_CODE_HOME and KIMI_CODE_BASE_URL from the agent env', async () => {
+ vi.mocked(readFile).mockImplementation(async (file) => {
+ if (file === '/custom/kimi/credentials/kimi-code.json') {
+ return credentialsJson(FRESH_EXPIRES_AT, 'custom-token');
+ }
+ throw new Error('ENOENT');
+ });
+ mockKimiApi({ usages: { limit_5h: { used_ratio: 0.1 } } });
+
+ const result = await fetchKimiCodeQuota({
+ env: {
+ KIMI_CODE_BASE_URL: 'https://api.kimi.ai/coding/v1',
+ KIMI_CODE_HOME: '/custom/kimi',
+ },
+ });
+
+ expect(result.status).toBe('ok');
+ expect(readFile).toHaveBeenCalledWith('/custom/kimi/credentials/kimi-code.json', 'utf8');
+ expect(fetch).toHaveBeenCalledWith(
+ 'https://api.kimi.ai/coding/v1/usages',
+ expect.objectContaining({
+ headers: expect.objectContaining({ Authorization: 'Bearer custom-token' }),
+ }),
+ );
+ });
+
+ it('prefers the explicit kimiCodeHomePath over the env', async () => {
+ vi.mocked(readFile).mockImplementation(async (file) => {
+ if (file === '/explicit/kimi/credentials/kimi-code.json') {
+ return credentialsJson(FRESH_EXPIRES_AT);
+ }
+ throw new Error('ENOENT');
+ });
+ mockKimiApi({ usages: {} });
+
+ const result = await fetchKimiCodeQuota({
+ env: { KIMI_CODE_HOME: '/custom/kimi' },
+ kimiCodeHomePath: '/explicit/kimi',
+ });
+
+ expect(result.status).toBe('ok');
+ expect(readFile).toHaveBeenCalledWith('/explicit/kimi/credentials/kimi-code.json', 'utf8');
+ });
+
+ it('keeps the snapshot ok when the identity endpoint fails', async () => {
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));
+ mockKimiApi({ usages: { limit_5h: { used_ratio: 0.1 } } });
+
+ const result = await fetchKimiCodeQuota();
+
+ expect(result.status).toBe('ok');
+ expect(result.identity).toBeNull();
+ });
+
+ it('aborts a hanging usage request and reports a timeout', async () => {
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));
+ vi.mocked(fetch).mockImplementation(
+ (_url, init) =>
+ new Promise((_, reject) => {
+ init?.signal?.addEventListener('abort', () => reject(new Error('aborted')));
+ }),
+ );
+
+ const resultPromise = fetchKimiCodeQuota();
+ await vi.advanceTimersByTimeAsync(10_000);
+ const result = await resultPromise;
+
+ expect(result.status).toBe('error');
+ expect(result.error).toContain('timed out');
+ });
+});
diff --git a/packages/heterogeneous-agents/src/quota-sampler/kimiCodeQuota.ts b/packages/heterogeneous-agents/src/quota-sampler/kimiCodeQuota.ts
new file mode 100644
index 00000000000..9956d8bf34f
--- /dev/null
+++ b/packages/heterogeneous-agents/src/quota-sampler/kimiCodeQuota.ts
@@ -0,0 +1,382 @@
+import { readFile, writeFile } from 'node:fs/promises';
+import { homedir } from 'node:os';
+import path from 'node:path';
+
+import {
+ buildKimiCodeQuotaWindows,
+ KIMI_CODE_MONTHLY_WINDOW_MINUTES,
+ KIMI_CODE_SESSION_WINDOW_MINUTES,
+ KIMI_CODE_WEEKLY_WINDOW_MINUTES,
+ kimiCodeQuotaReadings,
+} from '../quota/kimiCode';
+import type {
+ HeteroQuotaWindow,
+ KimiCodeExtraUsage,
+ KimiCodeQuotaSnapshot,
+ KimiCodeQuotaUnavailableReason,
+} from '../quota/snapshot';
+import type { QuotaAccountIdentity } from '../quota/types';
+
+/**
+ * How long a sampler host's snapshot cache may serve a Kimi Code quota reading
+ * without re-hitting the usage API. Matches the Claude cadence so every
+ * scheduled poll observes fresh data, while bursts still coalesce.
+ */
+export const KIMI_CODE_QUOTA_FRESH_MS = 90_000;
+
+const DEFAULT_BASE_URL = 'https://api.kimi.com/coding/v1';
+const OAUTH_CLIENT_ID = '17e5f671-d194-4dfb-9706-5516cb48c098';
+const OAUTH_TOKEN_URL = 'https://auth.kimi.com/api/oauth/token';
+const REQUEST_TIMEOUT_MS = 10_000;
+// Refresh a token expiring within this window instead of racing its expiry
+// mid-request.
+const TOKEN_EXPIRY_SKEW_MS = 60_000;
+// Booster wallet amounts are fixed-point: value / 1_000_000 = cents.
+const FIXED_POINT_CENTS = 1_000_000;
+
+export interface FetchKimiCodeQuotaOptions {
+ /**
+ * Agent-configured env overrides. A plain record rather than
+ * `NodeJS.ProcessEnv`: the root app augments `ProcessEnv` with required
+ * keys, which would make callers' partial env objects unassignable.
+ */
+ env?: Record<string, string | undefined>;
+ kimiCodeHomePath?: string | null;
+}
+
+interface KimiCodeCredentialsFile {
+ [key: string]: unknown;
+ access_token?: unknown;
+ expires_at?: unknown;
+ expires_in?: unknown;
+ refresh_token?: unknown;
+}
+
+type AccessTokenLookup =
+ | { accessToken: string; state: 'ok' }
+ | { message: string; state: 'error' }
+ | { state: 'expired' }
+ | { state: 'not-found' };
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null;
+
+// A trailing-slash regex (`/\/+$/`) is polynomial on slash-heavy input
+// (CodeQL js/redos); trim by index instead.
+const trimTrailingSlashes = (value: string): string => {
+ let end = value.length;
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
+ return value.slice(0, end);
+};
+
+const asNonEmpty = (value: string | null | undefined): string | null =>
+ typeof value === 'string' && value.trim().length > 0 ? value : null;
+
+const getKimiCodeHomePath = (options: FetchKimiCodeQuotaOptions) =>
+ asNonEmpty(options.kimiCodeHomePath) ??
+ asNonEmpty(options.env?.KIMI_CODE_HOME) ??
+ asNonEmpty(process.env.KIMI_CODE_HOME) ??
+ path.join(homedir(), '.kimi-code');
+
+const getKimiCodeBaseUrl = (options: FetchKimiCodeQuotaOptions) =>
+ trimTrailingSlashes(
+ asNonEmpty(options.env?.KIMI_CODE_BASE_URL) ??
+ asNonEmpty(process.env.KIMI_CODE_BASE_URL) ??
+ DEFAULT_BASE_URL,
+ );
+
+const baseSnapshot = () => ({
+ extraUsage: null,
+ monthly: null,
+ monthlyCode: null,
+ provider: 'kimi-code' as const,
+ session: null,
+ updatedAt: Date.now(),
+ weekly: null,
+});
+
+const errorSnapshot = (message: string): KimiCodeQuotaSnapshot => ({
+ ...baseSnapshot(),
+ error: message,
+ status: 'error',
+});
+
+const unavailableSnapshot = (reason: KimiCodeQuotaUnavailableReason): KimiCodeQuotaSnapshot => ({
+ ...baseSnapshot(),
+ error: null,
+ reason,
+ status: 'unavailable',
+});
+
+/**
+ * Exchange the refresh token for a new access token and persist the rotated
+ * credentials back to the CLI's credential file. A 4xx (or `invalid_grant`)
+ * means the login itself is gone; transport failures are transient errors.
+ */
+const refreshAccessToken = async (
+ credentialsPath: string,
+ credentials: KimiCodeCredentialsFile,
+ refreshToken: string,
+): Promise<AccessTokenLookup> => {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
+
+ let response: Response;
+ try {
+ response = await fetch(OAUTH_TOKEN_URL, {
+ body: new URLSearchParams({
+ client_id: OAUTH_CLIENT_ID,
+ grant_type: 'refresh_token',
+ refresh_token: refreshToken,
+ }),
+ headers: {
+ 'Accept': 'application/json',
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
+ method: 'POST',
+ signal: controller.signal,
+ });
+ } catch (error) {
+ return {
+ message: `Kimi Code token refresh failed: ${error instanceof Error ? error.message : String(error)}`,
+ state: 'error',
+ };
+ } finally {
+ clearTimeout(timeout);
+ }
+
+ const payload: unknown = await response.json().catch(() => null);
+ const errorCode = isRecord(payload) && typeof payload.error === 'string' ? payload.error : '';
+
+ if ((response.status >= 400 && response.status < 500) || errorCode === 'invalid_grant') {
+ return { state: 'expired' };
+ }
+
+ const newAccessToken =
+ isRecord(payload) && typeof payload.access_token === 'string' ? payload.access_token : '';
+ if (!response.ok || !newAccessToken) {
+ return { message: `Kimi Code token refresh failed (${response.status})`, state: 'error' };
+ }
+
+ const expiresIn =
+ isRecord(payload) &&
+ typeof payload.expires_in === 'number' &&
+ Number.isFinite(payload.expires_in)
+ ? payload.expires_in
+ : 3600;
+
+ const nextCredentials = {
+ ...credentials,
+ ...(isRecord(payload) ? payload : {}),
+ access_token: newAccessToken,
+ expires_at: Math.floor(Date.now() / 1000) + expiresIn,
+ refresh_token:
+ isRecord(payload) && typeof payload.refresh_token === 'string' && payload.refresh_token
+ ? payload.refresh_token
+ : refreshToken,
+ };
+
+ try {
+ await writeFile(credentialsPath, JSON.stringify(nextCredentials, null, 2), {
+ encoding: 'utf8',
+ mode: 0o600,
+ });
+ } catch {
+ // The rotated token is usable for this run even if persisting it fails.
+ }
+
+ return { accessToken: newAccessToken, state: 'ok' };
+};
+
+/**
+ * Locate the Kimi Code OAuth login written by the `kimi` CLI
+ * (`$KIMI_CODE_HOME/credentials/kimi-code.json`) and return a usable access
+ * token, refreshing it when it is about to expire.
+ */
+const resolveAccessToken = async (
+ options: FetchKimiCodeQuotaOptions,
+): Promise<AccessTokenLookup> => {
+ const credentialsPath = path.join(getKimiCodeHomePath(options), 'credentials', 'kimi-code.json');
+
+ let credentials: KimiCodeCredentialsFile;
+ try {
+ credentials = JSON.parse(await readFile(credentialsPath, 'utf8')) as KimiCodeCredentialsFile;
+ } catch {
+ return { state: 'not-found' };
+ }
+
+ const accessToken = typeof credentials.access_token === 'string' ? credentials.access_token : '';
+ if (!accessToken) return { state: 'not-found' };
+
+ const expiresAtMs =
+ typeof credentials.expires_at === 'number' ? credentials.expires_at * 1000 : 0;
+ if (expiresAtMs - Date.now() > TOKEN_EXPIRY_SKEW_MS) return { accessToken, state: 'ok' };
+
+ const refreshToken =
+ typeof credentials.refresh_token === 'string' ? credentials.refresh_token : '';
+ if (!refreshToken) return { state: 'expired' };
+
+ return refreshAccessToken(credentialsPath, credentials, refreshToken);
+};
+
+const numberValue = (value: unknown): number | undefined => {
+ if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;
+ if (typeof value === 'string') {
+ const parsed = Number(value);
+ return Number.isFinite(parsed) ? parsed : undefined;
+ }
+ return undefined;
+};
+
+const intValue = (value: unknown): number | null => {
+ const parsed = numberValue(value);
+ return parsed === undefined ? null : Math.trunc(parsed);
+};
+
+const fixedPointToCents = (value: number): number => {
+ const cents = value / FIXED_POINT_CENTS;
+ if (cents > 0 && cents < 1) return 1;
+ return Math.round(cents);
+};
+
+const parseUsageWindow = (raw: unknown, windowMinutes: number): HeteroQuotaWindow | null => {
+ if (!isRecord(raw)) return null;
+ const usedRatio = numberValue(raw.used_ratio);
+ if (usedRatio === undefined) return null;
+ const resetTime = typeof raw.reset_time === 'string' ? Date.parse(raw.reset_time) : Number.NaN;
+
+ return {
+ resetsAt: Number.isFinite(resetTime) ? resetTime : null,
+ usedPercent: usedRatio * 100,
+ windowMinutes,
+ };
+};
+
+const parseMoney = (raw: unknown): { cents: number; currency: string } | null => {
+ if (!isRecord(raw)) return null;
+ const cents = intValue(raw.priceInCents);
+ if (cents === null) return null;
+ return { cents, currency: typeof raw.currency === 'string' ? raw.currency : '' };
+};
+
+const parseBoosterWallet = (raw: unknown): KimiCodeExtraUsage | null => {
+ if (!isRecord(raw) || !isRecord(raw.balance)) return null;
+ if (raw.balance.type !== 'BOOSTER') return null;
+ const amount = intValue(raw.balance.amount);
+ if (amount === null || amount <= 0) return null;
+ const amountLeft = intValue(raw.balance.amountLeft);
+
+ const monthlyLimit = parseMoney(raw.monthlyChargeLimit);
+ const monthlyUsed = parseMoney(raw.monthlyUsed);
+
+ return {
+ balanceCents: amountLeft === null ? 0 : fixedPointToCents(amountLeft),
+ currency: monthlyLimit?.currency || monthlyUsed?.currency || 'USD',
+ monthlyChargeLimitCents: monthlyLimit?.cents ?? 0,
+ monthlyChargeLimitEnabled: raw.monthlyChargeLimitEnabled === true,
+ monthlyUsedCents: monthlyUsed?.cents ?? 0,
+ totalCents: fixedPointToCents(amount),
+ };
+};
+
+/**
+ * Best-effort account identity from `{baseUrl}/me`. Failure must never fail
+ * the quota snapshot, so every error collapses to `null`.
+ */
+const fetchKimiCodeIdentity = async (
+ baseUrl: string,
+ accessToken: string,
+): Promise<QuotaAccountIdentity | null> => {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
+
+ try {
+ const response = await fetch(`${baseUrl}/me`, {
+ headers: {
+ Accept: 'application/json',
+ Authorization: `Bearer ${accessToken}`,
+ },
+ signal: controller.signal,
+ });
+ if (!response.ok) return null;
+
+ const payload: unknown = await response.json();
+ if (!isRecord(payload) || typeof payload.user_id !== 'string' || !payload.user_id) return null;
+
+ return {
+ displayName:
+ typeof payload.nickname === 'string' && payload.nickname ? payload.nickname : undefined,
+ email: typeof payload.email === 'string' && payload.email ? payload.email : undefined,
+ externalAccountId: payload.user_id,
+ };
+ } catch {
+ return null;
+ } finally {
+ clearTimeout(timeout);
+ }
+};
+
+export const fetchKimiCodeQuota = async (
+ options: FetchKimiCodeQuotaOptions = {},
+): Promise<KimiCodeQuotaSnapshot> => {
+ const lookup = await resolveAccessToken(options);
+ if (lookup.state === 'not-found') return unavailableSnapshot('credentials-not-found');
+ if (lookup.state === 'expired') return unavailableSnapshot('credentials-expired');
+ if (lookup.state === 'error') return errorSnapshot(lookup.message);
+
+ const baseUrl = getKimiCodeBaseUrl(options);
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
+
+ try {
+ const response = await fetch(`${baseUrl}/usages`, {
+ headers: {
+ Accept: 'application/json',
+ Authorization: `Bearer ${lookup.accessToken}`,
+ },
+ signal: controller.signal,
+ });
+
+ if (!response.ok) {
+ return errorSnapshot(`Kimi Code usage API returned ${response.status}`);
+ }
+
+ const payload: unknown = await response.json();
+ const usages = isRecord(payload) && isRecord(payload.usages) ? payload.usages : {};
+ const capturedAt = Date.now();
+ // The panel windows are projected from the same readings we persist, so a
+ // limit can never render live yet go missing from the account's history.
+ const readings = kimiCodeQuotaReadings(
+ {
+ monthly: parseUsageWindow(usages.limit_month_total, KIMI_CODE_MONTHLY_WINDOW_MINUTES),
+ monthlyCode: parseUsageWindow(usages.limit_month_code, KIMI_CODE_MONTHLY_WINDOW_MINUTES),
+ session: parseUsageWindow(usages.limit_5h, KIMI_CODE_SESSION_WINDOW_MINUTES),
+ weekly: parseUsageWindow(usages.limit_7d, KIMI_CODE_WEEKLY_WINDOW_MINUTES),
+ },
+ capturedAt,
+ );
+ const windows = buildKimiCodeQuotaWindows(readings, capturedAt);
+
+ return {
+ error: null,
+ extraUsage: parseBoosterWallet(isRecord(payload) ? payload.boosterWallet : null),
+ identity: await fetchKimiCodeIdentity(baseUrl, lookup.accessToken),
+ monthly: windows.monthly,
+ monthlyCode: windows.monthlyCode,
+ provider: 'kimi-code',
+ readings,
+ session: windows.session,
+ status: 'ok',
+ updatedAt: capturedAt,
+ weekly: windows.weekly,
+ };
+ } catch (error) {
+ if (controller.signal.aborted) {
+ return errorSnapshot('Kimi Code usage API request timed out');
+ }
+
+ return errorSnapshot(error instanceof Error ? error.message : String(error));
+ } finally {
+ clearTimeout(timeout);
+ }
+};
diff --git a/packages/heterogeneous-agents/src/quota/index.ts b/packages/heterogeneous-agents/src/quota/index.ts
index 79a1c6bf4ee..3de7965ff4d 100644
--- a/packages/heterogeneous-agents/src/quota/index.ts
+++ b/packages/heterogeneous-agents/src/quota/index.ts
@@ -2,6 +2,7 @@ export * from './calibration';
export * from './codex';
export * from './cost';
export * from './identity';
+export * from './kimiCode';
export * from './loadBalancer';
export * from './readings';
export * from './snapshot';
diff --git a/packages/heterogeneous-agents/src/quota/kimiCode.test.ts b/packages/heterogeneous-agents/src/quota/kimiCode.test.ts
new file mode 100644
index 00000000000..e05943db5a8
--- /dev/null
+++ b/packages/heterogeneous-agents/src/quota/kimiCode.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildKimiCodeQuotaWindows, kimiCodeQuotaReadings } from './kimiCode';
+import { projectWindows } from './windows';
+
+const now = 1_800_000_000_000;
+const windows = {
+ monthly: { resetsAt: now + 180_000, usedPercent: 50, windowMinutes: 43_200 },
+ monthlyCode: { resetsAt: now + 240_000, usedPercent: 33, windowMinutes: 43_200 },
+ session: { resetsAt: now + 60_000, usedPercent: 23, windowMinutes: 300 },
+ weekly: { resetsAt: now + 120_000, usedPercent: 41, windowMinutes: 10_080 },
+};
+
+describe('Kimi Code persisted quota projection', () => {
+ it('roundtrips all four windows through unified readings', () => {
+ const readings = kimiCodeQuotaReadings(windows, now);
+ expect(buildKimiCodeQuotaWindows(readings, now)).toEqual(windows);
+ expect(projectWindows(readings)[2].windowSeconds).toBe(43_200 * 60);
+ });
+
+ it('maps each window to its limit type with an explicit window length', () => {
+ const readings = kimiCodeQuotaReadings(windows, now);
+
+ expect(readings.map((reading) => [reading.limitType, reading.windowMinutes])).toEqual([
+ ['session', 300],
+ ['weekly_all', 10_080],
+ ['month_total', 43_200],
+ ['month_code', 43_200],
+ ]);
+ expect(readings.every((reading) => reading.scopeKey === '')).toBe(true);
+ });
+
+ it('omits windows the provider did not report', () => {
+ const readings = kimiCodeQuotaReadings(
+ { monthly: null, monthlyCode: null, session: windows.session, weekly: null },
+ now,
+ );
+
+ expect(readings).toHaveLength(1);
+ expect(buildKimiCodeQuotaWindows(readings, now)).toEqual({
+ monthly: null,
+ monthlyCode: null,
+ session: windows.session,
+ weekly: null,
+ });
+ });
+
+ it('selects the latest reading independently per limit and refills expired windows', () => {
+ const old = kimiCodeQuotaReadings(windows, now);
+ const newer = { ...old[0], capturedAt: now + 1, utilization: 55 };
+ expect(buildKimiCodeQuotaWindows([...old, newer], now).session?.usedPercent).toBe(55);
+ expect(buildKimiCodeQuotaWindows(old, now + 120_001).weekly?.usedPercent).toBe(0);
+ expect(buildKimiCodeQuotaWindows(old, now + 120_001).monthly?.usedPercent).toBe(50);
+ });
+});
diff --git a/packages/heterogeneous-agents/src/quota/kimiCode.ts b/packages/heterogeneous-agents/src/quota/kimiCode.ts
new file mode 100644
index 00000000000..9f324cd0bd0
--- /dev/null
+++ b/packages/heterogeneous-agents/src/quota/kimiCode.ts
@@ -0,0 +1,80 @@
+import type { QuotaDisplayReading } from './readings';
+import { toQuotaWindow } from './readings';
+import type { HeteroQuotaWindow } from './snapshot';
+import type { QuotaLimitReading } from './types';
+
+export const KIMI_CODE_SESSION_WINDOW_MINUTES = 5 * 60;
+export const KIMI_CODE_WEEKLY_WINDOW_MINUTES = 7 * 24 * 60;
+export const KIMI_CODE_MONTHLY_WINDOW_MINUTES = 30 * 24 * 60;
+
+export interface KimiCodeQuotaWindows {
+ monthly: HeteroQuotaWindow | null;
+ monthlyCode: HeteroQuotaWindow | null;
+ session: HeteroQuotaWindow | null;
+ weekly: HeteroQuotaWindow | null;
+}
+
+/** Preserve provider limit kinds and window lengths across live and persisted views. */
+export const kimiCodeQuotaReadings = (
+ windows: KimiCodeQuotaWindows,
+ capturedAt: number,
+): QuotaLimitReading[] => {
+ const slots: [limitType: string, window: HeteroQuotaWindow | null, windowMinutes: number][] = [
+ ['session', windows.session, KIMI_CODE_SESSION_WINDOW_MINUTES],
+ ['weekly_all', windows.weekly, KIMI_CODE_WEEKLY_WINDOW_MINUTES],
+ ['month_total', windows.monthly, KIMI_CODE_MONTHLY_WINDOW_MINUTES],
+ ['month_code', windows.monthlyCode, KIMI_CODE_MONTHLY_WINDOW_MINUTES],
+ ];
+
+ return slots.flatMap(([limitType, window, windowMinutes]) =>
+ window
+ ? [
+ {
+ capturedAt,
+ limitType,
+ resetsAt: window.resetsAt,
+ scopeKey: '',
+ utilization: Math.round(window.usedPercent),
+ windowMinutes,
+ },
+ ]
+ : [],
+ );
+};
+
+/**
+ * Project limit readings onto the four windows the Kimi Code panel renders. The
+ * single source of that mapping: the live sampler and the persisted read model
+ * both go through here, so a limit can never be visible on one path and
+ * missing on the other.
+ */
+export const buildKimiCodeQuotaWindows = (
+ readings: QuotaDisplayReading[],
+ now: number,
+): KimiCodeQuotaWindows => {
+ const newest = new Map<string, QuotaDisplayReading>();
+ for (const reading of readings) {
+ if (
+ reading.limitType !== 'session' &&
+ reading.limitType !== 'weekly_all' &&
+ reading.limitType !== 'month_total' &&
+ reading.limitType !== 'month_code'
+ )
+ continue;
+ const previous = newest.get(reading.limitType);
+ if (!previous || previous.capturedAt < reading.capturedAt)
+ newest.set(reading.limitType, reading);
+ }
+
+ const window = (limitType: string) => {
+ const reading = newest.get(limitType);
+ return reading ? toQuotaWindow(reading, now) : null;
+ };
+
+ return {
+ monthly: window('month_total'),
+ monthlyCode: window('month_code'),
+ session: window('session'),
+ weekly: window('weekly_all'),
+ };
+};
diff --git a/packages/heterogeneous-agents/src/quota/snapshot.ts b/packages/heterogeneous-agents/src/quota/snapshot.ts
index ff775379b03..3cbe181c693 100644
--- a/packages/heterogeneous-agents/src/quota/snapshot.ts
+++ b/packages/heterogeneous-agents/src/quota/snapshot.ts
@@ -94,3 +94,34 @@ export interface ClaudeCodeQuotaSnapshot {
updatedAt: number;
weekly: HeteroQuotaWindow | null;
}
+
+/** Booster-wallet top-up balance reported alongside the Kimi Code rate limits. */
+export interface KimiCodeExtraUsage {
+ balanceCents: number;
+ currency: string;
+ monthlyChargeLimitCents: number;
+ monthlyChargeLimitEnabled: boolean;
+ monthlyUsedCents: number;
+ totalCents: number;
+}
+
+export type KimiCodeQuotaUnavailableReason = 'credentials-expired' | 'credentials-not-found';
+
+export interface KimiCodeQuotaSnapshot {
+ error: string | null;
+ extraUsage: KimiCodeExtraUsage | null;
+ identity?: QuotaAccountIdentity | null;
+ /** `limit_month_total` (windowMinutes 43200). */
+ monthly: HeteroQuotaWindow | null;
+ /** `limit_month_code` (windowMinutes 43200). */
+ monthlyCode: HeteroQuotaWindow | null;
+ provider: 'kimi-code';
+ readings?: QuotaLimitReading[];
+ reason?: KimiCodeQuotaUnavailableReason;
+ /** `limit_5h` (windowMinutes 300). */
+ session: HeteroQuotaWindow | null;
+ status: 'error' | 'ok' | 'unavailable';
+ updatedAt: number;
+ /** `limit_7d` (windowMinutes 10080). */
+ weekly: HeteroQuotaWindow | null;
+}
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 18c10572b29..5cbee5b4429 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -509,6 +509,18 @@ export default {
'heteroAgent.codexQuota.totalEarned_one': '{{count}} earned in total',
'heteroAgent.codexQuota.totalEarned_other': '{{count}} earned in total',
'heteroAgent.codexQuota.tooltip': 'View Codex quota',
+ 'heteroAgent.kimiCodeQuota.errorGeneric': "Couldn't load Kimi Code quota. Try again later.",
+ 'heteroAgent.kimiCodeQuota.extraUsage': 'Extra Usage',
+ 'heteroAgent.kimiCodeQuota.fiveHour': '5-hour',
+ 'heteroAgent.kimiCodeQuota.monthly': 'Monthly',
+ 'heteroAgent.kimiCodeQuota.monthlyCap': '{{used}} of {{limit}} used this month',
+ 'heteroAgent.kimiCodeQuota.monthlyCode': 'Monthly code',
+ 'heteroAgent.kimiCodeQuota.title': 'Kimi Code quota',
+ 'heteroAgent.kimiCodeQuota.tooltip': 'View Kimi Code quota',
+ 'heteroAgent.kimiCodeQuota.unavailableExpired':
+ 'Kimi Code login has expired. Sign in with the kimi CLI again, then refresh.',
+ 'heteroAgent.kimiCodeQuota.unavailableNotFound':
+ 'No Kimi Code login found. Run kimi in a terminal to sign in first.',
'heteroAgent.quota.compactLeft': '{{percent}}%',
'heteroAgent.quota.exhausted': 'Exhausted',
'heteroAgent.quota.duration.day_one': '{{count}}d',
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/KimiCodeQuotaMenu.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/KimiCodeQuotaMenu.tsx
new file mode 100644
index 00000000000..4480d891492
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/KimiCodeQuotaMenu.tsx
@@ -0,0 +1,158 @@
+'use client';
+
+import type { KimiCodeQuotaSnapshot } from '@lobechat/heterogeneous-agents/quota';
+import { Flexbox, Icon } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { WalletIcon } from 'lucide-react';
+import { memo, useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
+import { createKimiCodeQuotaReader } from '@/services/kimiCodeQuota';
+
+import type { QuotaWindowItem } from './QuotaMenu';
+import QuotaMenu, { createQuotaSourceKey } from './QuotaMenu';
+
+const styles = createStaticStyles(({ css }) => ({
+ extraUsage: css`
+ padding-block-start: 8px;
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+}));
+
+const createErrorSnapshot = (error: unknown): KimiCodeQuotaSnapshot => ({
+ error: error instanceof Error ? error.message : String(error),
+ extraUsage: null,
+ monthly: null,
+ monthlyCode: null,
+ provider: 'kimi-code',
+ session: null,
+ status: 'error',
+ updatedAt: Date.now(),
+ weekly: null,
+});
+
+const formatCents = (cents: number, currency: string) => {
+ try {
+ return new Intl.NumberFormat(undefined, { currency, style: 'currency' }).format(cents / 100);
+ } catch {
+ return `${(cents / 100).toFixed(2)} ${currency}`;
+ }
+};
+
+interface KimiCodeQuotaMenuProps {
+ deviceId?: string;
+ env?: Record<string, string>;
+}
+
+const KimiCodeQuotaMenu = memo<KimiCodeQuotaMenuProps>(({ deviceId, env }) => {
+ const { t } = useTranslation('chat');
+ const agentId = useAgentId();
+ const sourceKey = createQuotaSourceKey('kimi-code', agentId, deviceId, env);
+
+ const fetchQuota = useMemo(
+ () => createKimiCodeQuotaReader({ agentId, deviceId, env }),
+ [agentId, deviceId, env],
+ );
+
+ const getWindows = useCallback(
+ (quota: KimiCodeQuotaSnapshot): QuotaWindowItem[] => [
+ {
+ key: 'session',
+ label: t('heteroAgent.kimiCodeQuota.fiveHour'),
+ window: quota.session,
+ },
+ {
+ key: 'weekly',
+ label: t('heteroAgent.quota.weekly'),
+ window: quota.weekly,
+ },
+ {
+ key: 'monthly',
+ label: t('heteroAgent.kimiCodeQuota.monthly'),
+ window: quota.monthly,
+ },
+ {
+ key: 'monthlyCode',
+ label: t('heteroAgent.kimiCodeQuota.monthlyCode'),
+ window: quota.monthlyCode,
+ },
+ ],
+ [t],
+ );
+
+ const hasExtraData = useCallback((quota: KimiCodeQuotaSnapshot) => !!quota.extraUsage, []);
+
+ const getUnavailableText = useCallback(
+ (quota: KimiCodeQuotaSnapshot) => {
+ switch (quota.reason) {
+ case 'credentials-expired': {
+ return t('heteroAgent.kimiCodeQuota.unavailableExpired');
+ }
+ case 'credentials-not-found': {
+ return t('heteroAgent.kimiCodeQuota.unavailableNotFound');
+ }
+ default: {
+ return undefined;
+ }
+ }
+ },
+ [t],
+ );
+
+ const getErrorText = useCallback(() => t('heteroAgent.kimiCodeQuota.errorGeneric'), [t]);
+
+ const renderFooter = useCallback(
+ (quota: KimiCodeQuotaSnapshot) => {
+ const extraUsage = quota.extraUsage;
+ if (!extraUsage) return null;
+
+ return (
+ <Flexbox className={styles.extraUsage} gap={4}>
+ <Flexbox horizontal align={'center'} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={4}>
+ <Icon icon={WalletIcon} size={14} />
+ <Text strong style={{ fontSize: 12 }}>
+ {t('heteroAgent.kimiCodeQuota.extraUsage')}
+ </Text>
+ </Flexbox>
+ <Text style={{ fontSize: 12 }}>
+ {formatCents(extraUsage.balanceCents, extraUsage.currency)}
+ </Text>
+ </Flexbox>
+ {extraUsage.monthlyChargeLimitEnabled && (
+ <Text color={cssVar.colorTextTertiary} style={{ fontSize: 12 }}>
+ {t('heteroAgent.kimiCodeQuota.monthlyCap', {
+ limit: formatCents(extraUsage.monthlyChargeLimitCents, extraUsage.currency),
+ used: formatCents(extraUsage.monthlyUsedCents, extraUsage.currency),
+ })}
+ </Text>
+ )}
+ </Flexbox>
+ );
+ },
+ [t],
+ );
+
+ return (
+ <QuotaMenu
+ contentWidth={320}
+ createErrorSnapshot={createErrorSnapshot}
+ fetchQuota={fetchQuota}
+ getErrorText={getErrorText}
+ getRefreshErrorText={getErrorText}
+ getUnavailableText={getUnavailableText}
+ getWindows={getWindows}
+ hasExtraData={hasExtraData}
+ renderFooter={renderFooter}
+ sourceKey={sourceKey}
+ title={t('heteroAgent.kimiCodeQuota.title')}
+ tooltip={t('heteroAgent.kimiCodeQuota.tooltip')}
+ />
+ );
+});
+
+KimiCodeQuotaMenu.displayName = 'KimiCodeQuotaMenu';
+
+export default KimiCodeQuotaMenu;
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx
index c6d49c435c5..6e2792441f5 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx
@@ -3,6 +3,7 @@
*/
import type * as LobechatConstModule from '@lobechat/const';
import type * as ElectronClientIpcModule from '@lobechat/electron-client-ipc';
+import type { KimiCodeQuotaSnapshot } from '@lobechat/heterogeneous-agents/quota';
import type { HeterogeneousProviderConfig } from '@lobechat/types';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
@@ -11,11 +12,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import HeteroControlBar from '..';
import ClaudeCodeQuotaMenu from './ClaudeCodeQuotaMenu';
import CodexQuotaMenu from './CodexQuotaMenu';
+import KimiCodeQuotaMenu from './KimiCodeQuotaMenu';
const mockService = vi.hoisted(() => ({
consumeCodexRateLimitResetCredit: vi.fn(),
getClaudeCodeQuota: vi.fn(),
getCodexQuota: vi.fn(),
+ getKimiCodeQuota: vi.fn(),
}));
const effectiveAgencyConfig = vi.hoisted(() => ({
@@ -104,9 +107,10 @@ vi.mock('@/services/electron/heterogeneousAgent', () => ({
// A `deviceId` routes the live sample through the device gateway TRPC instead
// of Electron IPC (see `fetchClaudeCodeQuotaSnapshot`).
-const { mockLambdaClaudeQuota, mockLambdaCodexQuota } = vi.hoisted(() => ({
+const { mockLambdaClaudeQuota, mockLambdaCodexQuota, mockLambdaKimiCodeQuota } = vi.hoisted(() => ({
mockLambdaClaudeQuota: vi.fn(),
mockLambdaCodexQuota: vi.fn(),
+ mockLambdaKimiCodeQuota: vi.fn(),
}));
vi.mock('@/libs/trpc/client', () => ({
@@ -125,7 +129,9 @@ const mockQuotaService = vi.hoisted(() => ({
getLatestReadings: vi.fn(async (): Promise<unknown[]> => []),
ingestClaudeSnapshot: vi.fn(async () => undefined),
ingestCodexSnapshot: vi.fn(async () => undefined),
+ ingestKimiCodeSnapshot: vi.fn(async () => undefined),
refreshCodexQuota: vi.fn(),
+ refreshKimiCodeQuota: vi.fn(),
listAccounts: vi.fn(async (): Promise<unknown[]> => []),
listBindings: vi.fn(async (): Promise<unknown[]> => []),
}));
@@ -269,6 +275,21 @@ const codexSnapshot = (
...overrides,
});
+const kimiCodeSnapshot = (
+ overrides: Partial<KimiCodeQuotaSnapshot> = {},
+): KimiCodeQuotaSnapshot => ({
+ error: null,
+ extraUsage: null,
+ monthly: null,
+ monthlyCode: null,
+ provider: 'kimi-code',
+ session: null,
+ status: 'ok',
+ updatedAt: Date.now(),
+ weekly: null,
+ ...overrides,
+});
+
beforeEach(() => {
effectiveAgencyConfig.current = {
boundDeviceId: 'personal-device',
@@ -280,13 +301,17 @@ beforeEach(() => {
mockService.consumeCodexRateLimitResetCredit.mockReset();
mockService.getClaudeCodeQuota.mockReset();
mockService.getCodexQuota.mockReset();
+ mockService.getKimiCodeQuota.mockReset();
mockLambdaClaudeQuota.mockReset();
mockLambdaCodexQuota.mockReset();
+ mockLambdaKimiCodeQuota.mockReset();
mockQuotaService.refreshCodexQuota.mockImplementation(mockLambdaCodexQuota);
+ mockQuotaService.refreshKimiCodeQuota.mockImplementation(mockLambdaKimiCodeQuota);
toastErrorMock.mockReset();
toastSuccessMock.mockReset();
mockQuotaService.getLatestReadings.mockResolvedValue([]);
mockQuotaService.ingestClaudeSnapshot.mockClear();
+ mockQuotaService.ingestKimiCodeSnapshot.mockClear();
mockQuotaService.listAccounts.mockResolvedValue([]);
mockQuotaService.listBindings.mockResolvedValue([]);
});
@@ -380,6 +405,118 @@ describe('HeteroControlBar', () => {
expect(screen.queryByRole('button', { name: 'heteroAgent.claudeQuota.tooltip' })).toBeNull();
expect(mockService.getClaudeCodeQuota).not.toHaveBeenCalled();
});
+
+ it('shows local Kimi Code quota for a local execution target', async () => {
+ effectiveAgencyConfig.current = {
+ boundDeviceId: 'personal-device',
+ executionTarget: 'local',
+ heterogeneousProvider: { command: 'kimi', type: 'kimi-code' },
+ };
+ mockService.getKimiCodeQuota.mockResolvedValue(
+ kimiCodeSnapshot({ session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 } }),
+ );
+
+ render(<HeteroControlBar />);
+
+ expect(
+ await screen.findByRole('button', { name: 'heteroAgent.kimiCodeQuota.tooltip' }),
+ ).toBeTruthy();
+ expect(mockService.getKimiCodeQuota).toHaveBeenCalledWith({ env: undefined });
+ expect(mockService.getCodexQuota).not.toHaveBeenCalled();
+ });
+
+ it('shows Kimi Code quota sampled by a bound remote device', async () => {
+ effectiveAgencyConfig.current = {
+ boundDeviceId: 'remote-device',
+ executionTarget: 'device',
+ heterogeneousProvider: { command: 'kimi', type: 'kimi-code' },
+ };
+ mockLambdaKimiCodeQuota.mockResolvedValue(
+ kimiCodeSnapshot({ session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 } }),
+ );
+
+ render(<HeteroControlBar />);
+
+ expect(
+ await screen.findByRole('button', { name: 'heteroAgent.kimiCodeQuota.tooltip' }),
+ ).toBeTruthy();
+ expect(mockLambdaKimiCodeQuota).toHaveBeenCalledWith({
+ deviceId: 'remote-device',
+ env: undefined,
+ });
+ expect(mockService.getKimiCodeQuota).not.toHaveBeenCalled();
+ });
+});
+
+describe('KimiCodeQuotaMenu', () => {
+ it('renders all four windows and the Extra Usage footer from the snapshot', async () => {
+ mockService.getKimiCodeQuota.mockResolvedValue(
+ kimiCodeSnapshot({
+ extraUsage: {
+ balanceCents: 1234,
+ currency: 'USD',
+ monthlyChargeLimitCents: 5000,
+ monthlyChargeLimitEnabled: true,
+ monthlyUsedCents: 42,
+ totalCents: 2000,
+ },
+ monthly: { resetsAt: null, usedPercent: 55, windowMinutes: 43_200 },
+ monthlyCode: { resetsAt: null, usedPercent: 61, windowMinutes: 43_200 },
+ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
+ weekly: { resetsAt: null, usedPercent: 13, windowMinutes: 10_080 },
+ }),
+ );
+
+ render(<KimiCodeQuotaMenu />);
+
+ expect(await screen.findByText('heteroAgent.kimiCodeQuota.fiveHour')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.quota.weekly')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.kimiCodeQuota.monthly')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.kimiCodeQuota.monthlyCode')).toBeTruthy();
+ expect(screen.getByText('92%')).toBeTruthy();
+ expect(screen.getByText('39%')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.kimiCodeQuota.extraUsage')).toBeTruthy();
+ expect(
+ screen.getByText((content) => content.startsWith('heteroAgent.kimiCodeQuota.monthlyCap:')),
+ ).toBeTruthy();
+ // The trigger compacts every window into the tightest remaining value.
+ const trigger = screen.getByRole('button', { name: 'heteroAgent.kimiCodeQuota.tooltip' });
+ expect(trigger.textContent).toContain('heteroAgent.quota.compactLeft:39');
+ expect(mockService.getKimiCodeQuota).toHaveBeenCalledWith({ env: undefined });
+ });
+
+ it('omits the monthly cap line when the charge limit is disabled', async () => {
+ mockService.getKimiCodeQuota.mockResolvedValue(
+ kimiCodeSnapshot({
+ extraUsage: {
+ balanceCents: 1234,
+ currency: 'USD',
+ monthlyChargeLimitCents: 0,
+ monthlyChargeLimitEnabled: false,
+ monthlyUsedCents: 42,
+ totalCents: 2000,
+ },
+ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
+ }),
+ );
+
+ render(<KimiCodeQuotaMenu />);
+
+ expect(await screen.findByText('heteroAgent.kimiCodeQuota.extraUsage')).toBeTruthy();
+ expect(
+ screen.queryByText((content) => content.startsWith('heteroAgent.kimiCodeQuota.monthlyCap')),
+ ).toBeNull();
+ });
+
+ it('maps unavailable reasons to their localized explanations', async () => {
+ mockService.getKimiCodeQuota.mockResolvedValue(
+ kimiCodeSnapshot({ reason: 'credentials-not-found', status: 'unavailable' }),
+ );
+
+ render(<KimiCodeQuotaMenu />);
+
+ expect(await screen.findByText('heteroAgent.kimiCodeQuota.unavailableNotFound')).toBeTruthy();
+ });
});
describe('ClaudeCodeQuotaMenu', () => {
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/index.ts b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/index.ts
index b7201090cb5..e262976f9ab 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/index.ts
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/index.ts
@@ -1,2 +1,3 @@
export { default as ClaudeCodeQuotaMenu } from './ClaudeCodeQuotaMenu';
export { default as CodexQuotaMenu } from './CodexQuotaMenu';
+export { default as KimiCodeQuotaMenu } from './KimiCodeQuotaMenu';
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx
index a48a2f87fd3..40d02d16551 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx
@@ -23,7 +23,7 @@ import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
-import { ClaudeCodeQuotaMenu, CodexQuotaMenu } from './QuotaMenu';
+import { ClaudeCodeQuotaMenu, CodexQuotaMenu, KimiCodeQuotaMenu } from './QuotaMenu';
const styles = createStaticStyles(({ css }) => ({
// Pinned to the same 28px row as the plain ControlBar so the composer footer
@@ -168,6 +168,13 @@ const HeteroControlBar = memo(() => {
isSubscriptionAuth &&
heteroProvider?.type === 'codex' &&
(isLocalHeteroExecution || !!quotaDeviceId);
+ // Kimi Code carries no client-side auth mode: whether the login is a
+ // subscription is only knowable from the sampled snapshot, so gate exactly
+ // like Claude and let the snapshot's unavailable reason explain the rest.
+ const shouldShowKimiCodeQuota =
+ isSubscriptionAuth &&
+ heteroProvider?.type === 'kimi-code' &&
+ (isLocalHeteroExecution || !!quotaDeviceId);
if (isAccessLoading) return null;
@@ -197,7 +204,8 @@ const HeteroControlBar = memo(() => {
</Flexbox>
{(shouldShowApiCredits ||
(shouldShowClaudeQuota && quotaDeviceId) ||
- (shouldShowCodexQuota && quotaDeviceId)) && (
+ (shouldShowCodexQuota && quotaDeviceId) ||
+ (shouldShowKimiCodeQuota && quotaDeviceId)) && (
<Flexbox horizontal align={'center'} className={styles.rightGroup} gap={4}>
{shouldShowApiCredits && <ChatInputCredits />}
{shouldShowClaudeQuota && quotaDeviceId && (
@@ -210,6 +218,9 @@ const HeteroControlBar = memo(() => {
env={heteroProvider?.env}
/>
)}
+ {shouldShowKimiCodeQuota && quotaDeviceId && (
+ <KimiCodeQuotaMenu deviceId={quotaDeviceId} env={heteroProvider?.env} />
+ )}
</Flexbox>
)}
</Flexbox>
@@ -284,6 +295,9 @@ const HeteroControlBar = memo(() => {
env={heteroProvider?.env}
/>
)}
+ {shouldShowKimiCodeQuota && (
+ <KimiCodeQuotaMenu deviceId={quotaDeviceId} env={heteroProvider?.env} />
+ )}
{shouldShowClaudeQuota && (
<ClaudeCodeQuotaMenu deviceId={quotaDeviceId} env={heteroProvider?.env} />
)}
diff --git a/src/services/agentQuota.ts b/src/services/agentQuota.ts
index 4dd7283fb45..0dc4013755a 100644
--- a/src/services/agentQuota.ts
+++ b/src/services/agentQuota.ts
@@ -4,6 +4,8 @@ import type {
} from '@lobechat/electron-client-ipc';
import type {
CodexQuotaSnapshot,
+ KimiCodeExtraUsage,
+ KimiCodeQuotaSnapshot,
QuotaAccountIdentity,
QuotaLimitReading,
} from '@lobechat/heterogeneous-agents/quota';
@@ -29,6 +31,19 @@ class AgentQuotaService {
}): Promise<CodexQuotaSnapshot | null> =>
lambdaClient.agentQuota.refreshCodexQuota.mutate(params);
+ ingestKimiCodeSnapshot = async (params: {
+ extraUsage?: KimiCodeExtraUsage | null;
+ identity: QuotaAccountIdentity;
+ readings: QuotaLimitReading[];
+ }) => lambdaClient.agentQuota.ingestSnapshot.mutate({ ...params, provider: 'kimi-code' });
+
+ refreshKimiCodeQuota = async (params: {
+ deviceId: string;
+ env?: Record<string, string>;
+ force?: boolean;
+ }): Promise<KimiCodeQuotaSnapshot | null> =>
+ lambdaClient.agentQuota.refreshKimiCodeQuota.mutate(params);
+
/** Persist a live Claude snapshot (identity + readings) captured over IPC. */
ingestClaudeSnapshot = async (params: {
deviceId?: string;
@@ -96,7 +111,7 @@ class AgentQuotaService {
model?: string;
occurredAt?: number;
operationId?: string;
- provider: 'claude-code' | 'codex';
+ provider: 'claude-code' | 'codex' | 'kimi-code';
topicId?: string;
usage: {
cacheRead?: number;
diff --git a/src/services/electron/heterogeneousAgent.ts b/src/services/electron/heterogeneousAgent.ts
index 5a4e887bc55..534b50bbda6 100644
--- a/src/services/electron/heterogeneousAgent.ts
+++ b/src/services/electron/heterogeneousAgent.ts
@@ -2,6 +2,7 @@ import type {
ClaudeCodeQuotaSnapshot,
CodexQuotaSnapshot,
CodexRateLimitResetResult,
+ KimiCodeQuotaSnapshot,
} from '@lobechat/electron-client-ipc';
import type { HeterogeneousProviderBindingReference } from '@lobechat/heterogeneous-agents';
import type {
@@ -91,6 +92,14 @@ class HeterogeneousAgentService {
return this.ipc.heterogeneousAgent.getClaudeCodeQuota(params);
}
+ async getKimiCodeQuota(params?: {
+ env?: Record<string, string>;
+ force?: boolean;
+ kimiCodeHomePath?: string | null;
+ }): Promise<KimiCodeQuotaSnapshot> {
+ return this.ipc.heterogeneousAgent.getKimiCodeQuota(params);
+ }
+
/**
* Identity of the Claude login a spawn with this env would use — a pure
* local file read, safe to call once per run for usage attribution.
diff --git a/src/services/kimiCodeQuota.test.ts b/src/services/kimiCodeQuota.test.ts
new file mode 100644
index 00000000000..f83d2b8d6a8
--- /dev/null
+++ b/src/services/kimiCodeQuota.test.ts
@@ -0,0 +1,161 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentQuotaService } from './agentQuota';
+import { heterogeneousAgentService } from './electron/heterogeneousAgent';
+import { createKimiCodeQuotaReader } from './kimiCodeQuota';
+
+vi.mock('./agentQuota', () => ({
+ agentQuotaService: {
+ listAccounts: vi.fn(),
+ listBindings: vi.fn(),
+ getLatestReadings: vi.fn(),
+ ingestKimiCodeSnapshot: vi.fn(),
+ refreshKimiCodeQuota: vi.fn(),
+ },
+}));
+vi.mock('./electron/heterogeneousAgent', () => ({
+ heterogeneousAgentService: { getKimiCodeQuota: vi.fn() },
+}));
+
+const account = {
+ id: 'account-a',
+ provider: 'kimi-code',
+ externalAccountId: 'external-a',
+ updatedAt: new Date(),
+};
+const reading = {
+ capturedAt: Date.now(),
+ limitType: 'session',
+ resetsAt: Date.now() + 60000,
+ scopeKey: '',
+ utilization: 23,
+ windowMinutes: 300,
+};
+const sample = {
+ error: null,
+ extraUsage: null,
+ identity: { externalAccountId: 'external-a' },
+ monthly: null,
+ monthlyCode: null,
+ readings: [reading],
+ provider: 'kimi-code' as const,
+ session: { usedPercent: 23, windowMinutes: 300, resetsAt: reading.resetsAt },
+ status: 'ok' as const,
+ updatedAt: reading.capturedAt,
+ weekly: null,
+};
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ vi.mocked(agentQuotaService.listAccounts).mockResolvedValue([account] as never);
+ vi.mocked(agentQuotaService.listBindings).mockResolvedValue([]);
+ vi.mocked(agentQuotaService.getLatestReadings).mockResolvedValue([reading]);
+ vi.mocked(agentQuotaService.ingestKimiCodeSnapshot).mockResolvedValue(account as never);
+ vi.mocked(heterogeneousAgentService.getKimiCodeQuota).mockResolvedValue(sample);
+ vi.mocked(agentQuotaService.refreshKimiCodeQuota).mockResolvedValue(sample);
+});
+
+describe('account-scoped Kimi Code quota', () => {
+ it('renders fresh persisted local quota without probing the CLI', async () => {
+ const result = await createKimiCodeQuotaReader({})({});
+ expect(result.session?.usedPercent).toBe(23);
+ expect(heterogeneousAgentService.getKimiCodeQuota).not.toHaveBeenCalled();
+ });
+
+ it('publishes a fresh local sample to the unified account layer', async () => {
+ vi.mocked(agentQuotaService.listAccounts).mockResolvedValue([]);
+ const result = await createKimiCodeQuotaReader({})({});
+ expect(result.identity?.externalAccountId).toBe('external-a');
+ expect(agentQuotaService.ingestKimiCodeSnapshot).toHaveBeenCalledWith({
+ extraUsage: null,
+ identity: sample.identity,
+ readings: [reading],
+ });
+ });
+
+ it('publishes the wallet even when the windows did not move', async () => {
+ const extraUsage = {
+ balanceCents: 1234,
+ currency: 'USD',
+ monthlyChargeLimitCents: 5000,
+ monthlyChargeLimitEnabled: true,
+ monthlyUsedCents: 42,
+ totalCents: 2000,
+ };
+ // Same readings as persisted (fresh === []), but a live wallet is present.
+ vi.mocked(heterogeneousAgentService.getKimiCodeQuota).mockResolvedValue({
+ ...sample,
+ extraUsage,
+ });
+ await createKimiCodeQuotaReader({})({ force: true });
+ expect(agentQuotaService.ingestKimiCodeSnapshot).toHaveBeenCalledWith({
+ extraUsage,
+ identity: sample.identity,
+ readings: [],
+ });
+ });
+
+ it('surfaces an unavailable login instead of stale persisted quota', async () => {
+ vi.mocked(heterogeneousAgentService.getKimiCodeQuota).mockResolvedValue({
+ ...sample,
+ identity: undefined,
+ monthly: null,
+ readings: undefined,
+ reason: 'credentials-expired' as const,
+ session: null,
+ status: 'unavailable' as const,
+ });
+ const result = await createKimiCodeQuotaReader({})({ force: true });
+ expect(result.status).toBe('unavailable');
+ expect(result.reason).toBe('credentials-expired');
+ });
+
+ it('keeps local quota usable when the persistence backend is unavailable', async () => {
+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ vi.mocked(agentQuotaService.listAccounts).mockRejectedValue(new Error('offline'));
+ vi.mocked(agentQuotaService.ingestKimiCodeSnapshot).mockRejectedValue(new Error('offline'));
+ const result = await createKimiCodeQuotaReader({})();
+ expect(result.session?.usedPercent).toBe(23);
+ expect(result.status).toBe('ok');
+ } finally {
+ log.mockRestore();
+ }
+ });
+
+ it('does not re-ingest a cached sample on focus', async () => {
+ await createKimiCodeQuotaReader({})({ revalidate: true });
+ expect(agentQuotaService.ingestKimiCodeSnapshot).not.toHaveBeenCalled();
+ });
+
+ it('refreshes remote quota through agentQuota and keeps persisted data while offline', async () => {
+ const reader = createKimiCodeQuotaReader({ deviceId: 'device-a' });
+ expect((await reader()).session?.usedPercent).toBe(23);
+ expect(agentQuotaService.refreshKimiCodeQuota).toHaveBeenCalled();
+ expect(agentQuotaService.ingestKimiCodeSnapshot).not.toHaveBeenCalled();
+ vi.mocked(agentQuotaService.refreshKimiCodeQuota).mockResolvedValue(null);
+ expect((await reader({ revalidate: true })).session?.usedPercent).toBe(23);
+ expect(heterogeneousAgentService.getKimiCodeQuota).not.toHaveBeenCalled();
+ });
+
+ it('does not show another device account while discovering a new source', async () => {
+ vi.mocked(agentQuotaService.refreshKimiCodeQuota).mockResolvedValue(null);
+ const result = await createKimiCodeQuotaReader({ deviceId: 'device-b' })();
+ expect(result.session).toBeNull();
+ expect(result.status).toBe('error');
+ });
+
+ it('does not merge the previous account after the device changes login', async () => {
+ const reader = createKimiCodeQuotaReader({ deviceId: 'device-a' });
+ await reader();
+ vi.mocked(agentQuotaService.refreshKimiCodeQuota).mockResolvedValue({
+ ...sample,
+ identity: { externalAccountId: 'external-b' },
+ readings: [],
+ session: { ...sample.session, usedPercent: 80 },
+ });
+ const result = await reader({ revalidate: true });
+ expect(result.identity?.externalAccountId).toBe('external-b');
+ expect(result.session?.usedPercent).toBe(80);
+ });
+});
diff --git a/src/services/kimiCodeQuota.ts b/src/services/kimiCodeQuota.ts
new file mode 100644
index 00000000000..18e3013d7ee
--- /dev/null
+++ b/src/services/kimiCodeQuota.ts
@@ -0,0 +1,154 @@
+import type { KimiCodeQuotaSnapshot } from '@lobechat/heterogeneous-agents/quota';
+
+import { agentQuotaService } from './agentQuota';
+import { heterogeneousAgentService } from './electron/heterogeneousAgent';
+import { buildKimiCodePanelSnapshot } from './kimiCodeQuotaViewModel';
+
+const REFRESH_MS = 2 * 60_000;
+
+interface KimiCodeQuotaSource {
+ agentId?: string;
+ deviceId?: string;
+ env?: Record<string, string>;
+}
+
+interface FetchOptions {
+ force?: boolean;
+ onInterim?: (snapshot: KimiCodeQuotaSnapshot) => void;
+ revalidate?: boolean;
+}
+
+const readPersisted = async <T>(request: Promise<T>, fallback: T): Promise<T> => {
+ try {
+ return await request;
+ } catch (error) {
+ console.error('[kimiCodeQuota:read-persisted]', error);
+ return fallback;
+ }
+};
+
+/** Device/profile sources identify their login before reusing persisted data. */
+export const createKimiCodeQuotaReader = (source: KimiCodeQuotaSource) => {
+ let trustedAccountId: string | undefined;
+ let lastLive: KimiCodeQuotaSnapshot | null = null;
+ const readQuota = async (options: FetchOptions = {}): Promise<KimiCodeQuotaSnapshot> => {
+ const [allAccounts, bindings] = await Promise.all([
+ readPersisted(agentQuotaService.listAccounts(), []),
+ source.agentId ? readPersisted(agentQuotaService.listBindings(source.agentId), []) : [],
+ ]);
+ const accounts = allAccounts.filter((account) => account.provider === 'kimi-code');
+ const pinnedId = bindings.find((binding) => binding.role === 'pinned')?.accountId;
+ let account =
+ source.deviceId || source.env?.KIMI_CODE_HOME
+ ? accounts.find((item) => item.externalAccountId === trustedAccountId)
+ : (accounts.find((item) => item.externalAccountId === trustedAccountId) ??
+ accounts.find((item) => item.id === pinnedId) ??
+ accounts[0]);
+ let readings = account
+ ? await readPersisted(agentQuotaService.getLatestReadings(account.id), [])
+ : [];
+ const persisted =
+ account && readings.length ? buildKimiCodePanelSnapshot(account, readings, lastLive) : null;
+ const receivedAt = account?.updatedAt ? new Date(account.updatedAt).getTime() : 0;
+ if (persisted && !options.force && !options.revalidate && Date.now() - receivedAt < REFRESH_MS)
+ return persisted;
+ if (persisted) options.onInterim?.(persisted);
+
+ let live: KimiCodeQuotaSnapshot | null;
+ try {
+ live = source.deviceId
+ ? await agentQuotaService.refreshKimiCodeQuota({
+ env: source.env,
+ deviceId: source.deviceId,
+ ...(options.force ? { force: true } : {}),
+ })
+ : await heterogeneousAgentService.getKimiCodeQuota({
+ env: source.env,
+ ...(options.force ? { force: true } : {}),
+ });
+ } catch (error) {
+ console.error('[kimiCodeQuota:refresh]', error);
+ if (persisted) return persisted;
+ throw error;
+ }
+ if (live?.status === 'ok') lastLive = live;
+ const externalAccountId = live?.identity?.externalAccountId;
+ if (live?.status === 'ok' && externalAccountId) {
+ trustedAccountId = externalAccountId;
+ account = accounts.find((item) => item.externalAccountId === externalAccountId);
+ readings = account
+ ? await readPersisted(agentQuotaService.getLatestReadings(account.id), [])
+ : [];
+ const fresh = live.readings?.filter(
+ (reading) =>
+ !readings.some(
+ (previous) =>
+ previous.limitType === reading.limitType &&
+ previous.scopeKey === reading.scopeKey &&
+ previous.capturedAt >= reading.capturedAt,
+ ),
+ );
+ // Ingest when there are new readings OR a wallet to persist — the wallet
+ // moves independently of the limit windows.
+ if (!source.deviceId && (fresh?.length || live.extraUsage)) {
+ try {
+ account = await agentQuotaService.ingestKimiCodeSnapshot({
+ extraUsage: live.extraUsage,
+ identity: live.identity!,
+ readings: fresh ?? [],
+ });
+ } catch (error) {
+ console.error('[kimiCodeQuota:ingest]', error);
+ }
+ }
+ if (source.deviceId && !account) {
+ account = (await readPersisted(agentQuotaService.listAccounts(), [])).find(
+ (item) => item.provider === 'kimi-code' && item.externalAccountId === externalAccountId,
+ );
+ }
+ if (account)
+ readings = await readPersisted(agentQuotaService.getLatestReadings(account.id), []);
+ } else if (live?.status === 'ok') {
+ // A successful but unidentified login must not inherit the previous account.
+ trustedAccountId = undefined;
+ account = undefined;
+ readings = [];
+ }
+ // A deterministically unavailable login (missing/expired credentials) is a
+ // current fact, not a gap to paper over with stale readings — surface it so
+ // the panel shows the sign-in guidance instead of stale quota.
+ if (live?.status === 'unavailable') return live;
+ if (account && readings.length) return buildKimiCodePanelSnapshot(account, readings, live);
+ return (
+ live ??
+ persisted ?? {
+ error: 'Device is unavailable',
+ extraUsage: null,
+ monthly: null,
+ monthlyCode: null,
+ provider: 'kimi-code',
+ session: null,
+ status: 'error',
+ updatedAt: Date.now(),
+ weekly: null,
+ }
+ );
+ };
+ return Object.assign(readQuota, {
+ acceptLocalSnapshot: async (snapshot: KimiCodeQuotaSnapshot) => {
+ lastLive = snapshot;
+ if (
+ snapshot.status === 'ok' &&
+ snapshot.identity?.externalAccountId &&
+ snapshot.readings?.length
+ ) {
+ trustedAccountId = snapshot.identity.externalAccountId;
+ await agentQuotaService.ingestKimiCodeSnapshot({
+ extraUsage: snapshot.extraUsage,
+ identity: snapshot.identity,
+ readings: snapshot.readings,
+ });
+ }
+ },
+ });
+};
diff --git a/src/services/kimiCodeQuotaViewModel.test.ts b/src/services/kimiCodeQuotaViewModel.test.ts
new file mode 100644
index 00000000000..b0e2e0d0aec
--- /dev/null
+++ b/src/services/kimiCodeQuotaViewModel.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildKimiCodePanelSnapshot } from './kimiCodeQuotaViewModel';
+
+const now = 1_800_000_000_000;
+const account = { externalAccountId: 'a', updatedAt: new Date(now) };
+const reading = {
+ capturedAt: now,
+ limitType: 'session',
+ resetsAt: now + 60000,
+ scopeKey: '',
+ utilization: 23,
+ windowMinutes: 300,
+};
+const live = {
+ error: null,
+ extraUsage: null,
+ identity: { externalAccountId: 'b' },
+ monthly: null,
+ monthlyCode: null,
+ provider: 'kimi-code' as const,
+ readings: [{ ...reading, capturedAt: now + 1, utilization: 90 }],
+ session: null,
+ status: 'ok' as const,
+ updatedAt: now + 1,
+ weekly: null,
+};
+
+describe('Kimi Code account view', () => {
+ it('never merges quota from another account', () => {
+ expect(buildKimiCodePanelSnapshot(account, [reading], live, now).session?.usedPercent).toBe(23);
+ });
+ it('merges newer live buckets only for the same account', () => {
+ expect(
+ buildKimiCodePanelSnapshot(
+ account,
+ [reading],
+ { ...live, identity: { externalAccountId: 'a' } },
+ now,
+ ).session?.usedPercent,
+ ).toBe(90);
+ });
+ it('preserves persisted windows after a failed refresh', () => {
+ expect(
+ buildKimiCodePanelSnapshot(account, [reading], { ...live, status: 'error' }, now).session
+ ?.usedPercent,
+ ).toBe(23);
+ });
+ it('carries the Extra Usage balance only from a same-account live sample', () => {
+ const extraUsage = {
+ balanceCents: 1234,
+ currency: 'USD',
+ monthlyChargeLimitCents: 5000,
+ monthlyChargeLimitEnabled: true,
+ monthlyUsedCents: 42,
+ totalCents: 2000,
+ };
+ expect(
+ buildKimiCodePanelSnapshot(account, [reading], { ...live, extraUsage }, now).extraUsage,
+ ).toBeNull();
+ expect(
+ buildKimiCodePanelSnapshot(
+ account,
+ [reading],
+ { ...live, extraUsage, identity: { externalAccountId: 'a' } },
+ now,
+ ).extraUsage,
+ ).toEqual(extraUsage);
+ });
+ it('serves the Extra Usage wallet from account metadata between live samples', () => {
+ const extraUsage = {
+ balanceCents: 1234,
+ currency: 'USD',
+ monthlyChargeLimitCents: 5000,
+ monthlyChargeLimitEnabled: true,
+ monthlyUsedCents: 42,
+ totalCents: 2000,
+ };
+ const withWallet = { ...account, metadata: { extraUsage } };
+ // No live sample (fresh mount): the wallet survives from the account row.
+ expect(buildKimiCodePanelSnapshot(withWallet, [reading], null, now).extraUsage).toEqual(
+ extraUsage,
+ );
+ // An identity-matched live sample still wins over the persisted wallet.
+ const fresherWallet = { ...extraUsage, balanceCents: 999 };
+ expect(
+ buildKimiCodePanelSnapshot(
+ withWallet,
+ [reading],
+ { ...live, extraUsage: fresherWallet, identity: { externalAccountId: 'a' } },
+ now,
+ ).extraUsage,
+ ).toEqual(fresherWallet);
+ });
+ it('rebuilds all four windows from persisted readings', () => {
+ const readings = [
+ reading,
+ { ...reading, limitType: 'weekly_all', utilization: 40, windowMinutes: 10_080 },
+ { ...reading, limitType: 'month_total', utilization: 55, windowMinutes: 43_200 },
+ { ...reading, limitType: 'month_code', utilization: 61, windowMinutes: 43_200 },
+ ];
+ const snapshot = buildKimiCodePanelSnapshot(account, readings, null, now);
+ expect(snapshot.session?.usedPercent).toBe(23);
+ expect(snapshot.weekly?.usedPercent).toBe(40);
+ expect(snapshot.monthly?.usedPercent).toBe(55);
+ expect(snapshot.monthlyCode?.usedPercent).toBe(61);
+ });
+});
diff --git a/src/services/kimiCodeQuotaViewModel.ts b/src/services/kimiCodeQuotaViewModel.ts
new file mode 100644
index 00000000000..31eed76f95d
--- /dev/null
+++ b/src/services/kimiCodeQuotaViewModel.ts
@@ -0,0 +1,64 @@
+import type {
+ KimiCodeExtraUsage,
+ KimiCodeQuotaSnapshot,
+ QuotaAccountIdentity,
+ QuotaLimitReading,
+} from '@lobechat/heterogeneous-agents/quota';
+import {
+ buildKimiCodeQuotaWindows,
+ kimiCodeQuotaReadings,
+} from '@lobechat/heterogeneous-agents/quota';
+
+export const buildKimiCodePanelSnapshot = (
+ account: {
+ externalAccountId?: string | null;
+ metadata?: Record<string, unknown> | null;
+ updatedAt?: Date | string | null;
+ },
+ persisted: QuotaLimitReading[],
+ live: KimiCodeQuotaSnapshot | null,
+ now = Date.now(),
+): KimiCodeQuotaSnapshot => {
+ const sample =
+ live?.status === 'ok' && live.identity?.externalAccountId === account.externalAccountId
+ ? live
+ : null;
+ const liveReadings =
+ sample?.readings ??
+ (sample
+ ? kimiCodeQuotaReadings(
+ {
+ monthly: sample.monthly,
+ monthlyCode: sample.monthlyCode,
+ session: sample.session,
+ weekly: sample.weekly,
+ },
+ sample.updatedAt,
+ )
+ : []);
+ const windows = buildKimiCodeQuotaWindows([...persisted, ...liveReadings], now);
+ const identity: QuotaAccountIdentity = {
+ externalAccountId: account.externalAccountId ?? undefined,
+ };
+ // The wallet belongs to this account row (ingest writes it there), so it is
+ // safe to serve without an identity-matched live sample — unlike a wallet
+ // borrowed from another account's live sample.
+ const persistedExtraUsage =
+ (account.metadata?.['extraUsage'] as KimiCodeExtraUsage | null | undefined) ?? null;
+ return {
+ error: null,
+ extraUsage: sample?.extraUsage ?? persistedExtraUsage,
+ identity,
+ monthly: windows.monthly,
+ monthlyCode: windows.monthlyCode,
+ provider: 'kimi-code',
+ session: windows.session,
+ status: 'ok',
+ updatedAt:
+ Math.max(
+ account.updatedAt ? new Date(account.updatedAt).getTime() : 0,
+ sample?.updatedAt ?? 0,
+ ) || now,
+ weekly: windows.weekly,
+ };
+};