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(quota): sample Claude Code quota from bound devices with 2-minute refresh (#17797)

Arvin Xu9990347f885f
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
index 9be24442b33..d17bbd7fdd7 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
@@ -35,6 +35,13 @@ import {
buildHeteroExecStdinPayload,
buildHeterogeneousPrompt,
} from '@lobechat/heterogeneous-agents/protocol';
+import {
+ CLAUDE_CODE_QUOTA_FRESH_MS,
+ createQuotaCacheKey,
+ fetchClaudeCodeQuota,
+ QuotaSnapshotCache,
+ readClaudeCodeIdentity,
+} from '@lobechat/heterogeneous-agents/quota-sampler';
import type { AgentStreamEvent, UsageData } from '@lobechat/heterogeneous-agents/spawn';
import {
AgentStreamPipeline,
@@ -58,19 +65,11 @@ import { detectHeterogeneousCliCommand } from '@/modules/binaries';
import { resolveCliScript } from '@/modules/cliEmbedding';
import { getHeterogeneousAgentDriver } from '@/modules/heterogeneousAgent';
import { buildBrowserMcpTools } from '@/modules/heterogeneousAgent/browserMcpTools';
-import {
- fetchClaudeCodeQuota,
- readClaudeCodeIdentity,
-} from '@/modules/heterogeneousAgent/claudeCodeQuota';
import {
consumeCodexRateLimitResetCredit as consumeCodexRateLimitResetCreditRequest,
fetchCodexQuota,
} from '@/modules/heterogeneousAgent/codexQuota';
import { createLambdaFileStorePort } from '@/modules/heterogeneousAgent/fileStorePort';
-import {
- createQuotaCacheKey,
- QuotaSnapshotCache,
-} from '@/modules/heterogeneousAgent/quotaSnapshotCache';
import type {
HeterogeneousAgentBuildPlan,
HeterogeneousAgentImageAttachment,
@@ -350,7 +349,11 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
/** Lazy single MCP server, started on first claude-code prompt. */
private builtinMcpServer?: LobeBuiltinMcpServer;
private builtinMcpStartPromise?: Promise<LobeBuiltinMcpServer>;
- private readonly claudeCodeQuotaCache = new QuotaSnapshotCache<ClaudeCodeQuotaSnapshot>();
+ // Fresh window sits under the renderer's 2-minute auto-refresh so each
+ // scheduled poll reaches the usage API instead of a cache echo.
+ private readonly claudeCodeQuotaCache = new QuotaSnapshotCache<ClaudeCodeQuotaSnapshot>({
+ freshMs: CLAUDE_CODE_QUOTA_FRESH_MS,
+ });
private readonly codexQuotaCache = new QuotaSnapshotCache<CodexQuotaSnapshot>();
private get remoteServerConfigCtr() {
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.ts
index b778594bc87..fb5896e8c15 100644
--- a/apps/server/src/routers/lambda/device.ts
+++ b/apps/server/src/routers/lambda/device.ts
@@ -269,6 +269,30 @@ export const deviceRouter = router({
return result ?? null;
}),
+ /**
+ * Claude Code subscription quota sampled by the device with its own local
+ * credentials, so web clients can show live quota for a bound-device run.
+ * `null` when the device is offline or its client predates this RPC.
+ */
+ getClaudeCodeQuota: deviceProcedure
+ .input(
+ z.object({
+ deviceId: z.string(),
+ env: z.record(z.string(), z.string()).optional(),
+ force: z.boolean().optional(),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ const result = await deviceGateway.claudeCodeQuota({
+ deviceId: input.deviceId,
+ env: input.env,
+ force: input.force,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ return result ?? null;
+ }),
+
/** Query OpenCode's model catalog on the device that will execute the agent. */
listHeterogeneousAgentModels: deviceProcedure
.input(
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index 2b0c0daa8a1..b99af00fa59 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -10,6 +10,7 @@ import {
type GatewayMcpParams,
} from '@lobechat/device-gateway-client';
import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
+import type { ClaudeCodeQuotaSnapshot } from '@lobechat/heterogeneous-agents/quota';
import type {
DeviceGitAddWorktreeResult,
DeviceGitAheadBehind,
@@ -352,11 +353,12 @@ export class DeviceGateway {
}
/**
- * Generic helper for the granular git read RPCs (branch / PR / working-tree /
- * ahead-behind). Returns `undefined` when the gateway is unconfigured, the
- * device is offline, or the call fails — callers treat that as "unknown".
+ * Generic helper for granular device read RPCs (git branch / PR /
+ * working-tree / ahead-behind / Claude quota). Returns `undefined` when the
+ * gateway is unconfigured, the device is offline, or the call fails —
+ * callers treat that as "unknown".
*/
- private async invokeGitRead<T>(
+ private async invokeDeviceRead<T>(
method: string,
params: { deviceId: string; timeout?: number; userId: string; workspaceId?: string },
rpcParams: Record<string, unknown>,
@@ -385,7 +387,9 @@ export class DeviceGateway {
/** Branch name + detached flag for a directory on a remote device. */
gitBranch(params: { deviceId: string; path: string; userId: string; workspaceId?: string }) {
- return this.invokeGitRead<DeviceGitBranchInfo>('getGitBranch', params, { path: params.path });
+ return this.invokeDeviceRead<DeviceGitBranchInfo>('getGitBranch', params, {
+ path: params.path,
+ });
}
/** The GitHub PR linked to a branch in a directory on a remote device. */
@@ -397,7 +401,7 @@ export class DeviceGateway {
userId: string;
workspaceId?: string;
}) {
- return this.invokeGitRead<DeviceGitLinkedPullRequestResult>('getLinkedPullRequest', params, {
+ return this.invokeDeviceRead<DeviceGitLinkedPullRequestResult>('getLinkedPullRequest', params, {
branch: params.branch,
path: params.path,
pullRequestNumber: params.pullRequestNumber,
@@ -411,18 +415,37 @@ export class DeviceGateway {
userId: string;
workspaceId?: string;
}) {
- return this.invokeGitRead<DeviceGitWorkingTreeStatus>('getGitWorkingTreeStatus', params, {
+ return this.invokeDeviceRead<DeviceGitWorkingTreeStatus>('getGitWorkingTreeStatus', params, {
path: params.path,
});
}
/** Ahead/behind commit counts for a directory on a remote device. */
gitAheadBehind(params: { deviceId: string; path: string; userId: string; workspaceId?: string }) {
- return this.invokeGitRead<DeviceGitAheadBehind>('getGitAheadBehind', params, {
+ return this.invokeDeviceRead<DeviceGitAheadBehind>('getGitAheadBehind', params, {
path: params.path,
});
}
+ /**
+ * Claude Code subscription quota of the login on a remote device. The device
+ * samples the Anthropic usage API with its local credentials — same sampler
+ * as the desktop IPC path. `undefined` also covers older device clients that
+ * don't know this RPC yet.
+ */
+ claudeCodeQuota(params: {
+ deviceId: string;
+ env?: Record<string, string>;
+ force?: boolean;
+ userId: string;
+ workspaceId?: string;
+ }) {
+ return this.invokeDeviceRead<ClaudeCodeQuotaSnapshot>('getClaudeCodeQuota', 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;
@@ -430,7 +453,7 @@ export class DeviceGateway {
userId: string;
workspaceId?: string;
}) {
- return this.invokeGitRead<DeviceGitWorktreeListItem[]>('listGitWorktrees', params, {
+ return this.invokeDeviceRead<DeviceGitWorktreeListItem[]>('listGitWorktrees', params, {
path: params.path,
});
}
diff --git a/packages/device-control/package.json b/packages/device-control/package.json
index b41f4bf6891..76f59ffc5ef 100644
--- a/packages/device-control/package.json
+++ b/packages/device-control/package.json
@@ -14,6 +14,7 @@
"test:coverage": "bunx vitest run --coverage"
},
"dependencies": {
+ "@lobechat/heterogeneous-agents": "workspace:*",
"@lobechat/local-file-shell": "workspace:*",
"@lobechat/utils": "workspace:*",
"fast-glob": "^3.3.3",
diff --git a/packages/device-control/src/claudeCodeQuota.ts b/packages/device-control/src/claudeCodeQuota.ts
new file mode 100644
index 00000000000..a8f4b453315
--- /dev/null
+++ b/packages/device-control/src/claudeCodeQuota.ts
@@ -0,0 +1,35 @@
+import type { ClaudeCodeQuotaSnapshot } from '@lobechat/heterogeneous-agents/quota';
+import {
+ CLAUDE_CODE_QUOTA_FRESH_MS,
+ createQuotaCacheKey,
+ fetchClaudeCodeQuota,
+ QuotaSnapshotCache,
+} from '@lobechat/heterogeneous-agents/quota-sampler';
+
+export interface GetClaudeCodeQuotaParams {
+ /** Agent-configured env overrides (external-auth detection, CLAUDE_CONFIG_DIR). */
+ 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<ClaudeCodeQuotaSnapshot>({
+ freshMs: CLAUDE_CODE_QUOTA_FRESH_MS,
+});
+
+/**
+ * Sample the Claude Code subscription quota of the login on THIS device, for
+ * the `getClaudeCodeQuota` device RPC. Same sampler as the desktop IPC path:
+ * credentials from Keychain / config dir, snapshot from the Anthropic OAuth
+ * usage API — no CLI spawned.
+ */
+export const getClaudeCodeQuota = (
+ params: GetClaudeCodeQuotaParams = {},
+): Promise<ClaudeCodeQuotaSnapshot> =>
+ quotaCache.get(
+ createQuotaCacheKey('claude-code', params.env),
+ () => fetchClaudeCodeQuota({ env: params.env }),
+ { force: params.force },
+ );
diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.ts
index 5c391fd30b6..8a34a2d915a 100644
--- a/packages/device-control/src/dispatch.ts
+++ b/packages/device-control/src/dispatch.ts
@@ -22,6 +22,7 @@ import {
writeLocalFile,
} from '@lobechat/local-file-shell';
+import { getClaudeCodeQuota, type GetClaudeCodeQuotaParams } from './claudeCodeQuota';
import { prepareSkillDirectory } from './skillDirectory';
import type {
DeviceControlDeps,
@@ -48,6 +49,7 @@ export const DEVICE_RPC_METHODS = [
'unenrollWorkspace',
'initWorkspace',
'listHeterogeneousAgentModels',
+ 'getClaudeCodeQuota',
'listProjectSkills',
'prepareSkillDirectory',
'statPath',
@@ -122,6 +124,10 @@ export const executeDeviceRpc = async (
return deps.listHeterogeneousAgentModels(params as ListHeterogeneousAgentModelsParams);
}
+ case 'getClaudeCodeQuota': {
+ return getClaudeCodeQuota(params as GetClaudeCodeQuotaParams);
+ }
+
case 'listProjectSkills': {
return listProjectSkills(params as ListProjectSkillsParams, deps);
}
diff --git a/packages/electron-client-ipc/package.json b/packages/electron-client-ipc/package.json
index 7a5cc17d7e4..6e749ad10a8 100644
--- a/packages/electron-client-ipc/package.json
+++ b/packages/electron-client-ipc/package.json
@@ -5,6 +5,7 @@
"main": "src/index.ts",
"types": "src/index.ts",
"dependencies": {
+ "@lobechat/heterogeneous-agents": "workspace:*",
"sf-symbols-typescript": "^2.2.0"
},
"devDependencies": {
diff --git a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
index 3dd2dfabc85..f2e71cc1314 100644
--- a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
+++ b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
@@ -1,3 +1,5 @@
+import type { HeteroQuotaWindow } from '@lobechat/heterogeneous-agents/quota';
+
import type { HeterogeneousCliAgentType } from './binary';
export const AMP_CLI_INSTALL_DOCS_URL = 'https://ampcode.com/manual';
@@ -50,11 +52,17 @@ export interface HeterogeneousAgentRateLimitInfo {
status?: string;
}
-export interface HeteroQuotaWindow {
- resetsAt: number | null;
- usedPercent: number;
- windowMinutes: number;
-}
+// The Claude quota snapshot shapes are shared with the device RPC path
+// (`lh connect` samples the same snapshot), so they live in the
+// heterogeneous-agents quota entry; re-export them for existing IPC callers.
+export type {
+ ClaudeCodeAccountIdentity,
+ ClaudeCodeQuotaReading,
+ ClaudeCodeQuotaSnapshot,
+ ClaudeCodeQuotaUnavailableReason,
+ ClaudeCodeScopedWeekly,
+ HeteroQuotaWindow,
+} from '@lobechat/heterogeneous-agents/quota';
export type CodexQuotaWindow = HeteroQuotaWindow;
@@ -106,57 +114,6 @@ export interface CodexRateLimitResetResult {
quota: CodexQuotaSnapshot;
}
-/**
- * Why the quota can't be shown. `external-auth` means the agent is configured
- * with an API key / custom base url, so subscription quota does not apply;
- * the credential reasons mean no fresh OAuth login was found on this machine.
- */
-export type ClaudeCodeQuotaUnavailableReason =
- 'credentials-expired' | 'credentials-not-found' | 'external-auth';
-
-export interface ClaudeCodeScopedWeekly {
- /** Display name of the model the window is scoped to, e.g. "Fable". */
- modelName: string;
- window: HeteroQuotaWindow;
-}
-
-/** Account identity resolved from the local CLI config, for DB persistence. */
-export interface ClaudeCodeAccountIdentity {
- displayName?: string;
- email?: string;
- externalAccountId?: string;
- organizationId?: string;
- planTier?: string;
- rateLimitTier?: string;
-}
-
-/** One raw limit reading, for fossilizing into the quota data layer. */
-export interface ClaudeCodeQuotaReading {
- capturedAt: number;
- isActive?: boolean;
- limitType: string;
- resetsAt: number | null;
- scopeKey: string;
- severity?: string;
- utilization: number;
-}
-
-export interface ClaudeCodeQuotaSnapshot {
- error: string | null;
- /** Present when `status === 'ok'` and the local config carries an account. */
- identity?: ClaudeCodeAccountIdentity | null;
- provider: 'claude-code';
- /** Flat limit readings for DB persistence (mirrors `session`/`weekly`/scoped). */
- readings?: ClaudeCodeQuotaReading[];
- reason?: ClaudeCodeQuotaUnavailableReason;
- /** Model-scoped weekly window (e.g. Fable/Opus), when the plan reports one. */
- scopedWeekly: ClaudeCodeScopedWeekly | null;
- session: HeteroQuotaWindow | null;
- status: 'error' | 'ok' | 'unavailable';
- updatedAt: number;
- weekly: HeteroQuotaWindow | null;
-}
-
export interface HeterogeneousAgentSessionError {
agentType?: HeterogeneousCliAgentType;
code?: HeterogeneousAgentSessionErrorCode | string;
diff --git a/packages/heterogeneous-agents/package.json b/packages/heterogeneous-agents/package.json
index 30055fbf4fb..d9b78692257 100644
--- a/packages/heterogeneous-agents/package.json
+++ b/packages/heterogeneous-agents/package.json
@@ -11,6 +11,7 @@
"./models": "./src/models/index.ts",
"./protocol": "./src/protocol/index.ts",
"./quota": "./src/quota/index.ts",
+ "./quota-sampler": "./src/quota-sampler/index.ts",
"./resolveCliCommand": "./src/spawn/resolveCliCommand.ts",
"./scanHost": "./src/scan/scanHost.ts",
"./spawn": "./src/spawn/index.ts",
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeQuota.test.ts b/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.test.ts
similarity index 100%
rename from apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeQuota.test.ts
rename to packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.test.ts
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeQuota.ts b/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.ts
similarity index 94%
rename from apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeQuota.ts
rename to packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.ts
index 1cf6e8942c2..5a2055b5a09 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeQuota.ts
+++ b/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.ts
@@ -3,16 +3,22 @@ import { readFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import path from 'node:path';
+import { parseClaudeAccountIdentity } from '../quota/identity';
import type {
ClaudeCodeQuotaSnapshot,
ClaudeCodeQuotaUnavailableReason,
ClaudeCodeScopedWeekly,
HeteroQuotaWindow,
-} from '@lobechat/electron-client-ipc';
-import {
- mapClaudeUsageToReadings,
- parseClaudeAccountIdentity,
-} from '@lobechat/heterogeneous-agents/quota';
+} from '../quota/snapshot';
+import { mapClaudeUsageToReadings } from '../quota/usageApi';
+
+/**
+ * How long a sampler host's snapshot cache may serve a Claude quota reading
+ * without re-hitting the usage API. Kept just under the UI's 2-minute
+ * auto-refresh cadence so every scheduled poll observes fresh data, while
+ * bursts (multiple renderers / rapid re-mounts) still coalesce.
+ */
+export const CLAUDE_CODE_QUOTA_FRESH_MS = 90_000;
const OAUTH_USAGE_URL = 'https://api.anthropic.com/api/oauth/usage';
// The usage endpoint is the Claude Code `/usage` API; it requires the CLI's
@@ -60,7 +66,12 @@ const effectiveRoutingFlag = (
export interface FetchClaudeCodeQuotaOptions {
claudeConfigDirPath?: string | null;
- env?: NodeJS.ProcessEnv;
+ /**
+ * 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>;
}
interface ClaudeOAuthCredentials {
diff --git a/packages/heterogeneous-agents/src/quota-sampler/index.ts b/packages/heterogeneous-agents/src/quota-sampler/index.ts
new file mode 100644
index 00000000000..ea7c7d18d4e
--- /dev/null
+++ b/packages/heterogeneous-agents/src/quota-sampler/index.ts
@@ -0,0 +1,2 @@
+export * from './claudeCodeQuota';
+export * from './snapshotCache';
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/quotaSnapshotCache.test.ts b/packages/heterogeneous-agents/src/quota-sampler/snapshotCache.test.ts
similarity index 98%
rename from apps/desktop/src/main/modules/heterogeneousAgent/quotaSnapshotCache.test.ts
rename to packages/heterogeneous-agents/src/quota-sampler/snapshotCache.test.ts
index 2fb347de1b7..bcdc089399e 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/quotaSnapshotCache.test.ts
+++ b/packages/heterogeneous-agents/src/quota-sampler/snapshotCache.test.ts
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { createQuotaCacheKey, QuotaSnapshotCache } from './quotaSnapshotCache';
+import { createQuotaCacheKey, QuotaSnapshotCache } from './snapshotCache';
interface TestQuotaSnapshot {
error: string | null;
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/quotaSnapshotCache.ts b/packages/heterogeneous-agents/src/quota-sampler/snapshotCache.ts
similarity index 100%
rename from apps/desktop/src/main/modules/heterogeneousAgent/quotaSnapshotCache.ts
rename to packages/heterogeneous-agents/src/quota-sampler/snapshotCache.ts
diff --git a/packages/heterogeneous-agents/src/quota/index.ts b/packages/heterogeneous-agents/src/quota/index.ts
index 8705c77e86f..375efd6f58e 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 './cost';
export * from './identity';
export * from './loadBalancer';
+export * from './snapshot';
export * from './types';
export * from './usageApi';
export * from './windows';
diff --git a/packages/heterogeneous-agents/src/quota/snapshot.ts b/packages/heterogeneous-agents/src/quota/snapshot.ts
new file mode 100644
index 00000000000..3b28b91cefc
--- /dev/null
+++ b/packages/heterogeneous-agents/src/quota/snapshot.ts
@@ -0,0 +1,49 @@
+import type { QuotaAccountIdentity, QuotaLimitReading } from './types';
+
+/**
+ * Provider-quota snapshot shapes shared by every sampler host: the desktop
+ * main process (IPC), connected devices (`lh connect` RPC), and the web client
+ * that renders them. Pure types — the Node-only fetch lives in
+ * `../quota-sampler`.
+ */
+export interface HeteroQuotaWindow {
+ resetsAt: number | null;
+ usedPercent: number;
+ windowMinutes: number;
+}
+
+/**
+ * Why the quota can't be shown. `external-auth` means the agent is configured
+ * with an API key / custom base url, so subscription quota does not apply;
+ * the credential reasons mean no fresh OAuth login was found on this machine.
+ */
+export type ClaudeCodeQuotaUnavailableReason =
+ 'credentials-expired' | 'credentials-not-found' | 'external-auth';
+
+export interface ClaudeCodeScopedWeekly {
+ /** Display name of the model the window is scoped to, e.g. "Fable". */
+ modelName: string;
+ window: HeteroQuotaWindow;
+}
+
+/** Account identity resolved from the local CLI config, for DB persistence. */
+export type ClaudeCodeAccountIdentity = QuotaAccountIdentity;
+
+/** One raw limit reading, for fossilizing into the quota data layer. */
+export type ClaudeCodeQuotaReading = QuotaLimitReading;
+
+export interface ClaudeCodeQuotaSnapshot {
+ error: string | null;
+ /** Present when `status === 'ok'` and the local config carries an account. */
+ identity?: ClaudeCodeAccountIdentity | null;
+ provider: 'claude-code';
+ /** Flat limit readings for DB persistence (mirrors `session`/`weekly`/scoped). */
+ readings?: ClaudeCodeQuotaReading[];
+ reason?: ClaudeCodeQuotaUnavailableReason;
+ /** Model-scoped weekly window (e.g. Fable/Opus), when the plan reports one. */
+ scopedWeekly: ClaudeCodeScopedWeekly | null;
+ session: HeteroQuotaWindow | null;
+ status: 'error' | 'ok' | 'unavailable';
+ updatedAt: number;
+ weekly: HeteroQuotaWindow | null;
+}
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx
index da9dae03cd2..c1e695b6077 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx
@@ -135,6 +135,20 @@ const HeteroControlBar = memo(() => {
// so the quota badges gate on where THIS member's run actually executes.
const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId);
+ const heteroProvider = agencyConfig?.heterogeneousProvider;
+ const executionTarget = resolveExecutionTarget(agencyConfig, {
+ clientExecutionAvailable: isDesktop,
+ isHetero: !!heteroProvider,
+ workspaceScoped,
+ });
+ const isLocalHeteroExecution = executionTarget === 'local';
+ // An explicit bound device (including web's device-upgraded "local" pick)
+ // samples quota through the gateway; `auto` has no concrete device to ask
+ // and the cloud sandbox has no sampler, so both stay quota-less.
+ const quotaDeviceId = executionTarget === 'device' ? agencyConfig?.boundDeviceId : undefined;
+ const shouldShowClaudeQuota =
+ heteroProvider?.type === 'claude-code' && (isLocalHeteroExecution || !!quotaDeviceId);
+
if (isAccessLoading) return null;
// A can-use collaborator may choose only their execution device; working
@@ -148,17 +162,23 @@ const HeteroControlBar = memo(() => {
);
}
- // On web there's no full-access badge / skeleton — just the workspace controls
- // (the cloud repo switcher is rendered inside WorkspaceControls). The CLI
- // model + thinking-effort selector now lives in the input's bottom-left action
- // bar (see HeterogeneousChatInput), not in this strip.
+ // On web there's no full-access badge / skeleton — just the workspace
+ // controls (the cloud repo switcher is rendered inside WorkspaceControls)
+ // plus the Claude quota badge when the run executes on a bound device that
+ // can sample it. The CLI model + thinking-effort selector now lives in the
+ // input's bottom-left action bar (see HeterogeneousChatInput), not here.
if (!isDesktop) {
if (!agentId) return null;
return (
- <Flexbox horizontal align={'center'} className={styles.bar}>
+ <Flexbox horizontal align={'center'} className={styles.bar} justify={'space-between'}>
<Flexbox horizontal align={'center'} className={styles.leftGroup} gap={4}>
<WorkspaceControls alwaysShowWorkspace agentId={agentId} />
</Flexbox>
+ {shouldShowClaudeQuota && quotaDeviceId && (
+ <Flexbox horizontal align={'center'} className={styles.rightGroup} gap={4}>
+ <ClaudeCodeQuotaMenu deviceId={quotaDeviceId} env={heteroProvider?.env} />
+ </Flexbox>
+ )}
</Flexbox>
);
}
@@ -178,17 +198,13 @@ const HeteroControlBar = memo(() => {
<span className={styles.fullAccessLabel}>{tChat('heteroAgent.fullAccess.label')}</span>
</div>
);
- const heteroProvider = agencyConfig?.heterogeneousProvider;
- const isLocalHeteroExecution =
- resolveExecutionTarget(agencyConfig, {
- clientExecutionAvailable: isDesktop,
- isHetero: true,
- workspaceScoped,
- }) === 'local';
+ // Codex quota still needs the local CLI (spawned over IPC), so it stays
+ // desktop-local; the SDK runtime badge likewise reports this desktop's own
+ // in-process runtime, not a remote device's.
const shouldShowCodexQuota = heteroProvider?.type === 'codex' && isLocalHeteroExecution;
- const shouldShowClaudeQuota = heteroProvider?.type === 'claude-code' && isLocalHeteroExecution;
const shouldShowSdkRuntime =
- shouldShowClaudeQuota &&
+ heteroProvider?.type === 'claude-code' &&
+ isLocalHeteroExecution &&
runtimeStatus?.transport === 'claude-sdk' &&
visibleSdkRuntimeStates.has(runtimeStatus.state);
const sdkRuntimeClassName =
@@ -234,7 +250,9 @@ const HeteroControlBar = memo(() => {
{shouldShowCodexQuota && (
<CodexQuotaMenu command={heteroProvider?.command} env={heteroProvider?.env} />
)}
- {shouldShowClaudeQuota && <ClaudeCodeQuotaMenu env={heteroProvider?.env} />}
+ {shouldShowClaudeQuota && (
+ <ClaudeCodeQuotaMenu deviceId={quotaDeviceId} env={heteroProvider?.env} />
+ )}
{sdkRuntimeBadge}
<Tooltip title={tChat('heteroAgent.fullAccess.tooltip')}>{fullAccessBadge}</Tooltip>
</Flexbox>
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/ClaudeCodeQuotaMenu.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/ClaudeCodeQuotaMenu.tsx
index bb8de1be95c..a2570d2ea23 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/ClaudeCodeQuotaMenu.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/ClaudeCodeQuotaMenu.tsx
@@ -1,25 +1,26 @@
'use client';
import type { ClaudeCodeQuotaSnapshot } from '@lobechat/electron-client-ipc';
-import { memo, useCallback } from 'react';
+import { memo, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
import { agentQuotaService } from '@/services/agentQuota';
-import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';
+import { fetchClaudeCodeQuotaSnapshot } from '@/services/heteroAgentQuota';
import QuotaAccountSwitcher from './QuotaAccountSwitcher';
import type { FetchQuotaOptions, QuotaWindowItem } from './QuotaMenu';
import QuotaMenu, { createQuotaSourceKey } from './QuotaMenu';
-import { buildClaudeSnapshotFromWindows, isQuotaStale } from './quotaViewModel';
+import { buildClaudeSnapshotFromWindows, isQuotaStale, newestSeenAt } from './quotaViewModel';
/**
- * Only hit the live Anthropic usage API when the persisted data is this stale.
- * Kept low-frequency (1h) — the panel reads from our DB, so it stays instant and
- * fresh-enough without hammering the rate-limited usage endpoint. A manual
- * refresh always forces a live fetch.
+ * Hit the live Anthropic usage API when the newest persisted reading is this
+ * stale, and auto-refresh on the same cadence so the badge stays near-live.
+ * The sampler-side snapshot cache (90 s fresh window in the desktop main
+ * process / device host) is what actually protects the rate-limited usage
+ * endpoint.
*/
-const QUOTA_REFRESH_MS = 60 * 60 * 1000;
+const QUOTA_REFRESH_MS = 2 * 60 * 1000;
const createErrorSnapshot = (error: unknown): ClaudeCodeQuotaSnapshot => ({
error: error instanceof Error ? error.message : String(error),
@@ -47,56 +48,100 @@ const unavailableSnapshot = (
const isRateLimitError = (quota: ClaudeCodeQuotaSnapshot) => quota.error?.includes('429') ?? false;
interface ClaudeCodeQuotaMenuProps {
+ /** Bound execution device to sample instead of the local desktop login. */
+ deviceId?: string;
env?: Record<string, string>;
}
-const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ env }) => {
+const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) => {
const { t } = useTranslation('chat');
const agentId = useAgentId();
- const sourceKey = createQuotaSourceKey('claude-code', env);
+ const sourceKey = createQuotaSourceKey('claude-code', deviceId ?? 'local', env);
+ // A persisted account becomes eligible for a device only after this mounted
+ // menu has observed that device return the same external account identity.
+ // This avoids painting another machine's pinned/first account on a device
+ // switch while still preserving last-known-good data after later failures.
+ const trustedDeviceAccountsRef = useRef(new Map<string, string>());
/**
- * DB-first: render the persisted windows from our own database, and only fall
- * back to the live Anthropic usage API to refresh + ingest when the newest
- * persisted reading is older than QUOTA_REFRESH_MS (or the user forces it). So
- * the panel shows data instantly and survives a failing live fetch.
+ * DB-first: render the persisted windows from our own database, and go to the
+ * live Anthropic usage API to refresh + ingest when the newest persisted
+ * reading is older than QUOTA_REFRESH_MS, the caller revalidates (focus /
+ * popover open), or the user forces it. The persisted snapshot paints first
+ * through onInterim, so the panel shows data instantly and survives a failing
+ * live fetch.
*/
const fetchQuota = useCallback(
- async (options?: FetchQuotaOptions): Promise<ClaudeCodeQuotaSnapshot> => {
+ async (
+ options?: FetchQuotaOptions<ClaudeCodeQuotaSnapshot>,
+ ): Promise<ClaudeCodeQuotaSnapshot> => {
const force = !!options?.force;
// 1) Resolve the account to display — pinned for this agent, else the first.
- let accounts = await agentQuotaService.listAccounts().catch(() => []);
+ const [initialAccounts, bindings] = await Promise.all([
+ agentQuotaService.listAccounts().catch(() => []),
+ agentId ? agentQuotaService.listBindings(agentId).catch(() => []) : [],
+ ]);
+ let accounts = initialAccounts;
let claude = accounts.filter((a) => a.provider === 'claude-code');
- let pinnedId: string | undefined;
- if (agentId) {
- const bindings = await agentQuotaService.listBindings(agentId).catch(() => []);
- pinnedId = bindings.find((b) => b.role === 'pinned')?.accountId;
- }
- let account = claude.find((a) => a.id === pinnedId) ?? claude[0];
+ const pinnedId = bindings.find((b) => b.role === 'pinned')?.accountId;
+ const trustedExternalAccountId = deviceId
+ ? trustedDeviceAccountsRef.current.get(deviceId)
+ : undefined;
+ let account = deviceId
+ ? claude.find((a) => a.externalAccountId === trustedExternalAccountId)
+ : (claude.find((a) => a.id === pinnedId) ?? claude[0]);
let windows = account ? await agentQuotaService.getWindows(account.id).catch(() => []) : [];
- // 2) Throttled live refresh + ingest.
+ // 2) Throttled live refresh + ingest. Paint the persisted windows before
+ // awaiting the live fetch so the panel never blocks on it.
let live: ClaudeCodeQuotaSnapshot | null = null;
- if (force || isQuotaStale(windows, Date.now(), QUOTA_REFRESH_MS)) {
- live = await heterogeneousAgentService
- .getClaudeCodeQuota({ env, ...(force ? { force: true } : {}) })
- .catch(() => null);
+ if (
+ force ||
+ options?.revalidate ||
+ (deviceId && !trustedExternalAccountId) ||
+ isQuotaStale(account?.updatedAt, Date.now(), QUOTA_REFRESH_MS)
+ ) {
+ if (account && windows.length > 0) {
+ options?.onInterim?.(buildClaudeSnapshotFromWindows(account, windows));
+ }
+ live = await fetchClaudeCodeQuotaSnapshot({ deviceId, env, force }).catch(() => null);
const externalAccountId = live?.identity?.externalAccountId;
if (live?.status === 'ok' && externalAccountId && live.readings?.length) {
- await agentQuotaService
- .ingestClaudeSnapshot({ identity: live.identity!, readings: live.readings })
- .catch(() => {});
- accounts = await agentQuotaService.listAccounts().catch(() => accounts);
- claude = accounts.filter((a) => a.provider === 'claude-code');
- account =
- claude.find((a) => a.externalAccountId === externalAccountId) ??
- claude.find((a) => a.id === pinnedId) ??
- claude[0];
- windows = account
- ? await agentQuotaService.getWindows(account.id).catch(() => windows)
- : windows;
+ if (deviceId) trustedDeviceAccountsRef.current.set(deviceId, externalAccountId);
+
+ // A revalidation inside the main-process cache's fresh window gets the
+ // readings we already persisted echoed back (same capturedAt).
+ // Snapshots are append-only, so re-ingesting an echo would duplicate
+ // history rows and rerun calibration without new evidence — skip it.
+ const newestCapturedAt = live.readings.reduce((max, r) => Math.max(max, r.capturedAt), 0);
+ const matchingAccount = claude.find(
+ (candidate) => candidate.externalAccountId === externalAccountId,
+ );
+ const matchingWindows = matchingAccount
+ ? await agentQuotaService.getWindows(matchingAccount.id).catch(() => [])
+ : [];
+ const isCachedEcho =
+ !!matchingAccount && newestCapturedAt <= newestSeenAt(matchingWindows);
+
+ if (!isCachedEcho) {
+ await agentQuotaService
+ .ingestClaudeSnapshot({ deviceId, identity: live.identity!, readings: live.readings })
+ .catch(() => {});
+ accounts = await agentQuotaService.listAccounts().catch(() => accounts);
+ claude = accounts.filter((a) => a.provider === 'claude-code');
+ account =
+ claude.find((a) => a.externalAccountId === externalAccountId) ??
+ claude.find((a) => a.id === pinnedId) ??
+ claude[0];
+ windows = account
+ ? await agentQuotaService.getWindows(account.id).catch(() => windows)
+ : windows;
+ } else {
+ account = matchingAccount;
+ windows = matchingWindows;
+ }
}
}
@@ -108,7 +153,7 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ env }) => {
if (account && windows.length > 0) return buildClaudeSnapshotFromWindows(account, windows);
return live ?? unavailableSnapshot();
},
- [env, agentId],
+ [deviceId, env, agentId],
);
const getWindows = useCallback(
@@ -183,6 +228,7 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ env }) => {
return (
<QuotaMenu
+ autoRefreshMs={QUOTA_REFRESH_MS}
createErrorSnapshot={createErrorSnapshot}
fetchQuota={fetchQuota}
getErrorText={getErrorText}
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/CodexQuotaMenu.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/CodexQuotaMenu.tsx
index b4f4fc25b27..9b02831adab 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/CodexQuotaMenu.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/CodexQuotaMenu.tsx
@@ -142,7 +142,7 @@ const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, env }) => {
}, [sourceKey]);
const fetchQuota = useCallback(
- (options?: FetchQuotaOptions) =>
+ (options?: FetchQuotaOptions<CodexQuotaSnapshot>) =>
heterogeneousAgentService.getCodexQuota({
command,
env,
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.test.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.test.tsx
index 2fbd43d1852..4499672798f 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.test.tsx
@@ -86,6 +86,14 @@ vi.mock('@/services/electron/heterogeneousAgent', () => ({
heterogeneousAgentService: mockService,
}));
+// A `deviceId` routes the live sample through the device gateway TRPC instead
+// of Electron IPC (see `fetchClaudeCodeQuotaSnapshot`).
+const mockLambdaDeviceQuota = vi.hoisted(() => vi.fn());
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: { device: { getClaudeCodeQuota: { query: mockLambdaDeviceQuota } } },
+}));
+
// The menu reads persisted quota through TRPC before falling back to the live
// IPC fetch. Default to "nothing persisted yet" so these cases exercise the live
// path without each one stalling on a real HTTP request; individual tests can
@@ -190,6 +198,34 @@ const claudeSnapshot = (
...overrides,
});
+const persistedAccount = (updatedAt = Date.now()) => ({
+ externalAccountId: 'ext-1',
+ id: 'acc-1',
+ provider: 'claude-code',
+ updatedAt: new Date(updatedAt),
+});
+
+/** A persisted `agent_quota_windows` row whose newest reading is `lastSeenAt`. */
+const persistedSessionWindow = (lastSeenAt: number) => ({
+ lastSeenAt: new Date(lastSeenAt),
+ lastUtilization: 8,
+ limitType: 'session',
+ peakUtilization: 8,
+ resetsAt: null,
+ scopeKey: '',
+ windowSeconds: 300 * 60,
+});
+
+/** A live session reading as fossilized by the desktop sampler at `capturedAt`. */
+const liveSessionReading = (capturedAt: number) => ({
+ capturedAt,
+ isActive: true,
+ limitType: 'session',
+ resetsAt: null,
+ scopeKey: '',
+ utilization: 8,
+});
+
const codexSnapshot = (
overrides: Partial<ElectronClientIpcModule.CodexQuotaSnapshot> = {},
): ElectronClientIpcModule.CodexQuotaSnapshot => ({
@@ -217,6 +253,7 @@ beforeEach(() => {
toastErrorMock.mockReset();
toastSuccessMock.mockReset();
mockQuotaService.getWindows.mockResolvedValue([]);
+ mockQuotaService.ingestClaudeSnapshot.mockClear();
mockQuotaService.listAccounts.mockResolvedValue([]);
mockQuotaService.listBindings.mockResolvedValue([]);
});
@@ -550,6 +587,220 @@ describe('ClaudeCodeQuotaMenu', () => {
expect(await screen.findByText('heteroAgent.quota.noData')).toBeTruthy();
});
+
+ it('renders persisted windows without a live call while the newest reading is fresh', async () => {
+ mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 60_000)]);
+ mockQuotaService.getWindows.mockResolvedValue([persistedSessionWindow(Date.now() - 60_000)]);
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('92%')).toBeTruthy();
+ expect(mockService.getClaudeCodeQuota).not.toHaveBeenCalled();
+ });
+
+ it('refreshes from the live API when the newest persisted reading is stale', async () => {
+ // Under the previous 30 min policy this 31-minute-old reading is a
+ // conservative stale case; the gate now trips at 2 minutes.
+ mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 31 * 60_000)]);
+ mockQuotaService.getWindows.mockResolvedValue([
+ persistedSessionWindow(Date.now() - 31 * 60_000),
+ ]);
+ mockService.getClaudeCodeQuota.mockResolvedValue(claudeSnapshot());
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('92%')).toBeTruthy();
+ await waitFor(() =>
+ expect(mockService.getClaudeCodeQuota).toHaveBeenCalledWith({ env: undefined }),
+ );
+ });
+
+ it('paints persisted windows while a stale live refresh is still in flight', async () => {
+ mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 31 * 60_000)]);
+ mockQuotaService.getWindows.mockResolvedValue([
+ persistedSessionWindow(Date.now() - 31 * 60_000),
+ ]);
+ const requests: Array<(snapshot: ElectronClientIpcModule.ClaudeCodeQuotaSnapshot) => void> = [];
+ mockService.getClaudeCodeQuota.mockImplementation(
+ () =>
+ new Promise<ElectronClientIpcModule.ClaudeCodeQuotaSnapshot>((resolve) => {
+ requests.push(resolve);
+ }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ // The persisted snapshot lands before the live promise resolves — no skeleton.
+ expect(await screen.findByText('92%')).toBeTruthy();
+ expect(screen.queryByTestId('skeleton')).toBeNull();
+ expect((screen.getByTestId('refresh') as HTMLButtonElement).disabled).toBe(true);
+
+ await act(async () => {
+ requests[0](claudeSnapshot());
+ });
+
+ expect(screen.getByText('92%')).toBeTruthy();
+ expect((screen.getByTestId('refresh') as HTMLButtonElement).disabled).toBe(false);
+ });
+
+ it('revalidates against the live API when the window regains focus', async () => {
+ // 90 s: fresh for the mount gate (2 min) but past the focus gate (60 s).
+ mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 90_000)]);
+ mockQuotaService.getWindows.mockResolvedValue([persistedSessionWindow(Date.now() - 90_000)]);
+ mockService.getClaudeCodeQuota.mockResolvedValue(claudeSnapshot());
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ // Fresh persisted data: nothing hits the live API on mount…
+ expect(await screen.findByText('92%')).toBeTruthy();
+ expect(mockService.getClaudeCodeQuota).not.toHaveBeenCalled();
+
+ // …but regaining focus revalidates (the main-process cache rate-limits it).
+ await act(async () => {
+ window.dispatchEvent(new Event('focus'));
+ });
+
+ await waitFor(() => expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(1));
+ expect(mockService.getClaudeCodeQuota).toHaveBeenCalledWith({ env: undefined });
+ });
+
+ it('samples through the device gateway RPC when a deviceId is provided', async () => {
+ mockLambdaDeviceQuota.mockResolvedValue(
+ claudeSnapshot({ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 } }),
+ );
+
+ render(<ClaudeCodeQuotaMenu deviceId="remote-device" />);
+
+ await waitFor(() =>
+ expect(mockLambdaDeviceQuota).toHaveBeenCalledWith({
+ deviceId: 'remote-device',
+ env: undefined,
+ }),
+ );
+ expect(await screen.findByText('92%')).toBeTruthy();
+ expect(mockService.getClaudeCodeQuota).not.toHaveBeenCalled();
+ });
+
+ it('does not reuse another device account when the newly selected device is unavailable', async () => {
+ const capturedAt = Date.now();
+ const account = persistedAccount();
+ mockQuotaService.listAccounts.mockResolvedValue([account]);
+ mockQuotaService.getWindows.mockResolvedValue([persistedSessionWindow(capturedAt)]);
+ mockLambdaDeviceQuota.mockResolvedValueOnce(
+ claudeSnapshot({
+ identity: { externalAccountId: 'ext-1' },
+ readings: [liveSessionReading(capturedAt)],
+ }),
+ );
+
+ const { rerender } = render(<ClaudeCodeQuotaMenu deviceId="device-a" />);
+ expect(await screen.findByText('92%')).toBeTruthy();
+
+ mockLambdaDeviceQuota.mockResolvedValueOnce(null);
+ rerender(<ClaudeCodeQuotaMenu deviceId="device-b" />);
+
+ await waitFor(() =>
+ expect(mockLambdaDeviceQuota).toHaveBeenLastCalledWith({
+ deviceId: 'device-b',
+ env: undefined,
+ }),
+ );
+ await waitFor(() => expect(screen.queryByText('92%')).toBeNull());
+ });
+
+ it('auto-refreshes on the poll cadence while the tab stays visible', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ try {
+ mockQuotaService.listAccounts.mockResolvedValue([persistedAccount()]);
+ mockQuotaService.getWindows.mockResolvedValue([persistedSessionWindow(Date.now() - 60_000)]);
+ mockService.getClaudeCodeQuota.mockResolvedValue(claudeSnapshot());
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ // Fresh persisted data: nothing hits the live API on mount…
+ expect(await screen.findByText('92%')).toBeTruthy();
+ expect(mockService.getClaudeCodeQuota).not.toHaveBeenCalled();
+
+ // …but once the 2-minute cadence elapses the snapshot is stale and the
+ // scheduled poll revalidates against the live API.
+ await act(async () => {
+ vi.advanceTimersByTime(2 * 60_000 + 500);
+ });
+
+ await waitFor(() => expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(1));
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('does not re-ingest a cached live snapshot echoed back during revalidation', async () => {
+ // The sampler cache stays fresh for 90 s, so a focus revalidation can get
+ // the already-persisted readings back (same capturedAt). Snapshots are
+ // append-only — re-ingesting the echo would duplicate history rows.
+ // 90 s: fresh for the mount gate (2 min) but past the focus gate (60 s).
+ const persistedAt = Date.now() - 90_000;
+ mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 90_000)]);
+ mockQuotaService.getWindows.mockResolvedValue([persistedSessionWindow(persistedAt)]);
+ mockService.getClaudeCodeQuota.mockResolvedValue(
+ claudeSnapshot({
+ identity: { externalAccountId: 'ext-1' },
+ readings: [liveSessionReading(persistedAt)],
+ }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('92%')).toBeTruthy();
+
+ await act(async () => {
+ window.dispatchEvent(new Event('focus'));
+ });
+
+ await waitFor(() => expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(1));
+ expect(mockQuotaService.ingestClaudeSnapshot).not.toHaveBeenCalled();
+ });
+
+ it('ingests genuinely fresh readings surfaced by a revalidation', async () => {
+ const persistedAt = Date.now() - 90_000;
+ mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 90_000)]);
+ mockQuotaService.getWindows.mockResolvedValue([persistedSessionWindow(persistedAt)]);
+ const readings = [liveSessionReading(Date.now())];
+ mockService.getClaudeCodeQuota.mockResolvedValue(
+ claudeSnapshot({ identity: { externalAccountId: 'ext-1' }, readings }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('92%')).toBeTruthy();
+
+ await act(async () => {
+ window.dispatchEvent(new Event('focus'));
+ });
+
+ await waitFor(() =>
+ expect(mockQuotaService.ingestClaudeSnapshot).toHaveBeenCalledWith({
+ deviceId: undefined,
+ identity: { externalAccountId: 'ext-1' },
+ readings,
+ }),
+ );
+ });
+
+ it('skips the focus revalidation while the snapshot is under a minute old', async () => {
+ mockService.getClaudeCodeQuota.mockResolvedValue(
+ claudeSnapshot({ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 } }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('92%')).toBeTruthy();
+
+ await act(async () => {
+ window.dispatchEvent(new Event('focus'));
+ });
+
+ expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(1);
+ });
});
describe('CodexQuotaMenu', () => {
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.tsx
index ec5dd9a6a77..849b719c5ca 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.tsx
@@ -187,14 +187,31 @@ export interface QuotaMenuHelpers<S> {
now: number;
}
-export interface FetchQuotaOptions {
+export interface FetchQuotaOptions<S = unknown> {
force?: boolean;
+ /**
+ * Paint an intermediate snapshot (e.g. persisted DB data) immediately while
+ * a slower live refresh keeps running; the promise result stays authoritative.
+ */
+ onInterim?: (quota: S) => void;
+ /**
+ * Check the live source even when the local staleness gate would skip it
+ * (focus / popover revalidation). Unlike `force`, upstream snapshot caches
+ * may still answer from their fresh window.
+ */
+ revalidate?: boolean;
}
interface QuotaMenuProps<S extends QuotaSnapshotBase> {
+ /**
+ * Revalidate on this cadence while the tab is visible, so the badge stays
+ * near-live without user interaction. Upstream sampler caches must keep
+ * their fresh window below this for each poll to observe new data.
+ */
+ autoRefreshMs?: number;
contentWidth?: number;
createErrorSnapshot: (error: unknown) => S;
- fetchQuota: (options?: FetchQuotaOptions) => Promise<S>;
+ fetchQuota: (options?: FetchQuotaOptions<S>) => Promise<S>;
/** Localized explanation for `status: 'error'`; falls back to `error`. */
getErrorText?: (quota: S) => string | undefined;
/** Localized explanation for a manual refresh error when stale data is preserved. */
@@ -214,6 +231,7 @@ interface QuotaMenuProps<S extends QuotaSnapshotBase> {
interface LoadQuotaOptions {
manual?: boolean;
+ revalidate?: boolean;
}
/**
@@ -222,6 +240,7 @@ interface LoadQuotaOptions {
* reset countdowns. Agent specifics come in through the props.
*/
const QuotaMenu = <S extends QuotaSnapshotBase>({
+ autoRefreshMs,
contentWidth,
createErrorSnapshot,
fetchQuota,
@@ -317,7 +336,16 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
setLoading(true);
try {
- const nextQuota = await fetchQuota(options.manual ? { force: true } : undefined);
+ const nextQuota = await fetchQuota({
+ ...(options.manual ? { force: true } : {}),
+ ...(options.revalidate ? { revalidate: true } : {}),
+ onInterim: (interimQuota) => {
+ // Progressive paint: show the fast (persisted) snapshot while the
+ // live refresh continues; requestId still guards stale sources.
+ if (!isCurrentRequest(requestId, requestSourceKey)) return;
+ setQuotaSnapshot(interimQuota);
+ },
+ });
applyQuotaResult(nextQuota, options, requestId, requestSourceKey);
} catch (error) {
console.error('Failed to fetch agent quota:', error);
@@ -328,7 +356,7 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
}
}
},
- [applyQuotaResult, createErrorSnapshot, fetchQuota, isCurrentRequest],
+ [applyQuotaResult, createErrorSnapshot, fetchQuota, isCurrentRequest, setQuotaSnapshot],
);
useEffect(() => {
@@ -351,6 +379,60 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
};
}, []);
+ // Scheduled auto-refresh: quota burns down while the user just watches the
+ // agent work, so poll on the configured cadence whenever the tab is visible.
+ // Each tick re-checks staleness and the transient-error cooldown, and the
+ // sampler-side snapshot cache still coalesces concurrent pollers.
+ useEffect(() => {
+ if (!autoRefreshMs) return;
+
+ const interval = window.setInterval(() => {
+ if (document.visibilityState === 'hidden' || loading) return;
+
+ const currentTime = Date.now();
+ const recentlyFailed =
+ lastTransientErrorAtRef.current > 0 &&
+ currentTime - lastTransientErrorAtRef.current < QUOTA_RETRY_COOLDOWN_MS;
+
+ if (recentlyFailed) return;
+ if (quota && currentTime - quota.updatedAt < autoRefreshMs) return;
+
+ void loadQuota({ revalidate: true });
+ }, autoRefreshMs);
+
+ return () => {
+ window.clearInterval(interval);
+ };
+ }, [autoRefreshMs, loadQuota, loading, quota]);
+
+ // Revalidate when the window regains focus: the user may have burned quota
+ // elsewhere (another device, a terminal CLI session) meanwhile. Upstream
+ // snapshot caches (90 s fresh window + error cooldown in the sampler host)
+ // keep this from hammering the rate-limited live endpoints.
+ useEffect(() => {
+ const revalidateOnFocus = () => {
+ if (document.visibilityState === 'hidden' || loading) return;
+
+ const currentTime = Date.now();
+ const recentlyFailed =
+ lastTransientErrorAtRef.current > 0 &&
+ currentTime - lastTransientErrorAtRef.current < QUOTA_RETRY_COOLDOWN_MS;
+
+ if (recentlyFailed) return;
+ if (quota && currentTime - quota.updatedAt <= QUOTA_STALE_MS) return;
+
+ void loadQuota({ revalidate: true });
+ };
+
+ window.addEventListener('focus', revalidateOnFocus);
+ document.addEventListener('visibilitychange', revalidateOnFocus);
+
+ return () => {
+ window.removeEventListener('focus', revalidateOnFocus);
+ document.removeEventListener('visibilitychange', revalidateOnFocus);
+ };
+ }, [loadQuota, loading, quota]);
+
const formatDuration = useCallback(
(ms: number) => {
if (ms <= 0) return;
@@ -421,7 +503,7 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
currentTime - lastTransientErrorAtRef.current < QUOTA_RETRY_COOLDOWN_MS;
if ((!quota || currentTime - quota.updatedAt > QUOTA_STALE_MS) && !recentlyFailed) {
- void loadQuota();
+ void loadQuota({ revalidate: true });
}
},
[loadQuota, loading, quota],
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.test.ts b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.test.ts
index b9253485f81..f9b6ece2d85 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.test.ts
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.test.ts
@@ -12,6 +12,7 @@ const account = {
externalAccountId: '48bfd5c6',
planTier: 'max',
rateLimitTier: 'default_claude_max_20x',
+ updatedAt: new Date('2026-07-18T08:01:00Z'),
};
const windows: QuotaWindowRow[] = [
@@ -108,27 +109,27 @@ describe('buildClaudeSnapshotFromWindows', () => {
describe('isQuotaStale', () => {
const now = Date.parse('2026-07-18T09:00:00Z');
- const fresh: QuotaWindowRow = {
- lastSeenAt: new Date('2026-07-18T08:57:00Z'),
- lastUtilization: 10,
- limitType: 'session',
- peakUtilization: 10,
- resetsAt: reset,
- scopeKey: '',
- windowSeconds: 18_000,
- };
- it('is stale with no windows', () => {
- expect(isQuotaStale([], now, 5 * 60_000)).toBe(true);
+ it('is stale with no receipt time', () => {
+ expect(isQuotaStale(undefined, now, 5 * 60_000)).toBe(true);
});
- it('is fresh when newest reading is within maxAge', () => {
- expect(isQuotaStale([fresh], now, 5 * 60_000)).toBe(false);
+ it('is fresh when the server receipt is within maxAge', () => {
+ expect(isQuotaStale(new Date('2026-07-18T08:57:00Z'), now, 5 * 60_000)).toBe(false);
});
- it('is stale when newest reading is older than maxAge', () => {
- expect(
- isQuotaStale([{ ...fresh, lastSeenAt: new Date('2026-07-18T08:50:00Z') }], now, 5 * 60_000),
- ).toBe(true);
+ it('is stale when the server receipt is older than maxAge', () => {
+ expect(isQuotaStale(new Date('2026-07-18T08:50:00Z'), now, 5 * 60_000)).toBe(true);
+ });
+
+ it('ignores device clock skew when building display freshness', () => {
+ const deviceClockAhead = [{ ...windows[0], lastSeenAt: new Date('2026-07-19T09:00:00Z') }];
+ const snap = buildClaudeSnapshotFromWindows(
+ { ...account, updatedAt: new Date('2026-07-18T08:50:00Z') },
+ deviceClockAhead,
+ );
+
+ expect(snap.updatedAt).toBe(Date.parse('2026-07-18T08:50:00Z'));
+ expect(isQuotaStale(new Date(snap.updatedAt), now, 5 * 60_000)).toBe(true);
});
});
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.ts b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.ts
index 071cae3fe8e..7fa96c2696d 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.ts
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.ts
@@ -26,6 +26,7 @@ export interface QuotaAccountRow {
organizationId?: string | null;
planTier?: string | null;
rateLimitTier?: string | null;
+ updatedAt?: Date | string | null;
}
const toMs = (v: Date | string | null | undefined): number | null => {
@@ -70,7 +71,11 @@ export const buildClaudeSnapshotFromWindows = (
const weekly = windows.find(isWeeklyAll);
const scoped = windows.find((w) => w.limitType === 'weekly_scoped' && !!w.scopeKey);
- const updatedAt = windows.reduce((max, w) => Math.max(max, toMs(w.lastSeenAt) ?? 0), 0);
+ // Freshness is based on when our server received the snapshot, not on the
+ // sampling device's wall clock. Device timestamps remain on the windows for
+ // history and cached-echo detection, but clock skew must not suppress or
+ // accelerate browser refreshes.
+ const updatedAt = toMs(account.updatedAt) ?? 0;
return {
error: null,
@@ -84,9 +89,21 @@ export const buildClaudeSnapshotFromWindows = (
};
};
-/** Whether the newest persisted reading is older than `maxAgeMs`. */
-export const isQuotaStale = (windows: QuotaWindowRow[], now: number, maxAgeMs: number): boolean => {
- if (windows.length === 0) return true;
- const newest = windows.reduce((max, w) => Math.max(max, toMs(w.lastSeenAt) ?? 0), 0);
- return newest === 0 || now - newest > maxAgeMs;
+/**
+ * Newest persisted reading time across the windows (0 when none). `lastSeenAt`
+ * is written from the readings' `capturedAt`, so this compares 1:1 against a
+ * live snapshot's `capturedAt` values — both stamped by the desktop main
+ * process.
+ */
+export const newestSeenAt = (windows: QuotaWindowRow[]): number =>
+ windows.reduce((max, w) => Math.max(max, toMs(w.lastSeenAt) ?? 0), 0);
+
+/** Whether the server receipt time is older than `maxAgeMs`. */
+export const isQuotaStale = (
+ receivedAt: Date | string | null | undefined,
+ now: number,
+ maxAgeMs: number,
+): boolean => {
+ const receivedAtMs = toMs(receivedAt);
+ return receivedAtMs === null || now - receivedAtMs > maxAgeMs;
};
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
index 4052df0b56f..0c8ce0b2374 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
@@ -113,7 +113,8 @@ const HeterogeneousChatInput = memo(() => {
executionTarget === 'none';
// OpenCode can discover models on an explicit bound device; Claude Code and
- // Codex retain their existing local/sandbox-only selector behavior.
+ // Codex show the selector on every execution path (local / sandbox / device)
+ // since dispatch forwards --model/--effort everywhere.
const isSelectableHeteroProvider =
providerType === 'claude-code' || providerType === 'codex' || providerType === 'opencode';
const showHeteroModel =
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.test.ts b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.test.ts
index bd6299c5059..d3bee5c8967 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.test.ts
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.test.ts
@@ -22,33 +22,33 @@ describe('shouldShowHeteroModelSelector', () => {
).toBe(true);
});
- it('hides for explicit device runs because connected devices do not advertise selector args yet', () => {
+ it('shows for explicit device runs because dispatch forwards --model/--effort to the device', () => {
expect(
shouldShowHeteroModelSelector({
boundDeviceId: 'remote-device',
executionTarget: 'device',
isDesktopClient: false,
}),
- ).toBe(false);
+ ).toBe(true);
});
- it('hides for desktop-local selections opened from web because they dispatch to the bound device', () => {
+ it('shows for desktop-local selections opened from web (device dispatch forwards selector args)', () => {
expect(
shouldShowHeteroModelSelector({
boundDeviceId: 'desktop-device',
executionTarget: 'local',
isDesktopClient: false,
}),
- ).toBe(false);
+ ).toBe(true);
});
- it('hides for auto device routing because selector args are not forwarded there', () => {
+ it('shows for auto device routing because the auto-resolved device dispatch carries selector args', () => {
expect(
shouldShowHeteroModelSelector({
executionTarget: 'auto',
isDesktopClient: false,
}),
- ).toBe(false);
+ ).toBe(true);
});
it('shows OpenCode models for desktop-local execution', () => {
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.ts b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.ts
index a534a9fc06b..e4b7c202189 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.ts
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/shouldShowHeteroModelSelector.ts
@@ -13,17 +13,18 @@ export const shouldShowHeteroModelSelector = ({
isDesktopClient,
providerType,
}: ShouldShowHeteroModelSelectorParams): boolean => {
+ // OpenCode has no cloud-side model list — its selector needs a concrete
+ // runtime to discover models from: the desktop itself, or an explicit bound
+ // device that answers listHeterogeneousAgentModels.
if (providerType === 'opencode') {
if (executionTarget === 'local') return isDesktopClient;
return executionTarget === 'device' && !!boundDeviceId;
}
- if (executionTarget === 'auto' || executionTarget === 'device') return false;
-
- // A desktop "local" selection stores that desktop's connected-device id so
- // web clients can route back to the same machine. On web this is a device
- // dispatch, and selector args are not capability-gated for devices yet.
- if (!isDesktopClient && executionTarget === 'local' && boundDeviceId) return false;
-
+ // Claude Code / Codex model + effort picks are forwarded on every execution
+ // path: the desktop local spawn, the cloud sandbox, and device dispatch
+ // (explicit `device`, `auto` routing, and web-initiated runs on a bound
+ // desktop) all append `buildHeteroExecArgs` output to `lh hetero exec` — so
+ // the selector is always shown.
return true;
};
diff --git a/src/services/agentQuota.ts b/src/services/agentQuota.ts
index 760b3d0f1dc..be3d7405a96 100644
--- a/src/services/agentQuota.ts
+++ b/src/services/agentQuota.ts
@@ -13,10 +13,12 @@ import { lambdaClient } from '@/libs/trpc/client';
class AgentQuotaService {
/** Persist a live Claude snapshot (identity + readings) captured over IPC. */
ingestClaudeSnapshot = async (params: {
+ deviceId?: string;
identity: ClaudeCodeAccountIdentity;
readings: ClaudeCodeQuotaReading[];
}) =>
lambdaClient.agentQuota.ingestSnapshot.mutate({
+ deviceId: params.deviceId,
identity: params.identity,
provider: 'claude-code',
readings: params.readings.map((r) => ({ ...r, scopeKey: r.scopeKey ?? '' })),
diff --git a/src/services/heteroAgentQuota.ts b/src/services/heteroAgentQuota.ts
new file mode 100644
index 00000000000..3b442a4eaa6
--- /dev/null
+++ b/src/services/heteroAgentQuota.ts
@@ -0,0 +1,31 @@
+import type { ClaudeCodeQuotaSnapshot } from '@lobechat/electron-client-ipc';
+
+import { lambdaClient } from '@/libs/trpc/client';
+import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';
+
+export interface FetchClaudeCodeQuotaSnapshotParams {
+ /** Sample on this bound execution device via the gateway instead of local IPC. */
+ deviceId?: string;
+ env?: Record<string, string>;
+ force?: boolean;
+}
+
+/**
+ * Claude quota transport chokepoint, mirroring `GitService`: with a `deviceId`
+ * the bound execution device samples its own login through the
+ * `device.getClaudeCodeQuota` TRPC RPC; without one the local desktop samples
+ * over Electron IPC. `null` means the device is offline or its client predates
+ * the quota RPC — callers fall back to persisted windows.
+ */
+export const fetchClaudeCodeQuotaSnapshot = ({
+ deviceId,
+ env,
+ force,
+}: FetchClaudeCodeQuotaSnapshotParams): Promise<ClaudeCodeQuotaSnapshot | null> =>
+ deviceId
+ ? lambdaClient.device.getClaudeCodeQuota.query({
+ deviceId,
+ env,
+ ...(force ? { force: true } : {}),
+ })
+ : heterogeneousAgentService.getClaudeCodeQuota({ env, ...(force ? { force: true } : {}) });