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(hetero-agent): add Claude Code quota menu to chat input (#16669)

AmAzing-e12c00bfcaa1
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
index 86205183263..43754519e6e 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
@@ -9,6 +9,7 @@ import type { Readable, Writable } from 'node:stream';
import { finished as streamFinished } from 'node:stream/promises';
import type {
+ ClaudeCodeQuotaSnapshot,
CodexQuotaSnapshot,
HeterogeneousAgentSessionError,
} from '@lobechat/electron-client-ipc';
@@ -41,6 +42,7 @@ import { app as electronApp, BrowserWindow } from 'electron';
import { HETERO_AGENT_FILES_DIR, HETERO_AGENT_TRACING_DIR } from '@/const/heteroAgent';
import { detectHeterogeneousCliCommand } from '@/modules/binaries';
import { getHeterogeneousAgentDriver } from '@/modules/heterogeneousAgent';
+import { fetchClaudeCodeQuota } from '@/modules/heterogeneousAgent/claudeCodeQuota';
import { fetchCodexQuota } from '@/modules/heterogeneousAgent/codexQuota';
import type {
HeterogeneousAgentBuildPlan,
@@ -171,6 +173,10 @@ interface GetCodexQuotaParams {
env?: Record<string, string>;
}
+interface GetClaudeCodeQuotaParams {
+ env?: Record<string, string>;
+}
+
interface SessionInfo {
agentSessionId?: string;
}
@@ -1324,6 +1330,18 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
});
}
+ /**
+ * Read the Claude Code subscription quota. No CLI is spawned: the quota
+ * comes from Anthropic's OAuth usage API using the local `claude` login,
+ * and the request goes through the app's global proxy dispatcher.
+ */
+ @IpcMethod()
+ async getClaudeCodeQuota(
+ params: GetClaudeCodeQuotaParams = {},
+ ): Promise<ClaudeCodeQuotaSnapshot> {
+ return fetchClaudeCodeQuota({ env: params.env });
+ }
+
/**
* Signal the whole process tree spawned by this session.
*
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeQuota.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeQuota.test.ts
new file mode 100644
index 00000000000..59ba7b61e82
--- /dev/null
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeQuota.test.ts
@@ -0,0 +1,407 @@
+import { readFile } from 'node:fs/promises';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { fetchClaudeCodeQuota } from './claudeCodeQuota';
+
+vi.mock('node:fs/promises', () => ({
+ readFile: vi.fn(),
+}));
+
+const execFileMock = vi.hoisted(() => vi.fn());
+
+vi.mock('node:child_process', () => ({
+ execFile: execFileMock,
+}));
+
+vi.mock('node:os', () => ({
+ homedir: () => '/home/test',
+}));
+
+type ExecFileCallback = (error: Error | null, stdout: string, stderr: string) => void;
+
+const setPlatform = (value: string) => {
+ Object.defineProperty(process, 'platform', { configurable: true, value });
+};
+
+const mockKeychain = (result: string | Error) => {
+ execFileMock.mockImplementation(
+ (_cmd: string, _args: string[], _opts: unknown, callback: ExecFileCallback) => {
+ if (result instanceof Error) callback(result, '', '');
+ else callback(null, `${result}\n`, '');
+ },
+ );
+};
+
+const credentialsJson = (expiresAt: number, accessToken = 'file-token') =>
+ JSON.stringify({ claudeAiOauth: { accessToken, expiresAt, refreshToken: 'refresh' } });
+
+const okUsageResponse = (payload: unknown) =>
+ ({ json: async () => payload, ok: true, status: 200 }) as Response;
+
+const NOW = new Date('2026-07-02T12:00:00Z').getTime();
+const FRESH_EXPIRES_AT = NOW + 60 * 60 * 1000;
+const STALE_EXPIRES_AT = NOW - 60 * 60 * 1000;
+
+describe('fetchClaudeCodeQuota', () => {
+ const originalPlatform = process.platform;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(NOW);
+ vi.stubGlobal('fetch', vi.fn());
+ vi.stubEnv('CLAUDE_CONFIG_DIR', '');
+ vi.mocked(readFile).mockReset();
+ vi.mocked(readFile).mockRejectedValue(new Error('ENOENT'));
+ execFileMock.mockReset();
+ mockKeychain(new Error('keychain unavailable'));
+ });
+
+ afterEach(() => {
+ setPlatform(originalPlatform);
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ });
+
+ it('reports external auth without touching credentials when an Anthropic auth env is set', async () => {
+ const result = await fetchClaudeCodeQuota({ env: { ANTHROPIC_API_KEY: 'sk-test' } });
+
+ expect(result).toMatchObject({
+ provider: 'claude-code',
+ reason: 'external-auth',
+ status: 'unavailable',
+ });
+ expect(result.error).toContain('ANTHROPIC_API_KEY');
+ expect(execFileMock).not.toHaveBeenCalled();
+ expect(readFile).not.toHaveBeenCalled();
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it('reports external auth for third-party routing flags like Bedrock', async () => {
+ const result = await fetchClaudeCodeQuota({ env: { CLAUDE_CODE_USE_BEDROCK: '1' } });
+
+ expect(result).toMatchObject({ reason: 'external-auth', status: 'unavailable' });
+ expect(result.error).toContain('CLAUDE_CODE_USE_BEDROCK');
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it('honors routing flags inherited from the desktop process env', async () => {
+ vi.stubEnv('CLAUDE_CODE_USE_VERTEX', '1');
+
+ const result = await fetchClaudeCodeQuota();
+
+ expect(result).toMatchObject({ reason: 'external-auth', status: 'unavailable' });
+ expect(result.error).toContain('CLAUDE_CODE_USE_VERTEX');
+ });
+
+ it('lets the agent env disable an inherited routing flag', async () => {
+ setPlatform('linux');
+ vi.stubEnv('CLAUDE_CODE_USE_BEDROCK', '1');
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));
+ vi.mocked(fetch).mockResolvedValue(okUsageResponse({ five_hour: { utilization: 10 } }));
+
+ const result = await fetchClaudeCodeQuota({ env: { CLAUDE_CODE_USE_BEDROCK: '0' } });
+
+ expect(result.status).toBe('ok');
+ });
+
+ it('ignores disabled routing flags and falls through to the credential lookup', async () => {
+ setPlatform('linux');
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));
+ vi.mocked(fetch).mockResolvedValue(okUsageResponse({ five_hour: { utilization: 10 } }));
+
+ const result = await fetchClaudeCodeQuota({
+ env: { CLAUDE_CODE_USE_BEDROCK: '0', CLAUDE_CODE_USE_VERTEX: 'false' },
+ });
+
+ expect(result.status).toBe('ok');
+ });
+
+ it('reports missing credentials when neither keychain nor files hold a login', async () => {
+ setPlatform('darwin');
+
+ const result = await fetchClaudeCodeQuota();
+
+ expect(result).toMatchObject({ reason: 'credentials-not-found', status: 'unavailable' });
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it('reports expired credentials instead of refreshing them', async () => {
+ setPlatform('linux');
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(STALE_EXPIRES_AT));
+
+ const result = await fetchClaudeCodeQuota();
+
+ expect(result).toMatchObject({ reason: 'credentials-expired', status: 'unavailable' });
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it('maps usage windows from a keychain login on macOS', async () => {
+ setPlatform('darwin');
+ mockKeychain(
+ JSON.stringify({
+ claudeAiOauth: { accessToken: 'keychain-token', expiresAt: FRESH_EXPIRES_AT },
+ }),
+ );
+ vi.mocked(fetch).mockResolvedValue(
+ okUsageResponse({
+ five_hour: { resets_at: '2026-07-02T14:30:00Z', utilization: 35 },
+ seven_day: { resets_at: '2026-07-08T12:00:00Z', utilization: 62.5 },
+ }),
+ );
+
+ const result = await fetchClaudeCodeQuota();
+
+ expect(result).toMatchObject({
+ error: null,
+ provider: 'claude-code',
+ scopedWeekly: null,
+ session: {
+ resetsAt: Date.parse('2026-07-02T14:30:00Z'),
+ usedPercent: 35,
+ windowMinutes: 300,
+ },
+ status: 'ok',
+ weekly: {
+ resetsAt: Date.parse('2026-07-08T12:00:00Z'),
+ usedPercent: 62.5,
+ windowMinutes: 10_080,
+ },
+ });
+ expect(execFileMock).toHaveBeenCalledWith(
+ 'security',
+ ['find-generic-password', '-s', 'Claude Code-credentials', '-w'],
+ expect.objectContaining({ timeout: expect.any(Number) }),
+ expect.any(Function),
+ );
+ expect(fetch).toHaveBeenCalledWith(
+ 'https://api.anthropic.com/api/oauth/usage',
+ expect.objectContaining({
+ headers: expect.objectContaining({
+ 'Authorization': 'Bearer keychain-token',
+ 'anthropic-beta': 'oauth-2025-04-20',
+ }),
+ signal: expect.any(AbortSignal),
+ }),
+ );
+ });
+
+ it('reads the CLAUDE_CONFIG_DIR profile credentials file and the used_percentage field', async () => {
+ setPlatform('linux');
+ vi.mocked(readFile).mockImplementation(async (file) => {
+ if (file === '/custom/claude/.credentials.json') {
+ return credentialsJson(FRESH_EXPIRES_AT, 'custom-token');
+ }
+ throw new Error('ENOENT');
+ });
+ // resets_at in unix seconds; used_percentage instead of utilization
+ vi.mocked(fetch).mockResolvedValue(
+ okUsageResponse({
+ five_hour: { resets_at: 1_782_741_600, used_percentage: 140 },
+ }),
+ );
+
+ const result = await fetchClaudeCodeQuota({ env: { CLAUDE_CONFIG_DIR: '/custom/claude' } });
+
+ expect(result.status).toBe('ok');
+ // clamped to 100, seconds converted to ms
+ expect(result.session).toEqual({
+ resetsAt: 1_782_741_600 * 1000,
+ usedPercent: 100,
+ windowMinutes: 300,
+ });
+ expect(result.weekly).toBeNull();
+ expect(readFile).toHaveBeenCalledWith('/custom/claude/.credentials.json', 'utf8');
+ expect(fetch).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ headers: expect.objectContaining({ Authorization: 'Bearer custom-token' }),
+ }),
+ );
+ });
+
+ it('prefers the CLAUDE_CONFIG_DIR profile over a fresh default keychain login', async () => {
+ setPlatform('darwin');
+ mockKeychain(
+ JSON.stringify({
+ claudeAiOauth: { accessToken: 'default-account-token', expiresAt: FRESH_EXPIRES_AT },
+ }),
+ );
+ vi.mocked(readFile).mockImplementation(async (file) => {
+ if (file === '/custom/claude/.credentials.json') {
+ return credentialsJson(FRESH_EXPIRES_AT, 'profile-token');
+ }
+ throw new Error('ENOENT');
+ });
+ vi.mocked(fetch).mockResolvedValue(okUsageResponse({ five_hour: { utilization: 10 } }));
+
+ const result = await fetchClaudeCodeQuota({ env: { CLAUDE_CONFIG_DIR: '/custom/claude' } });
+
+ expect(result.status).toBe('ok');
+ // The custom profile's token is used and the default keychain is never consulted.
+ expect(execFileMock).not.toHaveBeenCalled();
+ expect(fetch).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ headers: expect.objectContaining({ Authorization: 'Bearer profile-token' }),
+ }),
+ );
+ });
+
+ it('reports not-found for an unauthenticated CLAUDE_CONFIG_DIR profile instead of falling back', async () => {
+ setPlatform('darwin');
+ mockKeychain(
+ JSON.stringify({
+ claudeAiOauth: { accessToken: 'default-account-token', expiresAt: FRESH_EXPIRES_AT },
+ }),
+ );
+
+ const result = await fetchClaudeCodeQuota({ env: { CLAUDE_CONFIG_DIR: '/custom/claude' } });
+
+ expect(result).toMatchObject({ reason: 'credentials-not-found', status: 'unavailable' });
+ expect(execFileMock).not.toHaveBeenCalled();
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it('prefers a fresh file login over an expired keychain login', async () => {
+ setPlatform('darwin');
+ mockKeychain(
+ JSON.stringify({
+ claudeAiOauth: { accessToken: 'stale-keychain-token', expiresAt: STALE_EXPIRES_AT },
+ }),
+ );
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT, 'fresh-file-token'));
+ vi.mocked(fetch).mockResolvedValue(okUsageResponse({ five_hour: { utilization: 10 } }));
+
+ const result = await fetchClaudeCodeQuota();
+
+ expect(result.status).toBe('ok');
+ expect(fetch).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ headers: expect.objectContaining({ Authorization: 'Bearer fresh-file-token' }),
+ }),
+ );
+ });
+
+ it('maps the model-scoped weekly window from the limits array (real response shape)', async () => {
+ setPlatform('linux');
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));
+ // Trimmed from a real /api/oauth/usage 200 response (2026-07-03).
+ vi.mocked(fetch).mockResolvedValue(
+ okUsageResponse({
+ five_hour: { resets_at: '2026-07-03T12:00:00.241917+00:00', utilization: 5 },
+ limits: [
+ {
+ is_active: false,
+ kind: 'session',
+ percent: 5,
+ resets_at: '2026-07-03T12:00:00.241917+00:00',
+ scope: null,
+ severity: 'normal',
+ },
+ {
+ is_active: false,
+ kind: 'weekly_all',
+ percent: 13,
+ resets_at: '2026-07-06T01:00:00.241941+00:00',
+ scope: null,
+ severity: 'normal',
+ },
+ {
+ is_active: true,
+ kind: 'weekly_scoped',
+ percent: 24,
+ resets_at: '2026-07-06T01:00:00.242225+00:00',
+ scope: { model: { display_name: 'Fable', id: null }, surface: null },
+ severity: 'normal',
+ },
+ ],
+ seven_day: { resets_at: '2026-07-06T01:00:00.241941+00:00', utilization: 13 },
+ seven_day_opus: null,
+ seven_day_sonnet: null,
+ }),
+ );
+
+ const result = await fetchClaudeCodeQuota();
+
+ expect(result).toMatchObject({
+ scopedWeekly: {
+ modelName: 'Fable',
+ window: {
+ resetsAt: Date.parse('2026-07-06T01:00:00.242225+00:00'),
+ usedPercent: 24,
+ windowMinutes: 10_080,
+ },
+ },
+ session: { usedPercent: 5, windowMinutes: 300 },
+ status: 'ok',
+ weekly: { usedPercent: 13, windowMinutes: 10_080 },
+ });
+ });
+
+ it('falls back to legacy fable_weekly fields when limits are absent', async () => {
+ setPlatform('linux');
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));
+ vi.mocked(fetch).mockResolvedValue(
+ okUsageResponse({
+ fable_weekly: { resets_at: '2026-07-08T12:00:00Z', utilization: 80 },
+ five_hour: { utilization: 20 },
+ seven_day: { utilization: 45 },
+ }),
+ );
+
+ const result = await fetchClaudeCodeQuota();
+
+ expect(result.scopedWeekly).toEqual({
+ modelName: 'Fable',
+ window: {
+ resetsAt: Date.parse('2026-07-08T12:00:00Z'),
+ usedPercent: 80,
+ windowMinutes: 10_080,
+ },
+ });
+ });
+
+ it('treats a 401 as an expired login', async () => {
+ setPlatform('linux');
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));
+ vi.mocked(fetch).mockResolvedValue({ ok: false, status: 401 } as Response);
+
+ const result = await fetchClaudeCodeQuota();
+
+ expect(result).toMatchObject({ reason: 'credentials-expired', status: 'unavailable' });
+ expect(result.error).toContain('401');
+ });
+
+ it('surfaces a 429 as a transient error', async () => {
+ setPlatform('linux');
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));
+ vi.mocked(fetch).mockResolvedValue({ ok: false, status: 429 } as Response);
+
+ const result = await fetchClaudeCodeQuota();
+
+ expect(result).toMatchObject({ status: 'error' });
+ expect(result.reason).toBeUndefined();
+ expect(result.error).toContain('429');
+ });
+
+ it('aborts a hanging usage request and reports a timeout', async () => {
+ setPlatform('linux');
+ 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 = fetchClaudeCodeQuota();
+ await vi.advanceTimersByTimeAsync(10_000);
+ const result = await resultPromise;
+
+ expect(result.status).toBe('error');
+ expect(result.error).toContain('timed out');
+ });
+});
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeQuota.ts b/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeQuota.ts
new file mode 100644
index 00000000000..42af4b2f7a3
--- /dev/null
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeQuota.ts
@@ -0,0 +1,351 @@
+import { execFile } from 'node:child_process';
+import { readFile } from 'node:fs/promises';
+import { homedir } from 'node:os';
+import path from 'node:path';
+
+import type {
+ ClaudeCodeQuotaSnapshot,
+ ClaudeCodeQuotaUnavailableReason,
+ ClaudeCodeScopedWeekly,
+ HeteroQuotaWindow,
+} from '@lobechat/electron-client-ipc';
+
+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
+// OAuth beta header and rejects unknown clients, so mirror the CLI contract.
+const OAUTH_BETA_HEADER = 'oauth-2025-04-20';
+const OAUTH_USER_AGENT = 'claude-cli/2.1.198 (external, cli)';
+const USAGE_TIMEOUT_MS = 10_000;
+
+const KEYCHAIN_SERVICE = 'Claude Code-credentials';
+const KEYCHAIN_TIMEOUT_MS = 3000;
+
+// Same trio the session spawn strips from inherited env: when an agent
+// explicitly configures one of these, `claude` runs on API-key/base-url auth
+// and the subscription quota below does not apply to it.
+const EXTERNAL_AUTH_ENV_KEYS = [
+ 'ANTHROPIC_API_KEY',
+ 'ANTHROPIC_AUTH_TOKEN',
+ 'ANTHROPIC_BASE_URL',
+] as const;
+
+// Boolean-ish flags that route Claude Code to a third-party provider
+// (AWS Bedrock / Google Vertex / Mantle), whose quotas are billed there —
+// the Anthropic subscription quota does not apply to those runs either.
+const EXTERNAL_ROUTING_FLAG_ENV_KEYS = [
+ 'CLAUDE_CODE_USE_BEDROCK',
+ 'CLAUDE_CODE_USE_MANTLE',
+ 'CLAUDE_CODE_USE_VERTEX',
+] as const;
+
+// The CLI treats these as booleans, so "0"/"false" must not count as enabled.
+const isRoutingFlagEnabled = (value: string | undefined) =>
+ !!value && !['0', 'false'].includes(value.trim().toLowerCase());
+
+/**
+ * Unlike the API-key trio (stripped from the inherited spawn env, so only the
+ * agent's own env matters), routing flags inherited from the desktop process
+ * DO reach the spawned CLI. Mirror the spawn-env merge: the agent env is
+ * spread last and wins — even to disable an inherited flag — and the process
+ * env fills the gaps.
+ */
+const effectiveRoutingFlag = (
+ options: FetchClaudeCodeQuotaOptions,
+ key: (typeof EXTERNAL_ROUTING_FLAG_ENV_KEYS)[number],
+): string | undefined => (options.env && key in options.env ? options.env[key] : process.env[key]);
+
+export interface FetchClaudeCodeQuotaOptions {
+ claudeConfigDirPath?: string | null;
+ env?: NodeJS.ProcessEnv;
+}
+
+interface ClaudeOAuthCredentials {
+ accessToken: string;
+ /** Unix ms timestamp; absent in older credential formats. */
+ expiresAt?: number;
+}
+
+type CredentialLookup =
+ | { credentials: ClaudeOAuthCredentials; state: 'ok' }
+ | { state: 'expired' }
+ | { state: 'not-found' };
+
+const baseSnapshot = () => ({
+ provider: 'claude-code' as const,
+ scopedWeekly: null,
+ session: null,
+ updatedAt: Date.now(),
+ weekly: null,
+});
+
+const errorSnapshot = (message: string): ClaudeCodeQuotaSnapshot => ({
+ ...baseSnapshot(),
+ error: message,
+ status: 'error',
+});
+
+const unavailableSnapshot = (
+ reason: ClaudeCodeQuotaUnavailableReason,
+ message: string,
+): ClaudeCodeQuotaSnapshot => ({
+ ...baseSnapshot(),
+ error: message,
+ reason,
+ status: 'unavailable',
+});
+
+const parseCredentialsJson = (raw: string): ClaudeOAuthCredentials | null => {
+ try {
+ const parsed = JSON.parse(raw) as {
+ claudeAiOauth?: { accessToken?: unknown; expiresAt?: unknown };
+ };
+ const oauth = parsed?.claudeAiOauth;
+ if (!oauth || typeof oauth.accessToken !== 'string' || !oauth.accessToken) return null;
+
+ return {
+ accessToken: oauth.accessToken,
+ ...(typeof oauth.expiresAt === 'number' && Number.isFinite(oauth.expiresAt)
+ ? { expiresAt: oauth.expiresAt }
+ : {}),
+ };
+ } catch {
+ return null;
+ }
+};
+
+const readKeychainCredentials = async (): Promise<ClaudeOAuthCredentials | null> => {
+ if (process.platform !== 'darwin') return null;
+
+ return new Promise((resolve) => {
+ execFile(
+ 'security',
+ ['find-generic-password', '-s', KEYCHAIN_SERVICE, '-w'],
+ { timeout: KEYCHAIN_TIMEOUT_MS },
+ (error, stdout) => {
+ resolve(error ? null : parseCredentialsJson(stdout.trim()));
+ },
+ );
+ });
+};
+
+const readFileCredentials = async (configDir: string): Promise<ClaudeOAuthCredentials | null> => {
+ try {
+ return parseCredentialsJson(await readFile(path.join(configDir, '.credentials.json'), 'utf8'));
+ } catch {
+ return null;
+ }
+};
+
+const asNonEmpty = (value: string | null | undefined): string | null =>
+ typeof value === 'string' && value.trim().length > 0 ? value : null;
+
+/**
+ * The config dir the spawned CLI would resolve: the explicit option, then the
+ * agent's session env (spread last onto the spawn env, so it wins), then the
+ * env inherited from the desktop process.
+ */
+const resolveExplicitConfigDir = (options: FetchClaudeCodeQuotaOptions): string | null =>
+ asNonEmpty(options.claudeConfigDirPath) ??
+ asNonEmpty(options.env?.CLAUDE_CONFIG_DIR) ??
+ asNonEmpty(process.env.CLAUDE_CONFIG_DIR);
+
+const isExpired = (credentials: ClaudeOAuthCredentials) =>
+ typeof credentials.expiresAt === 'number' && credentials.expiresAt <= Date.now();
+
+/**
+ * Locate the freshest Claude Code OAuth login. Access tokens are short-lived
+ * and only the `claude` CLI may rotate them (refreshing here would race the
+ * CLI's own refresh-token rotation and could log the user out), so an expired
+ * credential is reported as such instead of being refreshed.
+ *
+ * A custom `CLAUDE_CONFIG_DIR` is an isolated CLI profile: `claude` ignores
+ * the default Keychain / `~/.claude` login there (with a fresh default login
+ * and an empty custom dir, `claude auth status` reports logged out). So when
+ * one is configured, only that profile's credentials file is consulted —
+ * falling back to the default login would show another account's quota.
+ */
+const readClaudeOAuthCredentials = async (
+ options: FetchClaudeCodeQuotaOptions,
+): Promise<CredentialLookup> => {
+ const explicitDir = resolveExplicitConfigDir(options);
+ if (explicitDir) {
+ const fromFile = await readFileCredentials(explicitDir);
+ if (!fromFile) return { state: 'not-found' };
+ return isExpired(fromFile) ? { state: 'expired' } : { credentials: fromFile, state: 'ok' };
+ }
+
+ const candidates: ClaudeOAuthCredentials[] = [];
+
+ const fromKeychain = await readKeychainCredentials();
+ if (fromKeychain) candidates.push(fromKeychain);
+
+ const fromDefaultFile = await readFileCredentials(path.join(homedir(), '.claude'));
+ if (fromDefaultFile) candidates.push(fromDefaultFile);
+
+ if (candidates.length === 0) return { state: 'not-found' };
+
+ const fresh = candidates.find((credentials) => !isExpired(credentials));
+ return fresh ? { credentials: fresh, state: 'ok' } : { state: 'expired' };
+};
+
+interface OAuthUsageWindow {
+ resets_at?: number | string;
+ used_percentage?: number;
+ utilization?: number;
+}
+
+interface OAuthUsageLimit {
+ kind?: string;
+ percent?: number;
+ resets_at?: number | string;
+ scope?: { model?: { display_name?: string } } | null;
+}
+
+interface OAuthUsageResponse {
+ fable_seven_day?: OAuthUsageWindow;
+ fable_weekly?: OAuthUsageWindow;
+ five_hour?: OAuthUsageWindow;
+ limits?: OAuthUsageLimit[];
+ seven_day?: OAuthUsageWindow;
+ seven_day_fable?: OAuthUsageWindow;
+}
+
+const parseResetsAt = (value: number | string | undefined): number | null => {
+ if (typeof value === 'number' && Number.isFinite(value)) {
+ return value < 10_000_000_000 ? value * 1000 : value;
+ }
+
+ if (typeof value !== 'string' || !value.trim()) return null;
+
+ const numeric = Number(value);
+ if (Number.isFinite(numeric)) {
+ return numeric < 10_000_000_000 ? numeric * 1000 : numeric;
+ }
+
+ const parsed = Date.parse(value);
+ return Number.isFinite(parsed) ? parsed : null;
+};
+
+const mapUsageWindow = (
+ raw: OAuthUsageWindow | undefined,
+ windowMinutes: number,
+): HeteroQuotaWindow | null => {
+ const usedPercent =
+ typeof raw?.utilization === 'number' && Number.isFinite(raw.utilization)
+ ? raw.utilization
+ : typeof raw?.used_percentage === 'number' && Number.isFinite(raw.used_percentage)
+ ? raw.used_percentage
+ : null;
+
+ if (usedPercent === null) return null;
+
+ return {
+ resetsAt: parseResetsAt(raw?.resets_at),
+ usedPercent: Math.min(100, Math.max(0, usedPercent)),
+ windowMinutes,
+ };
+};
+
+/**
+ * Model-scoped weekly windows (e.g. the Fable weekly meter) are reported in
+ * the `limits` array as `kind: 'weekly_scoped'` with the model display name in
+ * `scope`, not as a top-level window field. Older deployments exposed a
+ * `fable_*` top-level window instead, so keep those as a fallback.
+ */
+const mapScopedWeekly = (payload: OAuthUsageResponse): ClaudeCodeScopedWeekly | null => {
+ const scoped = payload.limits?.find(
+ (limit) =>
+ limit?.kind === 'weekly_scoped' &&
+ typeof limit.percent === 'number' &&
+ Number.isFinite(limit.percent) &&
+ typeof limit.scope?.model?.display_name === 'string' &&
+ limit.scope.model.display_name.length > 0,
+ );
+
+ if (scoped) {
+ return {
+ modelName: scoped.scope!.model!.display_name!,
+ window: {
+ resetsAt: parseResetsAt(scoped.resets_at),
+ usedPercent: Math.min(100, Math.max(0, scoped.percent!)),
+ windowMinutes: 10_080,
+ },
+ };
+ }
+
+ const fableWindow = mapUsageWindow(
+ payload.fable_weekly ?? payload.fable_seven_day ?? payload.seven_day_fable,
+ 10_080,
+ );
+ return fableWindow ? { modelName: 'Fable', window: fableWindow } : null;
+};
+
+export const fetchClaudeCodeQuota = async (
+ options: FetchClaudeCodeQuotaOptions = {},
+): Promise<ClaudeCodeQuotaSnapshot> => {
+ const externalAuthKey =
+ EXTERNAL_AUTH_ENV_KEYS.find((key) => asNonEmpty(options.env?.[key])) ??
+ EXTERNAL_ROUTING_FLAG_ENV_KEYS.find((key) =>
+ isRoutingFlagEnabled(effectiveRoutingFlag(options, key)),
+ );
+ if (externalAuthKey) {
+ return unavailableSnapshot(
+ 'external-auth',
+ `Subscription quota does not apply when ${externalAuthKey} is configured`,
+ );
+ }
+
+ const lookup = await readClaudeOAuthCredentials(options);
+ if (lookup.state === 'not-found') {
+ return unavailableSnapshot('credentials-not-found', 'Claude Code login credentials not found');
+ }
+ if (lookup.state === 'expired') {
+ return unavailableSnapshot('credentials-expired', 'Claude Code login has expired');
+ }
+
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), USAGE_TIMEOUT_MS);
+
+ try {
+ const response = await fetch(OAUTH_USAGE_URL, {
+ headers: {
+ 'Authorization': `Bearer ${lookup.credentials.accessToken}`,
+ 'Content-Type': 'application/json',
+ 'User-Agent': OAUTH_USER_AGENT,
+ 'anthropic-beta': OAUTH_BETA_HEADER,
+ },
+ signal: controller.signal,
+ });
+
+ if (response.status === 401 || response.status === 403) {
+ return unavailableSnapshot(
+ 'credentials-expired',
+ `Anthropic usage API rejected the Claude Code login (${response.status})`,
+ );
+ }
+
+ if (!response.ok) {
+ return errorSnapshot(`Anthropic usage API returned ${response.status}`);
+ }
+
+ const payload = (await response.json()) as OAuthUsageResponse;
+
+ return {
+ error: null,
+ provider: 'claude-code',
+ scopedWeekly: mapScopedWeekly(payload),
+ session: mapUsageWindow(payload.five_hour, 300),
+ status: 'ok',
+ updatedAt: Date.now(),
+ weekly: mapUsageWindow(payload.seven_day, 10_080),
+ };
+ } catch (error) {
+ if (controller.signal.aborted) {
+ return errorSnapshot('Anthropic usage API request timed out');
+ }
+
+ return errorSnapshot(error instanceof Error ? error.message : String(error));
+ } finally {
+ clearTimeout(timeout);
+ }
+};
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index f36496334b0..deadaecb72a 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -264,6 +264,12 @@
"groupWizard.searchTemplates": "Search templates...",
"groupWizard.title": "Create Group",
"groupWizard.useTemplate": "Use Template",
+ "heteroAgent.claudeQuota.scopedWeekly": "Weekly ({{model}})",
+ "heteroAgent.claudeQuota.title": "Claude Code quota",
+ "heteroAgent.claudeQuota.tooltip": "View Claude Code quota",
+ "heteroAgent.claudeQuota.unavailableExpired": "Claude Code login has expired. Start a Claude Code conversation or run claude in a terminal, then refresh.",
+ "heteroAgent.claudeQuota.unavailableExternalAuth": "This agent uses an API key / custom endpoint, so subscription quota does not apply.",
+ "heteroAgent.claudeQuota.unavailableNotFound": "No Claude Code login found. Run claude in a terminal to sign in first.",
"heteroAgent.cloudNotConfigured.action": "Configure",
"heteroAgent.cloudNotConfigured.desc": "Configure your Claude Code token in agent profile to start sending messages.",
"heteroAgent.cloudNotConfigured.title": "Cloud credentials required",
@@ -271,31 +277,14 @@
"heteroAgent.cloudRepo.noRepos": "No repositories configured. Add them in agent settings.",
"heteroAgent.cloudRepo.notSet": "No repo selected",
"heteroAgent.cloudRepo.sectionTitle": "Repositories",
- "heteroAgent.codexQuota.compactLeft": "{{percent}}%",
- "heteroAgent.codexQuota.duration.day_one": "{{count}}d",
- "heteroAgent.codexQuota.duration.day_other": "{{count}}d",
- "heteroAgent.codexQuota.duration.hour_one": "{{count}}h",
- "heteroAgent.codexQuota.duration.hour_other": "{{count}}h",
- "heteroAgent.codexQuota.duration.minute_one": "{{count}}m",
- "heteroAgent.codexQuota.duration.minute_other": "{{count}}m",
"heteroAgent.codexQuota.expiresIn": "Expires in {{duration}}",
- "heteroAgent.codexQuota.left": "{{percent}}% left",
"heteroAgent.codexQuota.nextExpiresIn": "Next expires in {{duration}}",
- "heteroAgent.codexQuota.noData": "Codex quota is not available yet.",
- "heteroAgent.codexQuota.refresh": "Refresh Codex quota",
"heteroAgent.codexQuota.resetCreditsUnavailable": "Reset credits unavailable",
"heteroAgent.codexQuota.resetCredits_one": "1 rate-limit reset available",
"heteroAgent.codexQuota.resetCredits_other": "{{count}} rate-limit resets available",
"heteroAgent.codexQuota.resetCredits_zero": "No rate-limit resets available",
- "heteroAgent.codexQuota.resetsIn": "Resets in {{duration}}",
- "heteroAgent.codexQuota.resetsSoon": "Resets soon",
- "heteroAgent.codexQuota.session": "Session",
"heteroAgent.codexQuota.title": "Codex quota",
"heteroAgent.codexQuota.tooltip": "View Codex quota",
- "heteroAgent.codexQuota.unavailable": "Codex quota is unavailable.",
- "heteroAgent.codexQuota.updatedAgo": "Updated {{duration}} ago",
- "heteroAgent.codexQuota.updatedJustNow": "Updated just now",
- "heteroAgent.codexQuota.weekly": "Weekly",
"heteroAgent.executionTarget.auto": "Auto",
"heteroAgent.executionTarget.autoDesc": "Use an online device automatically, picking one when several are available",
"heteroAgent.executionTarget.downloadDesktop": "Get Desktop App",
@@ -339,6 +328,23 @@
"heteroAgent.modelSelector.speed.fastDesc": "1.5x speed, increased usage",
"heteroAgent.modelSelector.speed.standard": "Standard",
"heteroAgent.modelSelector.speed.standardDesc": "Default speed",
+ "heteroAgent.quota.compactLeft": "{{percent}}%",
+ "heteroAgent.quota.duration.day_one": "{{count}}d",
+ "heteroAgent.quota.duration.day_other": "{{count}}d",
+ "heteroAgent.quota.duration.hour_one": "{{count}}h",
+ "heteroAgent.quota.duration.hour_other": "{{count}}h",
+ "heteroAgent.quota.duration.minute_one": "{{count}}m",
+ "heteroAgent.quota.duration.minute_other": "{{count}}m",
+ "heteroAgent.quota.left": "{{percent}}% left",
+ "heteroAgent.quota.noData": "Quota is not available yet.",
+ "heteroAgent.quota.refresh": "Refresh quota",
+ "heteroAgent.quota.resetsIn": "Resets in {{duration}}",
+ "heteroAgent.quota.resetsSoon": "Resets soon",
+ "heteroAgent.quota.session": "Session",
+ "heteroAgent.quota.unavailable": "Quota is unavailable.",
+ "heteroAgent.quota.updatedAgo": "Updated {{duration}} ago",
+ "heteroAgent.quota.updatedJustNow": "Updated just now",
+ "heteroAgent.quota.weekly": "Weekly",
"heteroAgent.resumeReset.cwdChanged": "Working directory changed. Previous Claude Code session can only be resumed from its original directory, so a new conversation has started.",
"heteroAgent.resumeReset.resumeFailed": "The saved Codex thread could not be resumed safely, so a new conversation has started for this topic.",
"heteroAgent.switchCwd.cancel": "Cancel",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 5b0f9b0c164..882cfdffa2d 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -264,6 +264,12 @@
"groupWizard.searchTemplates": "搜索模板…",
"groupWizard.title": "创建群组",
"groupWizard.useTemplate": "使用模板",
+ "heteroAgent.claudeQuota.scopedWeekly": "每周({{model}})",
+ "heteroAgent.claudeQuota.title": "Claude Code 额度",
+ "heteroAgent.claudeQuota.tooltip": "查看 Claude Code 额度",
+ "heteroAgent.claudeQuota.unavailableExpired": "Claude Code 登录已过期,发起一次 Claude Code 对话或在终端运行 claude 后再刷新。",
+ "heteroAgent.claudeQuota.unavailableExternalAuth": "当前 Agent 使用 API Key / 自定义接入点运行,订阅额度不适用。",
+ "heteroAgent.claudeQuota.unavailableNotFound": "未找到 Claude Code 登录凭证,请先在终端运行 claude 完成登录。",
"heteroAgent.cloudNotConfigured.action": "立即配置",
"heteroAgent.cloudNotConfigured.desc": "请在 Agent 资料中配置 Claude Code Token,以开始发送消息。",
"heteroAgent.cloudNotConfigured.title": "需要配置云端凭证",
@@ -271,31 +277,14 @@
"heteroAgent.cloudRepo.noRepos": "未配置仓库,请在助理设置中添加。",
"heteroAgent.cloudRepo.notSet": "未选择仓库",
"heteroAgent.cloudRepo.sectionTitle": "代码仓库",
- "heteroAgent.codexQuota.compactLeft": "{{percent}}%",
- "heteroAgent.codexQuota.duration.day_one": "{{count}}天",
- "heteroAgent.codexQuota.duration.day_other": "{{count}}天",
- "heteroAgent.codexQuota.duration.hour_one": "{{count}}小时",
- "heteroAgent.codexQuota.duration.hour_other": "{{count}}小时",
- "heteroAgent.codexQuota.duration.minute_one": "{{count}}分钟",
- "heteroAgent.codexQuota.duration.minute_other": "{{count}}分钟",
"heteroAgent.codexQuota.expiresIn": "{{duration}}后过期",
- "heteroAgent.codexQuota.left": "剩余 {{percent}}%",
"heteroAgent.codexQuota.nextExpiresIn": "下一次将在 {{duration}}后过期",
- "heteroAgent.codexQuota.noData": "暂未获取到 Codex 额度。",
- "heteroAgent.codexQuota.refresh": "刷新 Codex 额度",
"heteroAgent.codexQuota.resetCreditsUnavailable": "额度重置次数不可用",
"heteroAgent.codexQuota.resetCredits_one": "1 次可用额度重置",
"heteroAgent.codexQuota.resetCredits_other": "{{count}} 次可用额度重置",
"heteroAgent.codexQuota.resetCredits_zero": "暂无可用额度重置",
- "heteroAgent.codexQuota.resetsIn": "{{duration}}后重置",
- "heteroAgent.codexQuota.resetsSoon": "即将重置",
- "heteroAgent.codexQuota.session": "会话",
"heteroAgent.codexQuota.title": "Codex 额度",
"heteroAgent.codexQuota.tooltip": "查看 Codex 额度",
- "heteroAgent.codexQuota.unavailable": "Codex 额度不可用。",
- "heteroAgent.codexQuota.updatedAgo": "{{duration}}前更新",
- "heteroAgent.codexQuota.updatedJustNow": "刚刚更新",
- "heteroAgent.codexQuota.weekly": "每周",
"heteroAgent.executionTarget.auto": "自动",
"heteroAgent.executionTarget.autoDesc": "自动使用在线设备,有多台时择一使用",
"heteroAgent.executionTarget.downloadDesktop": "下载桌面端",
@@ -339,6 +328,23 @@
"heteroAgent.modelSelector.speed.fastDesc": "1.5 倍速度,消耗更多用量",
"heteroAgent.modelSelector.speed.standard": "标准",
"heteroAgent.modelSelector.speed.standardDesc": "默认速度",
+ "heteroAgent.quota.compactLeft": "{{percent}}%",
+ "heteroAgent.quota.duration.day_one": "{{count}}天",
+ "heteroAgent.quota.duration.day_other": "{{count}}天",
+ "heteroAgent.quota.duration.hour_one": "{{count}}小时",
+ "heteroAgent.quota.duration.hour_other": "{{count}}小时",
+ "heteroAgent.quota.duration.minute_one": "{{count}}分钟",
+ "heteroAgent.quota.duration.minute_other": "{{count}}分钟",
+ "heteroAgent.quota.left": "剩余 {{percent}}%",
+ "heteroAgent.quota.noData": "暂未获取到额度。",
+ "heteroAgent.quota.refresh": "刷新额度",
+ "heteroAgent.quota.resetsIn": "{{duration}}后重置",
+ "heteroAgent.quota.resetsSoon": "即将重置",
+ "heteroAgent.quota.session": "会话",
+ "heteroAgent.quota.unavailable": "额度不可用。",
+ "heteroAgent.quota.updatedAgo": "{{duration}}前更新",
+ "heteroAgent.quota.updatedJustNow": "刚刚更新",
+ "heteroAgent.quota.weekly": "每周",
"heteroAgent.resumeReset.cwdChanged": "工作目录已切换,之前的 Claude Code 会话只能在原目录下继续,已开始新对话。",
"heteroAgent.resumeReset.resumeFailed": "已保存的 Codex 线程无法安全恢复,当前话题已自动开启新会话。",
"heteroAgent.switchCwd.cancel": "取消",
diff --git a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
index c97bd700850..0cdd555c57f 100644
--- a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
+++ b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
@@ -35,12 +35,14 @@ export interface HeterogeneousAgentRateLimitInfo {
status?: string;
}
-export interface CodexQuotaWindow {
+export interface HeteroQuotaWindow {
resetsAt: number | null;
usedPercent: number;
windowMinutes: number;
}
+export type CodexQuotaWindow = HeteroQuotaWindow;
+
export interface CodexRateLimitResetCredits {
availableCount: number;
credits?: {
@@ -62,6 +64,32 @@ export interface CodexQuotaSnapshot {
weekly: CodexQuotaWindow | null;
}
+/**
+ * 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;
+}
+
+export interface ClaudeCodeQuotaSnapshot {
+ error: string | null;
+ provider: 'claude-code';
+ 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?: string;
code?: HeterogeneousAgentSessionErrorCode | string;
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 5dc846978ab..f047638ad37 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -179,31 +179,40 @@ export default {
'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.codexQuota.compactLeft': '{{percent}}%',
- 'heteroAgent.codexQuota.duration.day_one': '{{count}}d',
- 'heteroAgent.codexQuota.duration.day_other': '{{count}}d',
- 'heteroAgent.codexQuota.duration.hour_one': '{{count}}h',
- 'heteroAgent.codexQuota.duration.hour_other': '{{count}}h',
- 'heteroAgent.codexQuota.duration.minute_one': '{{count}}m',
- 'heteroAgent.codexQuota.duration.minute_other': '{{count}}m',
+ 'heteroAgent.claudeQuota.scopedWeekly': 'Weekly ({{model}})',
+ 'heteroAgent.claudeQuota.title': 'Claude Code quota',
+ 'heteroAgent.claudeQuota.tooltip': 'View Claude Code quota',
+ 'heteroAgent.claudeQuota.unavailableExpired':
+ 'Claude Code login has expired. Start a Claude Code conversation or run claude in a terminal, then refresh.',
+ 'heteroAgent.claudeQuota.unavailableExternalAuth':
+ 'This agent uses an API key / custom endpoint, so subscription quota does not apply.',
+ 'heteroAgent.claudeQuota.unavailableNotFound':
+ 'No Claude Code login found. Run claude in a terminal to sign in first.',
'heteroAgent.codexQuota.expiresIn': 'Expires in {{duration}}',
- 'heteroAgent.codexQuota.left': '{{percent}}% left',
'heteroAgent.codexQuota.nextExpiresIn': 'Next expires in {{duration}}',
- 'heteroAgent.codexQuota.noData': 'Codex quota is not available yet.',
- 'heteroAgent.codexQuota.refresh': 'Refresh Codex quota',
'heteroAgent.codexQuota.resetCredits_one': '1 rate-limit reset available',
'heteroAgent.codexQuota.resetCredits_other': '{{count}} rate-limit resets available',
'heteroAgent.codexQuota.resetCredits_zero': 'No rate-limit resets available',
'heteroAgent.codexQuota.resetCreditsUnavailable': 'Reset credits unavailable',
- 'heteroAgent.codexQuota.resetsIn': 'Resets in {{duration}}',
- 'heteroAgent.codexQuota.resetsSoon': 'Resets soon',
- 'heteroAgent.codexQuota.session': 'Session',
'heteroAgent.codexQuota.title': 'Codex quota',
'heteroAgent.codexQuota.tooltip': 'View Codex quota',
- 'heteroAgent.codexQuota.unavailable': 'Codex quota is unavailable.',
- 'heteroAgent.codexQuota.updatedAgo': 'Updated {{duration}} ago',
- 'heteroAgent.codexQuota.updatedJustNow': 'Updated just now',
- 'heteroAgent.codexQuota.weekly': 'Weekly',
+ 'heteroAgent.quota.compactLeft': '{{percent}}%',
+ 'heteroAgent.quota.duration.day_one': '{{count}}d',
+ 'heteroAgent.quota.duration.day_other': '{{count}}d',
+ 'heteroAgent.quota.duration.hour_one': '{{count}}h',
+ 'heteroAgent.quota.duration.hour_other': '{{count}}h',
+ 'heteroAgent.quota.duration.minute_one': '{{count}}m',
+ 'heteroAgent.quota.duration.minute_other': '{{count}}m',
+ 'heteroAgent.quota.left': '{{percent}}% left',
+ 'heteroAgent.quota.noData': 'Quota is not available yet.',
+ 'heteroAgent.quota.refresh': 'Refresh quota',
+ 'heteroAgent.quota.resetsIn': 'Resets in {{duration}}',
+ 'heteroAgent.quota.resetsSoon': 'Resets soon',
+ 'heteroAgent.quota.session': 'Session',
+ 'heteroAgent.quota.unavailable': 'Quota is unavailable.',
+ 'heteroAgent.quota.updatedAgo': 'Updated {{duration}} ago',
+ 'heteroAgent.quota.updatedJustNow': 'Updated just now',
+ 'heteroAgent.quota.weekly': 'Weekly',
'heteroAgent.modelSelector.ariaLabel': 'Model: {{model}}. Reasoning: {{reasoning}}',
'heteroAgent.modelSelector.default': 'Default',
'heteroAgent.modelSelector.defaultConfig': 'Default config',
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ClaudeCodeQuotaMenu.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ClaudeCodeQuotaMenu.tsx
new file mode 100644
index 00000000000..ee2cbd1917e
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ClaudeCodeQuotaMenu.tsx
@@ -0,0 +1,86 @@
+'use client';
+
+import type { ClaudeCodeQuotaSnapshot } from '@lobechat/electron-client-ipc';
+import { memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';
+
+import QuotaMenu, { type QuotaWindowItem } from './QuotaMenu';
+
+const createErrorSnapshot = (error: unknown): ClaudeCodeQuotaSnapshot => ({
+ error: error instanceof Error ? error.message : String(error),
+ provider: 'claude-code',
+ scopedWeekly: null,
+ session: null,
+ status: 'error',
+ updatedAt: Date.now(),
+ weekly: null,
+});
+
+interface ClaudeCodeQuotaMenuProps {
+ env?: Record<string, string>;
+}
+
+const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ env }) => {
+ const { t } = useTranslation('chat');
+
+ const fetchQuota = useCallback(
+ () => heterogeneousAgentService.getClaudeCodeQuota({ env }),
+ [env],
+ );
+
+ const getWindows = useCallback(
+ (quota: ClaudeCodeQuotaSnapshot): QuotaWindowItem[] => [
+ { key: 'session', label: t('heteroAgent.quota.session'), window: quota.session },
+ { key: 'weekly', label: t('heteroAgent.quota.weekly'), window: quota.weekly },
+ ...(quota.scopedWeekly
+ ? [
+ {
+ key: 'scopedWeekly',
+ label: t('heteroAgent.claudeQuota.scopedWeekly', {
+ model: quota.scopedWeekly.modelName,
+ }),
+ window: quota.scopedWeekly.window,
+ },
+ ]
+ : []),
+ ],
+ [t],
+ );
+
+ const getUnavailableText = useCallback(
+ (quota: ClaudeCodeQuotaSnapshot) => {
+ switch (quota.reason) {
+ case 'credentials-expired': {
+ return t('heteroAgent.claudeQuota.unavailableExpired');
+ }
+ case 'credentials-not-found': {
+ return t('heteroAgent.claudeQuota.unavailableNotFound');
+ }
+ case 'external-auth': {
+ return t('heteroAgent.claudeQuota.unavailableExternalAuth');
+ }
+ default: {
+ return undefined;
+ }
+ }
+ },
+ [t],
+ );
+
+ return (
+ <QuotaMenu
+ createErrorSnapshot={createErrorSnapshot}
+ fetchQuota={fetchQuota}
+ getUnavailableText={getUnavailableText}
+ getWindows={getWindows}
+ title={t('heteroAgent.claudeQuota.title')}
+ tooltip={t('heteroAgent.claudeQuota.tooltip')}
+ />
+ );
+});
+
+ClaudeCodeQuotaMenu.displayName = 'ClaudeCodeQuotaMenu';
+
+export default ClaudeCodeQuotaMenu;
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/CodexQuotaMenu.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/CodexQuotaMenu.tsx
index 9aa022ef55c..234adb56093 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/CodexQuotaMenu.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/CodexQuotaMenu.tsx
@@ -1,99 +1,23 @@
'use client';
-import type { CodexQuotaSnapshot, CodexQuotaWindow } from '@lobechat/electron-client-ipc';
-import { ActionIcon, Flexbox, Icon, Popover, Skeleton, Text, Tooltip } from '@lobehub/ui';
-import { createStaticStyles, cssVar, cx } from 'antd-style';
-import { ChevronDownIcon, GaugeIcon, RefreshCwIcon, RotateCcwIcon } from 'lucide-react';
-import { memo, useCallback, useEffect, useMemo, useState } from 'react';
+import type { CodexQuotaSnapshot } from '@lobechat/electron-client-ipc';
+import { Flexbox, Icon, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { RotateCcwIcon } from 'lucide-react';
+import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';
-const QUOTA_STALE_MS = 60_000;
+import QuotaMenu, { type QuotaMenuHelpers, type QuotaWindowItem } from './QuotaMenu';
const styles = createStaticStyles(({ css }) => ({
- emptyState: css`
- padding-block: 10px;
- font-size: 12px;
- color: ${cssVar.colorTextDescription};
- `,
- error: css`
- padding: 8px;
- border: 1px solid ${cssVar.colorErrorBorder};
- border-radius: ${cssVar.borderRadius};
-
- font-size: 12px;
- color: ${cssVar.colorError};
-
- background: ${cssVar.colorErrorBg};
- `,
- header: css`
- padding-block-end: 8px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- popover: css`
- width: 292px;
- `,
- progressFill: css`
- height: 100%;
- border-radius: inherit;
- background: ${cssVar.colorSuccess};
- `,
- progressTrack: css`
- overflow: hidden;
-
- width: 100%;
- height: 6px;
- border-radius: 999px;
-
- background: ${cssVar.colorFillQuaternary};
- `,
resetCredits: css`
padding-block-start: 8px;
border-block-start: 1px solid ${cssVar.colorBorderSecondary};
`,
- trigger: css`
- cursor: pointer;
-
- display: flex;
- flex: none;
- gap: 6px;
- align-items: center;
-
- padding-block: 2px;
- padding-inline: 4px;
- border: 0;
- border-radius: 4px;
-
- font: inherit;
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- white-space: nowrap;
-
- appearance: none;
- background: transparent;
-
- transition: all 0.2s;
-
- &:hover {
- color: ${cssVar.colorTextSecondary};
- background: ${cssVar.colorFillSecondary};
- }
- `,
- triggerOpen: css`
- color: ${cssVar.colorTextSecondary};
- background: ${cssVar.colorFillSecondary};
- `,
- value: css`
- color: ${cssVar.colorText};
- `,
- window: css`
- min-width: 0;
- `,
}));
-const clampPercent = (value: number) => Math.min(100, Math.max(0, Math.round(value)));
-
const createErrorSnapshot = (error: unknown): CodexQuotaSnapshot => ({
error: error instanceof Error ? error.message : String(error),
provider: 'codex',
@@ -111,241 +35,82 @@ interface CodexQuotaMenuProps {
const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, env }) => {
const { t } = useTranslation('chat');
- const [open, setOpen] = useState(false);
- const [loading, setLoading] = useState(false);
- const [quota, setQuota] = useState<CodexQuotaSnapshot | null>(null);
- const [now, setNow] = useState(() => Date.now());
-
- const loadQuota = useCallback(async () => {
- setLoading(true);
-
- try {
- const nextQuota = await heterogeneousAgentService.getCodexQuota({ command, env });
- setQuota(nextQuota);
- } catch (error) {
- console.error('Failed to fetch Codex quota:', error);
- setQuota(createErrorSnapshot(error));
- } finally {
- setLoading(false);
- }
- }, [command, env]);
-
- useEffect(() => {
- void loadQuota();
- }, [loadQuota]);
-
- useEffect(() => {
- const interval = window.setInterval(() => setNow(Date.now()), QUOTA_STALE_MS);
-
- return () => {
- window.clearInterval(interval);
- };
- }, []);
-
- const formatDuration = useCallback(
- (ms: number) => {
- if (ms <= 0) return;
-
- const totalMinutes = Math.floor(ms / 60_000);
- const days = Math.floor(totalMinutes / (24 * 60));
- const hours = Math.floor((totalMinutes % (24 * 60)) / 60);
- const minutes = totalMinutes % 60;
- const parts: string[] = [];
-
- if (days > 0) parts.push(t('heteroAgent.codexQuota.duration.day', { count: days }));
- if (hours > 0) parts.push(t('heteroAgent.codexQuota.duration.hour', { count: hours }));
- if (minutes > 0 && parts.length < 2) {
- parts.push(t('heteroAgent.codexQuota.duration.minute', { count: minutes }));
- }
-
- return parts.slice(0, 2).join(' ') || undefined;
- },
- [t],
- );
- const formatResetCountdown = useCallback(
- (resetsAt: number | null | undefined) => {
- if (!resetsAt) return;
-
- const duration = formatDuration(resetsAt - now);
- return duration
- ? t('heteroAgent.codexQuota.resetsIn', { duration })
- : t('heteroAgent.codexQuota.resetsSoon');
- },
- [formatDuration, now, t],
+ const fetchQuota = useCallback(
+ () => heterogeneousAgentService.getCodexQuota({ command, env }),
+ [command, env],
);
- const formatUpdatedAt = useCallback(
- (updatedAt: number) => {
- const duration = formatDuration(now - updatedAt);
-
- return duration
- ? t('heteroAgent.codexQuota.updatedAgo', { duration })
- : t('heteroAgent.codexQuota.updatedJustNow');
- },
- [formatDuration, now, t],
+ const getWindows = useCallback(
+ (quota: CodexQuotaSnapshot): QuotaWindowItem[] => [
+ { key: 'session', label: t('heteroAgent.quota.session'), window: quota.session },
+ { key: 'weekly', label: t('heteroAgent.quota.weekly'), window: quota.weekly },
+ ],
+ [t],
);
- const sessionLeftPercent = quota?.session
- ? clampPercent(100 - quota.session.usedPercent)
- : undefined;
- const resetCreditCount = quota?.rateLimitResetCredits?.availableCount;
- const resetCreditExpiry = quota?.rateLimitResetCredits?.nextExpiresAt;
- const hasQuotaData = !!(quota?.session || quota?.weekly || quota?.rateLimitResetCredits);
-
- const handleOpenChange = useCallback(
- (nextOpen: boolean) => {
- setOpen(nextOpen);
-
- if (!nextOpen || loading) return;
- if (!quota || Date.now() - quota.updatedAt > QUOTA_STALE_MS) void loadQuota();
- },
- [loadQuota, loading, quota],
+ const hasExtraData = useCallback(
+ (quota: CodexQuotaSnapshot) => !!quota.rateLimitResetCredits,
+ [],
);
- const renderQuotaWindow = useCallback(
- (window: CodexQuotaWindow | null, label: string) => {
- if (!window) return null;
-
- const leftPercent = clampPercent(100 - window.usedPercent);
- const resetLabel = formatResetCountdown(window.resetsAt);
+ const renderFooter = useCallback(
+ (quota: CodexQuotaSnapshot, { formatDuration, now }: QuotaMenuHelpers) => {
+ const resetCreditCount = quota.rateLimitResetCredits?.availableCount;
+ const resetCreditExpiry = quota.rateLimitResetCredits?.nextExpiresAt;
- return (
- <Flexbox className={styles.window} gap={4} key={label}>
- <Text strong style={{ fontSize: 12 }}>
- {label}
- </Text>
- <div className={styles.progressTrack}>
- <div className={styles.progressFill} style={{ width: `${leftPercent}%` }} />
- </div>
- <Flexbox horizontal style={{ justifyContent: 'space-between' }}>
- <Text className={styles.value} style={{ fontSize: 12 }}>
- {t('heteroAgent.codexQuota.left', { percent: leftPercent })}
- </Text>
- {resetLabel && (
+ if (resetCreditCount === undefined)
+ return (
+ <Flexbox className={styles.resetCredits} gap={4}>
+ <Flexbox horizontal align={'center'} gap={6}>
+ <Icon icon={RotateCcwIcon} size={13} />
<Text style={{ fontSize: 12 }} type="secondary">
- {resetLabel}
+ {t('heteroAgent.codexQuota.resetCreditsUnavailable')}
</Text>
- )}
+ </Flexbox>
</Flexbox>
- </Flexbox>
- );
- },
- [formatResetCountdown, t],
- );
-
- const resetCreditExpiryLabel = useMemo(() => {
- if (!resetCreditExpiry || resetCreditCount === undefined) return;
-
- const duration = formatDuration(resetCreditExpiry - now);
- if (!duration) return;
-
- return resetCreditCount > 1
- ? t('heteroAgent.codexQuota.nextExpiresIn', { duration })
- : t('heteroAgent.codexQuota.expiresIn', { duration });
- }, [formatDuration, now, resetCreditCount, resetCreditExpiry, t]);
+ );
+
+ let expiryLabel: string | undefined;
+ if (resetCreditExpiry) {
+ const duration = formatDuration(resetCreditExpiry - now);
+ if (duration) {
+ expiryLabel =
+ resetCreditCount > 1
+ ? t('heteroAgent.codexQuota.nextExpiresIn', { duration })
+ : t('heteroAgent.codexQuota.expiresIn', { duration });
+ }
+ }
- const content = (
- <Flexbox className={styles.popover} gap={10}>
- <Flexbox horizontal align={'center'} className={styles.header} justify={'space-between'}>
- <Flexbox gap={2}>
- <Text strong>{t('heteroAgent.codexQuota.title')}</Text>
- {quota?.updatedAt && (
+ return (
+ <Flexbox className={styles.resetCredits} gap={4}>
+ <Flexbox horizontal align={'center'} gap={6}>
+ <Icon icon={RotateCcwIcon} size={13} />
+ <Text strong style={{ fontSize: 12 }}>
+ {t('heteroAgent.codexQuota.resetCredits', { count: resetCreditCount })}
+ </Text>
+ </Flexbox>
+ {expiryLabel && (
<Text style={{ fontSize: 12 }} type="secondary">
- {formatUpdatedAt(quota.updatedAt)}
+ {expiryLabel}
</Text>
)}
</Flexbox>
- <Tooltip title={t('heteroAgent.codexQuota.refresh')}>
- <ActionIcon
- disabled={loading}
- icon={RefreshCwIcon}
- size={'small'}
- onClick={() => void loadQuota()}
- />
- </Tooltip>
- </Flexbox>
-
- {loading && !hasQuotaData ? (
- <Flexbox gap={8}>
- <Skeleton.Button active block size="small" style={{ height: 18 }} />
- <Skeleton.Button active block size="small" style={{ height: 18 }} />
- <Skeleton.Button active block size="small" style={{ height: 18 }} />
- </Flexbox>
- ) : quota?.status === 'error' || quota?.status === 'unavailable' ? (
- <div className={styles.error}>{quota.error || t('heteroAgent.codexQuota.unavailable')}</div>
- ) : hasQuotaData ? (
- <>
- <Flexbox gap={10}>
- {renderQuotaWindow(quota?.session ?? null, t('heteroAgent.codexQuota.session'))}
- {renderQuotaWindow(quota?.weekly ?? null, t('heteroAgent.codexQuota.weekly'))}
- </Flexbox>
- {resetCreditCount !== undefined ? (
- <Flexbox className={styles.resetCredits} gap={4}>
- <Flexbox horizontal align={'center'} gap={6}>
- <Icon icon={RotateCcwIcon} size={13} />
- <Text strong style={{ fontSize: 12 }}>
- {t('heteroAgent.codexQuota.resetCredits', { count: resetCreditCount })}
- </Text>
- </Flexbox>
- {resetCreditExpiryLabel && (
- <Text style={{ fontSize: 12 }} type="secondary">
- {resetCreditExpiryLabel}
- </Text>
- )}
- </Flexbox>
- ) : (
- <Flexbox className={styles.resetCredits} gap={4}>
- <Flexbox horizontal align={'center'} gap={6}>
- <Icon icon={RotateCcwIcon} size={13} />
- <Text style={{ fontSize: 12 }} type="secondary">
- {t('heteroAgent.codexQuota.resetCreditsUnavailable')}
- </Text>
- </Flexbox>
- </Flexbox>
- )}
- </>
- ) : (
- <div className={styles.emptyState}>{t('heteroAgent.codexQuota.noData')}</div>
- )}
- </Flexbox>
- );
-
- const trigger = (
- <button
- aria-expanded={open}
- aria-haspopup="dialog"
- aria-label={t('heteroAgent.codexQuota.tooltip')}
- className={cx(styles.trigger, open && styles.triggerOpen)}
- type="button"
- >
- <Icon icon={GaugeIcon} size={14} />
- {sessionLeftPercent !== undefined && (
- <span>{t('heteroAgent.codexQuota.compactLeft', { percent: sessionLeftPercent })}</span>
- )}
- <Icon icon={ChevronDownIcon} size={12} />
- </button>
+ );
+ },
+ [t],
);
return (
- <Popover
- content={content}
- open={open}
- placement="topRight"
- trigger="click"
- styles={{
- content: {
- border: `1px solid ${cssVar.colorBorderSecondary}`,
- borderRadius: cssVar.borderRadiusLG,
- padding: 10,
- },
- }}
- onOpenChange={handleOpenChange}
- >
- <div>
- {open ? trigger : <Tooltip title={t('heteroAgent.codexQuota.tooltip')}>{trigger}</Tooltip>}
- </div>
- </Popover>
+ <QuotaMenu
+ createErrorSnapshot={createErrorSnapshot}
+ fetchQuota={fetchQuota}
+ getWindows={getWindows}
+ hasExtraData={hasExtraData}
+ renderFooter={renderFooter}
+ title={t('heteroAgent.codexQuota.title')}
+ tooltip={t('heteroAgent.codexQuota.tooltip')}
+ />
);
});
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx
index 97ca688212d..bc3aa33433a 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx
@@ -13,6 +13,7 @@ import { resolveExecutionTarget } from '@/helpers/executionTarget';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
+import ClaudeCodeQuotaMenu from './ClaudeCodeQuotaMenu';
import CodexQuotaMenu from './CodexQuotaMenu';
const styles = createStaticStyles(({ css }) => ({
@@ -100,12 +101,14 @@ const HeteroControlBar = memo(() => {
<span className={styles.fullAccessLabel}>{tChat('heteroAgent.fullAccess.label')}</span>
</div>
);
- const shouldShowCodexQuota =
- agencyConfig?.heterogeneousProvider?.type === 'codex' &&
+ const heteroProvider = agencyConfig?.heterogeneousProvider;
+ const isLocalHeteroExecution =
resolveExecutionTarget(agencyConfig, {
clientExecutionAvailable: isDesktop,
isHetero: true,
}) === 'local';
+ const shouldShowCodexQuota = heteroProvider?.type === 'codex' && isLocalHeteroExecution;
+ const shouldShowClaudeQuota = heteroProvider?.type === 'claude-code' && isLocalHeteroExecution;
return (
<Flexbox horizontal align={'center'} className={styles.bar} justify={'space-between'}>
@@ -114,11 +117,9 @@ const HeteroControlBar = memo(() => {
</Flexbox>
<Flexbox horizontal align={'center'} className={styles.rightGroup} gap={4}>
{shouldShowCodexQuota && (
- <CodexQuotaMenu
- command={agencyConfig.heterogeneousProvider?.command}
- env={agencyConfig.heterogeneousProvider?.env}
- />
+ <CodexQuotaMenu command={heteroProvider?.command} env={heteroProvider?.env} />
)}
+ {shouldShowClaudeQuota && <ClaudeCodeQuotaMenu env={heteroProvider?.env} />}
<Tooltip title={tChat('heteroAgent.fullAccess.tooltip')}>{fullAccessBadge}</Tooltip>
</Flexbox>
</Flexbox>
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.test.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.test.tsx
new file mode 100644
index 00000000000..72d1f0af3c1
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.test.tsx
@@ -0,0 +1,177 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import type { ClaudeCodeQuotaSnapshot, CodexQuotaSnapshot } from '@lobechat/electron-client-ipc';
+import { fireEvent, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import ClaudeCodeQuotaMenu from './ClaudeCodeQuotaMenu';
+import CodexQuotaMenu from './CodexQuotaMenu';
+
+const mockService = vi.hoisted(() => ({
+ getClaudeCodeQuota: vi.fn(),
+ getCodexQuota: vi.fn(),
+}));
+
+vi.mock('@/services/electron/heterogeneousAgent', () => ({
+ heterogeneousAgentService: mockService,
+}));
+
+// Render keys verbatim (with interpolated values appended) so assertions can
+// target the exact i18n key + params a snapshot should produce.
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, opts?: Record<string, unknown>) => {
+ const values = opts ? Object.values(opts) : [];
+ return values.length > 0 ? `${key}:${values.join(',')}` : key;
+ },
+ }),
+}));
+
+vi.mock('antd-style', () => ({
+ createStaticStyles: (
+ create: (utils: { css: (...args: unknown[]) => string }) => Record<string, string>,
+ ) => create({ css: () => 'cls' }),
+ cssVar: new Proxy({}, { get: (_target, prop) => `var(--${String(prop)})` }),
+ cx: (...args: unknown[]) => args.filter(Boolean).join(' '),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ ActionIcon: ({ disabled, onClick }: { disabled?: boolean; onClick?: () => void }) => (
+ <button data-testid="refresh" disabled={disabled} type="button" onClick={onClick} />
+ ),
+ Flexbox: ({ children, className }: { children?: ReactNode; className?: string }) => (
+ <div className={className}>{children}</div>
+ ),
+ Icon: () => <svg />,
+ // Render the popover content unconditionally so window rows are assertable
+ // without driving the open/close interaction.
+ Popover: ({ children, content }: { children?: ReactNode; content?: ReactNode }) => (
+ <div>
+ <div data-testid="popover-content">{content}</div>
+ {children}
+ </div>
+ ),
+ Skeleton: { Button: () => <div data-testid="skeleton" /> },
+ Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
+ Tooltip: ({ children }: { children?: ReactNode }) => <>{children}</>,
+}));
+
+const claudeSnapshot = (
+ overrides: Partial<ClaudeCodeQuotaSnapshot> = {},
+): ClaudeCodeQuotaSnapshot => ({
+ error: null,
+ provider: 'claude-code',
+ scopedWeekly: null,
+ session: null,
+ status: 'ok',
+ updatedAt: Date.now(),
+ weekly: null,
+ ...overrides,
+});
+
+const codexSnapshot = (overrides: Partial<CodexQuotaSnapshot> = {}): CodexQuotaSnapshot => ({
+ error: null,
+ provider: 'codex',
+ rateLimitResetCredits: null,
+ session: null,
+ status: 'ok',
+ updatedAt: Date.now(),
+ weekly: null,
+ ...overrides,
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('ClaudeCodeQuotaMenu', () => {
+ it('renders session, weekly, and model-scoped windows from the snapshot', async () => {
+ mockService.getClaudeCodeQuota.mockResolvedValue(
+ claudeSnapshot({
+ scopedWeekly: {
+ modelName: 'Fable',
+ window: { resetsAt: null, usedPercent: 24, windowMinutes: 10_080 },
+ },
+ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
+ weekly: { resetsAt: null, usedPercent: 13, windowMinutes: 10_080 },
+ }),
+ );
+
+ render(<ClaudeCodeQuotaMenu env={{ CLAUDE_CONFIG_DIR: '/custom' }} />);
+
+ expect(await screen.findByText('heteroAgent.quota.session')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.quota.weekly')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.claudeQuota.scopedWeekly:Fable')).toBeTruthy();
+ // 100 - usedPercent, session drives the compact trigger label
+ expect(screen.getByText('heteroAgent.quota.left:92')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.quota.compactLeft:92')).toBeTruthy();
+ expect(mockService.getClaudeCodeQuota).toHaveBeenCalledWith({
+ env: { CLAUDE_CONFIG_DIR: '/custom' },
+ });
+ });
+
+ it('maps unavailable reasons to their localized explanations', async () => {
+ mockService.getClaudeCodeQuota.mockResolvedValue(
+ claudeSnapshot({
+ error: 'raw main-process message',
+ reason: 'external-auth',
+ status: 'unavailable',
+ }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('heteroAgent.claudeQuota.unavailableExternalAuth')).toBeTruthy();
+ expect(screen.queryByText('raw main-process message')).toBeNull();
+ });
+
+ it('shows the raw error for error snapshots and refetches on refresh', async () => {
+ mockService.getClaudeCodeQuota.mockResolvedValue(
+ claudeSnapshot({ error: 'usage API returned 429', status: 'error' }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('usage API returned 429')).toBeTruthy();
+
+ fireEvent.click(screen.getByTestId('refresh'));
+ expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(2);
+ });
+
+ it('renders the empty state when the snapshot has no windows', async () => {
+ mockService.getClaudeCodeQuota.mockResolvedValue(claudeSnapshot());
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('heteroAgent.quota.noData')).toBeTruthy();
+ });
+});
+
+describe('CodexQuotaMenu', () => {
+ it('renders windows and the reset-credits footer', async () => {
+ mockService.getCodexQuota.mockResolvedValue(
+ codexSnapshot({
+ rateLimitResetCredits: { availableCount: 4, nextExpiresAt: null },
+ session: { resetsAt: null, usedPercent: 19, windowMinutes: 300 },
+ }),
+ );
+
+ render(<CodexQuotaMenu command="codex" />);
+
+ expect(await screen.findByText('heteroAgent.quota.left:81')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.codexQuota.resetCredits:4')).toBeTruthy();
+ expect(mockService.getCodexQuota).toHaveBeenCalledWith({ command: 'codex', env: undefined });
+ });
+
+ it('renders the credits-unavailable footer when the RPC omits credits', async () => {
+ mockService.getCodexQuota.mockResolvedValue(
+ codexSnapshot({ session: { resetsAt: null, usedPercent: 5, windowMinutes: 300 } }),
+ );
+
+ render(<CodexQuotaMenu />);
+
+ expect(await screen.findByText('heteroAgent.codexQuota.resetCreditsUnavailable')).toBeTruthy();
+ });
+});
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.tsx
new file mode 100644
index 00000000000..5746f891d40
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.tsx
@@ -0,0 +1,329 @@
+'use client';
+
+import type { HeteroQuotaWindow } from '@lobechat/electron-client-ipc';
+import { ActionIcon, Flexbox, Icon, Popover, Skeleton, Text, Tooltip } from '@lobehub/ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { ChevronDownIcon, GaugeIcon, RefreshCwIcon } from 'lucide-react';
+import type { ReactNode } from 'react';
+import { useCallback, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const QUOTA_STALE_MS = 60_000;
+
+const styles = createStaticStyles(({ css }) => ({
+ emptyState: css`
+ padding-block: 10px;
+ font-size: 12px;
+ color: ${cssVar.colorTextDescription};
+ `,
+ error: css`
+ padding: 8px;
+ border: 1px solid ${cssVar.colorErrorBorder};
+ border-radius: ${cssVar.borderRadius};
+
+ font-size: 12px;
+ color: ${cssVar.colorError};
+
+ background: ${cssVar.colorErrorBg};
+ `,
+ header: css`
+ padding-block-end: 8px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ popover: css`
+ width: 292px;
+ `,
+ progressFill: css`
+ height: 100%;
+ border-radius: inherit;
+ background: ${cssVar.colorSuccess};
+ `,
+ progressTrack: css`
+ overflow: hidden;
+
+ width: 100%;
+ height: 6px;
+ border-radius: 999px;
+
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ trigger: css`
+ cursor: pointer;
+
+ display: flex;
+ flex: none;
+ gap: 6px;
+ align-items: center;
+
+ padding-block: 2px;
+ padding-inline: 4px;
+ border: 0;
+ border-radius: 4px;
+
+ font: inherit;
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ white-space: nowrap;
+
+ appearance: none;
+ background: transparent;
+
+ transition: all 0.2s;
+
+ &:hover {
+ color: ${cssVar.colorTextSecondary};
+ background: ${cssVar.colorFillSecondary};
+ }
+ `,
+ triggerOpen: css`
+ color: ${cssVar.colorTextSecondary};
+ background: ${cssVar.colorFillSecondary};
+ `,
+ value: css`
+ color: ${cssVar.colorText};
+ `,
+ window: css`
+ min-width: 0;
+ `,
+}));
+
+const clampPercent = (value: number) => Math.min(100, Math.max(0, Math.round(value)));
+
+export interface QuotaSnapshotBase {
+ error: string | null;
+ status: 'error' | 'ok' | 'unavailable';
+ updatedAt: number;
+}
+
+export interface QuotaWindowItem {
+ key: string;
+ label: string;
+ window: HeteroQuotaWindow | null;
+}
+
+export interface QuotaMenuHelpers {
+ formatDuration: (ms: number) => string | undefined;
+ now: number;
+}
+
+interface QuotaMenuProps<S extends QuotaSnapshotBase> {
+ createErrorSnapshot: (error: unknown) => S;
+ fetchQuota: () => Promise<S>;
+ /** Localized explanation for `status: 'unavailable'`; falls back to `error`. */
+ getUnavailableText?: (quota: S) => string | undefined;
+ getWindows: (quota: S) => QuotaWindowItem[];
+ /** Extra agent-specific data (beyond windows) that makes the body worth rendering. */
+ hasExtraData?: (quota: S) => boolean;
+ renderFooter?: (quota: S, helpers: QuotaMenuHelpers) => ReactNode;
+ title: string;
+ tooltip: string;
+}
+
+/**
+ * Shared quota popover for local CLI agents: gauge trigger with the most
+ * binding window's remaining percent, plus per-window progress bars and
+ * reset countdowns. Agent specifics come in through the props.
+ */
+const QuotaMenu = <S extends QuotaSnapshotBase>({
+ createErrorSnapshot,
+ fetchQuota,
+ getUnavailableText,
+ getWindows,
+ hasExtraData,
+ renderFooter,
+ title,
+ tooltip,
+}: QuotaMenuProps<S>) => {
+ const { t } = useTranslation('chat');
+ const [open, setOpen] = useState(false);
+ const [loading, setLoading] = useState(false);
+ const [quota, setQuota] = useState<S | null>(null);
+ const [now, setNow] = useState(() => Date.now());
+
+ const loadQuota = useCallback(async () => {
+ setLoading(true);
+
+ try {
+ const nextQuota = await fetchQuota();
+ setQuota(nextQuota);
+ } catch (error) {
+ console.error('Failed to fetch agent quota:', error);
+ setQuota(createErrorSnapshot(error));
+ } finally {
+ setLoading(false);
+ }
+ }, [createErrorSnapshot, fetchQuota]);
+
+ useEffect(() => {
+ void loadQuota();
+ }, [loadQuota]);
+
+ useEffect(() => {
+ const interval = window.setInterval(() => setNow(Date.now()), QUOTA_STALE_MS);
+
+ return () => {
+ window.clearInterval(interval);
+ };
+ }, []);
+
+ const formatDuration = useCallback(
+ (ms: number) => {
+ if (ms <= 0) return;
+
+ const totalMinutes = Math.floor(ms / 60_000);
+ const days = Math.floor(totalMinutes / (24 * 60));
+ const hours = Math.floor((totalMinutes % (24 * 60)) / 60);
+ const minutes = totalMinutes % 60;
+ const parts: string[] = [];
+
+ if (days > 0) parts.push(t('heteroAgent.quota.duration.day', { count: days }));
+ if (hours > 0) parts.push(t('heteroAgent.quota.duration.hour', { count: hours }));
+ if (minutes > 0 && parts.length < 2) {
+ parts.push(t('heteroAgent.quota.duration.minute', { count: minutes }));
+ }
+
+ return parts.slice(0, 2).join(' ') || undefined;
+ },
+ [t],
+ );
+
+ const formatResetCountdown = useCallback(
+ (resetsAt: number | null | undefined) => {
+ if (!resetsAt) return;
+
+ const duration = formatDuration(resetsAt - now);
+ return duration
+ ? t('heteroAgent.quota.resetsIn', { duration })
+ : t('heteroAgent.quota.resetsSoon');
+ },
+ [formatDuration, now, t],
+ );
+
+ const formatUpdatedAt = useCallback(
+ (updatedAt: number) => {
+ const duration = formatDuration(now - updatedAt);
+
+ return duration
+ ? t('heteroAgent.quota.updatedAgo', { duration })
+ : t('heteroAgent.quota.updatedJustNow');
+ },
+ [formatDuration, now, t],
+ );
+
+ const windows = quota ? getWindows(quota) : [];
+ const firstWindow = windows.find((item) => item.window)?.window;
+ const compactLeftPercent = firstWindow ? clampPercent(100 - firstWindow.usedPercent) : undefined;
+ const hasQuotaData = windows.some((item) => item.window) || (!!quota && !!hasExtraData?.(quota));
+
+ const handleOpenChange = useCallback(
+ (nextOpen: boolean) => {
+ setOpen(nextOpen);
+
+ if (!nextOpen || loading) return;
+ if (!quota || Date.now() - quota.updatedAt > QUOTA_STALE_MS) void loadQuota();
+ },
+ [loadQuota, loading, quota],
+ );
+
+ const renderQuotaWindow = ({ key, label, window }: QuotaWindowItem) => {
+ if (!window) return null;
+
+ const leftPercent = clampPercent(100 - window.usedPercent);
+ const resetLabel = formatResetCountdown(window.resetsAt);
+
+ return (
+ <Flexbox className={styles.window} gap={4} key={key}>
+ <Text strong style={{ fontSize: 12 }}>
+ {label}
+ </Text>
+ <div className={styles.progressTrack}>
+ <div className={styles.progressFill} style={{ width: `${leftPercent}%` }} />
+ </div>
+ <Flexbox horizontal style={{ justifyContent: 'space-between' }}>
+ <Text className={styles.value} style={{ fontSize: 12 }}>
+ {t('heteroAgent.quota.left', { percent: leftPercent })}
+ </Text>
+ {resetLabel && (
+ <Text style={{ fontSize: 12 }} type="secondary">
+ {resetLabel}
+ </Text>
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+ };
+
+ const content = (
+ <Flexbox className={styles.popover} gap={10}>
+ <Flexbox horizontal align={'center'} className={styles.header} justify={'space-between'}>
+ <Flexbox gap={2}>
+ <Text strong>{title}</Text>
+ {quota?.updatedAt && (
+ <Text style={{ fontSize: 12 }} type="secondary">
+ {formatUpdatedAt(quota.updatedAt)}
+ </Text>
+ )}
+ </Flexbox>
+ <Tooltip title={t('heteroAgent.quota.refresh')}>
+ <ActionIcon
+ disabled={loading}
+ icon={RefreshCwIcon}
+ size={'small'}
+ onClick={() => void loadQuota()}
+ />
+ </Tooltip>
+ </Flexbox>
+
+ {loading && !hasQuotaData ? (
+ <Flexbox gap={8}>
+ <Skeleton.Button active block size="small" style={{ height: 18 }} />
+ <Skeleton.Button active block size="small" style={{ height: 18 }} />
+ <Skeleton.Button active block size="small" style={{ height: 18 }} />
+ </Flexbox>
+ ) : quota?.status === 'unavailable' ? (
+ <div className={styles.emptyState}>
+ {getUnavailableText?.(quota) || quota.error || t('heteroAgent.quota.unavailable')}
+ </div>
+ ) : quota?.status === 'error' ? (
+ <div className={styles.error}>{quota.error || t('heteroAgent.quota.unavailable')}</div>
+ ) : hasQuotaData ? (
+ <>
+ <Flexbox gap={10}>{windows.map((item) => renderQuotaWindow(item))}</Flexbox>
+ {quota && renderFooter?.(quota, { formatDuration, now })}
+ </>
+ ) : (
+ <div className={styles.emptyState}>{t('heteroAgent.quota.noData')}</div>
+ )}
+ </Flexbox>
+ );
+
+ const trigger = (
+ <button
+ aria-expanded={open}
+ aria-haspopup="dialog"
+ aria-label={tooltip}
+ className={cx(styles.trigger, open && styles.triggerOpen)}
+ type="button"
+ >
+ <Icon icon={GaugeIcon} size={14} />
+ {compactLeftPercent !== undefined && (
+ <span>{t('heteroAgent.quota.compactLeft', { percent: compactLeftPercent })}</span>
+ )}
+ <Icon icon={ChevronDownIcon} size={12} />
+ </button>
+ );
+
+ return (
+ <Popover
+ content={content}
+ open={open}
+ placement="topRight"
+ trigger="click"
+ onOpenChange={handleOpenChange}
+ >
+ <div>{open ? trigger : <Tooltip title={tooltip}>{trigger}</Tooltip>}</div>
+ </Popover>
+ );
+};
+
+export default QuotaMenu;
diff --git a/src/services/electron/heterogeneousAgent.test.ts b/src/services/electron/heterogeneousAgent.test.ts
new file mode 100644
index 00000000000..d040aa09767
--- /dev/null
+++ b/src/services/electron/heterogeneousAgent.test.ts
@@ -0,0 +1,94 @@
+import { describe, expect, it, vi } from 'vitest';
+
+const mockHeterogeneousAgent = vi.hoisted(() => ({
+ cancelSession: vi.fn(),
+ getClaudeCodeQuota: vi.fn(),
+ getCodexQuota: vi.fn(),
+ getSessionInfo: vi.fn(),
+ sendPrompt: vi.fn(),
+ startSession: vi.fn(),
+ stopSession: vi.fn(),
+ submitIntervention: vi.fn(),
+}));
+
+vi.mock('@/utils/electron/ipc', () => ({
+ ensureElectronIpc: () => ({
+ heterogeneousAgent: mockHeterogeneousAgent,
+ }),
+}));
+
+describe('heterogeneousAgentService', () => {
+ it('forwards getClaudeCodeQuota params over IPC and returns the snapshot', async () => {
+ const { heterogeneousAgentService } = await import('./heterogeneousAgent');
+
+ const snapshot = {
+ error: null,
+ provider: 'claude-code',
+ scopedWeekly: null,
+ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
+ status: 'ok',
+ updatedAt: 1,
+ weekly: null,
+ };
+ mockHeterogeneousAgent.getClaudeCodeQuota.mockResolvedValue(snapshot);
+
+ const params = { env: { CLAUDE_CONFIG_DIR: '/custom/claude' } };
+ await expect(heterogeneousAgentService.getClaudeCodeQuota(params)).resolves.toEqual(snapshot);
+ expect(mockHeterogeneousAgent.getClaudeCodeQuota).toHaveBeenCalledWith(params);
+ });
+
+ it('forwards getCodexQuota params over IPC and returns the snapshot', async () => {
+ const { heterogeneousAgentService } = await import('./heterogeneousAgent');
+
+ const snapshot = {
+ error: null,
+ provider: 'codex',
+ session: null,
+ status: 'ok',
+ updatedAt: 1,
+ weekly: null,
+ };
+ mockHeterogeneousAgent.getCodexQuota.mockResolvedValue(snapshot);
+
+ const params = { command: '/usr/local/bin/codex', env: { CODEX_HOME: '/tmp/codex' } };
+ await expect(heterogeneousAgentService.getCodexQuota(params)).resolves.toEqual(snapshot);
+ expect(mockHeterogeneousAgent.getCodexQuota).toHaveBeenCalledWith(params);
+ });
+
+ it('forwards session lifecycle calls over IPC', async () => {
+ const { heterogeneousAgentService } = await import('./heterogeneousAgent');
+
+ mockHeterogeneousAgent.startSession.mockResolvedValue({ sessionId: 's1' });
+ await expect(
+ heterogeneousAgentService.startSession({ agentType: 'claude-code', command: 'claude' }),
+ ).resolves.toEqual({ sessionId: 's1' });
+
+ await heterogeneousAgentService.sendPrompt('s1', 'hi', 'op1');
+ expect(mockHeterogeneousAgent.sendPrompt).toHaveBeenCalledWith({
+ imageList: undefined,
+ operationId: 'op1',
+ prompt: 'hi',
+ sessionId: 's1',
+ });
+
+ await heterogeneousAgentService.cancelSession('s1');
+ expect(mockHeterogeneousAgent.cancelSession).toHaveBeenCalledWith({ sessionId: 's1' });
+
+ await heterogeneousAgentService.stopSession('s1');
+ expect(mockHeterogeneousAgent.stopSession).toHaveBeenCalledWith({ sessionId: 's1' });
+
+ await heterogeneousAgentService.getSessionInfo('s1');
+ expect(mockHeterogeneousAgent.getSessionInfo).toHaveBeenCalledWith({ sessionId: 's1' });
+
+ await heterogeneousAgentService.submitIntervention({
+ operationId: 'op1',
+ result: { answer: 'yes' },
+ toolCallId: 't1',
+ });
+ expect(mockHeterogeneousAgent.submitIntervention).toHaveBeenCalledWith({
+ operationId: 'op1',
+ result: { answer: 'yes' },
+ toolCallId: 't1',
+ });
+ });
+});
diff --git a/src/services/electron/heterogeneousAgent.ts b/src/services/electron/heterogeneousAgent.ts
index f06eca7a427..e1df062332f 100644
--- a/src/services/electron/heterogeneousAgent.ts
+++ b/src/services/electron/heterogeneousAgent.ts
@@ -1,4 +1,4 @@
-import type { CodexQuotaSnapshot } from '@lobechat/electron-client-ipc';
+import type { ClaudeCodeQuotaSnapshot, CodexQuotaSnapshot } from '@lobechat/electron-client-ipc';
import { ensureElectronIpc } from '@/utils/electron/ipc';
@@ -49,6 +49,12 @@ class HeterogeneousAgentService {
return this.ipc.heterogeneousAgent.getCodexQuota(params);
}
+ async getClaudeCodeQuota(params?: {
+ env?: Record<string, string>;
+ }): Promise<ClaudeCodeQuotaSnapshot> {
+ return this.ipc.heterogeneousAgent.getClaudeCodeQuota(params);
+ }
+
/**
* Submit the user's answer (or cancellation) for a pending CC
* AskUserQuestion intervention. The main process routes it to the