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.

🐛 fix(agent-quota): make Claude Code account switching actually switch the login (#21342)

Arvin Xu7979f96b0082
diff --git a/apps/desktop/src/main/const/heteroAgent.ts b/apps/desktop/src/main/const/heteroAgent.ts
index fd723ebbf62..939816a6cdd 100644
--- a/apps/desktop/src/main/const/heteroAgent.ts
+++ b/apps/desktop/src/main/const/heteroAgent.ts
@@ -8,10 +8,12 @@
* - `<HETERO_AGENT_DIR>/files` — downloaded-file cache
* - `<HETERO_AGENT_DIR>/tracing` — CLI trace sessions (packaged / opted-in)
* - `<HETERO_AGENT_DIR>/bindings` — stable provider-bound CLI profiles
+ * - `<HETERO_AGENT_DIR>/claude-accounts` — one Claude Code login per account
* - `<HETERO_AGENT_DIR>/runs` — per-run resources removed after execution
*/
export const HETERO_AGENT_DIR = 'heteroAgent';
export const HETERO_AGENT_BINDINGS_DIR = `${HETERO_AGENT_DIR}/bindings`;
+export const HETERO_AGENT_CLAUDE_ACCOUNTS_DIR = `${HETERO_AGENT_DIR}/claude-accounts`;
export const HETERO_AGENT_FILES_DIR = `${HETERO_AGENT_DIR}/files`;
export const HETERO_AGENT_RUNS_DIR = `${HETERO_AGENT_DIR}/runs`;
export const HETERO_AGENT_TRACING_DIR = `${HETERO_AGENT_DIR}/tracing`;
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
index fab6916d80a..6eec4b72795 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
@@ -1,3 +1,4 @@
+import type { ClaudeCodeAccountProfiles } from '@/modules/heterogeneousAgent/claudeCodeAccounts';
import type { RemoteServerAuth } from '@/modules/heterogeneousAgent/fileStorePort';
import type HeterogeneousAgentImplementation from './HeterogeneousAgentImpl';
@@ -16,6 +17,7 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
static override readonly groupName = 'heterogeneousAgent';
private implementationPromise?: Promise<Implementation>;
+ private claudeCodeAccountsPromise?: Promise<ClaudeCodeAccountProfiles>;
/**
* Resolved on this side of the lazy boundary and handed to the implementation.
@@ -49,6 +51,23 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
return this.implementationPromise;
};
+ /** Local Claude Code logins (default + per-account profiles), loaded on first use. */
+ private getClaudeCodeAccounts = (): Promise<ClaudeCodeAccountProfiles> => {
+ this.claudeCodeAccountsPromise ??= Promise.all([
+ import('@/modules/heterogeneousAgent/claudeCodeAccountsHost'),
+ import('./HeterogeneousAgentImpl'),
+ ])
+ .then(([{ createClaudeCodeAccountProfiles }, { buildInheritedSpawnEnv }]) =>
+ createClaudeCodeAccountProfiles(this.app, () => buildInheritedSpawnEnv()),
+ )
+ .catch((error) => {
+ this.claudeCodeAccountsPromise = undefined;
+ throw error;
+ });
+
+ return this.claudeCodeAccountsPromise;
+ };
+
@IpcMethod()
async startSession(...args: Parameters<Implementation['startSession']>) {
return (await this.getImplementation()).startSession(...args);
@@ -106,6 +125,50 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
return (await this.getImplementation()).getClaudeCodeQuota(...args);
}
+ /** Every Claude Code account signed in on this machine, and where its login lives. */
+ @IpcMethod()
+ async listClaudeCodeAccounts() {
+ return (await this.getClaudeCodeAccounts()).list();
+ }
+
+ /** The local login a run for this provider account must spawn with. */
+ @IpcMethod()
+ async resolveClaudeCodeAccount(params: { externalAccountId: string }) {
+ return (await this.getClaudeCodeAccounts()).resolve(params.externalAccountId);
+ }
+
+ /**
+ * External-provider routing flags (`CLAUDE_CODE_USE_BEDROCK` …) a session
+ * spawn inherits from this desktop's process env. The renderer cannot see
+ * that env, yet those flags take the run off the subscription login.
+ */
+ @IpcMethod()
+ async getClaudeCodeInheritedRoutingEnv() {
+ const [{ buildInheritedSpawnEnv }, { CLAUDE_CODE_EXTERNAL_ROUTING_ENV_KEYS }] =
+ await Promise.all([
+ import('./HeterogeneousAgentImpl'),
+ import('@lobechat/heterogeneous-agents/quota'),
+ ]);
+ const inherited = buildInheritedSpawnEnv();
+ const flags: Record<string, string> = {};
+ for (const key of CLAUDE_CODE_EXTERNAL_ROUTING_ENV_KEYS) {
+ const value = inherited[key];
+ if (value !== undefined) flags[key] = value;
+ }
+ return flags;
+ }
+
+ /** Sign an account in to its own profile; resolves once the browser login lands. */
+ @IpcMethod()
+ async loginClaudeCodeAccount(params: { email?: string } = {}) {
+ return (await this.getClaudeCodeAccounts()).login(params);
+ }
+
+ @IpcMethod()
+ async cancelClaudeCodeAccountLogin() {
+ return (await this.getClaudeCodeAccounts()).cancelLogin();
+ }
+
@IpcMethod()
async getKimiCodeQuota(...args: Parameters<Implementation['getKimiCodeQuota']>) {
return (await this.getImplementation()).getKimiCodeQuota(...args);
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
index d243384dfa4..049c02983d0 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -182,6 +182,7 @@ import { createLogger } from '@/utils/logger';
import BrowserControlCtr from './BrowserControlCtr';
import { sendPromptWithCodexAppServer } from './codexAppServer';
import type { AgentSession, CliTraceSession, SendPromptParams } from './heterogeneousAgentSession';
+import { claudeProfileDirOf } from './heterogeneousAgentSession';
import RemoteServerConfigCtr from './RemoteServerConfigCtr';
const logger = createLogger('controllers:HeterogeneousAgentCtr');
@@ -1736,7 +1737,7 @@ export default class HeterogeneousAgentCtr {
) {
try {
const ensured = await ensureClaudeCodeResumeTranscript({
- configDir: session.hostedProviderBinding?.profileDir,
+ configDir: claudeProfileDirOf(session),
cwd: session.cwd,
messages: params.resumeReplayMessages,
sessionId: session.agentSessionId,
@@ -3467,10 +3468,7 @@ export default class HeterogeneousAgentCtr {
}
const turn = (await this.readClaudeCodeReplayTurn({
- configDir:
- params.replayTranscriptConfigDir ??
- session.env?.CLAUDE_CONFIG_DIR ??
- session.hostedProviderBinding?.profileDir,
+ configDir: params.replayTranscriptConfigDir ?? claudeProfileDirOf(session),
cwd: session.cwd,
// The prompt this run was given — re-checked here, not just at probe time.
expectedPrompt: params.prompt,
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.codexLifecycle.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.codexLifecycle.test.ts
index 97ba416c8ec..4e5d1d8c7ff 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.codexLifecycle.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.codexLifecycle.test.ts
@@ -60,6 +60,10 @@ describe('HeterogeneousAgentCtr Codex lifecycle', () => {
controls.codexAppServerConsumerCount.value = 0;
controls.codexAppServerRunMock.mockReset();
vi.stubEnv('LOBE_CODEX_APP_SERVER', '');
+ // A desktop launched from an agent shell inherits that run's identity;
+ // the assertions below are about what the app adds, not the host shell.
+ for (const key of ['LOBEHUB_PROCESS_TOPIC', 'AGENT_BROWSER_NAMESPACE'])
+ vi.stubEnv(key, undefined);
vi.mocked(existsSync).mockReturnValue(true);
// The fake desktop path is a directory for spawn preflight; ledger IO stays real.
vi.mocked(statSync).mockReturnValue({ isDirectory: () => true } as ReturnType<typeof statSync>);
diff --git a/apps/desktop/src/main/controllers/heterogeneousAgentSession.test.ts b/apps/desktop/src/main/controllers/heterogeneousAgentSession.test.ts
new file mode 100644
index 00000000000..e8ab2af05fc
--- /dev/null
+++ b/apps/desktop/src/main/controllers/heterogeneousAgentSession.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest';
+
+import { claudeProfileDirOf } from './heterogeneousAgentSession';
+
+describe('claudeProfileDirOf', () => {
+ it('follows a profile the session env picked, e.g. a routed account', () => {
+ // Resume recovery used to read only the hosted binding, so a rebuilt
+ // transcript for a routed account landed where `--resume` never looks.
+ expect(claudeProfileDirOf({ env: { CLAUDE_CONFIG_DIR: '/profiles/work' } })).toBe(
+ '/profiles/work',
+ );
+ });
+
+ it('falls back to the hosted binding profile, then the default ~/.claude', () => {
+ expect(
+ claudeProfileDirOf({ hostedProviderBinding: { profileDir: '/bindings/x' } as never }),
+ ).toBe('/bindings/x');
+ expect(claudeProfileDirOf({})).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts b/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts
index 433acb34a9e..3f21785445c 100644
--- a/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts
+++ b/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts
@@ -161,3 +161,14 @@ export interface CliTraceSession {
dir: string;
writeQueue: Promise<void>;
}
+
+/**
+ * The Claude profile a session's CLI reads its transcripts from: a profile the
+ * session env picked (agent env or account routing via `CLAUDE_CONFIG_DIR`),
+ * else a hosted provider binding's profile, else the default `~/.claude`
+ * (`undefined`). Resume recovery and replay must agree with the spawn on it.
+ */
+export const claudeProfileDirOf = (
+ session: Pick<AgentSession, 'env' | 'hostedProviderBinding'>,
+): string | undefined =>
+ session.env?.CLAUDE_CONFIG_DIR ?? session.hostedProviderBinding?.profileDir;
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeAccounts.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeAccounts.test.ts
new file mode 100644
index 00000000000..ca883f6aa8f
--- /dev/null
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeAccounts.test.ts
@@ -0,0 +1,330 @@
+import { EventEmitter } from 'node:events';
+import { existsSync, readFileSync } from 'node:fs';
+import type * as FsPromises from 'node:fs/promises';
+import { lstat, mkdir, mkdtemp, readlink, rm, symlink, utimes, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ ClaudeCodeAccountProfiles,
+ type ClaudeCodeLoginSpawnParams,
+ resolveDefaultClaudeConfigDir,
+ RETIRED_PROFILE_GRACE_MS,
+} from './claudeCodeAccounts';
+
+const fakeFs = vi.hoisted(() => ({
+ home: '',
+ /** Simulated Keychain latency of each login check, and how many overlap. */
+ loginCheckDelayMs: 0,
+ inFlight: 0,
+ maxInFlight: 0,
+}));
+
+vi.mock('node:fs/promises', async (importOriginal) => {
+ const actual = await importOriginal<typeof FsPromises>();
+ return { ...actual, symlink: vi.fn(actual.symlink) };
+});
+
+vi.mock('node:child_process', () => ({
+ execFile: vi.fn((_cmd: string, _args: string[], _opts: unknown, callback: () => void) =>
+ callback(),
+ ),
+}));
+
+// The sampler reads `<profile>/.claude.json` for identity and the profile's
+// credentials for "signed in"; mirror both over the temp dirs used here.
+vi.mock('@lobechat/heterogeneous-agents/quota-sampler', () => {
+ const dirOf = (options: { claudeConfigDirPath?: string | null }) =>
+ options.claudeConfigDirPath ?? path.join(fakeFs.home, '.claude');
+ const identityFile = (options: { claudeConfigDirPath?: string | null }) =>
+ options.claudeConfigDirPath
+ ? path.join(options.claudeConfigDirPath, '.claude.json')
+ : path.join(fakeFs.home, '.claude.json');
+ return {
+ claudeCodeKeychainService: (dir?: string | null) => `svc-${dir ?? 'default'}`,
+ hasClaudeCodeLogin: async (options: { claudeConfigDirPath?: string | null }) => {
+ fakeFs.inFlight += 1;
+ fakeFs.maxInFlight = Math.max(fakeFs.maxInFlight, fakeFs.inFlight);
+ await new Promise((resolve) => setTimeout(resolve, fakeFs.loginCheckDelayMs));
+ fakeFs.inFlight -= 1;
+ return existsSync(path.join(dirOf(options), '.credentials.json'));
+ },
+ readClaudeCodeIdentity: async (options: { claudeConfigDirPath?: string | null }) => {
+ try {
+ const { oauthAccount } = JSON.parse(readFileSync(identityFile(options), 'utf8'));
+ return { email: oauthAccount.emailAddress, externalAccountId: oauthAccount.accountUuid };
+ } catch {
+ return null;
+ }
+ },
+ };
+});
+
+const writeLogin = async (configDir: string | null, accountUuid: string) => {
+ const dir = configDir ?? path.join(fakeFs.home, '.claude');
+ const identityFile = configDir
+ ? path.join(configDir, '.claude.json')
+ : path.join(fakeFs.home, '.claude.json');
+ await mkdir(dir, { recursive: true });
+ await writeFile(
+ identityFile,
+ JSON.stringify({ oauthAccount: { accountUuid, emailAddress: `${accountUuid}@x.com` } }),
+ );
+ await writeFile(path.join(dir, '.credentials.json'), '{}');
+};
+
+class FakeChild extends EventEmitter {
+ kill = vi.fn((signal: string) => {
+ this.emit('exit', null, signal);
+ return true;
+ });
+}
+
+describe('ClaudeCodeAccountProfiles', () => {
+ let root: string;
+ let spawned: ClaudeCodeLoginSpawnParams[];
+ let child: FakeChild;
+ let profiles: ClaudeCodeAccountProfiles;
+
+ beforeEach(async () => {
+ fakeFs.home = await mkdtemp(path.join(tmpdir(), 'cc-accounts-home-'));
+ Object.assign(fakeFs, { inFlight: 0, loginCheckDelayMs: 0, maxInFlight: 0 });
+ root = path.join(fakeFs.home, 'profiles');
+ spawned = [];
+ profiles = new ClaudeCodeAccountProfiles({
+ defaultConfigDir: path.join(fakeFs.home, '.claude'),
+ root,
+ spawnLogin: async (params) => {
+ spawned.push(params);
+ child = new FakeChild();
+ return child as never;
+ },
+ });
+ });
+
+ afterEach(async () => {
+ await rm(fakeFs.home, { force: true, recursive: true });
+ });
+
+ /** Start a login and let the fake CLI sign `accountUuid` in to the new profile. */
+ const loginAs = async (accountUuid: string, email?: string) => {
+ const before = spawned.length;
+ const pending = profiles.login({ email });
+ await vi.waitFor(() => expect(spawned.length).toBe(before + 1));
+ const { configDir } = spawned.at(-1)!;
+ await writeLogin(configDir, accountUuid);
+ child.emit('exit', 0, null);
+ return pending;
+ };
+
+ it('lists the default login and each signed-in profile once', async () => {
+ await writeLogin(null, 'acc-default');
+ await writeLogin(path.join(root, 'a'), 'acc-a');
+ await writeLogin(path.join(root, 'b'), 'acc-a');
+ await mkdir(path.join(root, 'signed-out'), { recursive: true });
+
+ const accounts = await profiles.list();
+
+ expect(accounts.map((a) => [a.configDir, a.identity.externalAccountId])).toEqual([
+ [null, 'acc-default'],
+ [path.join(root, 'a'), 'acc-a'],
+ ]);
+ });
+
+ it('checks every login at once instead of one Keychain lookup after another', async () => {
+ await writeLogin(null, 'acc-default');
+ for (const id of ['a', 'b', 'c']) await writeLogin(path.join(root, id), `acc-${id}`);
+ fakeFs.loginCheckDelayMs = 20;
+
+ const accounts = await profiles.list();
+
+ expect(fakeFs.maxInFlight).toBe(4);
+ // Concurrency does not change the default-first order.
+ expect(accounts.map((a) => a.identity.externalAccountId)).toEqual([
+ 'acc-default',
+ 'acc-a',
+ 'acc-b',
+ 'acc-c',
+ ]);
+ });
+
+ it('resolves an account to the default login, its profile, or missing', async () => {
+ await writeLogin(null, 'acc-default');
+ await writeLogin(path.join(root, 'p1'), 'acc-p1');
+
+ expect(await profiles.resolve('acc-default')).toEqual({ kind: 'default' });
+ expect(await profiles.resolve('acc-p1')).toEqual({
+ configDir: path.join(root, 'p1'),
+ kind: 'profile',
+ });
+ expect(await profiles.resolve('acc-elsewhere')).toEqual({ kind: 'missing' });
+ });
+
+ it('shares transcripts with the default dir so a switched conversation can resume', async () => {
+ await writeLogin(path.join(root, 'p1'), 'acc-p1');
+
+ await profiles.resolve('acc-p1');
+
+ const link = path.join(root, 'p1', 'projects');
+ expect((await lstat(link)).isSymbolicLink()).toBe(true);
+ expect(await readlink(link)).toBe(path.join(fakeFs.home, '.claude', 'projects'));
+ });
+
+ it('shares with an inherited CLAUDE_CONFIG_DIR, the dir the default login runs on', async () => {
+ const inheritedDir = path.join(fakeFs.home, 'custom-claude');
+ profiles = new ClaudeCodeAccountProfiles({
+ defaultConfigDir: resolveDefaultClaudeConfigDir(
+ { CLAUDE_CONFIG_DIR: inheritedDir },
+ fakeFs.home,
+ ),
+ root,
+ spawnLogin: async () => new FakeChild() as never,
+ });
+ await writeLogin(path.join(root, 'p1'), 'acc-p1');
+
+ await profiles.resolve('acc-p1');
+
+ expect(await readlink(path.join(root, 'p1', 'projects'))).toBe(
+ path.join(inheritedDir, 'projects'),
+ );
+ });
+
+ it('falls back to ~/.claude when no CLAUDE_CONFIG_DIR is inherited', () => {
+ expect(resolveDefaultClaudeConfigDir({}, '/home/me')).toBe(path.join('/home/me', '.claude'));
+ expect(resolveDefaultClaudeConfigDir({ CLAUDE_CONFIG_DIR: ' ' }, '/home/me')).toBe(
+ path.join('/home/me', '.claude'),
+ );
+ });
+
+ it('still resolves a profile when its shared entries cannot be linked', async () => {
+ await writeLogin(path.join(root, 'p1'), 'acc-p1');
+ // `~/.claude` is not a directory, so even creating `projects` fails.
+ await writeFile(path.join(fakeFs.home, '.claude'), 'not a dir');
+
+ expect(await profiles.resolve('acc-p1')).toEqual({
+ configDir: path.join(root, 'p1'),
+ kind: 'profile',
+ });
+ });
+
+ it('links shared directories as junctions on Windows, which need no elevation', async () => {
+ await writeLogin(path.join(root, 'p1'), 'acc-p1');
+ await mkdir(path.join(fakeFs.home, '.claude', 'skills'), { recursive: true });
+ await writeFile(path.join(fakeFs.home, '.claude', 'settings.json'), '{}');
+ const platform = process.platform;
+ Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' });
+ try {
+ await profiles.resolve('acc-p1');
+ } finally {
+ Object.defineProperty(process, 'platform', { configurable: true, value: platform });
+ }
+
+ const typeOf = (name: string) =>
+ vi
+ .mocked(symlink)
+ .mock.calls.find(([, target]) => target === path.join(root, 'p1', name))?.[2];
+ expect(typeOf('projects')).toBe('junction');
+ expect(typeOf('skills')).toBe('junction');
+ expect(typeOf('settings.json')).toBeUndefined();
+ });
+
+ it('signs a new account in to its own profile through `claude auth login`', async () => {
+ const account = await loginAs('acc-new', '[email protected]');
+
+ expect(spawned).toHaveLength(1);
+ expect(spawned[0].args).toEqual(['auth', 'login', '--claudeai', '--email', '[email protected]']);
+ expect(path.dirname(spawned[0].configDir)).toBe(root);
+ expect(account).toEqual({
+ configDir: spawned[0].configDir,
+ identity: expect.objectContaining({ externalAccountId: 'acc-new' }),
+ });
+ expect(await profiles.resolve('acc-new')).toEqual({
+ configDir: spawned[0].configDir,
+ kind: 'profile',
+ });
+ });
+
+ it('replaces the older profile when an account signs in again', async () => {
+ const first = await loginAs('acc-1');
+ const second = await loginAs('acc-1');
+
+ expect(second.configDir).not.toBe(first.configDir);
+ expect((await profiles.list()).map((a) => a.configDir)).toEqual([second.configDir]);
+ expect(await profiles.resolve('acc-1')).toEqual({
+ configDir: second.configDir,
+ kind: 'profile',
+ });
+ });
+
+ it('keeps a replaced profile for in-flight runs, then forgets it after the grace period', async () => {
+ const first = await loginAs('acc-1');
+ await loginAs('acc-1');
+
+ // A run that recorded the old path can still recover its transcript there.
+ expect(existsSync(first.configDir!)).toBe(true);
+
+ const expired = (Date.now() - RETIRED_PROFILE_GRACE_MS - 60_000) / 1000;
+ await utimes(path.join(first.configDir!, '.lobehub-retired'), expired, expired);
+ await profiles.list();
+
+ expect(existsSync(first.configDir!)).toBe(false);
+ });
+
+ it('honors a cancel that lands after the CLI already exited', async () => {
+ await writeLogin(path.join(root, 'old'), 'acc-1');
+ const pending = profiles.login();
+ await vi.waitFor(() => expect(spawned).toHaveLength(1));
+ await writeLogin(spawned[0].configDir, 'acc-1');
+
+ child.emit('exit', 0, null);
+ profiles.cancelLogin();
+
+ await expect(pending).rejects.toThrow('cancelled');
+ // Nothing committed: the new login is gone and the existing profile untouched.
+ expect(existsSync(spawned[0].configDir)).toBe(false);
+ expect(await profiles.resolve('acc-1')).toEqual({
+ configDir: path.join(root, 'old'),
+ kind: 'profile',
+ });
+ });
+
+ it('drops the new profile when the account is already the default login', async () => {
+ await writeLogin(null, 'acc-default');
+
+ const account = await loginAs('acc-default');
+
+ expect(account.configDir).toBeNull();
+ expect(existsSync(spawned[0].configDir)).toBe(false);
+ });
+
+ it('cancels a sign-in in progress and removes its half-made profile', async () => {
+ const pending = profiles.login();
+ await vi.waitFor(() => expect(spawned).toHaveLength(1));
+
+ expect(profiles.cancelLogin()).toBe(true);
+
+ await expect(pending).rejects.toThrow('cancelled');
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ expect(existsSync(spawned[0].configDir)).toBe(false);
+ });
+
+ it('rejects a second sign-in while one is running', async () => {
+ const pending = profiles.login();
+
+ await expect(profiles.login()).rejects.toThrow('already in progress');
+
+ profiles.cancelLogin();
+ await expect(pending).rejects.toThrow();
+ });
+
+ it('fails a sign-in that exits without a login', async () => {
+ const pending = profiles.login();
+ await vi.waitFor(() => expect(spawned).toHaveLength(1));
+ child.emit('exit', 0, null);
+
+ await expect(pending).rejects.toThrow('without a login');
+ expect(existsSync(spawned[0].configDir)).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeAccounts.ts b/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeAccounts.ts
new file mode 100644
index 00000000000..ba0afc83714
--- /dev/null
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeAccounts.ts
@@ -0,0 +1,342 @@
+import { type ChildProcess, execFile } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { lstat, mkdir, readdir, rm, stat, symlink, writeFile } from 'node:fs/promises';
+import { homedir } from 'node:os';
+import path from 'node:path';
+
+import type {
+ ClaudeCodeAccountResolution,
+ ClaudeCodeLocalAccount,
+ QuotaAccountIdentity,
+} from '@lobechat/heterogeneous-agents/quota';
+import {
+ claudeCodeKeychainService,
+ hasClaudeCodeLogin,
+ readClaudeCodeIdentity,
+} from '@lobechat/heterogeneous-agents/quota-sampler';
+
+const DIRECTORY_MODE = 0o700;
+
+/**
+ * A profile replaced by a newer sign-in of the same account is retired, not
+ * deleted: an in-flight run may have recorded its path, and recovery after a
+ * restart replays the transcript from there. It is forgotten once the grace
+ * period has passed.
+ */
+const RETIRED_MARKER = '.lobehub-retired';
+export const RETIRED_PROFILE_GRACE_MS = 7 * 24 * 60 * 60 * 1000;
+
+/** OAuth in the browser is human-paced; give up on an abandoned login eventually. */
+export const CLAUDE_CODE_LOGIN_TIMEOUT_MS = 10 * 60 * 1000;
+
+/**
+ * Entries of the default login's config dir a per-account profile links instead of
+ * owning. Transcripts (`projects`) are shared so a conversation can switch
+ * accounts and still `--resume` its native history; the rest is the user's own
+ * CLI setup, which should not change with the account. Credentials and the
+ * account identity (`.claude.json`) stay per profile — that is the point.
+ */
+const SHARED_ENTRIES = [
+ 'projects',
+ 'settings.json',
+ 'CLAUDE.md',
+ 'agents',
+ 'commands',
+ 'skills',
+ 'plugins',
+ 'output-styles',
+] as const;
+
+export type { ClaudeCodeAccountResolution, ClaudeCodeLocalAccount };
+
+export interface ClaudeCodeLoginSpawnParams {
+ args: string[];
+ configDir: string;
+}
+
+interface LoginInProgress {
+ cancelled?: boolean;
+ configDir: string;
+ process?: ChildProcess;
+}
+
+/**
+ * The config dir of the default login — the one a spawn with no routing
+ * override uses, and the profiles share entries with: a `CLAUDE_CONFIG_DIR`
+ * the desktop process inherited, else `~/.claude`. Same resolution as the
+ * login lookup (`readSignedInIdentity(null)`), so both sides of an account
+ * switch see one transcript tree.
+ */
+export const resolveDefaultClaudeConfigDir = (
+ inheritedEnv: Record<string, string | undefined>,
+ home: string = homedir(),
+): string => {
+ const inherited = inheritedEnv.CLAUDE_CONFIG_DIR;
+ return inherited?.trim() ? inherited : path.join(home, '.claude');
+};
+
+export interface ClaudeCodeAccountProfilesOptions {
+ /** The default login's config dir, which profiles share entries with. */
+ defaultConfigDir: string;
+ /** Root holding one directory per account profile. */
+ root: string;
+ /** Start `claude <args>` with `CLAUDE_CONFIG_DIR=<configDir>`. */
+ spawnLogin: (params: ClaudeCodeLoginSpawnParams) => Promise<ChildProcess>;
+ timeoutMs?: number;
+}
+
+/**
+ * The signed-in identity of one login. `null` configDir is whatever a spawn
+ * with no routing override uses — the default login, or a `CLAUDE_CONFIG_DIR`
+ * the desktop process itself inherited.
+ */
+const readSignedInIdentity = async (
+ configDir: string | null,
+): Promise<QuotaAccountIdentity | null> => {
+ const options = { claudeConfigDirPath: configDir };
+ const identity = await readClaudeCodeIdentity(options).catch(() => null);
+ if (!identity?.externalAccountId) return null;
+ return (await hasClaudeCodeLogin(options).catch(() => false)) ? identity : null;
+};
+
+/**
+ * Drop a profile and the macOS Keychain item its login lives in — removing
+ * only the directory would strand a live OAuth token in the Keychain. `rm`
+ * unlinks the shared-entry symlinks without following them into the default dir.
+ */
+const forgetProfile = async (configDir: string) => {
+ await rm(configDir, { force: true, recursive: true });
+ if (process.platform !== 'darwin') return;
+ await new Promise<void>((resolve) => {
+ execFile(
+ 'security',
+ ['delete-generic-password', '-s', claudeCodeKeychainService(configDir)],
+ { timeout: 3000 },
+ () => resolve(),
+ );
+ });
+};
+
+/**
+ * Windows only creates file and directory symlinks with Developer Mode or
+ * elevation; a junction links a directory without either. Elsewhere the type
+ * is ignored.
+ */
+const linkTypeFor = async (source: string): Promise<'junction' | undefined> => {
+ if (process.platform !== 'win32') return undefined;
+ return (await stat(source)).isDirectory() ? 'junction' : undefined;
+};
+
+const retireProfile = async (configDir: string) => {
+ await writeFile(path.join(configDir, RETIRED_MARKER), new Date().toISOString());
+};
+
+const exists = async (target: string) => {
+ try {
+ await lstat(target);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+/**
+ * The Claude Code logins this machine can run on: the default login plus one
+ * isolated `CLAUDE_CONFIG_DIR` profile per account the user signed in to from
+ * LobeHub. Account routing maps the account the server picked to one of these;
+ * an account with no local login here cannot run here.
+ */
+export class ClaudeCodeAccountProfiles {
+ readonly #defaultConfigDir: string;
+ readonly #root: string;
+ readonly #spawnLogin: ClaudeCodeAccountProfilesOptions['spawnLogin'];
+ readonly #timeoutMs: number;
+ #login?: LoginInProgress;
+
+ constructor(options: ClaudeCodeAccountProfilesOptions) {
+ this.#defaultConfigDir = options.defaultConfigDir;
+ this.#root = options.root;
+ this.#spawnLogin = options.spawnLogin;
+ this.#timeoutMs = options.timeoutMs ?? CLAUDE_CODE_LOGIN_TIMEOUT_MS;
+ }
+
+ /** Every signed-in local login, default first; one entry per account. */
+ list = async (): Promise<ClaudeCodeLocalAccount[]> => {
+ const accounts: ClaudeCodeLocalAccount[] = [];
+ const seen = new Set<string>();
+ const add = (configDir: string | null, identity: QuotaAccountIdentity | null) => {
+ const id = identity?.externalAccountId;
+ if (!identity || !id || seen.has(id)) return;
+ seen.add(id);
+ accounts.push({ configDir, identity });
+ };
+
+ // A sign-in still running has no account yet.
+ const configDirs = [
+ null,
+ ...(await this.#profileDirs()).filter((dir) => dir !== this.#login?.configDir),
+ ];
+ // Each check may wait on a Keychain lookup with its own timeout: scan all
+ // logins at once, then keep the default-first order when deduping.
+ const identities = await Promise.all(configDirs.map((dir) => readSignedInIdentity(dir)));
+ configDirs.forEach((dir, index) => add(dir, identities[index]));
+
+ return accounts;
+ };
+
+ /** Map a provider account to the local login a spawn should use for it. */
+ resolve = async (externalAccountId: string): Promise<ClaudeCodeAccountResolution> => {
+ const match = (await this.list()).find(
+ (account) => account.identity.externalAccountId === externalAccountId,
+ );
+ if (!match) return { kind: 'missing' };
+ if (!match.configDir) return { kind: 'default' };
+
+ // Sharing is best-effort: the profile runs without it (a missing
+ // transcript is rebuilt into the profile on resume), so a link problem
+ // must not fail the lookup and with it the run.
+ await this.#linkSharedEntries(match.configDir).catch(() => {});
+ return { configDir: match.configDir, kind: 'profile' };
+ };
+
+ /**
+ * Sign an account in to a fresh profile through `claude auth login`, which
+ * opens the browser and returns once the OAuth callback lands. A login that
+ * turns out to be an account this machine already has replaces that
+ * account's profile (or is dropped, for the default login), so each account
+ * keeps exactly one local login.
+ */
+ login = async (options: { email?: string } = {}): Promise<ClaudeCodeLocalAccount> => {
+ if (this.#login) throw new Error('A Claude Code sign-in is already in progress');
+
+ const configDir = path.join(this.#root, randomUUID());
+ const login: LoginInProgress = { configDir };
+ this.#login = login;
+ // Cancel can land at any await, including after the CLI already exited:
+ // nothing may be committed once it has.
+ const assertNotCancelled = () => {
+ if (login.cancelled) throw new Error('Claude Code sign-in was cancelled');
+ };
+
+ try {
+ await mkdir(configDir, { mode: DIRECTORY_MODE, recursive: true });
+ await this.#linkSharedEntries(configDir);
+ const args = ['auth', 'login', '--claudeai'];
+ if (options.email) args.push('--email', options.email);
+ assertNotCancelled();
+ const child = await this.#spawnLogin({ args, configDir });
+ login.process = child;
+ if (login.cancelled) child.kill('SIGTERM');
+ await this.#waitForExit(child);
+ assertNotCancelled();
+
+ const identity = await readSignedInIdentity(configDir);
+ if (!identity) throw new Error('Claude Code sign-in finished without a login');
+
+ const existing = (await this.list()).find(
+ (account) => account.identity.externalAccountId === identity.externalAccountId,
+ );
+ assertNotCancelled();
+ if (existing && !existing.configDir) {
+ await forgetProfile(configDir);
+ return existing;
+ }
+ if (existing?.configDir) await retireProfile(existing.configDir);
+
+ return { configDir, identity };
+ } catch (error) {
+ await forgetProfile(configDir);
+ throw error;
+ } finally {
+ this.#login = undefined;
+ }
+ };
+
+ /** Abort the sign-in in progress, if any; its half-made profile is removed. */
+ cancelLogin = (): boolean => {
+ const login = this.#login;
+ if (!login) return false;
+ login.cancelled = true;
+ login.process?.kill('SIGTERM');
+ return true;
+ };
+
+ /** Live profile dirs; retired ones are skipped, and forgotten after the grace period. */
+ #profileDirs = async (): Promise<string[]> => {
+ let dirs: string[];
+ try {
+ const entries = await readdir(this.#root, { withFileTypes: true });
+ dirs = entries
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => path.join(this.#root, entry.name))
+ .sort();
+ } catch {
+ return [];
+ }
+
+ const retiredAt = await Promise.all(
+ dirs.map((dir) =>
+ stat(path.join(dir, RETIRED_MARKER)).then(
+ (marker) => marker.mtimeMs,
+ () => undefined,
+ ),
+ ),
+ );
+ const now = Date.now();
+ await Promise.all(
+ dirs.map((dir, index) => {
+ const at = retiredAt[index];
+ return at !== undefined && now - at > RETIRED_PROFILE_GRACE_MS
+ ? forgetProfile(dir).catch(() => {})
+ : undefined;
+ }),
+ );
+ return dirs.filter((_, index) => retiredAt[index] === undefined);
+ };
+
+ /**
+ * Link the shared entries that exist in the default login's config dir
+ * (always `projects`, so transcripts written from either side land in one
+ * place). Idempotent, and never replaces an entry the profile already has.
+ */
+ #linkSharedEntries = async (configDir: string) => {
+ const defaultDir = this.#defaultConfigDir;
+ await mkdir(path.join(defaultDir, 'projects'), { recursive: true });
+
+ for (const name of SHARED_ENTRIES) {
+ const source = path.join(defaultDir, name);
+ const target = path.join(configDir, name);
+ if (!(await exists(source)) || (await exists(target))) continue;
+ try {
+ await symlink(source, target, await linkTypeFor(source));
+ } catch {
+ // A concurrent resolve made it first, or the filesystem refuses links:
+ // the profile still runs without that entry, and a missing transcript
+ // is rebuilt into the profile on resume.
+ }
+ }
+ };
+
+ #waitForExit = (child: ChildProcess) =>
+ new Promise<void>((resolve, reject) => {
+ let stderr = '';
+ child.stderr?.on('data', (chunk) => {
+ stderr = `${stderr}${chunk}`.slice(-2000);
+ });
+ const timer = setTimeout(() => {
+ child.kill('SIGTERM');
+ reject(new Error('Claude Code sign-in timed out'));
+ }, this.#timeoutMs);
+
+ child.once('error', (error) => {
+ clearTimeout(timer);
+ reject(error);
+ });
+ child.once('exit', (code, signal) => {
+ clearTimeout(timer);
+ if (code === 0) resolve();
+ else if (signal) reject(new Error('Claude Code sign-in was cancelled'));
+ else reject(new Error(stderr.trim() || `claude auth login exited with code ${code}`));
+ });
+ });
+}
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeAccountsHost.ts b/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeAccountsHost.ts
new file mode 100644
index 00000000000..ce016fc0b2f
--- /dev/null
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeAccountsHost.ts
@@ -0,0 +1,41 @@
+import { spawn } from 'node:child_process';
+import path from 'node:path';
+
+import { detectHeterogeneousCliCommand } from '@lobechat/heterogeneous-agents/resolveCliCommand';
+
+import { HETERO_AGENT_CLAUDE_ACCOUNTS_DIR } from '@/const/heteroAgent';
+import type { App } from '@/core/App';
+import { buildProxyEnv } from '@/modules/networkProxy/envBuilder';
+
+import { ClaudeCodeAccountProfiles, resolveDefaultClaudeConfigDir } from './claudeCodeAccounts';
+
+/**
+ * Bind the account profiles to this desktop: profiles live under the app's
+ * storage, and the login runs the same `claude` binary (and PATH / proxy) a
+ * session would. `inheritedEnv` is the session spawn's inherited env, so an
+ * exported `ANTHROPIC_API_KEY` cannot hijack the login either.
+ */
+export const createClaudeCodeAccountProfiles = (
+ app: App,
+ inheritedEnv: () => NodeJS.ProcessEnv,
+): ClaudeCodeAccountProfiles =>
+ new ClaudeCodeAccountProfiles({
+ defaultConfigDir: resolveDefaultClaudeConfigDir(inheritedEnv()),
+ root: path.join(app.appStoragePath, HETERO_AGENT_CLAUDE_ACCOUNTS_DIR),
+ spawnLogin: async ({ args, configDir }) => {
+ const status = await detectHeterogeneousCliCommand('claude-code', 'claude');
+ if (!status.available || !status.path) throw new Error('Claude Code CLI is not installed');
+
+ return spawn(status.path, args, {
+ env: {
+ ...inheritedEnv(),
+ ...(status.resolvedPathEnv ? { PATH: status.resolvedPathEnv } : {}),
+ ...buildProxyEnv(app.storeManager.get('networkProxy')),
+ CLAUDE_CONFIG_DIR: configDir,
+ },
+ // No TTY: the CLI opens the browser and waits for its localhost
+ // OAuth callback instead of prompting for a pasted code.
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ },
+ });
diff --git a/apps/server/src/routers/lambda/agentQuota.ts b/apps/server/src/routers/lambda/agentQuota.ts
index 642081041c5..3a403598610 100644
--- a/apps/server/src/routers/lambda/agentQuota.ts
+++ b/apps/server/src/routers/lambda/agentQuota.ts
@@ -341,12 +341,14 @@ export const agentQuotaRouter = router({
agentId: z.string(),
modelScope: z.string().optional(),
provider: z.string().optional(),
+ runnableExternalAccountIds: z.array(z.string()).optional(),
}),
)
.query(async ({ ctx, input }) =>
ctx.quotaService.selectForAgent(input.agentId, {
modelScope: input.modelScope,
provider: input.provider,
+ runnableExternalAccountIds: input.runnableExternalAccountIds,
}),
),
});
diff --git a/apps/server/src/services/agentQuota/__tests__/index.test.ts b/apps/server/src/services/agentQuota/__tests__/index.test.ts
index ae7549b6ca3..6a4502ff6dc 100644
--- a/apps/server/src/services/agentQuota/__tests__/index.test.ts
+++ b/apps/server/src/services/agentQuota/__tests__/index.test.ts
@@ -184,6 +184,49 @@ describe('AgentQuotaService.selectForAgent', () => {
claudeAccount.id,
);
});
+
+ it('balances only across accounts the caller can run, but still returns a pin', async () => {
+ const bindings = new AgentAccountBindingModel(serverDB, userId);
+ await serverDB.insert(agents).values([{ id: 'agent-3', slug: 'agent-3', title: 'A3', userId }]);
+ const local = await service.ingestSnapshot({
+ identity: { externalAccountId: 'local-acc' },
+ provider: 'claude-code',
+ readings: [],
+ });
+ const remote = await service.ingestSnapshot({
+ identity: { externalAccountId: 'remote-acc' },
+ provider: 'claude-code',
+ readings: [],
+ });
+ await bindings.upsert({ accountId: local.id, agentId: 'agent-3', role: QuotaBindingRole.pool });
+ await bindings.upsert({
+ accountId: remote.id,
+ agentId: 'agent-3',
+ role: QuotaBindingRole.pool,
+ });
+
+ const onlyRemote = { provider: 'claude-code', runnableExternalAccountIds: ['remote-acc'] };
+ const onlyLocal = { provider: 'claude-code', runnableExternalAccountIds: ['local-acc'] };
+ expect((await service.selectForAgent('agent-3', onlyRemote))?.accountId).toBe(remote.id);
+ expect((await service.selectForAgent('agent-3', onlyLocal))?.accountId).toBe(local.id);
+ expect(
+ await service.selectForAgent('agent-3', {
+ provider: 'claude-code',
+ runnableExternalAccountIds: [],
+ }),
+ ).toBeNull();
+
+ // A pinned account the caller cannot run is still the answer.
+ await bindings.upsert({
+ accountId: remote.id,
+ agentId: 'agent-3',
+ role: QuotaBindingRole.pinned,
+ });
+ expect(await service.selectForAgent('agent-3', onlyLocal)).toMatchObject({
+ accountId: remote.id,
+ reason: 'pinned',
+ });
+ });
});
describe('AgentQuotaService.listLatestReadings', () => {
diff --git a/apps/server/src/services/agentQuota/index.ts b/apps/server/src/services/agentQuota/index.ts
index b0822cc8edb..cfa0fd9aac9 100644
--- a/apps/server/src/services/agentQuota/index.ts
+++ b/apps/server/src/services/agentQuota/index.ts
@@ -68,6 +68,17 @@ export interface QuotaUsageTurn {
* `@lobechat/heterogeneous-agents/quota` module; this class only wires it to
* the database models.
*/
+interface SelectAccountOptions {
+ modelScope?: string;
+ now?: number;
+ provider?: string;
+ /**
+ * Provider account ids the caller holds a local login for. Auto mode only
+ * balances across these; omitted = every pooled account is runnable.
+ */
+ runnableExternalAccountIds?: string[];
+}
+
export class AgentQuotaService {
private accounts: AgentProviderAccountModel;
private bindings: AgentAccountBindingModel;
@@ -416,7 +427,7 @@ export class AgentQuotaService {
*/
selectForAgent = async (
agentId: string,
- options: { modelScope?: string; now?: number; provider?: string } = {},
+ options: SelectAccountOptions = {},
): Promise<{
accountId: string;
credentialMode: string;
@@ -441,7 +452,7 @@ export class AgentQuotaService {
private selectAccountId = async (
agentId: string,
- options: { modelScope?: string; now?: number; provider?: string },
+ options: SelectAccountOptions,
): Promise<{ accountId: string; reason: 'pinned' | 'balanced' } | null> => {
let bindings = (await this.bindings.listByAgent(agentId)).filter((b) => b.enabled);
// Bindings are written provider-blind; a caller that names its provider
@@ -457,7 +468,21 @@ export class AgentQuotaService {
const pinned = bindings.find((b) => b.role === QuotaBindingRole.pinned);
if (pinned) return { accountId: pinned.accountId, reason: 'pinned' };
- const pool = bindings.filter((b) => b.role === QuotaBindingRole.pool);
+ let pool = bindings.filter((b) => b.role === QuotaBindingRole.pool);
+ // Auto mode may only land on an account the caller can actually run. A
+ // pin is still returned as-is: the caller must say it cannot run it,
+ // rather than quietly run another account.
+ if (options.runnableExternalAccountIds) {
+ const runnable = new Set(options.runnableExternalAccountIds);
+ // One read of the caller's accounts rather than a lookup per binding.
+ const externalIdById = new Map(
+ (await this.accounts.list()).map((account) => [account.id, account.externalAccountId]),
+ );
+ pool = pool.filter((b) => {
+ const externalId = externalIdById.get(b.accountId);
+ return !!externalId && runnable.has(externalId);
+ });
+ }
if (pool.length === 0) return null;
const now = options.now ?? Date.now();
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 14f9c3f94ee..28ffe197099 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1312,6 +1312,8 @@
"heteroAgent.apiMode.protocolMismatch": "The provider \"{{providerId}}\" does not expose a protocol supported by {{agentType}}.",
"heteroAgent.apiMode.providerUnavailable": "The provider \"{{providerId}}\" is disabled or no longer available.",
"heteroAgent.claudeQuota.accountActive": "In use",
+ "heteroAgent.claudeQuota.accountNotSignedIn": "The Claude Code account {{account}} isn't signed in on this device. Sign in to it from Manage accounts, or switch to another account.",
+ "heteroAgent.claudeQuota.accountResolveFailed": "Couldn't look up this Claude Code account's login on this device. Try again, or switch to another account.",
"heteroAgent.claudeQuota.accountSwitch": "Switch",
"heteroAgent.claudeQuota.accounts": "Accounts",
"heteroAgent.claudeQuota.calendar.accountUnavailable": "The quota account for this snapshot is unavailable",
@@ -1349,7 +1351,9 @@
"heteroAgent.claudeQuota.calendar.windowUtilization": "{{percent}}% used",
"heteroAgent.claudeQuota.errorGeneric": "Couldn't reach the quota service. Tap refresh to retry.",
"heteroAgent.claudeQuota.errorRateLimited": "Claude Code quota is temporarily rate limited. Please try again later.",
+ "heteroAgent.claudeQuota.manage.add": "Add account",
"heteroAgent.claudeQuota.manage.addHint": "Sign in to the Claude Code CLI and the account shows up here automatically.",
+ "heteroAgent.claudeQuota.manage.addHintDesktop": "Each account signs in on this device; runs use the account you pick.",
"heteroAgent.claudeQuota.manage.autoNoAccount": "No eligible account — enable one below.",
"heteroAgent.claudeQuota.manage.autoRoutingTo": "Now routing to {{account}}",
"heteroAgent.claudeQuota.manage.confirmSwitch": "Confirm switch",
@@ -1363,15 +1367,21 @@
"heteroAgent.claudeQuota.manage.exhausted": "Exhausted",
"heteroAgent.claudeQuota.manage.labelField": "Display name",
"heteroAgent.claudeQuota.manage.labelPlaceholder": "Defaults to the account email",
+ "heteroAgent.claudeQuota.manage.loginFailed": "Sign-in didn't finish. Try again.",
+ "heteroAgent.claudeQuota.manage.loginSuccess": "Signed in as {{account}}",
+ "heteroAgent.claudeQuota.manage.loginWaiting": "Finish signing in in your browser…",
"heteroAgent.claudeQuota.manage.modeAuto": "Auto balance",
"heteroAgent.claudeQuota.manage.modeAutoHint": "Route each run to the account with the most weekly headroom.",
"heteroAgent.claudeQuota.manage.modeManual": "Pin one",
"heteroAgent.claudeQuota.manage.modeManualHint": "Always run this agent on the account you pick.",
"heteroAgent.claudeQuota.manage.more": "More",
+ "heteroAgent.claudeQuota.manage.notSignedIn": "Not signed in on this device",
"heteroAgent.claudeQuota.manage.remove": "Remove account",
+ "heteroAgent.claudeQuota.manage.signIn": "Sign in",
"heteroAgent.claudeQuota.manage.title": "Claude Code accounts",
"heteroAgent.claudeQuota.manage.use": "Use",
"heteroAgent.claudeQuota.manage.weeklyLeft": "{{percent}}% weekly",
+ "heteroAgent.claudeQuota.noRunnableAccount": "None of the Claude Code accounts in this agent's rotation are signed in on this device. Sign one in from Manage accounts, or add a signed-in account to the rotation.",
"heteroAgent.claudeQuota.refreshRateLimited": "Quota refresh is temporarily rate limited. Showing the last available data.",
"heteroAgent.claudeQuota.scopedWeekly": "Weekly ({{model}})",
"heteroAgent.claudeQuota.title": "Claude Code quota",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index b15aaf9a195..aa782211c62 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1312,6 +1312,8 @@
"heteroAgent.apiMode.protocolMismatch": "服务商「{{providerId}}」未提供 {{agentType}} 支持的协议。",
"heteroAgent.apiMode.providerUnavailable": "服务商「{{providerId}}」已禁用或不再可用。",
"heteroAgent.claudeQuota.accountActive": "使用中",
+ "heteroAgent.claudeQuota.accountNotSignedIn": "Claude Code 账号 {{account}} 未在本机登录。请在账号管理中登录该账号,或切换到其他账号。",
+ "heteroAgent.claudeQuota.accountResolveFailed": "无法在本机查找该 Claude Code 账号的登录。请重试,或切换到其他账号。",
"heteroAgent.claudeQuota.accountSwitch": "切换",
"heteroAgent.claudeQuota.accounts": "账号",
"heteroAgent.claudeQuota.calendar.accountUnavailable": "当前快照对应的额度账号不可用",
@@ -1349,7 +1351,9 @@
"heteroAgent.claudeQuota.calendar.windowUtilization": "已用 {{percent}}%",
"heteroAgent.claudeQuota.errorGeneric": "无法连接额度服务,点击刷新重试。",
"heteroAgent.claudeQuota.errorRateLimited": "Claude Code 额度查询暂时被限流,请稍后再试。",
+ "heteroAgent.claudeQuota.manage.add": "添加账号",
"heteroAgent.claudeQuota.manage.addHint": "在 Claude Code CLI 中登录后,账号会自动出现在这里。",
+ "heteroAgent.claudeQuota.manage.addHintDesktop": "每个账号在本机单独登录,运行时使用你选定的账号。",
"heteroAgent.claudeQuota.manage.autoNoAccount": "暂无可用账号,请在下方启用一个。",
"heteroAgent.claudeQuota.manage.autoRoutingTo": "当前分配到 {{account}}",
"heteroAgent.claudeQuota.manage.confirmSwitch": "确认切换",
@@ -1363,15 +1367,21 @@
"heteroAgent.claudeQuota.manage.exhausted": "已用尽",
"heteroAgent.claudeQuota.manage.labelField": "显示名称",
"heteroAgent.claudeQuota.manage.labelPlaceholder": "默认使用账号邮箱",
+ "heteroAgent.claudeQuota.manage.loginFailed": "登录未完成,请重试。",
+ "heteroAgent.claudeQuota.manage.loginSuccess": "已登录 {{account}}",
+ "heteroAgent.claudeQuota.manage.loginWaiting": "请在浏览器中完成登录…",
"heteroAgent.claudeQuota.manage.modeAuto": "自动均衡",
"heteroAgent.claudeQuota.manage.modeAutoHint": "每次运行自动分配到本周余量最多的账号。",
"heteroAgent.claudeQuota.manage.modeManual": "指定账号",
"heteroAgent.claudeQuota.manage.modeManualHint": "该助手始终使用你选定的账号运行。",
"heteroAgent.claudeQuota.manage.more": "更多",
+ "heteroAgent.claudeQuota.manage.notSignedIn": "本机未登录",
"heteroAgent.claudeQuota.manage.remove": "移除账号",
+ "heteroAgent.claudeQuota.manage.signIn": "登录",
"heteroAgent.claudeQuota.manage.title": "Claude Code 账号",
"heteroAgent.claudeQuota.manage.use": "使用",
"heteroAgent.claudeQuota.manage.weeklyLeft": "本周剩余 {{percent}}%",
+ "heteroAgent.claudeQuota.noRunnableAccount": "该助手轮换中的 Claude Code 账号都未在本机登录。请在账号管理中登录其中一个,或把本机已登录的账号加入轮换。",
"heteroAgent.claudeQuota.refreshRateLimited": "额度刷新暂时被限流,当前显示上次获取的数据。",
"heteroAgent.claudeQuota.scopedWeekly": "每周({{model}})",
"heteroAgent.claudeQuota.title": "Claude Code 额度",
diff --git a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
index 5aac13f24a0..8710efbc58b 100644
--- a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
+++ b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
@@ -61,6 +61,8 @@ export interface HeterogeneousAgentRateLimitInfo {
// heterogeneous-agents quota entry; re-export them for existing IPC callers.
export type {
ClaudeCodeAccountIdentity,
+ ClaudeCodeAccountResolution,
+ ClaudeCodeLocalAccount,
ClaudeCodeQuotaReading,
ClaudeCodeQuotaSnapshot,
ClaudeCodeQuotaUnavailableReason,
diff --git a/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.test.ts b/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.test.ts
index aa1f21789eb..a044d7fab71 100644
--- a/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.test.ts
+++ b/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.test.ts
@@ -2,7 +2,7 @@ import { readFile } from 'node:fs/promises';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { fetchClaudeCodeQuota } from './claudeCodeQuota';
+import { claudeCodeKeychainService, fetchClaudeCodeQuota } from './claudeCodeQuota';
vi.mock('node:fs/promises', () => ({
readFile: vi.fn(),
@@ -33,6 +33,23 @@ const mockKeychain = (result: string | Error) => {
);
};
+/** One Keychain item per service name, like the real login keychain. */
+const mockKeychainItems = (items: Record<string, string>) => {
+ execFileMock.mockImplementation(
+ (_cmd: string, args: string[], _opts: unknown, callback: ExecFileCallback) => {
+ const service = args[args.indexOf('-s') + 1];
+ const item = items[service];
+ if (item === undefined) callback(new Error('item could not be found'), '', '');
+ else callback(null, `${item}\n`, '');
+ },
+ );
+};
+
+const keychainServiceArg = (call: unknown[]) => {
+ const args = call[1] as string[];
+ return args[args.indexOf('-s') + 1];
+};
+
const credentialsJson = (expiresAt: number, accessToken = 'file-token') =>
JSON.stringify({ claudeAiOauth: { accessToken, expiresAt, refreshToken: 'refresh' } });
@@ -213,11 +230,6 @@ describe('fetchClaudeCodeQuota', () => {
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');
@@ -225,12 +237,19 @@ describe('fetchClaudeCodeQuota', () => {
throw new Error('ENOENT');
});
vi.mocked(fetch).mockResolvedValue(okUsageResponse({ five_hour: { utilization: 10 } }));
+ mockKeychainItems({
+ 'Claude Code-credentials': JSON.stringify({
+ claudeAiOauth: { accessToken: 'default-account-token', expiresAt: FRESH_EXPIRES_AT },
+ }),
+ });
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();
+ // The custom profile's token is used and the default keychain item is never consulted.
+ expect(execFileMock.mock.calls.map(keychainServiceArg)).toEqual([
+ claudeCodeKeychainService('/custom/claude'),
+ ]);
expect(fetch).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({
@@ -239,18 +258,43 @@ describe('fetchClaudeCodeQuota', () => {
);
});
- it('reports not-found for an unauthenticated CLAUDE_CONFIG_DIR profile instead of falling back', async () => {
+ it('reads a CLAUDE_CONFIG_DIR profile login from its own macOS Keychain item', async () => {
setPlatform('darwin');
- mockKeychain(
- JSON.stringify({
+ mockKeychainItems({
+ 'Claude Code-credentials': JSON.stringify({
claudeAiOauth: { accessToken: 'default-account-token', expiresAt: FRESH_EXPIRES_AT },
}),
+ [claudeCodeKeychainService('/custom/claude')]: JSON.stringify({
+ claudeAiOauth: { accessToken: 'profile-keychain-token', expiresAt: FRESH_EXPIRES_AT },
+ }),
+ });
+ vi.mocked(fetch).mockResolvedValue(okUsageResponse({ five_hour: { utilization: 10 } }));
+
+ const result = await fetchClaudeCodeQuota({ env: { CLAUDE_CONFIG_DIR: '/custom/claude' } });
+
+ expect(result.status).toBe('ok');
+ expect(fetch).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ headers: expect.objectContaining({ Authorization: 'Bearer profile-keychain-token' }),
+ }),
);
+ });
+
+ it('reports not-found for an unauthenticated CLAUDE_CONFIG_DIR profile instead of falling back', async () => {
+ setPlatform('darwin');
+ mockKeychainItems({
+ 'Claude Code-credentials': 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(execFileMock.mock.calls.map(keychainServiceArg)).toEqual([
+ claudeCodeKeychainService('/custom/claude'),
+ ]);
expect(fetch).not.toHaveBeenCalled();
});
@@ -473,3 +517,14 @@ describe('fetchClaudeCodeQuota', () => {
expect(result.error).toContain('timed out');
});
});
+
+describe('claudeCodeKeychainService', () => {
+ it('matches the CLI: bare name by default, sha256(dir)[0..8] suffix for a profile', () => {
+ expect(claudeCodeKeychainService()).toBe('Claude Code-credentials');
+ // sha256('/Users/me/.claude-work') starts with these 8 hex chars.
+ expect(claudeCodeKeychainService('/Users/me/.claude-work')).toMatch(
+ /^Claude Code-credentials-[\da-f]{8}$/,
+ );
+ expect(claudeCodeKeychainService('/a')).not.toBe(claudeCodeKeychainService('/b'));
+ });
+});
diff --git a/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.ts b/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.ts
index 282fb5dc2df..3fd7230a7f0 100644
--- a/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.ts
+++ b/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.ts
@@ -1,8 +1,14 @@
import { execFile } from 'node:child_process';
+import { createHash } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import path from 'node:path';
+import type { ClaudeCodeExternalRoutingEnvKey } from '../quota/claudeCodeRouting';
+import {
+ CLAUDE_CODE_EXTERNAL_ROUTING_ENV_KEYS,
+ isClaudeCodeRoutingFlagEnabled,
+} from '../quota/claudeCodeRouting';
import { buildClaudeQuotaWindows } from '../quota/readings';
import type { ClaudeCodeQuotaSnapshot, ClaudeCodeQuotaUnavailableReason } from '../quota/snapshot';
import { parseClaudeAccountIdentity } from './identity';
@@ -27,6 +33,20 @@ const USAGE_TIMEOUT_MS = 10_000;
const KEYCHAIN_SERVICE = 'Claude Code-credentials';
const KEYCHAIN_TIMEOUT_MS = 3000;
+/**
+ * The macOS Keychain item the CLI stores a login under. The default profile
+ * uses the bare service name; a `CLAUDE_CONFIG_DIR` profile gets its own item,
+ * suffixed with the first 8 hex chars of the SHA-256 of the (NFC) dir path —
+ * so two profiles never share, or overwrite, one login.
+ */
+export const claudeCodeKeychainService = (configDir?: string | null): string =>
+ configDir
+ ? `${KEYCHAIN_SERVICE}-${createHash('sha256')
+ .update(configDir.normalize('NFC'))
+ .digest('hex')
+ .slice(0, 8)}`
+ : KEYCHAIN_SERVICE;
+
// 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.
@@ -36,19 +56,6 @@ const EXTERNAL_AUTH_ENV_KEYS = [
'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
@@ -58,7 +65,7 @@ const isRoutingFlagEnabled = (value: string | undefined) =>
*/
const effectiveRoutingFlag = (
options: FetchClaudeCodeQuotaOptions,
- key: (typeof EXTERNAL_ROUTING_FLAG_ENV_KEYS)[number],
+ key: ClaudeCodeExternalRoutingEnvKey,
): string | undefined => (options.env && key in options.env ? options.env[key] : process.env[key]);
export interface FetchClaudeCodeQuotaOptions {
@@ -140,13 +147,15 @@ const parseCredentialsJson = (raw: string): ClaudeOAuthCredentials | null => {
}
};
-const readKeychainCredentials = async (): Promise<ClaudeOAuthCredentials | null> => {
+const readKeychainCredentials = async (
+ configDir?: string | null,
+): Promise<ClaudeOAuthCredentials | null> => {
if (process.platform !== 'darwin') return null;
return new Promise((resolve) => {
execFile(
'security',
- ['find-generic-password', '-s', KEYCHAIN_SERVICE, '-w'],
+ ['find-generic-password', '-s', claudeCodeKeychainService(configDir), '-w'],
{ timeout: KEYCHAIN_TIMEOUT_MS },
(error, stdout) => {
resolve(error ? null : parseCredentialsJson(stdout.trim()));
@@ -188,26 +197,21 @@ const isExpired = (credentials: ClaudeOAuthCredentials) =>
* 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.
+ * one is configured, only that profile's own Keychain item and credentials
+ * file are 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();
+ const fromKeychain = await readKeychainCredentials(explicitDir);
if (fromKeychain) candidates.push(fromKeychain);
- const fromDefaultFile = await readFileCredentials(path.join(homedir(), '.claude'));
- if (fromDefaultFile) candidates.push(fromDefaultFile);
+ const fromFile = await readFileCredentials(explicitDir ?? path.join(homedir(), '.claude'));
+ if (fromFile) candidates.push(fromFile);
if (candidates.length === 0) return { state: 'not-found' };
@@ -215,6 +219,14 @@ const readClaudeOAuthCredentials = async (
return fresh ? { credentials: fresh, state: 'ok' } : { state: 'expired' };
};
+/**
+ * Whether the profile a spawn with these options would use holds a login at
+ * all. An expired access token still counts: the CLI refreshes it on its own,
+ * so only a profile with no credential anywhere is signed out.
+ */
+export const hasClaudeCodeLogin = async (options: FetchClaudeCodeQuotaOptions): Promise<boolean> =>
+ (await readClaudeOAuthCredentials(options)).state !== 'not-found';
+
/**
* Read the account identity for DB persistence. `~/.claude.json` (or the
* explicit profile dir's copy) carries `oauthAccount`; the credential blob
@@ -249,8 +261,8 @@ export const fetchClaudeCodeQuota = async (
): 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)),
+ CLAUDE_CODE_EXTERNAL_ROUTING_ENV_KEYS.find((key) =>
+ isClaudeCodeRoutingFlagEnabled(effectiveRoutingFlag(options, key)),
);
if (externalAuthKey) {
return unavailableSnapshot(
diff --git a/packages/heterogeneous-agents/src/quota/claudeCodeRouting.test.ts b/packages/heterogeneous-agents/src/quota/claudeCodeRouting.test.ts
new file mode 100644
index 00000000000..27109a4469f
--- /dev/null
+++ b/packages/heterogeneous-agents/src/quota/claudeCodeRouting.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest';
+
+import { claudeCodeRoutesExternally } from './claudeCodeRouting';
+
+describe('claudeCodeRoutesExternally', () => {
+ it.each([
+ ['an enabled agent flag', { CLAUDE_CODE_USE_BEDROCK: '1' }, {}, true],
+ ['an enabled inherited flag', {}, { CLAUDE_CODE_USE_VERTEX: 'true' }, true],
+ [
+ 'an agent flag switching the inherited one off',
+ { CLAUDE_CODE_USE_MANTLE: 'false' },
+ { CLAUDE_CODE_USE_MANTLE: '1' },
+ false,
+ ],
+ ['flags set to off', { CLAUDE_CODE_USE_BEDROCK: '0' }, { CLAUDE_CODE_USE_VERTEX: ' ' }, false],
+ ['no flags', undefined, {}, false],
+ ])('treats %s per the spawn-env merge', (_label, agentEnv, inherited, expected) => {
+ expect(claudeCodeRoutesExternally(agentEnv, inherited)).toBe(expected);
+ });
+});
diff --git a/packages/heterogeneous-agents/src/quota/claudeCodeRouting.ts b/packages/heterogeneous-agents/src/quota/claudeCodeRouting.ts
new file mode 100644
index 00000000000..cc8616d5093
--- /dev/null
+++ b/packages/heterogeneous-agents/src/quota/claudeCodeRouting.ts
@@ -0,0 +1,32 @@
+/**
+ * Boolean-ish flags that route Claude Code to a third-party provider (AWS
+ * Bedrock / Mantle / Google Vertex), billed there with no Anthropic
+ * subscription login involved.
+ */
+export const CLAUDE_CODE_EXTERNAL_ROUTING_ENV_KEYS = [
+ 'CLAUDE_CODE_USE_BEDROCK',
+ 'CLAUDE_CODE_USE_MANTLE',
+ 'CLAUDE_CODE_USE_VERTEX',
+] as const;
+
+export type ClaudeCodeExternalRoutingEnvKey =
+ (typeof CLAUDE_CODE_EXTERNAL_ROUTING_ENV_KEYS)[number];
+
+/** The CLI reads these as booleans, so "0" / "false" must not count as enabled. */
+export const isClaudeCodeRoutingFlagEnabled = (value: string | undefined): boolean =>
+ !!value?.trim() && !['0', 'false'].includes(value.trim().toLowerCase());
+
+/**
+ * Whether a run goes to an external provider, given the agent's configured
+ * env and the flags it inherits. The agent's value wins per key — even to
+ * switch an inherited flag off — and the inherited value fills the gaps. The
+ * web app's account routing decides with it; the quota sampler applies the
+ * same rule per key.
+ */
+export const claudeCodeRoutesExternally = (
+ agentEnv: Record<string, string | undefined> | undefined,
+ inheritedEnv: Record<string, string | undefined> = {},
+): boolean =>
+ CLAUDE_CODE_EXTERNAL_ROUTING_ENV_KEYS.some((key) =>
+ isClaudeCodeRoutingFlagEnabled(agentEnv && key in agentEnv ? agentEnv[key] : inheritedEnv[key]),
+ );
diff --git a/packages/heterogeneous-agents/src/quota/index.ts b/packages/heterogeneous-agents/src/quota/index.ts
index 0a3cc276528..bacd972077a 100644
--- a/packages/heterogeneous-agents/src/quota/index.ts
+++ b/packages/heterogeneous-agents/src/quota/index.ts
@@ -1,4 +1,5 @@
export * from './calibration';
+export * from './claudeCodeRouting';
export * from './codex';
export * from './cost';
export * from './kimiCode';
diff --git a/packages/heterogeneous-agents/src/quota/snapshot.ts b/packages/heterogeneous-agents/src/quota/snapshot.ts
index 5ee5d64af9c..69987b70af4 100644
--- a/packages/heterogeneous-agents/src/quota/snapshot.ts
+++ b/packages/heterogeneous-agents/src/quota/snapshot.ts
@@ -78,6 +78,19 @@ export interface ClaudeCodeScopedWeekly {
/** Account identity resolved from the local CLI config, for DB persistence. */
export type ClaudeCodeAccountIdentity = QuotaAccountIdentity;
+/**
+ * A Claude Code login on one machine. `configDir: null` is the default login
+ * (no `CLAUDE_CONFIG_DIR` override); otherwise the account's own profile.
+ */
+export interface ClaudeCodeLocalAccount {
+ configDir: string | null;
+ identity: ClaudeCodeAccountIdentity;
+}
+
+/** Which local login a run for one provider account must spawn with. */
+export type ClaudeCodeAccountResolution =
+ { kind: 'default' } | { configDir: string; kind: 'profile' } | { kind: 'missing' };
+
/** One raw limit reading, for fossilizing into the quota data layer. */
export type ClaudeCodeQuotaReading = QuotaLimitReading;
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index a5cae7dbd56..c311ea7aaad 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -17,6 +17,20 @@ export default {
'backgroundActivity.topic': 'Conversation',
'backgroundActivity.unavailable':
'Resource data is unavailable. Displayed values may be out of date.',
+ 'heteroAgent.claudeQuota.accountNotSignedIn':
+ "The Claude Code account {{account}} isn't signed in on this device. Sign in to it from Manage accounts, or switch to another account.",
+ 'heteroAgent.claudeQuota.accountResolveFailed':
+ "Couldn't look up this Claude Code account's login on this device. Try again, or switch to another account.",
+ 'heteroAgent.claudeQuota.manage.add': 'Add account',
+ 'heteroAgent.claudeQuota.manage.addHintDesktop':
+ 'Each account signs in on this device; runs use the account you pick.',
+ 'heteroAgent.claudeQuota.manage.loginFailed': "Sign-in didn't finish. Try again.",
+ 'heteroAgent.claudeQuota.manage.loginSuccess': 'Signed in as {{account}}',
+ 'heteroAgent.claudeQuota.manage.loginWaiting': 'Finish signing in in your browser…',
+ 'heteroAgent.claudeQuota.manage.notSignedIn': 'Not signed in on this device',
+ 'heteroAgent.claudeQuota.manage.signIn': 'Sign in',
+ 'heteroAgent.claudeQuota.noRunnableAccount':
+ "None of the Claude Code accounts in this agent's rotation are signed in on this device. Sign one in from Manage accounts, or add a signed-in account to the rotation.",
'processExplorer.copyPid': 'Copy PID',
'processExplorer.filter': 'Filter',
'processExplorer.live': 'Live · updates every 2 s',
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/ClaudeCodeQuotaMenu.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/ClaudeCodeQuotaMenu.tsx
index b0441606b06..71b089159a0 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/ClaudeCodeQuotaMenu.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/ClaudeCodeQuotaMenu.tsx
@@ -1,5 +1,6 @@
'use client';
+import { isDesktop } from '@lobechat/const';
import type { ClaudeCodeQuotaSnapshot } from '@lobechat/electron-client-ipc';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -7,6 +8,7 @@ import { useTranslation } from 'react-i18next';
import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
import { useSingleton } from '@/hooks/useSingleton';
import { agentQuotaService } from '@/services/agentQuota';
+import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';
import { fetchClaudeCodeQuotaSnapshot } from '@/services/heteroAgentQuota';
import { getAgentQuotaStoreState } from '@/store/agentQuota';
@@ -61,6 +63,25 @@ type ClaudeCodePanelSnapshot = ClaudeCodeQuotaSnapshot & {
sampleFailed?: boolean;
};
+/**
+ * Env that samples the local login a pinned account runs on: its profile, the
+ * default login, or `null` when this desktop has no login for it (sampling
+ * the default login then would paint another account's quota under its name).
+ * An agent env that picks its own profile already wins over routing.
+ */
+const resolvePinnedSampleEnv = async (
+ externalAccountId: string | null | undefined,
+ env: Record<string, string> | undefined,
+): Promise<Record<string, string> | undefined | null> => {
+ if (!isDesktop || !externalAccountId || env?.CLAUDE_CONFIG_DIR) return env;
+ const resolution = await heterogeneousAgentService
+ .resolveClaudeCodeAccount(externalAccountId)
+ .catch(() => null);
+ if (resolution?.kind === 'profile') return { ...env, CLAUDE_CONFIG_DIR: resolution.configDir };
+ if (resolution?.kind === 'missing') return null;
+ return env;
+};
+
const isRateLimitError = (quota: ClaudeCodeQuotaSnapshot) => quota.error?.includes('429') ?? false;
interface ClaudeCodeQuotaMenuProps {
@@ -122,10 +143,23 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =
const interim = buildClaudePanelSnapshot(account, readings, null);
if (hasRenderableWindow(interim)) options?.onInterim?.(interim);
}
- live = await fetchClaudeCodeQuotaSnapshot({ deviceId, env, force }).catch(() => {
- liveFailed = true;
- return null;
- });
+ // Auto mode may route a run to any local login, and it balances on
+ // their readings: keep every local login sampled, not just this one.
+ // Never awaited — the panel must not wait on the other logins.
+ if (isDesktop && !deviceId) void quotaStore.refreshClaudeLocalAccounts().catch(() => {});
+ // A local pin runs on that account's own login: sample that login, not
+ // the default one, or the panel would show another account's quota.
+ const sampleEnv =
+ !deviceId && pinnedId && account?.id === pinnedId
+ ? await resolvePinnedSampleEnv(account.externalAccountId, env)
+ : env;
+ live =
+ sampleEnv === null
+ ? null
+ : await fetchClaudeCodeQuotaSnapshot({ deviceId, env: sampleEnv, force }).catch(() => {
+ liveFailed = true;
+ return null;
+ });
const externalAccountId = live?.identity?.externalAccountId;
if (live?.status === 'ok' && externalAccountId && live.readings?.length) {
@@ -272,6 +306,9 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =
return (
<QuotaMenu
+ // The account manager is where accounts are added and switched, and an
+ // account with no readings yet is exactly when it is needed.
+ alwaysRenderHeader
autoRefreshMs={QUOTA_REFRESH_MS}
createErrorSnapshot={createErrorSnapshot}
fetchQuota={fetchQuota}
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.test.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.test.tsx
index c7391e8fd93..5280d202fb0 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.test.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.test.tsx
@@ -1,10 +1,13 @@
/**
* @vitest-environment happy-dom
*/
-import { act, fireEvent, render, screen } from '@testing-library/react';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { type ReactElement } from 'react';
+import { SWRConfig } from 'swr';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { agentQuotaService } from '@/services/agentQuota';
+import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';
import { useAgentQuotaStore } from '@/store/agentQuota';
import {
QUOTA_ACCOUNTS_KEY,
@@ -15,6 +18,18 @@ import {
import QuotaAccountManager from './QuotaAccountManagerModal';
import { isolateQuotaReplica } from './testUtils';
+const desktop = vi.hoisted(() => ({ value: false }));
+
+vi.mock('@lobechat/const', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>();
+ return {
+ ...actual,
+ get isDesktop() {
+ return desktop.value;
+ },
+ };
+});
+
const account = (id: string) =>
({
email: `${id}@example.com`,
@@ -68,6 +83,25 @@ describe('QuotaAccountManager', () => {
expect(checkedOption()).toContain('heteroAgent.claudeQuota.manage.modeAuto');
});
+ it('treats another coding agent’s pin as Auto for Claude and leaves it alone', async () => {
+ vi.spyOn(agentQuotaService, 'listAccounts').mockResolvedValue([
+ account('a1'),
+ { ...account('kimi'), provider: 'kimi-code' } as QuotaAccount,
+ ]);
+ vi.spyOn(agentQuotaService, 'listBindings').mockResolvedValue([
+ binding('b1', 'a1', 'pool'),
+ binding('b2', 'kimi', 'pinned'),
+ ]);
+
+ render(<QuotaAccountManager agentId={'agent-1'} />);
+
+ // Claude routing skips the Kimi pin, so for Claude this agent is on Auto.
+ await vi.waitFor(() =>
+ expect(checkedOption()).toContain('heteroAgent.claudeQuota.manage.modeAuto'),
+ );
+ expect(screen.getByText(/heteroAgent\.claudeQuota\.manage\.autoRoutingTo/)).toBeTruthy();
+ });
+
it('selects the pinned account once the bindings load', async () => {
let answerBindings!: (rows: QuotaBinding[]) => void;
vi.spyOn(agentQuotaService, 'listBindings').mockImplementation(
@@ -138,3 +172,140 @@ describe('QuotaAccountManager', () => {
expect((await removeItem()).getAttribute('aria-disabled')).not.toBe('true');
});
});
+
+const localLogin = (externalAccountId: string, configDir: string | null) => ({
+ configDir,
+ identity: { email: `${externalAccountId}@example.com`, externalAccountId },
+});
+
+const radioFor = (email: string) =>
+ screen
+ .getAllByRole('radio')
+ .find((radio) => radio.closest('label')?.textContent?.includes(email))!;
+
+/** The local-login list is device data in the SWR cache: give each case its own. */
+const renderWithFreshCache = (ui: ReactElement) =>
+ render(<SWRConfig value={{ provider: () => new Map() }}>{ui}</SWRConfig>);
+
+describe('QuotaAccountManager on the desktop', () => {
+ beforeEach(() => {
+ desktop.value = true;
+ isolateQuotaReplica();
+ vi.spyOn(agentQuotaService, 'listAccounts').mockResolvedValue([
+ account('here'),
+ account('away'),
+ ]);
+ vi.spyOn(agentQuotaService, 'getLatestReadings').mockResolvedValue([]);
+ vi.spyOn(agentQuotaService, 'listBindings').mockResolvedValue([
+ binding('b1', 'here', 'pool'),
+ binding('b2', 'away', 'pool'),
+ ]);
+ vi.spyOn(heterogeneousAgentService, 'listClaudeCodeAccounts').mockResolvedValue([
+ localLogin('ext-here', null),
+ ] as never);
+ vi.spyOn(heterogeneousAgentService, 'getClaudeCodeQuota').mockResolvedValue({
+ status: 'unavailable',
+ } as never);
+ });
+
+ afterEach(() => {
+ desktop.value = false;
+ vi.restoreAllMocks();
+ });
+
+ it('marks an account with no login on this device and keeps it from being picked', async () => {
+ renderWithFreshCache(<QuotaAccountManager agentId={'agent-1'} />);
+
+ await screen.findByText('heteroAgent.claudeQuota.manage.notSignedIn');
+ expect(radioFor('[email protected]').getAttribute('aria-disabled')).toBe('true');
+ expect(radioFor('[email protected]').getAttribute('aria-disabled')).not.toBe('true');
+ expect(screen.getAllByText('heteroAgent.claudeQuota.manage.notSignedIn')).toHaveLength(1);
+ });
+
+ it('lists only Claude Code accounts, never another coding agent’s', async () => {
+ vi.mocked(agentQuotaService.listAccounts).mockResolvedValue([
+ account('here'),
+ { ...account('kimi'), provider: 'kimi-code' } as QuotaAccount,
+ ]);
+
+ renderWithFreshCache(<QuotaAccountManager agentId={'agent-1'} />);
+
+ await screen.findByText('[email protected]');
+ expect(screen.queryByText('[email protected]')).toBeNull();
+ });
+
+ it('registers the default login even when its usage call fails', async () => {
+ vi.mocked(heterogeneousAgentService.listClaudeCodeAccounts).mockResolvedValue([
+ localLogin('ext-default', null),
+ ] as never);
+ vi.mocked(heterogeneousAgentService.getClaudeCodeQuota).mockRejectedValue(
+ new Error('403 request blocked'),
+ );
+ const ingest = vi
+ .spyOn(agentQuotaService, 'ingestClaudeSnapshot')
+ .mockResolvedValue({} as never);
+
+ renderWithFreshCache(<QuotaAccountManager agentId={'agent-1'} />);
+
+ await waitFor(() =>
+ expect(ingest).toHaveBeenCalledWith({
+ identity: expect.objectContaining({ externalAccountId: 'ext-default' }),
+ readings: [],
+ }),
+ );
+ });
+
+ it('never previews Auto routing to an account this device cannot run', async () => {
+ // Only `away` (no login here) is in rotation: runtime has nothing to route to.
+ vi.mocked(agentQuotaService.listBindings).mockResolvedValue([
+ binding('b1', 'here', 'disabled'),
+ binding('b2', 'away', 'pool'),
+ ]);
+
+ renderWithFreshCache(<QuotaAccountManager agentId={'agent-1'} />);
+
+ await screen.findByText('heteroAgent.claudeQuota.manage.notSignedIn');
+ expect(screen.getByText('heteroAgent.claudeQuota.manage.autoNoAccount')).toBeTruthy();
+ expect(screen.queryByText(/heteroAgent\.claudeQuota\.manage\.autoRoutingTo/)).toBeNull();
+ });
+
+ it('signs the account in on this device from its row', async () => {
+ const login = vi
+ .spyOn(heterogeneousAgentService, 'loginClaudeCodeAccount')
+ .mockResolvedValue(localLogin('ext-away', '/profiles/away') as never);
+
+ renderWithFreshCache(<QuotaAccountManager agentId={'agent-1'} />);
+ fireEvent.click(await screen.findByText('heteroAgent.claudeQuota.manage.signIn'));
+
+ await waitFor(() => expect(login).toHaveBeenCalledWith({ email: '[email protected]' }));
+ });
+
+ it('adds a new account through the browser and puts it in rotation', async () => {
+ let finishLogin!: (value: unknown) => void;
+ vi.spyOn(heterogeneousAgentService, 'loginClaudeCodeAccount').mockImplementation(
+ () => new Promise((resolve) => (finishLogin = resolve)) as never,
+ );
+ const bindAccount = vi
+ .spyOn(agentQuotaService, 'bindAccount')
+ .mockResolvedValue(binding('b3', 'new', 'pool') as never);
+ vi.spyOn(agentQuotaService, 'ingestClaudeSnapshot').mockResolvedValue({} as never);
+
+ renderWithFreshCache(<QuotaAccountManager agentId={'agent-1'} />);
+ fireEvent.click(
+ await screen.findByRole('button', { name: /heteroAgent\.claudeQuota\.manage\.add/ }),
+ );
+
+ // Waiting on the browser: the footer says so and offers Cancel.
+ await screen.findByText('heteroAgent.claudeQuota.manage.loginWaiting');
+
+ vi.mocked(agentQuotaService.listAccounts).mockResolvedValue([
+ account('here'),
+ account('away'),
+ account('new'),
+ ]);
+ await act(async () => finishLogin(localLogin('ext-new', '/profiles/new')));
+
+ await waitFor(() => expect(bindAccount).toHaveBeenCalledWith('agent-1', 'new', 'pool'));
+ expect(screen.queryByText('heteroAgent.claudeQuota.manage.loginWaiting')).toBeNull();
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsx
index ea637041c4b..af13c17043e 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsx
@@ -1,5 +1,6 @@
'use client';
+import { isDesktop } from '@lobechat/const';
import { currentUtilization, isWeeklyAllLimit } from '@lobechat/heterogeneous-agents/quota';
import { createStaticStyles, cssVar, DropdownMenu, Flexbox, Icon } from '@lobehub/ui';
import {
@@ -11,17 +12,19 @@ import {
RadioGroup,
Switch,
Text,
+ toast,
} from '@lobehub/ui';
import { t as i18nT } from 'i18next';
import {
CheckIcon,
MoreHorizontalIcon,
PencilIcon,
+ PlusIcon,
Trash2Icon,
XIcon,
ZapIcon,
} from 'lucide-react';
-import { memo, type MouseEvent, useCallback, useMemo, useState } from 'react';
+import { memo, type MouseEvent, useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { cacheScope } from '@/libs/replica';
@@ -124,6 +127,9 @@ const QuotaAccountManager = memo<{ agentId: string }>(({ agentId }) => {
renameQuotaAccount,
switchQuotaAccount,
unbindQuotaAccount,
+ useFetchClaudeLocalAccounts,
+ loginClaudeAccount,
+ cancelClaudeAccountLogin,
] = useAgentQuotaStore((s) => [
s.useFetchQuotaAccounts,
s.useFetchQuotaBindings,
@@ -131,17 +137,36 @@ const QuotaAccountManager = memo<{ agentId: string }>(({ agentId }) => {
s.renameQuotaAccount,
s.switchQuotaAccount,
s.unbindQuotaAccount,
+ s.useFetchClaudeLocalAccounts,
+ s.loginClaudeAccount,
+ s.cancelClaudeAccountLogin,
]);
const scope = cacheScope.use();
const { error: accountsError } = useFetchQuotaAccounts();
useFetchQuotaBindings(agentId);
+ // Only the desktop runs Claude Code locally, so only it has logins to show.
+ useFetchClaudeLocalAccounts(isDesktop);
+ const localAccounts = useAgentQuotaStore((s) => s.claudeLocalAccounts);
+ const loginPending = useAgentQuotaStore((s) => s.claudeLoginPending);
// A hydrated empty list may be an outdated snapshot: only the server's answer
// (or a failed first read) settles "no accounts yet".
const accountsConfirmed = useAgentQuotaStore(agentQuotaSelectors.isAccountsConfirmed(scope));
// The replica paints the last-known pool on open; the server confirms behind it.
- const accounts = useAgentQuotaStore(agentQuotaSelectors.accounts) ?? EMPTY_ACCOUNTS;
+ const allAccounts = useAgentQuotaStore(agentQuotaSelectors.accounts) ?? EMPTY_ACCOUNTS;
+ // The pool holds every coding agent's accounts; this manager (and the run
+ // routing behind it) only speaks for Claude Code.
+ const accounts = useMemo(
+ () => allAccounts.filter((a) => a.provider === 'claude-code'),
+ [allAccounts],
+ );
const loadedBindings = useAgentQuotaStore(agentQuotaSelectors.bindings(agentId));
- const bindings = loadedBindings ?? EMPTY_BINDINGS;
+ // Bindings are provider-blind; another coding agent's pin is not a Claude
+ // choice (Claude routing skips it), so this manager neither shows nor
+ // touches bindings of accounts it does not list.
+ const bindings = useMemo(() => {
+ const claudeIds = new Set(accounts.map((a) => a.id));
+ return (loadedBindings ?? EMPTY_BINDINGS).filter((b) => claudeIds.has(b.accountId));
+ }, [accounts, loadedBindings]);
// Until this agent's bindings are on screen, every row would read as "off"
// and Auto as routing to nobody: keep the mode and per-account controls
// disabled and show no routing hint instead of acting on that guess.
@@ -187,6 +212,17 @@ const QuotaAccountManager = memo<{ agentId: string }>(({ agentId }) => {
[roleOf],
);
+ /**
+ * Whether a run on this desktop can use the account. Unknown (web, or the
+ * logins not listed yet) counts as yes, so nothing is gated on a guess.
+ */
+ const signedInHere = useCallback(
+ (account: Account) =>
+ !localAccounts ||
+ localAccounts.some((l) => l.identity.externalAccountId === account.externalAccountId),
+ [localAccounts],
+ );
+
const pinnedId = bindings.find((b) => b.role === 'pinned')?.accountId;
const current = pinnedId ?? AUTO;
const selected = pending ?? current;
@@ -205,10 +241,11 @@ const QuotaAccountManager = memo<{ agentId: string }>(({ agentId }) => {
// Preview which account Auto would route to (most weekly headroom in the pool).
const routeId = useMemo(() => {
if (selected !== AUTO) return null;
- const pool = accounts.filter((a) => inRotation(a.id));
+ // Runtime routing only balances across logins this device holds.
+ const pool = accounts.filter((a) => inRotation(a.id) && signedInHere(a));
if (pool.length === 0) return null;
return [...pool].sort((a, b) => (weeklyById[b.id] ?? 100) - (weeklyById[a.id] ?? 100))[0].id;
- }, [selected, accounts, inRotation, weeklyById]);
+ }, [selected, accounts, inRotation, signedInHere, weeklyById]);
const routeAccount = accounts.find((a) => a.id === routeId);
const applySelection = useCallback(
@@ -258,6 +295,35 @@ const QuotaAccountManager = memo<{ agentId: string }>(({ agentId }) => {
[editLabel, renameQuotaAccount, run],
);
+ // A cancelled sign-in rejects too, but is not a failure worth a toast.
+ const loginCancelled = useRef(false);
+ const signIn = useCallback(
+ async (email?: string) => {
+ loginCancelled.current = false;
+ try {
+ const local = await loginClaudeAccount(email);
+ const account = agentQuotaSelectors
+ .accounts(useAgentQuotaStore.getState())
+ ?.find((a) => a.externalAccountId === local.identity.externalAccountId);
+ // A new login joins this agent's rotation, ready to be picked.
+ if (account && !bindingOf(account.id))
+ await bindQuotaAccount(agentId, account.id, 'pool').catch(() => {});
+ toast.success(
+ t('heteroAgent.claudeQuota.manage.loginSuccess', {
+ account: local.identity.email || local.identity.externalAccountId,
+ }),
+ );
+ } catch {
+ if (!loginCancelled.current) toast.error(t('heteroAgent.claudeQuota.manage.loginFailed'));
+ }
+ },
+ [agentId, bindQuotaAccount, bindingOf, loginClaudeAccount, t],
+ );
+ const cancelSignIn = useCallback(() => {
+ loginCancelled.current = true;
+ void cancelClaudeAccountLogin();
+ }, [cancelClaudeAccountLogin]);
+
const preventRadioSelection = useCallback((event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
@@ -299,6 +365,7 @@ const QuotaAccountManager = memo<{ agentId: string }>(({ agentId }) => {
},
...accounts.map((a) => {
const rotate = inRotation(a.id);
+ const runnable = signedInHere(a);
const weekly = weeklyById[a.id];
const isEditing = editingId === a.id;
const menuItems = [
@@ -320,7 +387,7 @@ const QuotaAccountManager = memo<{ agentId: string }>(({ agentId }) => {
];
return {
- disabled: busy || !canEditBindings || !rotate || isEditing,
+ disabled: busy || !canEditBindings || !rotate || !runnable || isEditing,
label: (
<Flexbox
horizontal
@@ -365,7 +432,12 @@ const QuotaAccountManager = memo<{ agentId: string }>(({ agentId }) => {
</Flexbox>
{/* Only a real quota reading gets a subline; a disabled row is
conveyed by the dimmed state, and no-data shows nothing. */}
- {rotate && weekly != null && (
+ {!runnable && (
+ <Text style={{ fontSize: 12 }} type={'secondary'}>
+ {t('heteroAgent.claudeQuota.manage.notSignedIn')}
+ </Text>
+ )}
+ {runnable && rotate && weekly != null && (
<Text style={{ fontSize: 12 }} type={'secondary'}>
{weekly === 0
? t('heteroAgent.claudeQuota.manage.exhausted')
@@ -375,6 +447,18 @@ const QuotaAccountManager = memo<{ agentId: string }>(({ agentId }) => {
</Text>
)}
</Flexbox>
+ {!runnable && (
+ <span className={styles.interactive} onClick={preventRadioSelection}>
+ <Button
+ disabled={loginPending}
+ size={'small'}
+ style={{ flex: 'none' }}
+ onClick={() => void signIn(a.email ?? undefined)}
+ >
+ {t('heteroAgent.claudeQuota.manage.signIn')}
+ </Button>
+ </span>
+ )}
<span className={styles.interactive} onClick={preventRadioSelection}>
<Switch
checked={rotate}
@@ -416,6 +500,34 @@ const QuotaAccountManager = memo<{ agentId: string }>(({ agentId }) => {
{t('heteroAgent.claudeQuota.manage.confirmSwitch')}
</Button>
</Flexbox>
+ ) : isDesktop ? (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.footer}
+ gap={8}
+ justify={'space-between'}
+ >
+ <Text className={styles.hint}>
+ {loginPending
+ ? t('heteroAgent.claudeQuota.manage.loginWaiting')
+ : t('heteroAgent.claudeQuota.manage.addHintDesktop')}
+ </Text>
+ {loginPending ? (
+ <Button size={'small'} style={{ flex: 'none' }} onClick={cancelSignIn}>
+ {i18nT('cancel', { ns: 'common' })}
+ </Button>
+ ) : (
+ <Button
+ icon={PlusIcon}
+ size={'small'}
+ style={{ flex: 'none' }}
+ onClick={() => void signIn()}
+ >
+ {t('heteroAgent.claudeQuota.manage.add')}
+ </Button>
+ )}
+ </Flexbox>
) : (
<Text className={styles.hint} style={{ marginBlockStart: 4 }}>
{t('heteroAgent.claudeQuota.manage.addHint')}
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.claudeCode.test.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.claudeCode.test.tsx
new file mode 100644
index 00000000000..665ed069995
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.claudeCode.test.tsx
@@ -0,0 +1,936 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import type * as LobechatConstModule from '@lobechat/const';
+import type * as ElectronClientIpcModule from '@lobechat/electron-client-ipc';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { openQuotaCalendarModal } from '@/features/AgentQuotaCalendar';
+import { cacheScope } from '@/libs/replica';
+import { hashQuotaSourceKey, quotaPanelResource } from '@/store/agentQuota/projection';
+
+import ClaudeCodeQuotaMenu from './ClaudeCodeQuotaMenu';
+import { createQuotaSourceKey } from './QuotaMenu';
+import {
+ claudeSnapshot,
+ isolateQuotaReplica,
+ liveSessionReading,
+ persistedAccount,
+ persistedSessionReading,
+ waitForQuotaIdle,
+} from './testUtils';
+
+const mockService = vi.hoisted(() => ({
+ consumeCodexRateLimitResetCredit: vi.fn(),
+ getClaudeCodeQuota: vi.fn(),
+ getCodexQuota: vi.fn(),
+ getKimiCodeQuota: vi.fn(),
+ listClaudeCodeAccounts: vi.fn(async () => [] as unknown[]),
+}));
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal<typeof LobechatConstModule>()),
+ isDesktop: true,
+}));
+
+vi.mock('@lobechat/electron-client-ipc', async (importOriginal) => ({
+ ...(await importOriginal<typeof ElectronClientIpcModule>()),
+ useWatchBroadcast: vi.fn(),
+}));
+
+vi.mock('@/features/AgentQuotaCalendar', () => ({
+ openQuotaCalendarModal: vi.fn(),
+}));
+
+vi.mock('@/features/ChatInput/hooks/useAgentId', () => ({ useAgentId: () => 'agent-1' }));
+
+const { confirmModalMock, toastErrorMock, toastSuccessMock } = vi.hoisted(() => ({
+ confirmModalMock: vi.fn(),
+ toastErrorMock: vi.fn(),
+ toastSuccessMock: vi.fn(),
+}));
+
+const translate = vi.hoisted(() => (key: string, opts?: Record<string, unknown>) => {
+ const values = opts ? Object.values(opts) : [];
+ return values.length > 0 ? `${key}:${values.join(',')}` : key;
+});
+
+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 { mockLambdaClaudeQuota, mockLambdaCodexQuota, mockLambdaKimiCodeQuota } = vi.hoisted(() => ({
+ mockLambdaClaudeQuota: vi.fn(),
+ mockLambdaCodexQuota: vi.fn(),
+ mockLambdaKimiCodeQuota: vi.fn(),
+}));
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ device: {
+ getClaudeCodeQuota: { query: mockLambdaClaudeQuota },
+ },
+ },
+}));
+
+// 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
+// hand it persisted accounts/windows.
+const mockQuotaService = vi.hoisted(() => ({
+ getLatestReadings: vi.fn(async (): Promise<unknown[]> => []),
+ ingestClaudeSnapshot: vi.fn(async () => undefined),
+ ingestCodexSnapshot: vi.fn(async () => undefined),
+ ingestKimiCodeSnapshot: vi.fn(async () => undefined),
+ refreshCodexQuota: vi.fn(),
+ refreshKimiCodeQuota: vi.fn(),
+ listAccounts: vi.fn(async (): Promise<unknown[]> => []),
+ listBindings: vi.fn(async (): Promise<unknown[]> => []),
+}));
+
+vi.mock('@/services/agentQuota', () => ({ agentQuotaService: mockQuotaService }));
+
+// 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: translate,
+ }),
+}));
+
+vi.mock('@lobehub/ui', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>();
+ const factories: ((original: typeof importOriginal) => unknown)[] = [
+ async (importOriginal) => {
+ return {
+ ...(await importOriginal<object>()),
+ ActionIcon: ({
+ disabled,
+ onClick,
+ title,
+ }: {
+ disabled?: boolean;
+ onClick?: () => void;
+ title?: string;
+ }) => (
+ <button
+ aria-label={title}
+ data-testid={title ? 'calendar' : '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,
+ onOpenChange,
+ }: {
+ children?: ReactNode;
+ content?: ReactNode;
+ onOpenChange?: (open: boolean) => void;
+ }) => (
+ <div>
+ <div data-testid="popover-content">{content}</div>
+ <div data-testid="quota-trigger" onClick={() => onOpenChange?.(true)}>
+ {children}
+ </div>
+ </div>
+ ),
+ Skeleton: { Button: () => <div data-testid="skeleton" /> },
+ Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
+ Tooltip: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ };
+ },
+ async (importOriginal) => ({
+ ...((await importOriginal()) as Record<string, unknown>),
+ ActionIcon: ({
+ onClick,
+ title,
+ disabled,
+ }: {
+ disabled?: boolean;
+ onClick?: (e: React.MouseEvent) => void;
+ title?: string;
+ }) => (
+ <button
+ aria-label={title}
+ data-testid={title ? 'calendar' : 'refresh'}
+ disabled={disabled}
+ type="button"
+ onClick={onClick}
+ />
+ ),
+ confirmModal: confirmModalMock,
+ Skeleton: ({ height }: { height?: number }) => (
+ <div data-height={height} data-testid="skeleton" />
+ ),
+ toast: {
+ error: toastErrorMock,
+ success: toastSuccessMock,
+ },
+ }),
+ ];
+ const merged: Record<string, unknown> = { ...actual };
+ for (const factory of factories) {
+ const part = (await factory(importOriginal)) as Record<string, unknown>;
+ for (const [key, value] of Object.entries(part)) if (value !== actual[key]) merged[key] = value;
+ }
+ return merged;
+});
+
+beforeEach(() => {
+ isolateQuotaReplica();
+ confirmModalMock.mockReset();
+ mockService.consumeCodexRateLimitResetCredit.mockReset();
+ mockService.getClaudeCodeQuota.mockReset();
+ mockService.getCodexQuota.mockReset();
+ mockService.getKimiCodeQuota.mockReset();
+ mockLambdaClaudeQuota.mockReset();
+ mockLambdaCodexQuota.mockReset();
+ mockLambdaKimiCodeQuota.mockReset();
+ mockQuotaService.refreshCodexQuota.mockImplementation(mockLambdaCodexQuota);
+ mockQuotaService.refreshKimiCodeQuota.mockImplementation(mockLambdaKimiCodeQuota);
+ toastErrorMock.mockReset();
+ toastSuccessMock.mockReset();
+ mockQuotaService.getLatestReadings.mockResolvedValue([]);
+ mockQuotaService.ingestClaudeSnapshot.mockClear();
+ mockQuotaService.ingestKimiCodeSnapshot.mockClear();
+ mockQuotaService.listAccounts.mockClear().mockResolvedValue([]);
+ mockQuotaService.listBindings.mockClear().mockResolvedValue([]);
+ vi.mocked(openQuotaCalendarModal).mockClear();
+});
+
+describe('ClaudeCodeQuotaMenu', () => {
+ it('opens the usage calendar for the claude-code account from the header switcher', async () => {
+ mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 60_000)]);
+ mockQuotaService.getLatestReadings.mockResolvedValue([
+ persistedSessionReading(Date.now() - 60_000),
+ ]);
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ fireEvent.click(await screen.findByTestId('calendar'));
+
+ expect(openQuotaCalendarModal).toHaveBeenCalledWith({
+ externalAccountId: 'ext-1',
+ provider: 'claude-code',
+ });
+ });
+
+ 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();
+ expect(screen.getByText('92%')).toBeTruthy();
+ const trigger = screen.getByRole('button', { name: 'heteroAgent.claudeQuota.tooltip' });
+ expect(trigger.textContent).toContain(
+ 'heteroAgent.quota.weekly heteroAgent.quota.compactLeft:87',
+ );
+ expect(trigger.textContent).toContain('Fable heteroAgent.quota.compactLeft:76');
+ expect(mockService.getClaudeCodeQuota).toHaveBeenCalledWith({
+ env: { CLAUDE_CONFIG_DIR: '/custom' },
+ });
+ });
+
+ it('shows the tightest global window and Fable as separate compact values', async () => {
+ mockService.getClaudeCodeQuota.mockResolvedValue(
+ claudeSnapshot({
+ scopedWeekly: {
+ modelName: 'Fable',
+ window: { resetsAt: null, usedPercent: 100, windowMinutes: 10_080 },
+ },
+ session: { resetsAt: null, usedPercent: 49, windowMinutes: 300 },
+ weekly: { resetsAt: null, usedPercent: 53, windowMinutes: 10_080 },
+ }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('heteroAgent.quota.exhausted')).toBeTruthy();
+ const trigger = screen.getByRole('button', { name: 'heteroAgent.claudeQuota.tooltip' });
+ expect(trigger.textContent).toContain(
+ 'heteroAgent.quota.weekly heteroAgent.quota.compactLeft:47',
+ );
+ expect(trigger.textContent).toContain('Fable heteroAgent.quota.compactLeft:0');
+ expect(trigger.textContent).not.toContain('heteroAgent.quota.exhausted');
+ expect(
+ [...trigger.querySelectorAll('[data-quota-level]')].map((item) =>
+ item.getAttribute('data-quota-level'),
+ ),
+ ).toEqual(['normal', 'low']);
+ });
+
+ it('warns below 15 percent and keeps compact zero quota numeric', async () => {
+ mockService.getClaudeCodeQuota.mockResolvedValue(
+ claudeSnapshot({
+ session: { resetsAt: null, usedPercent: 100, windowMinutes: 300 },
+ weekly: { resetsAt: null, usedPercent: 86, windowMinutes: 10_080 },
+ }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findAllByText('heteroAgent.quota.exhausted')).toHaveLength(1);
+ expect(screen.getByText('14%')).toBeTruthy();
+ expect(
+ screen.getByRole('button', { name: 'heteroAgent.claudeQuota.tooltip' }).textContent,
+ ).toContain('heteroAgent.quota.session heteroAgent.quota.compactLeft:0');
+ // Only the 14%-left weekly window warns; the exhausted session reads as
+ // "nothing to do until reset" and stays grey rather than alarm-orange.
+ expect(document.querySelectorAll('[data-quota-level="low"]')).toHaveLength(2);
+ });
+
+ 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('samples every local login on refresh, so Auto balances on fresh readings', async () => {
+ // Auto may route to a profile login the panel is not showing.
+ mockService.listClaudeCodeAccounts.mockResolvedValueOnce([
+ { configDir: null, identity: { externalAccountId: 'ext-default' } },
+ { configDir: '/profiles/work', identity: { externalAccountId: 'ext-work' } },
+ ]);
+ mockService.getClaudeCodeQuota.mockResolvedValue(claudeSnapshot({ status: 'unavailable' }));
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ await waitFor(() =>
+ expect(mockService.getClaudeCodeQuota).toHaveBeenCalledWith(
+ expect.objectContaining({ env: { CLAUDE_CONFIG_DIR: '/profiles/work' } }),
+ ),
+ );
+ });
+
+ it('keeps the account manager reachable when the sample is unavailable', async () => {
+ // e.g. the usage API is blocked on this network: adding or switching an
+ // account must not depend on a reading existing.
+ mockService.getClaudeCodeQuota.mockResolvedValue(
+ claudeSnapshot({ reason: 'request-blocked', status: 'unavailable' }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(
+ await screen.findByText('heteroAgent.claudeQuota.unavailableRequestBlocked'),
+ ).toBeTruthy();
+ expect(screen.getByText('heteroAgent.claudeQuota.manage.entry')).toBeTruthy();
+ });
+
+ it('explains a network-blocked sample instead of reporting an expired login', async () => {
+ mockService.getClaudeCodeQuota.mockResolvedValue(
+ claudeSnapshot({ error: 'blocked (403)', reason: 'request-blocked', status: 'unavailable' }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(
+ await screen.findByText('heteroAgent.claudeQuota.unavailableRequestBlocked'),
+ ).toBeTruthy();
+ expect(screen.queryByText('heteroAgent.claudeQuota.unavailableExpired')).toBeNull();
+ });
+
+ it('keeps the unavailable explanation on screen while a retry is in flight', async () => {
+ mockService.getClaudeCodeQuota.mockResolvedValueOnce(
+ claudeSnapshot({ error: 'expired', reason: 'credentials-expired', status: 'unavailable' }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('heteroAgent.claudeQuota.unavailableExpired')).toBeTruthy();
+
+ mockService.getClaudeCodeQuota.mockImplementation(() => new Promise(() => {}));
+ fireEvent.click(screen.getByTestId('refresh'));
+
+ await waitFor(() => expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(2));
+ expect((screen.getByTestId('refresh') as HTMLButtonElement).disabled).toBe(true);
+ expect(screen.queryByTestId('skeleton')).toBeNull();
+ expect(screen.getByText('heteroAgent.claudeQuota.unavailableExpired')).toBeTruthy();
+ });
+
+ it('shows a friendly rate-limit message for first-load 429 errors', async () => {
+ mockService.getClaudeCodeQuota.mockResolvedValue(
+ claudeSnapshot({ error: 'Anthropic usage API returned 429', status: 'error' }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('heteroAgent.claudeQuota.errorRateLimited')).toBeTruthy();
+ expect(screen.queryByText('Anthropic usage API returned 429')).toBeNull();
+
+ fireEvent.click(screen.getByTestId('refresh'));
+ // the refresh resolves the persisted account first, so the live call lands a
+ // tick later than the click
+ await waitFor(() => expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(2));
+ expect(mockService.getClaudeCodeQuota).toHaveBeenLastCalledWith({
+ env: undefined,
+ force: true,
+ });
+ });
+
+ it('keeps cached windows visible when the main-process refresh is rate-limited', async () => {
+ mockService.getClaudeCodeQuota.mockResolvedValue(
+ claudeSnapshot({
+ error: 'Anthropic usage API returned 429',
+ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
+ status: 'error',
+ updatedAt: Date.now() - 5 * 60_000,
+ }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('92%')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.claudeQuota.refreshRateLimited')).toBeTruthy();
+ expect(screen.queryByText('heteroAgent.claudeQuota.errorRateLimited')).toBeNull();
+ });
+
+ it('falls back to the live snapshot when the account identity is unresolvable', async () => {
+ // Quota comes from the keychain, but ~/.claude.json may carry no
+ // oauthAccount.accountUuid — nothing can be persisted, so the live readings
+ // must still render instead of an empty panel.
+ mockService.getClaudeCodeQuota.mockResolvedValue(
+ claudeSnapshot({
+ identity: undefined,
+ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
+ }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('92%')).toBeTruthy();
+ expect(mockQuotaService.ingestClaudeSnapshot).not.toHaveBeenCalled();
+ });
+
+ it('falls back to the live snapshot when a persisted account has no windows', async () => {
+ // An account row can exist while every reading was dropped (e.g. no usable
+ // reset), which used to render "unavailable" despite a healthy live fetch.
+ mockQuotaService.listAccounts.mockResolvedValue([
+ { externalAccountId: 'ext-1', id: 'acc-1', provider: 'claude-code' },
+ ]);
+ mockQuotaService.getLatestReadings.mockResolvedValue([]);
+ mockService.getClaudeCodeQuota.mockResolvedValue(
+ claudeSnapshot({ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 } }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('92%')).toBeTruthy();
+ });
+
+ it('degrades to the unavailable state when the live quota request rejects', async () => {
+ mockService.getClaudeCodeQuota.mockRejectedValueOnce(new Error('network failed'));
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ // Nothing persisted and the live fetch blew up: show the neutral empty state
+ // rather than leaking a raw transport error into the panel.
+ expect(await screen.findAllByText('heteroAgent.quota.unavailable')).not.toHaveLength(0);
+ expect(screen.queryByText('network failed')).toBeNull();
+ });
+
+ it('keeps the previous quota data when an automatic stale refresh is rate-limited', async () => {
+ const staleUpdatedAt = Date.now() - 61_000;
+
+ mockService.getClaudeCodeQuota
+ .mockResolvedValueOnce(
+ claudeSnapshot({
+ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
+ updatedAt: staleUpdatedAt,
+ }),
+ )
+ .mockResolvedValueOnce(
+ claudeSnapshot({ error: 'Anthropic usage API returned 429', status: 'error' }),
+ )
+ .mockResolvedValueOnce(
+ claudeSnapshot({
+ session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 },
+ }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('92%')).toBeTruthy();
+
+ fireEvent.click(screen.getByTestId('quota-trigger'));
+
+ await waitFor(() => expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(2));
+ expect(screen.getByText('92%')).toBeTruthy();
+ expect(screen.queryByText('Anthropic usage API returned 429')).toBeNull();
+ expect(screen.queryByText('heteroAgent.claudeQuota.refreshRateLimited')).toBeNull();
+
+ fireEvent.click(screen.getByTestId('quota-trigger'));
+
+ expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps stale data and shows a friendly prompt when manual refresh is rate-limited', async () => {
+ mockService.getClaudeCodeQuota
+ .mockResolvedValueOnce(
+ claudeSnapshot({
+ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
+ }),
+ )
+ .mockResolvedValueOnce(
+ claudeSnapshot({ error: 'Anthropic usage API returned 429', status: 'error' }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('92%')).toBeTruthy();
+
+ fireEvent.click(screen.getByTestId('refresh'));
+
+ await screen.findByText('heteroAgent.claudeQuota.refreshRateLimited');
+ expect(screen.getByText('92%')).toBeTruthy();
+ expect(screen.queryByText('Anthropic usage API returned 429')).toBeNull();
+ });
+
+ it('does not preserve quota data after switching Claude Code credential source', async () => {
+ mockService.getClaudeCodeQuota
+ .mockResolvedValueOnce(
+ claudeSnapshot({
+ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
+ }),
+ )
+ .mockResolvedValueOnce(
+ claudeSnapshot({ error: 'Anthropic usage API returned 429', status: 'error' }),
+ );
+
+ const { rerender } = render(<ClaudeCodeQuotaMenu env={{ CLAUDE_CONFIG_DIR: '/profile-a' }} />);
+
+ expect(await screen.findByText('92%')).toBeTruthy();
+
+ rerender(<ClaudeCodeQuotaMenu env={{ CLAUDE_CONFIG_DIR: '/profile-b' }} />);
+
+ await waitFor(() => expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(2));
+ expect(await screen.findByText('heteroAgent.claudeQuota.errorRateLimited')).toBeTruthy();
+ expect(screen.queryByText('92%')).toBeNull();
+ });
+
+ it('ignores stale request loading updates after switching Claude Code credential source', async () => {
+ const requests: Array<(snapshot: ElectronClientIpcModule.ClaudeCodeQuotaSnapshot) => void> = [];
+ mockService.getClaudeCodeQuota.mockImplementation(
+ () =>
+ new Promise<ElectronClientIpcModule.ClaudeCodeQuotaSnapshot>((resolve) => {
+ requests.push(resolve);
+ }),
+ );
+
+ const { rerender } = render(<ClaudeCodeQuotaMenu env={{ CLAUDE_CONFIG_DIR: '/profile-a' }} />);
+
+ await waitFor(() => expect(requests).toHaveLength(1));
+
+ rerender(<ClaudeCodeQuotaMenu env={{ CLAUDE_CONFIG_DIR: '/profile-b' }} />);
+
+ await waitFor(() => expect(requests).toHaveLength(2));
+
+ await act(async () => {
+ requests[0](
+ claudeSnapshot({
+ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
+ }),
+ );
+ });
+
+ expect(screen.getAllByTestId('skeleton')).toHaveLength(3);
+ expect(screen.queryByText('heteroAgent.quota.noData')).toBeNull();
+ expect((screen.getByTestId('refresh') as HTMLButtonElement).disabled).toBe(true);
+
+ await act(async () => {
+ requests[1](
+ claudeSnapshot({
+ session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 },
+ }),
+ );
+ });
+
+ expect(await screen.findByText('80%')).toBeTruthy();
+ expect((screen.getByTestId('refresh') as HTMLButtonElement).disabled).toBe(false);
+ });
+
+ 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();
+ });
+
+ it('shows the live sample when the persisted window has already reset', async () => {
+ // A device offline since yesterday leaves a reading behind whose window has
+ // since reset. Its 100% describes spend that already refilled, so a sample
+ // attributable to the same account must lead.
+ mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 60 * 60_000)]);
+ mockQuotaService.getLatestReadings.mockResolvedValue([
+ {
+ ...persistedSessionReading(Date.now() - 24 * 60 * 60_000),
+ resetsAt: Date.now() - 60 * 60_000,
+ utilization: 100,
+ },
+ ]);
+ mockService.getClaudeCodeQuota.mockResolvedValue(
+ claudeSnapshot({
+ identity: { externalAccountId: 'ext-1' },
+ readings: [{ ...liveSessionReading(Date.now()), utilization: 4 }],
+ session: { resetsAt: null, usedPercent: 4, windowMinutes: 300 },
+ }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ // 96% left from the live sample — not the reset row's 100%, and not empty.
+ expect(await screen.findByText('96%')).toBeTruthy();
+ expect(screen.queryByText('heteroAgent.quota.noData')).toBeNull();
+ });
+
+ it('will not paint an unattributable sample under a named account', async () => {
+ // Same setup, except the sample carries no account identity (no
+ // `oauthAccount` in ~/.claude.json while the quota came from the keychain).
+ // With several logins on the machine it may belong to another account, so
+ // the panel keeps the account's own refilled window instead.
+ mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 60 * 60_000)]);
+ mockQuotaService.getLatestReadings.mockResolvedValue([
+ {
+ ...persistedSessionReading(Date.now() - 24 * 60 * 60_000),
+ resetsAt: Date.now() - 60 * 60_000,
+ utilization: 100,
+ },
+ ]);
+ mockService.getClaudeCodeQuota.mockResolvedValue(
+ claudeSnapshot({ session: { resetsAt: null, usedPercent: 4, windowMinutes: 300 } }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ // The reset window reads as refilled; the unattributable 96% is not shown.
+ expect(await screen.findByText('100%')).toBeTruthy();
+ expect(screen.queryByText('96%')).toBeNull();
+ });
+
+ it('keeps the 5-hour row on screen as refilled once its window resets', async () => {
+ // The regression: after five idle hours the session window rolls over and
+ // the panel used to drop the row entirely, leaving the weekly limit alone
+ // as if the plan had no session limit. A reset window is free, not absent.
+ mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 60_000)]);
+ mockQuotaService.getLatestReadings.mockResolvedValue([
+ {
+ ...persistedSessionReading(Date.now() - 60_000),
+ resetsAt: Date.now() - 30 * 60_000,
+ utilization: 83,
+ },
+ {
+ capturedAt: Date.now() - 60_000,
+ limitType: 'weekly_all',
+ resetsAt: Date.now() + 4 * 24 * 60 * 60_000,
+ scopeKey: '',
+ utilization: 21,
+ },
+ ]);
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ // Session refilled to 100% left, weekly still at 79% — two rows, not one.
+ expect(await screen.findByText('100%')).toBeTruthy();
+ expect(screen.getByText('79%')).toBeTruthy();
+ expect(mockService.getClaudeCodeQuota).not.toHaveBeenCalled();
+ });
+
+ it('renders persisted windows without a live call while the newest reading is fresh', async () => {
+ mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 60_000)]);
+ mockQuotaService.getLatestReadings.mockResolvedValue([
+ persistedSessionReading(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.getLatestReadings.mockResolvedValue([
+ persistedSessionReading(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('explains a blocked live refresh under the persisted windows it could not update', async () => {
+ mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 31 * 60_000)]);
+ mockQuotaService.getLatestReadings.mockResolvedValue([
+ persistedSessionReading(Date.now() - 31 * 60_000),
+ ]);
+ mockService.getClaudeCodeQuota.mockResolvedValue(
+ claudeSnapshot({ error: 'blocked (403)', reason: 'request-blocked', status: 'unavailable' }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(
+ await screen.findByText('heteroAgent.claudeQuota.unavailableRequestBlocked'),
+ ).toBeTruthy();
+ expect(screen.getByText('92%')).toBeTruthy();
+ });
+
+ it('paints persisted windows while a stale live refresh is still in flight', async () => {
+ mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 31 * 60_000)]);
+ mockQuotaService.getLatestReadings.mockResolvedValue([
+ persistedSessionReading(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.getLatestReadings.mockResolvedValue([
+ persistedSessionReading(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();
+ await waitForQuotaIdle();
+ 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 () => {
+ mockLambdaClaudeQuota.mockResolvedValue(
+ claudeSnapshot({ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 } }),
+ );
+
+ render(<ClaudeCodeQuotaMenu deviceId="remote-device" />);
+
+ await waitFor(() =>
+ expect(mockLambdaClaudeQuota).toHaveBeenCalledWith({
+ deviceId: 'remote-device',
+ env: undefined,
+ }),
+ );
+ expect(await screen.findByText('92%')).toBeTruthy();
+ expect(mockService.getClaudeCodeQuota).not.toHaveBeenCalled();
+ });
+
+ it('keeps the stored snapshot when a cold load of a device fails to sample', async () => {
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ const storage = quotaPanelResource.storage!;
+ const sourceKey = createQuotaSourceKey('claude-code', 'agent-1', 'remote-device', undefined);
+ const row = { queryKey: hashQuotaSourceKey(sourceKey), scope: cacheScope.get() };
+ await storage.set(row, {
+ data: claudeSnapshot({ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 } }),
+ updatedAt: 1,
+ });
+ // No trusted device account yet on a cold load, and the device RPC fails.
+ mockLambdaClaudeQuota.mockRejectedValue(new Error('device offline'));
+
+ render(<ClaudeCodeQuotaMenu deviceId="remote-device" />);
+
+ await waitFor(() => expect(mockLambdaClaudeQuota).toHaveBeenCalled());
+ await waitForQuotaIdle();
+ await waitFor(() => expect(screen.getAllByText('92%').length).toBeGreaterThan(0));
+ expect(screen.queryByText('heteroAgent.quota.unavailable')).toBeNull();
+ expect(await storage.get(row)).toMatchObject({ data: { status: 'ok' } });
+ });
+
+ 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.getLatestReadings.mockResolvedValue([persistedSessionReading(capturedAt)]);
+ mockLambdaClaudeQuota.mockResolvedValueOnce(
+ claudeSnapshot({
+ identity: { externalAccountId: 'ext-1' },
+ readings: [liveSessionReading(capturedAt)],
+ }),
+ );
+
+ const { rerender } = render(<ClaudeCodeQuotaMenu deviceId="device-a" />);
+ expect(await screen.findByText('92%')).toBeTruthy();
+
+ mockLambdaClaudeQuota.mockResolvedValueOnce(null);
+ rerender(<ClaudeCodeQuotaMenu deviceId="device-b" />);
+
+ await waitFor(() =>
+ expect(mockLambdaClaudeQuota).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 {
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ get: () => 'visible',
+ });
+
+ mockQuotaService.listAccounts.mockResolvedValue([persistedAccount()]);
+ mockQuotaService.getLatestReadings.mockResolvedValue([
+ persistedSessionReading(Date.now() - 60_000),
+ ]);
+ mockService.getClaudeCodeQuota.mockResolvedValue(claudeSnapshot());
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('92%')).toBeTruthy();
+ expect(mockService.getClaudeCodeQuota).not.toHaveBeenCalled();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2 * 60_000 + 500);
+ });
+
+ 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.getLatestReadings.mockResolvedValue([persistedSessionReading(persistedAt)]);
+ mockService.getClaudeCodeQuota.mockResolvedValue(
+ claudeSnapshot({
+ identity: { externalAccountId: 'ext-1' },
+ readings: [liveSessionReading(persistedAt)],
+ }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('92%')).toBeTruthy();
+ await waitForQuotaIdle();
+
+ 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.getLatestReadings.mockResolvedValue([persistedSessionReading(persistedAt)]);
+ const readings = [liveSessionReading(Date.now())];
+ mockService.getClaudeCodeQuota.mockResolvedValue(
+ claudeSnapshot({ identity: { externalAccountId: 'ext-1' }, readings }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('92%')).toBeTruthy();
+ await waitForQuotaIdle();
+
+ 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 waitForQuotaIdle();
+
+ await act(async () => {
+ window.dispatchEvent(new Event('focus'));
+ });
+
+ expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx
index 2b322db2982..e4269b47fe8 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx
@@ -15,16 +15,7 @@ import ClaudeCodeQuotaMenu from './ClaudeCodeQuotaMenu';
import CodexQuotaMenu from './CodexQuotaMenu';
import KimiCodeQuotaMenu from './KimiCodeQuotaMenu';
import { createQuotaSourceKey } from './QuotaMenu';
-import {
- claudeSnapshot,
- codexSnapshot,
- isolateQuotaReplica,
- kimiCodeSnapshot,
- liveSessionReading,
- persistedAccount,
- persistedSessionReading,
- waitForQuotaIdle,
-} from './testUtils';
+import { claudeSnapshot, codexSnapshot, isolateQuotaReplica, kimiCodeSnapshot } from './testUtils';
const mockService = vi.hoisted(() => ({
consumeCodexRateLimitResetCredit: vi.fn(),
@@ -385,698 +376,6 @@ describe('KimiCodeQuotaMenu', () => {
});
});
-describe('ClaudeCodeQuotaMenu', () => {
- it('opens the usage calendar for the claude-code account from the header switcher', async () => {
- mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 60_000)]);
- mockQuotaService.getLatestReadings.mockResolvedValue([
- persistedSessionReading(Date.now() - 60_000),
- ]);
-
- render(<ClaudeCodeQuotaMenu />);
-
- fireEvent.click(await screen.findByTestId('calendar'));
-
- expect(openQuotaCalendarModal).toHaveBeenCalledWith({
- externalAccountId: 'ext-1',
- provider: 'claude-code',
- });
- });
-
- 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();
- expect(screen.getByText('92%')).toBeTruthy();
- const trigger = screen.getByRole('button', { name: 'heteroAgent.claudeQuota.tooltip' });
- expect(trigger.textContent).toContain(
- 'heteroAgent.quota.weekly heteroAgent.quota.compactLeft:87',
- );
- expect(trigger.textContent).toContain('Fable heteroAgent.quota.compactLeft:76');
- expect(mockService.getClaudeCodeQuota).toHaveBeenCalledWith({
- env: { CLAUDE_CONFIG_DIR: '/custom' },
- });
- });
-
- it('shows the tightest global window and Fable as separate compact values', async () => {
- mockService.getClaudeCodeQuota.mockResolvedValue(
- claudeSnapshot({
- scopedWeekly: {
- modelName: 'Fable',
- window: { resetsAt: null, usedPercent: 100, windowMinutes: 10_080 },
- },
- session: { resetsAt: null, usedPercent: 49, windowMinutes: 300 },
- weekly: { resetsAt: null, usedPercent: 53, windowMinutes: 10_080 },
- }),
- );
-
- render(<ClaudeCodeQuotaMenu />);
-
- expect(await screen.findByText('heteroAgent.quota.exhausted')).toBeTruthy();
- const trigger = screen.getByRole('button', { name: 'heteroAgent.claudeQuota.tooltip' });
- expect(trigger.textContent).toContain(
- 'heteroAgent.quota.weekly heteroAgent.quota.compactLeft:47',
- );
- expect(trigger.textContent).toContain('Fable heteroAgent.quota.compactLeft:0');
- expect(trigger.textContent).not.toContain('heteroAgent.quota.exhausted');
- expect(
- [...trigger.querySelectorAll('[data-quota-level]')].map((item) =>
- item.getAttribute('data-quota-level'),
- ),
- ).toEqual(['normal', 'low']);
- });
-
- it('warns below 15 percent and keeps compact zero quota numeric', async () => {
- mockService.getClaudeCodeQuota.mockResolvedValue(
- claudeSnapshot({
- session: { resetsAt: null, usedPercent: 100, windowMinutes: 300 },
- weekly: { resetsAt: null, usedPercent: 86, windowMinutes: 10_080 },
- }),
- );
-
- render(<ClaudeCodeQuotaMenu />);
-
- expect(await screen.findAllByText('heteroAgent.quota.exhausted')).toHaveLength(1);
- expect(screen.getByText('14%')).toBeTruthy();
- expect(
- screen.getByRole('button', { name: 'heteroAgent.claudeQuota.tooltip' }).textContent,
- ).toContain('heteroAgent.quota.session heteroAgent.quota.compactLeft:0');
- // Only the 14%-left weekly window warns; the exhausted session reads as
- // "nothing to do until reset" and stays grey rather than alarm-orange.
- expect(document.querySelectorAll('[data-quota-level="low"]')).toHaveLength(2);
- });
-
- 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('explains a network-blocked sample instead of reporting an expired login', async () => {
- mockService.getClaudeCodeQuota.mockResolvedValue(
- claudeSnapshot({ error: 'blocked (403)', reason: 'request-blocked', status: 'unavailable' }),
- );
-
- render(<ClaudeCodeQuotaMenu />);
-
- expect(
- await screen.findByText('heteroAgent.claudeQuota.unavailableRequestBlocked'),
- ).toBeTruthy();
- expect(screen.queryByText('heteroAgent.claudeQuota.unavailableExpired')).toBeNull();
- });
-
- it('keeps the unavailable explanation on screen while a retry is in flight', async () => {
- mockService.getClaudeCodeQuota.mockResolvedValueOnce(
- claudeSnapshot({ error: 'expired', reason: 'credentials-expired', status: 'unavailable' }),
- );
-
- render(<ClaudeCodeQuotaMenu />);
-
- expect(await screen.findByText('heteroAgent.claudeQuota.unavailableExpired')).toBeTruthy();
-
- mockService.getClaudeCodeQuota.mockImplementation(() => new Promise(() => {}));
- fireEvent.click(screen.getByTestId('refresh'));
-
- await waitFor(() => expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(2));
- expect((screen.getByTestId('refresh') as HTMLButtonElement).disabled).toBe(true);
- expect(screen.queryByTestId('skeleton')).toBeNull();
- expect(screen.getByText('heteroAgent.claudeQuota.unavailableExpired')).toBeTruthy();
- });
-
- it('shows a friendly rate-limit message for first-load 429 errors', async () => {
- mockService.getClaudeCodeQuota.mockResolvedValue(
- claudeSnapshot({ error: 'Anthropic usage API returned 429', status: 'error' }),
- );
-
- render(<ClaudeCodeQuotaMenu />);
-
- expect(await screen.findByText('heteroAgent.claudeQuota.errorRateLimited')).toBeTruthy();
- expect(screen.queryByText('Anthropic usage API returned 429')).toBeNull();
-
- fireEvent.click(screen.getByTestId('refresh'));
- // the refresh resolves the persisted account first, so the live call lands a
- // tick later than the click
- await waitFor(() => expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(2));
- expect(mockService.getClaudeCodeQuota).toHaveBeenLastCalledWith({
- env: undefined,
- force: true,
- });
- });
-
- it('keeps cached windows visible when the main-process refresh is rate-limited', async () => {
- mockService.getClaudeCodeQuota.mockResolvedValue(
- claudeSnapshot({
- error: 'Anthropic usage API returned 429',
- session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
- status: 'error',
- updatedAt: Date.now() - 5 * 60_000,
- }),
- );
-
- render(<ClaudeCodeQuotaMenu />);
-
- expect(await screen.findByText('92%')).toBeTruthy();
- expect(screen.getByText('heteroAgent.claudeQuota.refreshRateLimited')).toBeTruthy();
- expect(screen.queryByText('heteroAgent.claudeQuota.errorRateLimited')).toBeNull();
- });
-
- it('falls back to the live snapshot when the account identity is unresolvable', async () => {
- // Quota comes from the keychain, but ~/.claude.json may carry no
- // oauthAccount.accountUuid — nothing can be persisted, so the live readings
- // must still render instead of an empty panel.
- mockService.getClaudeCodeQuota.mockResolvedValue(
- claudeSnapshot({
- identity: undefined,
- session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
- }),
- );
-
- render(<ClaudeCodeQuotaMenu />);
-
- expect(await screen.findByText('92%')).toBeTruthy();
- expect(mockQuotaService.ingestClaudeSnapshot).not.toHaveBeenCalled();
- });
-
- it('falls back to the live snapshot when a persisted account has no windows', async () => {
- // An account row can exist while every reading was dropped (e.g. no usable
- // reset), which used to render "unavailable" despite a healthy live fetch.
- mockQuotaService.listAccounts.mockResolvedValue([
- { externalAccountId: 'ext-1', id: 'acc-1', provider: 'claude-code' },
- ]);
- mockQuotaService.getLatestReadings.mockResolvedValue([]);
- mockService.getClaudeCodeQuota.mockResolvedValue(
- claudeSnapshot({ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 } }),
- );
-
- render(<ClaudeCodeQuotaMenu />);
-
- expect(await screen.findByText('92%')).toBeTruthy();
- });
-
- it('degrades to the unavailable state when the live quota request rejects', async () => {
- mockService.getClaudeCodeQuota.mockRejectedValueOnce(new Error('network failed'));
-
- render(<ClaudeCodeQuotaMenu />);
-
- // Nothing persisted and the live fetch blew up: show the neutral empty state
- // rather than leaking a raw transport error into the panel.
- expect(await screen.findAllByText('heteroAgent.quota.unavailable')).not.toHaveLength(0);
- expect(screen.queryByText('network failed')).toBeNull();
- });
-
- it('keeps the previous quota data when an automatic stale refresh is rate-limited', async () => {
- const staleUpdatedAt = Date.now() - 61_000;
-
- mockService.getClaudeCodeQuota
- .mockResolvedValueOnce(
- claudeSnapshot({
- session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
- updatedAt: staleUpdatedAt,
- }),
- )
- .mockResolvedValueOnce(
- claudeSnapshot({ error: 'Anthropic usage API returned 429', status: 'error' }),
- )
- .mockResolvedValueOnce(
- claudeSnapshot({
- session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 },
- }),
- );
-
- render(<ClaudeCodeQuotaMenu />);
-
- expect(await screen.findByText('92%')).toBeTruthy();
-
- fireEvent.click(screen.getByTestId('quota-trigger'));
-
- await waitFor(() => expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(2));
- expect(screen.getByText('92%')).toBeTruthy();
- expect(screen.queryByText('Anthropic usage API returned 429')).toBeNull();
- expect(screen.queryByText('heteroAgent.claudeQuota.refreshRateLimited')).toBeNull();
-
- fireEvent.click(screen.getByTestId('quota-trigger'));
-
- expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(2);
- });
-
- it('keeps stale data and shows a friendly prompt when manual refresh is rate-limited', async () => {
- mockService.getClaudeCodeQuota
- .mockResolvedValueOnce(
- claudeSnapshot({
- session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
- }),
- )
- .mockResolvedValueOnce(
- claudeSnapshot({ error: 'Anthropic usage API returned 429', status: 'error' }),
- );
-
- render(<ClaudeCodeQuotaMenu />);
-
- expect(await screen.findByText('92%')).toBeTruthy();
-
- fireEvent.click(screen.getByTestId('refresh'));
-
- await screen.findByText('heteroAgent.claudeQuota.refreshRateLimited');
- expect(screen.getByText('92%')).toBeTruthy();
- expect(screen.queryByText('Anthropic usage API returned 429')).toBeNull();
- });
-
- it('does not preserve quota data after switching Claude Code credential source', async () => {
- mockService.getClaudeCodeQuota
- .mockResolvedValueOnce(
- claudeSnapshot({
- session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
- }),
- )
- .mockResolvedValueOnce(
- claudeSnapshot({ error: 'Anthropic usage API returned 429', status: 'error' }),
- );
-
- const { rerender } = render(<ClaudeCodeQuotaMenu env={{ CLAUDE_CONFIG_DIR: '/profile-a' }} />);
-
- expect(await screen.findByText('92%')).toBeTruthy();
-
- rerender(<ClaudeCodeQuotaMenu env={{ CLAUDE_CONFIG_DIR: '/profile-b' }} />);
-
- await waitFor(() => expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(2));
- expect(await screen.findByText('heteroAgent.claudeQuota.errorRateLimited')).toBeTruthy();
- expect(screen.queryByText('92%')).toBeNull();
- });
-
- it('ignores stale request loading updates after switching Claude Code credential source', async () => {
- const requests: Array<(snapshot: ElectronClientIpcModule.ClaudeCodeQuotaSnapshot) => void> = [];
- mockService.getClaudeCodeQuota.mockImplementation(
- () =>
- new Promise<ElectronClientIpcModule.ClaudeCodeQuotaSnapshot>((resolve) => {
- requests.push(resolve);
- }),
- );
-
- const { rerender } = render(<ClaudeCodeQuotaMenu env={{ CLAUDE_CONFIG_DIR: '/profile-a' }} />);
-
- await waitFor(() => expect(requests).toHaveLength(1));
-
- rerender(<ClaudeCodeQuotaMenu env={{ CLAUDE_CONFIG_DIR: '/profile-b' }} />);
-
- await waitFor(() => expect(requests).toHaveLength(2));
-
- await act(async () => {
- requests[0](
- claudeSnapshot({
- session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
- }),
- );
- });
-
- expect(screen.getAllByTestId('skeleton')).toHaveLength(3);
- expect(screen.queryByText('heteroAgent.quota.noData')).toBeNull();
- expect((screen.getByTestId('refresh') as HTMLButtonElement).disabled).toBe(true);
-
- await act(async () => {
- requests[1](
- claudeSnapshot({
- session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 },
- }),
- );
- });
-
- expect(await screen.findByText('80%')).toBeTruthy();
- expect((screen.getByTestId('refresh') as HTMLButtonElement).disabled).toBe(false);
- });
-
- 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();
- });
-
- it('shows the live sample when the persisted window has already reset', async () => {
- // A device offline since yesterday leaves a reading behind whose window has
- // since reset. Its 100% describes spend that already refilled, so a sample
- // attributable to the same account must lead.
- mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 60 * 60_000)]);
- mockQuotaService.getLatestReadings.mockResolvedValue([
- {
- ...persistedSessionReading(Date.now() - 24 * 60 * 60_000),
- resetsAt: Date.now() - 60 * 60_000,
- utilization: 100,
- },
- ]);
- mockService.getClaudeCodeQuota.mockResolvedValue(
- claudeSnapshot({
- identity: { externalAccountId: 'ext-1' },
- readings: [{ ...liveSessionReading(Date.now()), utilization: 4 }],
- session: { resetsAt: null, usedPercent: 4, windowMinutes: 300 },
- }),
- );
-
- render(<ClaudeCodeQuotaMenu />);
-
- // 96% left from the live sample — not the reset row's 100%, and not empty.
- expect(await screen.findByText('96%')).toBeTruthy();
- expect(screen.queryByText('heteroAgent.quota.noData')).toBeNull();
- });
-
- it('will not paint an unattributable sample under a named account', async () => {
- // Same setup, except the sample carries no account identity (no
- // `oauthAccount` in ~/.claude.json while the quota came from the keychain).
- // With several logins on the machine it may belong to another account, so
- // the panel keeps the account's own refilled window instead.
- mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 60 * 60_000)]);
- mockQuotaService.getLatestReadings.mockResolvedValue([
- {
- ...persistedSessionReading(Date.now() - 24 * 60 * 60_000),
- resetsAt: Date.now() - 60 * 60_000,
- utilization: 100,
- },
- ]);
- mockService.getClaudeCodeQuota.mockResolvedValue(
- claudeSnapshot({ session: { resetsAt: null, usedPercent: 4, windowMinutes: 300 } }),
- );
-
- render(<ClaudeCodeQuotaMenu />);
-
- // The reset window reads as refilled; the unattributable 96% is not shown.
- expect(await screen.findByText('100%')).toBeTruthy();
- expect(screen.queryByText('96%')).toBeNull();
- });
-
- it('keeps the 5-hour row on screen as refilled once its window resets', async () => {
- // The regression: after five idle hours the session window rolls over and
- // the panel used to drop the row entirely, leaving the weekly limit alone
- // as if the plan had no session limit. A reset window is free, not absent.
- mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 60_000)]);
- mockQuotaService.getLatestReadings.mockResolvedValue([
- {
- ...persistedSessionReading(Date.now() - 60_000),
- resetsAt: Date.now() - 30 * 60_000,
- utilization: 83,
- },
- {
- capturedAt: Date.now() - 60_000,
- limitType: 'weekly_all',
- resetsAt: Date.now() + 4 * 24 * 60 * 60_000,
- scopeKey: '',
- utilization: 21,
- },
- ]);
-
- render(<ClaudeCodeQuotaMenu />);
-
- // Session refilled to 100% left, weekly still at 79% — two rows, not one.
- expect(await screen.findByText('100%')).toBeTruthy();
- expect(screen.getByText('79%')).toBeTruthy();
- expect(mockService.getClaudeCodeQuota).not.toHaveBeenCalled();
- });
-
- it('renders persisted windows without a live call while the newest reading is fresh', async () => {
- mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 60_000)]);
- mockQuotaService.getLatestReadings.mockResolvedValue([
- persistedSessionReading(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.getLatestReadings.mockResolvedValue([
- persistedSessionReading(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('explains a blocked live refresh under the persisted windows it could not update', async () => {
- mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 31 * 60_000)]);
- mockQuotaService.getLatestReadings.mockResolvedValue([
- persistedSessionReading(Date.now() - 31 * 60_000),
- ]);
- mockService.getClaudeCodeQuota.mockResolvedValue(
- claudeSnapshot({ error: 'blocked (403)', reason: 'request-blocked', status: 'unavailable' }),
- );
-
- render(<ClaudeCodeQuotaMenu />);
-
- expect(
- await screen.findByText('heteroAgent.claudeQuota.unavailableRequestBlocked'),
- ).toBeTruthy();
- expect(screen.getByText('92%')).toBeTruthy();
- });
-
- it('paints persisted windows while a stale live refresh is still in flight', async () => {
- mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 31 * 60_000)]);
- mockQuotaService.getLatestReadings.mockResolvedValue([
- persistedSessionReading(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.getLatestReadings.mockResolvedValue([
- persistedSessionReading(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();
- await waitForQuotaIdle();
- 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 () => {
- mockLambdaClaudeQuota.mockResolvedValue(
- claudeSnapshot({ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 } }),
- );
-
- render(<ClaudeCodeQuotaMenu deviceId="remote-device" />);
-
- await waitFor(() =>
- expect(mockLambdaClaudeQuota).toHaveBeenCalledWith({
- deviceId: 'remote-device',
- env: undefined,
- }),
- );
- expect(await screen.findByText('92%')).toBeTruthy();
- expect(mockService.getClaudeCodeQuota).not.toHaveBeenCalled();
- });
-
- it('keeps the stored snapshot when a cold load of a device fails to sample', async () => {
- vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
- const storage = quotaPanelResource.storage!;
- const sourceKey = createQuotaSourceKey('claude-code', 'agent-1', 'remote-device', undefined);
- const row = { queryKey: hashQuotaSourceKey(sourceKey), scope: cacheScope.get() };
- await storage.set(row, {
- data: claudeSnapshot({ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 } }),
- updatedAt: 1,
- });
- // No trusted device account yet on a cold load, and the device RPC fails.
- mockLambdaClaudeQuota.mockRejectedValue(new Error('device offline'));
-
- render(<ClaudeCodeQuotaMenu deviceId="remote-device" />);
-
- await waitFor(() => expect(mockLambdaClaudeQuota).toHaveBeenCalled());
- await waitForQuotaIdle();
- await waitFor(() => expect(screen.getAllByText('92%').length).toBeGreaterThan(0));
- expect(screen.queryByText('heteroAgent.quota.unavailable')).toBeNull();
- expect(await storage.get(row)).toMatchObject({ data: { status: 'ok' } });
- });
-
- 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.getLatestReadings.mockResolvedValue([persistedSessionReading(capturedAt)]);
- mockLambdaClaudeQuota.mockResolvedValueOnce(
- claudeSnapshot({
- identity: { externalAccountId: 'ext-1' },
- readings: [liveSessionReading(capturedAt)],
- }),
- );
-
- const { rerender } = render(<ClaudeCodeQuotaMenu deviceId="device-a" />);
- expect(await screen.findByText('92%')).toBeTruthy();
-
- mockLambdaClaudeQuota.mockResolvedValueOnce(null);
- rerender(<ClaudeCodeQuotaMenu deviceId="device-b" />);
-
- await waitFor(() =>
- expect(mockLambdaClaudeQuota).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 {
- Object.defineProperty(document, 'visibilityState', {
- configurable: true,
- get: () => 'visible',
- });
-
- mockQuotaService.listAccounts.mockResolvedValue([persistedAccount()]);
- mockQuotaService.getLatestReadings.mockResolvedValue([
- persistedSessionReading(Date.now() - 60_000),
- ]);
- mockService.getClaudeCodeQuota.mockResolvedValue(claudeSnapshot());
-
- render(<ClaudeCodeQuotaMenu />);
-
- expect(await screen.findByText('92%')).toBeTruthy();
- expect(mockService.getClaudeCodeQuota).not.toHaveBeenCalled();
-
- await act(async () => {
- await vi.advanceTimersByTimeAsync(2 * 60_000 + 500);
- });
-
- 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.getLatestReadings.mockResolvedValue([persistedSessionReading(persistedAt)]);
- mockService.getClaudeCodeQuota.mockResolvedValue(
- claudeSnapshot({
- identity: { externalAccountId: 'ext-1' },
- readings: [liveSessionReading(persistedAt)],
- }),
- );
-
- render(<ClaudeCodeQuotaMenu />);
-
- expect(await screen.findByText('92%')).toBeTruthy();
- await waitForQuotaIdle();
-
- 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.getLatestReadings.mockResolvedValue([persistedSessionReading(persistedAt)]);
- const readings = [liveSessionReading(Date.now())];
- mockService.getClaudeCodeQuota.mockResolvedValue(
- claudeSnapshot({ identity: { externalAccountId: 'ext-1' }, readings }),
- );
-
- render(<ClaudeCodeQuotaMenu />);
-
- expect(await screen.findByText('92%')).toBeTruthy();
- await waitForQuotaIdle();
-
- 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 waitForQuotaIdle();
-
- await act(async () => {
- window.dispatchEvent(new Event('focus'));
- });
-
- expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(1);
- });
-});
-
describe('CodexQuotaMenu', () => {
it('opens the usage calendar for the codex account from the header switcher', async () => {
mockService.getCodexQuota.mockResolvedValue(
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx
index dc372233e30..2437c3aa1a5 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx
@@ -215,6 +215,12 @@ export interface FetchQuotaOptions<S = unknown> {
}
interface QuotaMenuProps<S extends QuotaSnapshotBase> {
+ /**
+ * Keep `renderHeader` on screen when there are no windows to show (an
+ * unavailable / failed / empty sample), for headers that carry controls the
+ * user needs in exactly those states — e.g. adding or switching an account.
+ */
+ alwaysRenderHeader?: boolean;
/**
* Revalidate on this cadence while the tab is visible, so the badge stays
* near-live without user interaction. Upstream sampler caches must keep
@@ -277,6 +283,7 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
hasExtraData,
renderFooter,
renderHeader,
+ alwaysRenderHeader,
sourceKey = 'default',
title,
tooltip,
@@ -673,13 +680,19 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
<Skeleton height={18} />
</Flexbox>
) : quota?.status === 'unavailable' ? (
- <div className={styles.emptyState}>
- {getUnavailableText?.(quota) || quota.error || t('heteroAgent.quota.unavailable')}
- </div>
+ <>
+ {alwaysRenderHeader && renderHeader?.(quota, { applyQuota, formatDuration, now })}
+ <div className={styles.emptyState}>
+ {getUnavailableText?.(quota) || quota.error || t('heteroAgent.quota.unavailable')}
+ </div>
+ </>
) : quota?.status === 'error' && !hasQuotaData ? (
- <div className={styles.error}>
- {getErrorText?.(quota) || quota.error || t('heteroAgent.quota.unavailable')}
- </div>
+ <>
+ {alwaysRenderHeader && renderHeader?.(quota, { applyQuota, formatDuration, now })}
+ <div className={styles.error}>
+ {getErrorText?.(quota) || quota.error || t('heteroAgent.quota.unavailable')}
+ </div>
+ </>
) : hasQuotaData ? (
<>
{quota && renderHeader?.(quota, { applyQuota, formatDuration, now })}
@@ -697,7 +710,12 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
)}
</>
) : (
- <div className={styles.emptyState}>{t('heteroAgent.quota.noData')}</div>
+ <>
+ {alwaysRenderHeader &&
+ quota &&
+ renderHeader?.(quota, { applyQuota, formatDuration, now })}
+ <div className={styles.emptyState}>{t('heteroAgent.quota.noData')}</div>
+ </>
)}
</Flexbox>
);
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 54f2df2a722..bfc36d7dc90 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -922,6 +922,8 @@ export const imessageKeys = {
};
// Desktop/electron IPC fetches — roots keep their existing `electron:getXxx` value.
export const electronKeys = {
+ /** Claude Code logins held on this machine (device-local, never persisted). */
+ claudeCodeAccounts: def('electron:claudeCodeAccounts', () => ['electron:claudeCodeAccounts']),
appTrayVisible: def('electron:getAppTrayVisible', () => ['electron:getAppTrayVisible']),
desktopHotkeys: def('electron:getDesktopHotkeys', () => ['electron:getDesktopHotkeys']),
gatewayDeviceInfo: def('electron:getGatewayDeviceInfo', () => ['electron:getGatewayDeviceInfo']),
diff --git a/src/services/agentQuota.ts b/src/services/agentQuota.ts
index 513af70d73f..30ec3eba9a0 100644
--- a/src/services/agentQuota.ts
+++ b/src/services/agentQuota.ts
@@ -102,7 +102,7 @@ class AgentQuotaService {
/** Who the load balancer would pick right now (Auto mode preview + reason). */
selectAccountForAgent = async (
agentId: string,
- options?: { modelScope?: string; provider?: string },
+ options?: { modelScope?: string; provider?: string; runnableExternalAccountIds?: string[] },
) => lambdaClient.agentQuota.selectAccountForAgent.query({ agentId, ...options });
/** One assistant turn's consumption → usage ledger (idempotent by message id). */
diff --git a/src/services/electron/heterogeneousAgent.ts b/src/services/electron/heterogeneousAgent.ts
index 2e0693b2b41..ca18e2019fb 100644
--- a/src/services/electron/heterogeneousAgent.ts
+++ b/src/services/electron/heterogeneousAgent.ts
@@ -1,4 +1,6 @@
import type {
+ ClaudeCodeAccountResolution,
+ ClaudeCodeLocalAccount,
ClaudeCodeQuotaSnapshot,
CodexQuotaSnapshot,
CodexRateLimitResetResult,
@@ -163,6 +165,30 @@ class HeterogeneousAgentService {
return this.ipc.heterogeneousAgent.getClaudeCodeIdentity(params);
}
+ /** Every Claude Code account signed in on this machine (default login first). */
+ async listClaudeCodeAccounts(): Promise<ClaudeCodeLocalAccount[]> {
+ return this.ipc.heterogeneousAgent.listClaudeCodeAccounts();
+ }
+
+ /** The local login a run for this provider account must spawn with. */
+ async resolveClaudeCodeAccount(externalAccountId: string): Promise<ClaudeCodeAccountResolution> {
+ return this.ipc.heterogeneousAgent.resolveClaudeCodeAccount({ externalAccountId });
+ }
+
+ /** External-provider routing flags a session spawn inherits from the desktop's env. */
+ async getClaudeCodeInheritedRoutingEnv(): Promise<Record<string, string>> {
+ return this.ipc.heterogeneousAgent.getClaudeCodeInheritedRoutingEnv();
+ }
+
+ /** Sign an account in to its own profile; resolves once the browser login completes. */
+ async loginClaudeCodeAccount(params?: { email?: string }): Promise<ClaudeCodeLocalAccount> {
+ return this.ipc.heterogeneousAgent.loginClaudeCodeAccount(params);
+ }
+
+ async cancelClaudeCodeAccountLogin(): Promise<boolean> {
+ return this.ipc.heterogeneousAgent.cancelClaudeCodeAccountLogin();
+ }
+
/**
* Submit the user's answer (or cancellation) for a pending CC
* AskUserQuestion intervention. The main process routes it to the
diff --git a/src/store/agentQuota/action.ts b/src/store/agentQuota/action.ts
index eaf3a3c018f..df26bea46e4 100644
--- a/src/store/agentQuota/action.ts
+++ b/src/store/agentQuota/action.ts
@@ -1,8 +1,14 @@
+import { isDesktop } from '@lobechat/const';
+import type { ClaudeCodeLocalAccount } from '@lobechat/electron-client-ipc';
import isEqual from 'fast-deep-equal';
+import { type SWRResponse } from 'swr';
import { type StateCreator } from 'zustand';
import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
+import { mutate, useClientDataSWR } from '@/libs/swr';
+import { electronKeys } from '@/libs/swr/keys';
import { agentQuotaService } from '@/services/agentQuota';
+import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';
import { type StoreSetter } from '@/store/types';
import { flattenActions } from '@/store/utils/flattenActions';
@@ -301,6 +307,60 @@ export class ActionImpl {
await this.#refresh(this.#accounts, QUOTA_ACCOUNTS_KEY);
};
+ // ---- local Claude Code logins (desktop) ----
+
+ /**
+ * The Claude logins this desktop holds. Listing also samples each login's
+ * quota into the pool: the quota panel only samples the login it shows, Auto
+ * mode can only balance on readings that exist, and a login whose usage call
+ * fails (e.g. a blocked network) must still show up as an account.
+ */
+ useFetchClaudeLocalAccounts = (enabled = true): SWRResponse<ClaudeCodeLocalAccount[]> =>
+ useClientDataSWR(
+ enabled ? electronKeys.claudeCodeAccounts() : null,
+ () => this.#syncClaudeLocalAccounts(),
+ {
+ onSuccess: (claudeLocalAccounts: ClaudeCodeLocalAccount[]) =>
+ this.#set({ claudeLocalAccounts }, false, 'claudeLocalAccounts'),
+ revalidateOnFocus: false,
+ },
+ );
+
+ /**
+ * Sample every local login into the pool now, without a view mounted. The
+ * quota panel calls this on its refresh: in Auto mode runs may land on any
+ * local profile, and balancing reads these readings, so they must not go
+ * stale while the account manager is closed.
+ */
+ refreshClaudeLocalAccounts = async (): Promise<void> => {
+ const claudeLocalAccounts = await this.#syncClaudeLocalAccounts();
+ this.#set({ claudeLocalAccounts }, false, 'claudeLocalAccounts');
+ };
+
+ /**
+ * Sign an account in to this desktop through the browser (`claude auth
+ * login` in a profile of its own), then add it to the pool.
+ */
+ loginClaudeAccount = async (email?: string): Promise<ClaudeCodeLocalAccount> => {
+ this.#set({ claudeLoginPending: true }, false, 'claudeLoginPending');
+ try {
+ const account = await heterogeneousAgentService.loginClaudeCodeAccount(
+ email ? { email } : undefined,
+ );
+ await this.#ingestLocalLogin(account, true).catch(() => false);
+ await mutate(electronKeys.claudeCodeAccounts());
+ await this.#refresh(this.#accounts, QUOTA_ACCOUNTS_KEY);
+ return account;
+ } finally {
+ this.#set({ claudeLoginPending: false }, false, 'claudeLoginPending');
+ }
+ };
+
+ /** Abort the browser sign-in in progress; `loginClaudeAccount` then rejects. */
+ cancelClaudeAccountLogin = async (): Promise<void> => {
+ await heterogeneousAgentService.cancelClaudeCodeAccountLogin();
+ };
+
/**
* Drop every quota view and confirmation when the data context changes
* (desktop `refreshUserData` / `disconnectRemoteServer`), even when the next
@@ -320,10 +380,55 @@ export class ActionImpl {
// Live panel samples are not replica fetches, so `clear()` cannot retire them.
this.#resetGeneration += 1;
this.#set({ ...initialState }, false, 'resetAgentQuotaStore');
+ // Local logins outlive the data context, but their accounts must land in
+ // the new context's pool: list (and ingest) them again.
+ if (isDesktop) void mutate(electronKeys.claudeCodeAccounts()).catch(() => {});
};
// ---- internals ----
+ #syncClaudeLocalAccounts = async (): Promise<ClaudeCodeLocalAccount[]> => {
+ const accounts = await heterogeneousAgentService.listClaudeCodeAccounts();
+ const ingested = await Promise.all(
+ accounts.map((account) => this.#ingestLocalLogin(account).catch(() => false)),
+ );
+ if (ingested.some(Boolean)) await this.#refresh(this.#accounts, QUOTA_ACCOUNTS_KEY);
+ return accounts;
+ };
+
+ /**
+ * Sample one local login and persist it. A login whose usage call fails still
+ * registers its account (no readings), so a fresh sign-in always shows up.
+ * Returns whether anything new reached the server.
+ */
+ #ingestLocalLogin = async (account: ClaudeCodeLocalAccount, force = false): Promise<boolean> => {
+ const live = await heterogeneousAgentService
+ .getClaudeCodeQuota({
+ ...(account.configDir && { env: { CLAUDE_CONFIG_DIR: account.configDir } }),
+ ...(force && { force: true }),
+ })
+ .catch(() => null);
+ const identity = live?.identity ?? account.identity;
+ const readings = live?.status === 'ok' ? (live.readings ?? []) : [];
+
+ const known = (await this.readQuotaAccounts().catch(() => [])).find(
+ (row) => row.externalAccountId === identity.externalAccountId,
+ );
+ if (known) {
+ if (readings.length === 0) return false;
+ // The main-process cache echoes a sample already persisted (same
+ // capturedAt); snapshots are append-only, so never ingest it twice.
+ const persisted = await this.readQuotaReadings(known.id).catch(() => []);
+ const newest = (rows: { capturedAt: number }[]) =>
+ rows.reduce((max, row) => Math.max(max, row.capturedAt), 0);
+ if (newest(readings) <= newest(persisted)) return false;
+ }
+
+ await agentQuotaService.ingestClaudeSnapshot({ identity, readings });
+ if (known) await this.readQuotaReadings(known.id, { fresh: true }).catch(() => []);
+ return true;
+ };
+
/**
* A sampler read (`readQuota*`) seeds the sync cache, but SWR still
* revalidates a seeded entry on mount: a panel opened right after the menu
diff --git a/src/store/agentQuota/initialState.ts b/src/store/agentQuota/initialState.ts
index 74ad20eb959..6e0e3dca85d 100644
--- a/src/store/agentQuota/initialState.ts
+++ b/src/store/agentQuota/initialState.ts
@@ -1,3 +1,5 @@
+import type { ClaudeCodeLocalAccount } from '@lobechat/electron-client-ipc';
+
import { createReplicaState, type ReplicaState } from '@/libs/replica';
import type {
@@ -9,6 +11,13 @@ import type {
} from './projection';
export interface State {
+ /**
+ * Claude Code logins held on THIS desktop (default login + per-account
+ * profiles). `undefined` until listed, and always on the web.
+ */
+ claudeLocalAccounts?: ClaudeCodeLocalAccount[];
+ /** A browser sign-in started from the account manager is in progress. */
+ claudeLoginPending: boolean;
/** Replica view of the quota account list (one entry, `QUOTA_ACCOUNTS_KEY`). */
quotaAccountsMap: Record<string, QuotaAccount[]>;
/** Replica bookkeeping of `quotaAccountsMap`. */
@@ -39,6 +48,8 @@ export interface State {
}
export const initialState: State = {
+ claudeLocalAccounts: undefined,
+ claudeLoginPending: false,
quotaAccountsMap: {},
quotaAccountsReplica: createReplicaState(),
quotaBindingsMap: {},
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
index e514fa98b58..bcf3154da3c 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -2005,7 +2005,7 @@ export const executeHeterogeneousAgent = async (
// before; a quota-service failure must never block the run.
const quotaAccountPlan = providerBindingActive
? { env: {}, externalAccountId: undefined }
- : await resolveQuotaAccountSpawnPlan(context.agentId, adapterType);
+ : await resolveQuotaAccountSpawnPlan(context.agentId, adapterType, heterogeneousProvider.env);
const sessionEnv = {
// Tell the CLI which LobeHub conversation and workspace it runs inside.
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.test.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.test.ts
index a7791581b7a..da7968b699f 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.test.ts
@@ -3,9 +3,21 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { resolveQuotaAccountSpawnPlan } from './resolveQuotaAccountEnv';
const selectAccountForAgent = vi.hoisted(() => vi.fn());
+const listAccounts = vi.hoisted(() => vi.fn());
+const listClaudeCodeAccounts = vi.hoisted(() => vi.fn());
+const resolveClaudeCodeAccount = vi.hoisted(() => vi.fn());
+const getClaudeCodeInheritedRoutingEnv = vi.hoisted(() => vi.fn());
vi.mock('@/services/agentQuota', () => ({
- agentQuotaService: { selectAccountForAgent },
+ agentQuotaService: { listAccounts, selectAccountForAgent },
+}));
+
+vi.mock('@/services/electron/heterogeneousAgent', () => ({
+ heterogeneousAgentService: {
+ getClaudeCodeInheritedRoutingEnv,
+ listClaudeCodeAccounts,
+ resolveClaudeCodeAccount,
+ },
}));
const selection = (over: Record<string, unknown> = {}) => ({
@@ -17,45 +29,191 @@ const selection = (over: Record<string, unknown> = {}) => ({
...over,
});
+const localAccount = (externalAccountId: string, configDir: string | null) => ({
+ configDir,
+ identity: { externalAccountId },
+});
+
beforeEach(() => {
selectAccountForAgent.mockReset();
+ listAccounts.mockReset().mockResolvedValue([]);
+ listClaudeCodeAccounts
+ .mockReset()
+ .mockResolvedValue([localAccount('ext-default', null), localAccount('ext-1', '/profiles/one')]);
+ resolveClaudeCodeAccount.mockReset();
+ getClaudeCodeInheritedRoutingEnv.mockReset().mockResolvedValue({});
});
describe('resolveQuotaAccountSpawnPlan', () => {
- it('routes a config-dir account via CLAUDE_CONFIG_DIR', async () => {
- selectAccountForAgent.mockResolvedValue(
- selection({ credentialRef: { configDir: '/profiles/work', origin: 'config-dir' } }),
- );
+ it('runs a switched-to account on its own local profile', async () => {
+ selectAccountForAgent.mockResolvedValue(selection());
+ resolveClaudeCodeAccount.mockResolvedValue({ configDir: '/profiles/one', kind: 'profile' });
const plan = await resolveQuotaAccountSpawnPlan('agt-1', 'claude-code');
- expect(plan.env).toEqual({ CLAUDE_CONFIG_DIR: '/profiles/work' });
- expect(plan.accountId).toBe('acc-1');
- expect(plan.externalAccountId).toBe('ext-1');
- expect(plan.reason).toBe('pinned');
+ expect(resolveClaudeCodeAccount).toHaveBeenCalledWith('ext-1');
+ expect(plan.env).toEqual({ CLAUDE_CONFIG_DIR: '/profiles/one' });
+ expect(plan).toMatchObject({
+ accountId: 'acc-1',
+ externalAccountId: 'ext-1',
+ reason: 'pinned',
+ });
});
- it('keeps the default login (no override) for a keychain account', async () => {
- selectAccountForAgent.mockResolvedValue(selection());
+ it('keeps the default login (no override) when the account is the default login', async () => {
+ selectAccountForAgent.mockResolvedValue(selection({ externalAccountId: 'ext-default' }));
+ resolveClaudeCodeAccount.mockResolvedValue({ kind: 'default' });
const plan = await resolveQuotaAccountSpawnPlan('agt-1', 'claude-code');
expect(plan.env).toEqual({});
- expect(plan.externalAccountId).toBe('ext-1');
+ expect(plan.externalAccountId).toBe('ext-default');
});
- it('attributes but never injects env for a managed account', async () => {
+ it('fails a pinned account that is not signed in here instead of running another one', async () => {
+ selectAccountForAgent.mockResolvedValue(selection({ externalAccountId: 'ext-elsewhere' }));
+ resolveClaudeCodeAccount.mockResolvedValue({ kind: 'missing' });
+ listAccounts.mockResolvedValue([{ email: '[email protected]', id: 'acc-1', label: null }]);
+
+ // Names the account so the run error says which login is missing.
+ await expect(resolveQuotaAccountSpawnPlan('agt-1', 'claude-code')).rejects.toThrow('[email protected]');
+ });
+
+ it('re-balances Auto mode onto the accounts signed in here', async () => {
+ selectAccountForAgent
+ .mockResolvedValueOnce(selection({ externalAccountId: 'ext-away', reason: 'balanced' }))
+ .mockResolvedValueOnce(selection({ accountId: 'acc-2', reason: 'balanced' }));
+ resolveClaudeCodeAccount.mockImplementation(async (id: string) =>
+ id === 'ext-1' ? { configDir: '/profiles/one', kind: 'profile' } : { kind: 'missing' },
+ );
+
+ const plan = await resolveQuotaAccountSpawnPlan('agt-1', 'claude-code');
+
+ expect(selectAccountForAgent).toHaveBeenLastCalledWith('agt-1', {
+ provider: 'claude-code',
+ runnableExternalAccountIds: ['ext-default', 'ext-1'],
+ });
+ expect(plan).toMatchObject({ accountId: 'acc-2', env: { CLAUDE_CONFIG_DIR: '/profiles/one' } });
+ // The re-pick is mapped from the listing, not from another scan of the logins.
+ expect(resolveClaudeCodeAccount).toHaveBeenCalledTimes(1);
+ expect(listClaudeCodeAccounts).toHaveBeenCalledTimes(1);
+ });
+
+ it('fails Auto mode when no account in the rotation is signed in here', async () => {
+ selectAccountForAgent
+ .mockResolvedValueOnce(selection({ externalAccountId: 'ext-away', reason: 'balanced' }))
+ .mockResolvedValueOnce(null);
+ resolveClaudeCodeAccount.mockResolvedValue({ kind: 'missing' });
+
+ // Never falls back to the default login, which is not in the rotation.
+ await expect(resolveQuotaAccountSpawnPlan('agt-1', 'claude-code')).rejects.toThrow(/rotation/);
+ });
+
+ it('fails Auto mode when the desktop cannot list its logins for a re-pick', async () => {
selectAccountForAgent.mockResolvedValue(
- selection({
- credentialMode: 'managed',
- credentialRef: { configDir: '/x', origin: 'config-dir' },
- }),
+ selection({ externalAccountId: 'ext-away', reason: 'balanced' }),
+ );
+ resolveClaudeCodeAccount.mockResolvedValue({ kind: 'missing' });
+ listClaudeCodeAccounts.mockRejectedValue(new Error('no ipc'));
+
+ // The selected login is absent, so the default login must not run in its place.
+ await expect(resolveQuotaAccountSpawnPlan('agt-1', 'claude-code')).rejects.toThrow(
+ /Couldn't look up/,
);
+ });
+
+ it.each([
+ ['its own profile', { CLAUDE_CONFIG_DIR: '/agent/own-profile' }],
+ ['an API key', { ANTHROPIC_API_KEY: 'sk-ant-xxx' }],
+ ['Bedrock', { CLAUDE_CODE_USE_BEDROCK: '1' }],
+ ['Vertex', { CLAUDE_CODE_USE_VERTEX: 'true' }],
+ ])('lets an agent env that picks %s win over a stale pin', async (_label, agentEnv) => {
+ selectAccountForAgent.mockResolvedValue(selection({ externalAccountId: 'ext-elsewhere' }));
+ resolveClaudeCodeAccount.mockResolvedValue({ kind: 'missing' });
+
+ expect(await resolveQuotaAccountSpawnPlan('agt-1', 'claude-code', agentEnv)).toEqual({
+ env: {},
+ });
+ expect(selectAccountForAgent).not.toHaveBeenCalled();
+ });
+
+ it('never lists local logins for an agent with no account bindings', async () => {
+ selectAccountForAgent.mockResolvedValue(null);
+
+ expect(await resolveQuotaAccountSpawnPlan('agt-1', 'claude-code')).toEqual({ env: {} });
+ expect(listClaudeCodeAccounts).not.toHaveBeenCalled();
+ expect(resolveClaudeCodeAccount).not.toHaveBeenCalled();
+ expect(getClaudeCodeInheritedRoutingEnv).not.toHaveBeenCalled();
+ });
+
+ it.each(['pinned', 'balanced'])(
+ 'fails a %s run whose local login lookup fails, never starting on the default login',
+ async (reason) => {
+ selectAccountForAgent.mockResolvedValue(selection({ reason }));
+ resolveClaudeCodeAccount.mockRejectedValue(new Error('EACCES'));
+
+ await expect(resolveQuotaAccountSpawnPlan('agt-1', 'claude-code')).rejects.toThrow(
+ /Couldn't look up/,
+ );
+ },
+ );
+
+ it.each([
+ ['Bedrock', { CLAUDE_CODE_USE_BEDROCK: '1' }],
+ ['Vertex', { CLAUDE_CODE_USE_VERTEX: 'true' }],
+ ])(
+ 'lets a %s flag inherited from the desktop win over a stale pin',
+ async (_label, inherited) => {
+ selectAccountForAgent.mockResolvedValue(selection({ externalAccountId: 'ext-elsewhere' }));
+ resolveClaudeCodeAccount.mockResolvedValue({ kind: 'missing' });
+ getClaudeCodeInheritedRoutingEnv.mockResolvedValue(inherited);
+
+ // No subscription login runs, so neither the pin nor its attribution applies.
+ expect(await resolveQuotaAccountSpawnPlan('agt-1', 'claude-code')).toEqual({ env: {} });
+ expect(resolveClaudeCodeAccount).not.toHaveBeenCalled();
+ },
+ );
+
+ it('keeps routing when the agent env switches an inherited flag off', async () => {
+ selectAccountForAgent.mockResolvedValue(selection());
+ resolveClaudeCodeAccount.mockResolvedValue({ configDir: '/profiles/one', kind: 'profile' });
+ getClaudeCodeInheritedRoutingEnv.mockResolvedValue({ CLAUDE_CODE_USE_BEDROCK: '1' });
+
+ const plan = await resolveQuotaAccountSpawnPlan('agt-1', 'claude-code', {
+ CLAUDE_CODE_USE_BEDROCK: '0',
+ });
+
+ expect(plan).toMatchObject({ accountId: 'acc-1', env: { CLAUDE_CONFIG_DIR: '/profiles/one' } });
+ });
+
+ it('keeps routing when the desktop cannot report its inherited flags', async () => {
+ selectAccountForAgent.mockResolvedValue(selection());
+ resolveClaudeCodeAccount.mockResolvedValue({ configDir: '/profiles/one', kind: 'profile' });
+ getClaudeCodeInheritedRoutingEnv.mockRejectedValue(new Error('no such ipc'));
+
+ const plan = await resolveQuotaAccountSpawnPlan('agt-1', 'claude-code');
+
+ expect(plan.env).toEqual({ CLAUDE_CONFIG_DIR: '/profiles/one' });
+ });
+
+ it('keeps routing when an external-provider flag is set to off', async () => {
+ selectAccountForAgent.mockResolvedValue(selection({ externalAccountId: 'ext-elsewhere' }));
+ resolveClaudeCodeAccount.mockResolvedValue({ kind: 'missing' });
+
+ // `0` / `false` leave the subscription login in charge, so the stale pin still counts.
+ await expect(
+ resolveQuotaAccountSpawnPlan('agt-1', 'claude-code', { CLAUDE_CODE_USE_BEDROCK: '0' }),
+ ).rejects.toThrow(/isn't signed in on this device/);
+ });
+
+ it('attributes but never injects env for a managed account', async () => {
+ selectAccountForAgent.mockResolvedValue(selection({ credentialMode: 'managed' }));
const plan = await resolveQuotaAccountSpawnPlan('agt-1', 'claude-code');
expect(plan.env).toEqual({});
expect(plan.accountId).toBe('acc-1');
+ expect(resolveClaudeCodeAccount).not.toHaveBeenCalled();
});
it.each([
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.ts
index 0550c7da485..869398cefca 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.ts
@@ -1,4 +1,8 @@
+import { claudeCodeRoutesExternally } from '@lobechat/heterogeneous-agents/quota';
+import { t } from 'i18next';
+
import { agentQuotaService } from '@/services/agentQuota';
+import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';
export interface QuotaAccountSpawnPlan {
/** Account chosen for this run, when routing applied. */
@@ -12,30 +16,129 @@ export interface QuotaAccountSpawnPlan {
const NO_ROUTING: QuotaAccountSpawnPlan = { env: {} };
+type AccountSelection = NonNullable<
+ Awaited<ReturnType<typeof agentQuotaService.selectAccountForAgent>>
+>;
+
+/**
+ * Where this desktop holds the chosen account's login. `null` = nothing to
+ * map (a managed account, or no external id): the spawn keeps the default
+ * login, as before routing existed. A failed lookup is NOT that — the run
+ * fails instead of starting on a login nobody selected.
+ */
+const resolveLocalLogin = async (selection: AccountSelection) => {
+ if (selection.credentialMode !== 'referenced' || !selection.externalAccountId) return null;
+ try {
+ return await heterogeneousAgentService.resolveClaudeCodeAccount(selection.externalAccountId);
+ } catch (error) {
+ console.error('[HeterogeneousAgent] Claude Code account resolution failed:', error);
+ throw new Error(t('heteroAgent.claudeQuota.accountResolveFailed', { ns: 'chat' }), {
+ cause: error,
+ });
+ }
+};
+
+/**
+ * Agent env keys that already choose which login (or credential) the CLI
+ * uses. The executor spreads the agent's env last, so with any of these set
+ * account routing could only be overridden — or, worse, block the run over a
+ * pin the agent does not even use.
+ */
+const AGENT_LOGIN_ENV_KEYS = [
+ 'CLAUDE_CONFIG_DIR',
+ 'ANTHROPIC_API_KEY',
+ 'ANTHROPIC_AUTH_TOKEN',
+ 'ANTHROPIC_BASE_URL',
+] as const;
+
+/** The agent's own env decides the login, so subscription routing must stay out. */
+const agentEnvPicksLogin = (env?: Record<string, string>) =>
+ AGENT_LOGIN_ENV_KEYS.some((key) => env?.[key]?.trim()) || claudeCodeRoutesExternally(env);
+
+/**
+ * Bedrock / Mantle / Vertex flags the desktop process exports reach the CLI
+ * too, unless the agent env overrides them — a run on an external provider
+ * involves no subscription login at all. An older desktop without the IPC
+ * reports none, so routing still applies there.
+ */
+const inheritedEnvRoutesExternally = async (agentEnv?: Record<string, string>) => {
+ const inherited = await heterogeneousAgentService
+ .getClaudeCodeInheritedRoutingEnv()
+ .catch(() => ({}));
+ return claudeCodeRoutesExternally(agentEnv, inherited);
+};
+
/**
* Resolve which provider account this agent should run on and turn the choice
- * into spawn env. The mapping mirrors how the CLI itself scopes logins:
+ * into spawn env. Account rows are shared across devices, but a login is not:
+ * the desktop maps the chosen account to the login it holds on THIS machine —
*
- * - `config-dir` account → `CLAUDE_CONFIG_DIR=<dir>` (an isolated CLI profile);
- * - `keychain` / `default-file` account → no override, the default login is it;
- * - `managed` accounts (cloud-held token) are not runnable locally yet;
- * - no bindings / quota service unreachable → `{}`, spawn behaves as before.
+ * - the default login → no override;
+ * - the account's own profile → `CLAUDE_CONFIG_DIR=<profile>`;
+ * - no local login → the run fails with a clear reason, never falls back to an
+ * unselected login: a pinned account names the missing login, and Auto mode
+ * re-selects among the accounts this device can run, failing when the
+ * rotation holds none of them.
*
- * The result is spread BEFORE `heterogeneousProvider.env`: an env the user put
- * on the agent explicitly is a stronger, more specific choice than pool
- * routing, and must keep winning.
+ * No bindings, or the quota service unreachable, → `{}` and the spawn behaves
+ * as before; a desktop that fails to look up its logins fails the run. An env
+ * that picks its own login or an external provider — the agent's
+ * (`agentEnvPicksLogin`) or one inherited from the desktop — wins over
+ * routing; the result is also spread BEFORE `heterogeneousProvider.env` for
+ * the same reason.
*/
export const resolveQuotaAccountSpawnPlan = async (
agentId: string | undefined,
adapterType: string,
+ agentEnv?: Record<string, string>,
): Promise<QuotaAccountSpawnPlan> => {
// Codex accounts exist in the DB but have no runnable credential mapping yet.
if (adapterType !== 'claude-code' || !agentId) return NO_ROUTING;
+ if (agentEnvPicksLogin(agentEnv)) return NO_ROUTING;
+
+ const select = (runnableExternalAccountIds?: string[]) =>
+ agentQuotaService
+ .selectAccountForAgent(agentId, {
+ provider: adapterType,
+ ...(runnableExternalAccountIds && { runnableExternalAccountIds }),
+ })
+ .catch(() => null);
- const selection = await agentQuotaService
- .selectAccountForAgent(agentId, { provider: adapterType })
- .catch(() => null);
+ // Unbound agents (the common case) stop here without touching local logins.
+ let selection = await select();
if (!selection) return NO_ROUTING;
+ if (await inheritedEnvRoutesExternally(agentEnv)) return NO_ROUTING;
+
+ let resolution = await resolveLocalLogin(selection);
+
+ // Auto picked an account this desktop has no login for: pick again among
+ // the ones it has. (Listing first on every run would cost unbound agents
+ // a Keychain read per profile for nothing.)
+ if (resolution?.kind === 'missing' && selection.reason === 'balanced') {
+ // The selected login is known to be absent here, so a failed listing must
+ // stop the run — falling back would start it on a login nobody selected.
+ const local = await heterogeneousAgentService.listClaudeCodeAccounts().catch((error) => {
+ console.error('[HeterogeneousAgent] Claude Code account listing failed:', error);
+ throw new Error(t('heteroAgent.claudeQuota.accountResolveFailed', { ns: 'chat' }), {
+ cause: error,
+ });
+ });
+
+ const runnable = local.flatMap((account) => account.identity.externalAccountId ?? []);
+ const rebalanced = await select(runnable);
+ // The listing just read every login, so map the new pick from it rather
+ // than scanning the logins again.
+ const login = rebalanced
+ ? local.find((account) => account.identity.externalAccountId === rebalanced.externalAccountId)
+ : undefined;
+ if (!rebalanced || !login)
+ throw new Error(t('heteroAgent.claudeQuota.noRunnableAccount', { ns: 'chat' }));
+
+ selection = rebalanced;
+ resolution = login.configDir
+ ? { configDir: login.configDir, kind: 'profile' }
+ : { kind: 'default' };
+ }
const attribution = {
accountId: selection.accountId,
@@ -43,13 +146,22 @@ export const resolveQuotaAccountSpawnPlan = async (
reason: selection.reason,
};
- if (selection.credentialMode !== 'referenced') return { ...attribution, env: {} };
+ if (resolution?.kind === 'profile')
+ return { ...attribution, env: { CLAUDE_CONFIG_DIR: resolution.configDir } };
- const ref = selection.credentialRef;
- if (ref?.origin === 'config-dir' && ref.configDir) {
- return { ...attribution, env: { CLAUDE_CONFIG_DIR: ref.configDir } };
+ if (resolution?.kind === 'missing' && selection.reason === 'pinned') {
+ const pinnedId = selection.accountId;
+ const account = await agentQuotaService
+ .listAccounts()
+ .then((accounts) => accounts.find((a) => a.id === pinnedId))
+ .catch(() => undefined);
+ throw new Error(
+ t('heteroAgent.claudeQuota.accountNotSignedIn', {
+ account: account?.label || account?.email || selection.externalAccountId,
+ ns: 'chat',
+ }),
+ );
}
- // Default login (keychain / ~/.claude): nothing to override.
return { ...attribution, env: {} };
};