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.

♻️ refactor(hetero): unify local and remote Codex account quota (#19678)

Arvin Xu8f5a65efdb35
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/codexQuota.ts b/apps/desktop/src/main/modules/heterogeneousAgent/codexQuota.ts
index d01580683d7..35e369a0005 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/codexQuota.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/codexQuota.ts
@@ -1,643 +1,8 @@
-import type { ChildProcess } from 'node:child_process';
-import { spawn } from 'node:child_process';
-import { readFile } from 'node:fs/promises';
-import { homedir } from 'node:os';
-import path from 'node:path';
-
-import type {
- CodexQuotaSnapshot,
- CodexQuotaWindow,
- CodexRateLimitResetCredit,
- CodexRateLimitResetCredits,
- CodexRateLimitResetOutcome,
- CodexRateLimitSnapshot,
-} from '@lobechat/electron-client-ipc';
-import { buildCodexAppServerArgs, resolveCliSpawnPlan } from '@lobechat/heterogeneous-agents/spawn';
-
-const RPC_TIMEOUT_MS = 10_000;
-const CODEX_PRIMARY_WINDOW_MINUTES = 5 * 60;
-const CODEX_SECONDARY_WINDOW_MINUTES = 7 * 24 * 60;
-const RESET_CONSUME_TIMEOUT_MS = 30_000;
-const RESET_CREDITS_TIMEOUT_MS = 5_000;
-const CODEX_RATE_LIMIT_RESET_CREDITS_URL =
- 'https://chatgpt.com/backend-api/wham/rate-limit-reset-credits';
-const CODEX_RATE_LIMIT_RESET_CONSUME_URL = `${CODEX_RATE_LIMIT_RESET_CREDITS_URL}/consume`;
-
-export interface FetchCodexQuotaOptions {
- codexHomePath?: string | null;
- command?: string;
- env?: NodeJS.ProcessEnv;
-}
-
-export interface ConsumeCodexRateLimitResetCreditOptions extends FetchCodexQuotaOptions {
- creditId?: string;
- idempotencyKey: string;
-}
-
-interface RpcResponse {
- error?: { message?: string };
- id?: number;
- result?: unknown;
-}
-
-interface RpcRateWindow {
- resetsAt?: number;
- usedPercent?: number;
- windowDurationMins?: number;
-}
-
-interface RpcRateLimitSnapshot {
- limitId?: string | null;
- limitName?: string | null;
- primary?: RpcRateWindow;
- secondary?: RpcRateWindow;
-}
-
-interface RpcRateLimitResetCredit {
- expiresAt?: number | string | null;
- grantedAt?: number | string | null;
- id?: string;
- redeemedAt?: number | string | null;
- redeemStartedAt?: number | string | null;
- resetType?: string;
- status?: string;
- title?: string | null;
-}
-
-interface RpcRateLimitsResponse {
- rateLimitResetCredits?: {
- availableCount?: number;
- credits?: RpcRateLimitResetCredit[] | null;
- nextExpiresAt?: number | string | null;
- totalEarnedCount?: number;
- } | null;
- rateLimits?: RpcRateLimitSnapshot;
- rateLimitsByLimitId?: Record<string, RpcRateLimitSnapshot> | null;
-}
-
-interface CodexAuthFile {
- tokens?: {
- access_token?: string;
- account_id?: string;
- };
-}
-
-interface BackendRateLimitResetCreditsResponse {
- available_count?: number;
- credits?: {
- expires_at?: number | string | null;
- granted_at?: number | string | null;
- id?: string;
- redeem_started_at?: number | string | null;
- redeemed_at?: number | string | null;
- reset_type?: string;
- status?: string;
- title?: string | null;
- }[];
- total_earned_count?: number;
-}
-
-interface BackendConsumeRateLimitResetCreditResponse {
- code?: string;
-}
-
-interface RpcConsumeRateLimitResetCreditResponse {
- outcome?: string;
-}
-
-interface CodexBackendAuth {
- headers: Record<string, string>;
-}
-
-const getCodexHomePath = ({ codexHomePath, env }: FetchCodexQuotaOptions) =>
- codexHomePath ?? env?.CODEX_HOME ?? process.env.CODEX_HOME ?? path.join(homedir(), '.codex');
-
-const errorSnapshot = (message: string): CodexQuotaSnapshot => ({
- error: message,
- provider: 'codex',
- session: null,
- status: 'error',
- updatedAt: Date.now(),
- weekly: null,
-});
-
-const buildRpcMessage = (id: number, method: string, params: unknown = {}) =>
- `${JSON.stringify({ id, jsonrpc: '2.0', method, params })}\n`;
-
-const parseCreditTimestamp = (value: number | string | null | undefined): number | null => {
- if (typeof value === 'number' && Number.isFinite(value)) {
- return value < 10_000_000_000 ? value * 1000 : value;
- }
-
- if (typeof value !== 'string' || !value.trim()) return null;
-
- const numeric = Number(value);
- if (Number.isFinite(numeric)) {
- return numeric < 10_000_000_000 ? numeric * 1000 : numeric;
- }
-
- const parsed = Date.parse(value);
- return Number.isFinite(parsed) ? parsed : null;
-};
-
-const normalizeCreditStatus = (status?: string) => status?.toLowerCase() ?? 'unknown';
-
-const normalizeCreditText = (value: string | null | undefined) => {
- if (typeof value !== 'string') return null;
- const trimmed = value.trim();
- return trimmed || null;
-};
-
-const mapRpcResetCredit = (credit: RpcRateLimitResetCredit): CodexRateLimitResetCredit => ({
- expiresAt: parseCreditTimestamp(credit.expiresAt),
- grantedAt: parseCreditTimestamp(credit.grantedAt),
- id: normalizeCreditText(credit.id),
- redeemStartedAt: parseCreditTimestamp(credit.redeemStartedAt),
- redeemedAt: parseCreditTimestamp(credit.redeemedAt),
- resetType: normalizeCreditText(credit.resetType),
- status: normalizeCreditStatus(credit.status),
- title: normalizeCreditText(credit.title),
-});
-
-const mapBackendResetCredit = (
- credit: NonNullable<BackendRateLimitResetCreditsResponse['credits']>[number],
-): CodexRateLimitResetCredit => ({
- expiresAt: parseCreditTimestamp(credit.expires_at),
- grantedAt: parseCreditTimestamp(credit.granted_at),
- id: normalizeCreditText(credit.id),
- redeemStartedAt: parseCreditTimestamp(credit.redeem_started_at),
- redeemedAt: parseCreditTimestamp(credit.redeemed_at),
- resetType: normalizeCreditText(credit.reset_type),
- status: normalizeCreditStatus(credit.status),
- title: normalizeCreditText(credit.title),
-});
-
-const getNextAvailableCreditExpiry = (
- credits: CodexRateLimitResetCredits['credits'] | undefined,
- now = Date.now(),
-) =>
- credits
- ?.filter(
- (credit) =>
- credit.status === 'available' &&
- typeof credit.expiresAt === 'number' &&
- credit.expiresAt > now,
- )
- .map((credit) => credit.expiresAt as number)
- .sort((a, b) => a - b)[0] ?? null;
-
-const mapRpcResetCredits = (
- raw: RpcRateLimitsResponse['rateLimitResetCredits'],
-): CodexRateLimitResetCredits | null | undefined => {
- if (raw === null) return null;
- if (raw === undefined) return undefined;
- if (typeof raw.availableCount !== 'number' || !Number.isFinite(raw.availableCount)) return null;
-
- const credits = Array.isArray(raw.credits) ? raw.credits.map(mapRpcResetCredit) : undefined;
-
- return {
- availableCount: Math.max(0, Math.floor(raw.availableCount)),
- ...(credits ? { credits } : {}),
- nextExpiresAt: parseCreditTimestamp(raw.nextExpiresAt) ?? getNextAvailableCreditExpiry(credits),
- ...(typeof raw.totalEarnedCount === 'number' && Number.isFinite(raw.totalEarnedCount)
- ? { totalEarnedCount: Math.max(0, Math.floor(raw.totalEarnedCount)) }
- : {}),
- };
-};
-
-const mapBackendResetCredits = (
- raw: BackendRateLimitResetCreditsResponse | null | undefined,
-): CodexRateLimitResetCredits | null => {
- if (!raw) return null;
-
- const credits = raw.credits?.map(mapBackendResetCredit);
- const availableCount =
- typeof raw.available_count === 'number' && Number.isFinite(raw.available_count)
- ? raw.available_count
- : (credits?.filter((credit) => credit.status === 'available').length ?? null);
-
- if (availableCount === null) return null;
-
- return {
- availableCount: Math.max(0, Math.floor(availableCount)),
- ...(credits ? { credits } : {}),
- nextExpiresAt: getNextAvailableCreditExpiry(credits),
- ...(typeof raw.total_earned_count === 'number' && Number.isFinite(raw.total_earned_count)
- ? { totalEarnedCount: Math.max(0, Math.floor(raw.total_earned_count)) }
- : {}),
- };
-};
-
-const readCodexBackendAuth = async (
- options: FetchCodexQuotaOptions,
-): Promise<CodexBackendAuth | null> => {
- let auth: CodexAuthFile;
-
- try {
- const authPath = path.join(getCodexHomePath(options), 'auth.json');
- auth = JSON.parse(await readFile(authPath, 'utf8')) as CodexAuthFile;
- } catch {
- return null;
- }
-
- const accessToken = auth.tokens?.access_token;
- if (!accessToken) return null;
-
- const headers: Record<string, string> = {
- 'Authorization': `Bearer ${accessToken}`,
- 'OpenAI-Beta': 'codex-1',
- 'User-Agent': 'codex-cli',
- 'originator': 'LobeHub Desktop',
- };
-
- if (auth.tokens?.account_id) {
- headers['ChatGPT-Account-Id'] = auth.tokens.account_id;
- }
-
- return { headers };
-};
-
-const fetchBackendResetCredits = async (
- auth: CodexBackendAuth,
-): Promise<CodexRateLimitResetCredits | null> => {
- const controller = new AbortController();
- let timeout: ReturnType<typeof setTimeout> | undefined;
- const timeoutPromise = new Promise<null>((resolve) => {
- timeout = setTimeout(() => {
- controller.abort();
- resolve(null);
- }, RESET_CREDITS_TIMEOUT_MS);
- });
-
- const fetchPromise = (async () => {
- const response = await fetch(CODEX_RATE_LIMIT_RESET_CREDITS_URL, {
- ...auth,
- signal: controller.signal,
- });
- if (!response.ok) return null;
-
- const payload = (await response.json()) as BackendRateLimitResetCreditsResponse;
- return mapBackendResetCredits(payload);
- })();
-
- try {
- return await Promise.race([fetchPromise, timeoutPromise]);
- } finally {
- if (timeout) clearTimeout(timeout);
- }
-};
-
-const mapConsumeOutcome = (outcome: string | undefined): CodexRateLimitResetOutcome => {
- switch (outcome) {
- case 'already_redeemed':
- case 'alreadyRedeemed': {
- return 'alreadyRedeemed';
- }
- case 'no_credit':
- case 'noCredit': {
- return 'noCredit';
- }
- case 'nothing_to_reset':
- case 'nothingToReset': {
- return 'nothingToReset';
- }
- case 'reset': {
- return 'reset';
- }
- default: {
- throw new Error(`Unknown Codex rate-limit reset outcome: ${outcome ?? 'missing'}`);
- }
- }
-};
-
-const consumeBackendResetCredit = async (
- auth: CodexBackendAuth,
- options: ConsumeCodexRateLimitResetCreditOptions,
-): Promise<CodexRateLimitResetOutcome> => {
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), RESET_CONSUME_TIMEOUT_MS);
-
- try {
- const response = await fetch(CODEX_RATE_LIMIT_RESET_CONSUME_URL, {
- body: JSON.stringify({
- ...(options.creditId ? { credit_id: options.creditId } : {}),
- redeem_request_id: options.idempotencyKey,
- }),
- headers: {
- ...auth.headers,
- 'Content-Type': 'application/json',
- },
- method: 'POST',
- signal: controller.signal,
- });
- if (!response.ok) {
- throw new Error(`Codex rate-limit reset failed: HTTP ${response.status}`);
- }
-
- const payload = (await response.json()) as BackendConsumeRateLimitResetCreditResponse;
- return mapConsumeOutcome(payload.code);
- } finally {
- clearTimeout(timeout);
- }
-};
-
-const mapRpcWindow = (
- raw: RpcRateWindow | undefined,
- fallbackWindowMinutes: number,
-): CodexQuotaWindow | null => {
- if (!raw || typeof raw.usedPercent !== 'number' || !Number.isFinite(raw.usedPercent)) {
- return null;
- }
-
- const windowMinutes =
- typeof raw.windowDurationMins === 'number' &&
- Number.isFinite(raw.windowDurationMins) &&
- raw.windowDurationMins > 0
- ? Math.floor(raw.windowDurationMins)
- : fallbackWindowMinutes;
-
- return {
- resetsAt: parseCreditTimestamp(raw.resetsAt),
- usedPercent: Math.min(100, Math.max(0, raw.usedPercent)),
- windowMinutes,
- };
-};
-
-const mapRpcRateLimitSnapshot = (
- raw: RpcRateLimitSnapshot | undefined,
- fallbackLimitId: string,
-): CodexRateLimitSnapshot | null => {
- if (!raw) return null;
-
- const primary = mapRpcWindow(raw.primary, CODEX_PRIMARY_WINDOW_MINUTES);
- const secondary = mapRpcWindow(raw.secondary, CODEX_SECONDARY_WINDOW_MINUTES);
- if (!primary && !secondary) return null;
-
- return {
- limitId: normalizeCreditText(raw.limitId) ?? fallbackLimitId,
- limitName: normalizeCreditText(raw.limitName),
- primary,
- secondary,
- };
-};
-
-const mapRpcRateLimits = (wrapper: RpcRateLimitsResponse): CodexRateLimitSnapshot[] => {
- const snapshots = new Map<string, CodexRateLimitSnapshot>();
-
- const addSnapshot = (raw: RpcRateLimitSnapshot | undefined, fallbackLimitId: string) => {
- const snapshot = mapRpcRateLimitSnapshot(raw, fallbackLimitId);
- if (!snapshot) return;
-
- const normalizedId = snapshot.limitId.toLowerCase();
- if (!snapshots.has(normalizedId)) snapshots.set(normalizedId, snapshot);
- };
-
- addSnapshot(wrapper.rateLimits, 'codex');
-
- const additionalLimits = Object.entries(wrapper.rateLimitsByLimitId ?? {}).sort(
- ([left], [right]) => left.localeCompare(right),
- );
- for (const [limitId, snapshot] of additionalLimits) addSnapshot(snapshot, limitId);
-
- return [...snapshots.values()];
-};
-
-const cleanupRpcListeners = (
- child: ChildProcess,
- listeners: {
- close: () => void;
- error: (error: Error) => void;
- stderrData: (chunk: Buffer) => void;
- stdoutData: (chunk: Buffer) => void;
- },
-) => {
- child.stdout?.off('data', listeners.stdoutData);
- child.stderr?.off('data', listeners.stderrData);
- child.off('error', listeners.error);
- child.off('close', listeners.close);
-};
-
-interface RpcRequestConfig {
- failureMessage: string;
- method: string;
- params?: unknown;
- timeoutMs?: number;
-}
-
-const requestViaRpc = async <T>(
- options: FetchCodexQuotaOptions,
- { failureMessage, method, params, timeoutMs = RPC_TIMEOUT_MS }: RpcRequestConfig,
-): Promise<T> =>
- new Promise<T>((resolve, reject) => {
- let buffer = '';
- let child: ChildProcess | null = null;
- let initId: number | null = null;
- let stderr = '';
- let finished = false;
- let requestId: number | null = null;
- let rpcId = 0;
- let timeout: ReturnType<typeof setTimeout> | undefined;
-
- // Headless app-server only. TUI flags such as `-a untrusted` are parsed
- // before the subcommand, and current Codex CLI rejects `untrusted`
- // (`--ask-for-approval` accepts only `on-request` and `never`).
- const rpcArgs = buildCodexAppServerArgs();
-
- const cleanup = (kill: boolean) => {
- if (finished) return false;
- finished = true;
- if (timeout) {
- clearTimeout(timeout);
- timeout = undefined;
- }
- if (child) {
- cleanupRpcListeners(child, listeners);
- if (kill) child.kill();
- }
- return true;
- };
-
- const settleError = (error: Error, kill = false) => {
- if (!cleanup(kill)) return;
- reject(error);
- };
-
- const settleResult = (result: T) => {
- if (!cleanup(true)) return;
- resolve(result);
- };
-
- const sendRpc = (child: ChildProcess, method: string, params?: unknown) => {
- const id = ++rpcId;
- child.stdin?.write(buildRpcMessage(id, method, params));
- return id;
- };
-
- const sendNotification = (child: ChildProcess, method: string) => {
- child.stdin?.write(`${JSON.stringify({ jsonrpc: '2.0', method, params: {} })}\n`);
- };
-
- const onStdoutData = (chunk: Buffer) => {
- buffer += chunk.toString();
-
- let newlineIndex: number;
- while ((newlineIndex = buffer.indexOf('\n')) !== -1) {
- const line = buffer.slice(0, newlineIndex).trim();
- buffer = buffer.slice(newlineIndex + 1);
- if (!line) continue;
-
- try {
- const message = JSON.parse(line) as RpcResponse;
- if (message.id === initId) {
- if (message.error) {
- settleError(
- new Error(message.error.message ?? `${failureMessage}: initialize`),
- true,
- );
- return;
- }
- if (!child) return;
- sendNotification(child, 'initialized');
- requestId = sendRpc(child, method, params);
- continue;
- }
-
- if (requestId !== null && message.id === requestId) {
- if (message.error) {
- settleError(new Error(message.error.message ?? failureMessage), true);
- return;
- }
- settleResult(message.result as T);
- }
- } catch {
- // Ignore non-JSON output from the RPC process.
- }
- }
- };
-
- const onStderrData = (chunk: Buffer) => {
- stderr += chunk.toString();
- };
-
- const listeners = {
- close: () => settleError(new Error(stderr.trim() || `${failureMessage}: RPC exited`), false),
- error: (error: Error) => settleError(error, false),
- stderrData: onStderrData,
- stdoutData: onStdoutData,
- };
-
- timeout = setTimeout(() => {
- settleError(new Error(`${failureMessage}: RPC timed out`), true);
- }, timeoutMs);
-
- void resolveCliSpawnPlan(options.command ?? 'codex', rpcArgs)
- .then((spawnPlan) => {
- if (finished) return;
-
- child = spawn(spawnPlan.command, spawnPlan.args, {
- env: {
- ...process.env,
- ...options.env,
- ...(options.codexHomePath ? { CODEX_HOME: options.codexHomePath } : {}),
- },
- stdio: ['pipe', 'pipe', 'pipe'],
- windowsHide: true,
- });
- child.stdout?.on('data', listeners.stdoutData);
- child.stderr?.on('data', listeners.stderrData);
- child.on('error', listeners.error);
- child.on('close', listeners.close);
- initId = sendRpc(child, 'initialize', {
- clientInfo: { name: 'lobehub', version: '1.0.0' },
- });
- })
- .catch((error: unknown) => {
- const message = error instanceof Error ? error.message : 'Failed to resolve Codex command';
- settleError(new Error(message), true);
- });
- });
-
-const fetchViaRpc = async (
- options: FetchCodexQuotaOptions,
- auth: CodexBackendAuth | null,
-): Promise<CodexQuotaSnapshot> => {
- try {
- const wrapper = await requestViaRpc<RpcRateLimitsResponse>(options, {
- failureMessage: 'Codex rate-limit request failed',
- method: 'account/rateLimits/read',
- });
- const rateLimits = mapRpcRateLimits(wrapper);
- const defaultRateLimit =
- rateLimits.find(({ limitId }) => limitId.toLowerCase() === 'codex') ?? rateLimits[0];
- const rateLimitResetCredits = mapRpcResetCredits(wrapper?.rateLimitResetCredits);
- let backendCredits: CodexRateLimitResetCredits | null = null;
-
- // Older Codex app-server versions expose only availableCount. Use the same
- // backend contract as Codex/CodexBar to fill the detail rows when needed.
- if (auth && rateLimitResetCredits?.credits === undefined) {
- try {
- backendCredits = await fetchBackendResetCredits(auth);
- } catch {
- backendCredits = null;
- }
- }
-
- return {
- error: null,
- provider: 'codex',
- rateLimitResetCredits:
- backendCredits ?? (rateLimitResetCredits === undefined ? undefined : rateLimitResetCredits),
- rateLimits,
- session: defaultRateLimit?.primary ?? null,
- status: 'ok',
- updatedAt: Date.now(),
- weekly: defaultRateLimit?.secondary ?? null,
- };
- } catch (error) {
- return errorSnapshot(
- error instanceof Error ? error.message : 'Codex rate-limit request failed',
- );
- }
-};
-
-export const fetchCodexQuota = async (
- options: FetchCodexQuotaOptions = {},
-): Promise<CodexQuotaSnapshot> => {
- const auth = await readCodexBackendAuth(options);
- return fetchViaRpc(options, auth);
-};
-
-export const consumeCodexRateLimitResetCredit = async (
- options: ConsumeCodexRateLimitResetCreditOptions,
-): Promise<CodexRateLimitResetOutcome> => {
- const idempotencyKey = options.idempotencyKey.trim();
- const creditId = options.creditId?.trim();
- if (!idempotencyKey) throw new Error('Codex reset idempotency key is required');
- if (options.creditId !== undefined && !creditId) {
- throw new Error('Codex reset credit ID must not be empty');
- }
-
- const normalizedOptions = { ...options, creditId, idempotencyKey };
- const auth = await readCodexBackendAuth(normalizedOptions);
-
- try {
- const response = await requestViaRpc<RpcConsumeRateLimitResetCreditResponse>(
- normalizedOptions,
- {
- failureMessage: 'Codex rate-limit reset failed',
- method: 'account/rateLimitResetCredit/consume',
- params: {
- ...(creditId ? { creditId } : {}),
- idempotencyKey,
- },
- timeoutMs: RESET_CONSUME_TIMEOUT_MS,
- },
- );
- return mapConsumeOutcome(response?.outcome);
- } catch (rpcError) {
- // The reset endpoint predates the app-server consume method. Reuse the same
- // idempotency key so falling back is safe even if the RPC response was lost.
- if (!auth) throw rpcError;
- return consumeBackendResetCredit(auth, normalizedOptions);
- }
-};
+export type {
+ ConsumeCodexRateLimitResetCreditOptions,
+ FetchCodexQuotaOptions,
+} from '@lobechat/heterogeneous-agents/quota-sampler';
+export {
+ consumeCodexRateLimitResetCredit,
+ fetchCodexQuota,
+} from '@lobechat/heterogeneous-agents/quota-sampler';
diff --git a/apps/server/src/routers/lambda/__tests__/agentQuota.ingestSnapshot.test.ts b/apps/server/src/routers/lambda/__tests__/agentQuota.ingestSnapshot.test.ts
index ff065124bdb..70a4eb2c86f 100644
--- a/apps/server/src/routers/lambda/__tests__/agentQuota.ingestSnapshot.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agentQuota.ingestSnapshot.test.ts
@@ -15,6 +15,14 @@ vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({
}),
}));
+const mockCodexQuota = vi.fn();
+const mockFindAccount = vi.fn();
+const mockLatestReadings = vi.fn();
+const mockVisibleDevice = vi.fn();
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: { codexQuota: mockCodexQuota },
+}));
+vi.mock('../deviceWorkspaceGuard', () => ({ assertWorkspaceDeviceVisible: mockVisibleDevice }));
const mockFindByDeviceId = vi.fn();
const mockFindWorkspaceDeviceById = vi.fn();
const mockIngestSnapshot = vi.fn(async () => ({ ok: true }));
@@ -33,7 +41,7 @@ vi.mock('@/database/models/agentQuota', () => ({
return {};
}),
AgentProviderAccountModel: vi.fn(function () {
- return {};
+ return { findByExternalId: mockFindAccount };
}),
AgentQuotaWindowModel: vi.fn(function () {
return {};
@@ -42,7 +50,7 @@ vi.mock('@/database/models/agentQuota', () => ({
vi.mock('@/server/services/agentQuota', () => ({
AgentQuotaService: vi.fn(function () {
- return { ingestSnapshot: mockIngestSnapshot };
+ return { ingestSnapshot: mockIngestSnapshot, listLatestReadings: mockLatestReadings };
}),
}));
@@ -141,3 +149,56 @@ describe('agentQuota.ingestSnapshot device resolution', () => {
expect(mockFindWorkspaceDeviceById).not.toHaveBeenCalled();
});
});
+
+describe('agentQuota.refreshCodexQuota', () => {
+ const snapshot = {
+ error: null,
+ identity: { externalAccountId: 'codex-account' },
+ provider: 'codex',
+ readings: READINGS,
+ status: 'ok',
+ updatedAt: 1_700_000_000_000,
+ };
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockVisibleDevice.mockResolvedValue(undefined);
+ mockFindAccount.mockResolvedValue(undefined);
+ mockLatestReadings.mockResolvedValue([]);
+ mockFindByDeviceId.mockResolvedValue({ id: 'device-row' });
+ mockFindWorkspaceDeviceById.mockResolvedValue(undefined);
+ mockCodexQuota.mockResolvedValue(snapshot);
+ });
+
+ it('refreshes and persists the remote account rather than returning an isolated device sample', async () => {
+ const result = await createCaller().refreshCodexQuota({ deviceId: 'remote' });
+ expect(result).toEqual(snapshot);
+ expect(mockIngestSnapshot).toHaveBeenCalledWith({
+ deviceId: 'device-row',
+ identity: snapshot.identity,
+ provider: 'codex',
+ readings: READINGS,
+ });
+ });
+
+ it('does not append the same cached readings twice', async () => {
+ mockFindAccount.mockResolvedValue({ id: 'account' });
+ mockLatestReadings.mockResolvedValue(READINGS);
+ await createCaller().refreshCodexQuota({ deviceId: 'remote' });
+ expect(mockIngestSnapshot).not.toHaveBeenCalled();
+ });
+
+ it('does not persist an unidentified sample', async () => {
+ mockCodexQuota.mockResolvedValue({ ...snapshot, identity: null });
+ await createCaller().refreshCodexQuota({ deviceId: 'remote' });
+ expect(mockIngestSnapshot).not.toHaveBeenCalled();
+ });
+
+ it('checks workspace device visibility before sampling', async () => {
+ mockVisibleDevice.mockRejectedValue(new Error('hidden device'));
+ await expect(
+ createCaller('workspace').refreshCodexQuota({ deviceId: 'remote' }),
+ ).rejects.toThrow('hidden device');
+ expect(mockCodexQuota).not.toHaveBeenCalled();
+ expect(mockIngestSnapshot).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/agentQuota.ts b/apps/server/src/routers/lambda/agentQuota.ts
index 318084a54d1..a7b78122b30 100644
--- a/apps/server/src/routers/lambda/agentQuota.ts
+++ b/apps/server/src/routers/lambda/agentQuota.ts
@@ -1,5 +1,6 @@
import { z } from 'zod';
+import { cloudWorkspaceAuth } from '@/business/server/trpc-middlewares/workspaceAuth';
import {
AgentAccountBindingModel,
AgentProviderAccountModel,
@@ -9,12 +10,16 @@ import { DeviceModel } from '@/database/models/device';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { AgentQuotaService } from '@/server/services/agentQuota';
+import { deviceGateway } from '@/server/services/deviceGateway';
+
+import { assertWorkspaceDeviceVisible } from './deviceWorkspaceGuard';
const quotaProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
const workspaceId = ctx.workspaceId ?? undefined;
return opts.next({
ctx: {
+ deviceModel: new DeviceModel(ctx.serverDB, ctx.userId, workspaceId),
accountModel: new AgentProviderAccountModel(ctx.serverDB, ctx.userId, workspaceId),
bindingModel: new AgentAccountBindingModel(ctx.serverDB, ctx.userId, workspaceId),
quotaService: new AgentQuotaService(ctx.serverDB, ctx.userId, workspaceId),
@@ -27,6 +32,8 @@ const providerSchema = z.enum(['claude-code', 'codex']);
const readingSchema = z.object({
capturedAt: z.number(),
+ windowMinutes: z.number().int().positive().optional(),
+ limitName: z.string().nullable().optional(),
isActive: z.boolean().optional(),
limitType: z.string(),
rateLimited: z.boolean().optional(),
@@ -37,6 +44,59 @@ const readingSchema = z.object({
});
export const agentQuotaRouter = router({
+ /** Refresh on the execution device and publish its sample to the account quota layer. */
+ refreshCodexQuota: quotaProcedure
+ .use(cloudWorkspaceAuth)
+ .input(
+ z.object({
+ command: z.string().optional(),
+ deviceId: z.string(),
+ env: z.record(z.string(), z.string()).optional(),
+ force: z.boolean().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ if (ctx.workspaceId) await assertWorkspaceDeviceVisible(ctx.deviceModel, input.deviceId);
+ const snapshot = await deviceGateway.codexQuota({
+ ...input,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+ if (
+ snapshot?.status !== 'ok' ||
+ !snapshot.identity?.externalAccountId ||
+ !snapshot.readings?.length
+ )
+ return snapshot ?? null;
+ const account = await ctx.accountModel.findByExternalId(
+ 'codex',
+ snapshot.identity.externalAccountId,
+ );
+ const latest = account ? await ctx.quotaService.listLatestReadings(account.id) : [];
+ const readings = snapshot.readings.filter(
+ (reading) =>
+ !latest.some(
+ (previous) =>
+ previous.limitType === reading.limitType &&
+ previous.scopeKey === reading.scopeKey &&
+ previous.capturedAt >= reading.capturedAt,
+ ),
+ );
+ if (readings.length) {
+ const device =
+ (ctx.workspaceId
+ ? await ctx.deviceModel.findWorkspaceDeviceById(input.deviceId)
+ : undefined) ?? (await ctx.deviceModel.findByDeviceId(input.deviceId));
+ await ctx.quotaService.ingestSnapshot({
+ deviceId: device?.id,
+ identity: snapshot.identity,
+ provider: 'codex',
+ readings,
+ });
+ }
+ return snapshot;
+ }),
+
// ── ingestion (desktop sampler → DB) ──────────────────────────────────────
ingestSnapshot: quotaProcedure
.input(
diff --git a/apps/server/src/services/agentQuota/__tests__/index.test.ts b/apps/server/src/services/agentQuota/__tests__/index.test.ts
index cf548210e5f..f7b04c1335a 100644
--- a/apps/server/src/services/agentQuota/__tests__/index.test.ts
+++ b/apps/server/src/services/agentQuota/__tests__/index.test.ts
@@ -245,3 +245,30 @@ describe('AgentQuotaService.recordUsage', () => {
// no throw = pass; the row is accountId-null and excluded from calibration
});
});
+
+describe('Codex quota persistence', () => {
+ it('preserves provider bucket names and monthly durations through DB reads and projection', async () => {
+ const capturedAt = Date.now();
+ const reading = {
+ capturedAt,
+ limitName: 'Other models',
+ limitType: 'weekly_all',
+ resetsAt: capturedAt + 100000,
+ scopeKey: 'codex_other',
+ utilization: 41,
+ windowMinutes: 43200,
+ };
+ const account = await service.ingestSnapshot({
+ identity,
+ provider: 'codex',
+ readings: [reading],
+ });
+ expect(await service.listLatestReadings(account.id)).toContainEqual(
+ expect.objectContaining(reading),
+ );
+ expect(await service.listSnapshotSeries(account.id, new Date(capturedAt - 1))).toContainEqual(
+ expect.objectContaining(reading),
+ );
+ expect((await windows.listByAccount(account.id))[0].windowSeconds).toBe(43200 * 60);
+ });
+});
diff --git a/apps/server/src/services/agentQuota/index.ts b/apps/server/src/services/agentQuota/index.ts
index f6e19906cd2..f6ddf9221ee 100644
--- a/apps/server/src/services/agentQuota/index.ts
+++ b/apps/server/src/services/agentQuota/index.ts
@@ -34,6 +34,17 @@ import {
import { claudeModelPrice } from './pricing';
+const readQuotaWindowMetadata = (raw: Record<string, unknown> | null) => ({
+ ...(typeof raw?.windowMinutes === 'number' &&
+ Number.isFinite(raw.windowMinutes) &&
+ raw.windowMinutes > 0
+ ? { windowMinutes: raw.windowMinutes }
+ : {}),
+ ...(typeof raw?.limitName === 'string' || raw?.limitName === null
+ ? { limitName: raw.limitName }
+ : {}),
+});
+
export interface AccountLoadView extends AccountLoad {
capacityUsd?: number;
label?: string | null;
@@ -116,6 +127,7 @@ export class AgentQuotaService {
capturedAt: new Date(r.capturedAt),
deviceId,
isActive: r.isActive,
+ raw: { windowMinutes: r.windowMinutes, limitName: r.limitName },
limitType: r.limitType,
resetsAt: r.resetsAt == null ? null : new Date(r.resetsAt),
scopeKey: r.scopeKey,
@@ -190,7 +202,7 @@ export class AgentQuotaService {
method: result.method,
sampleCount: result.sampleCount,
scopeKey,
- windowSeconds: windowSecondsForKind(limitType),
+ windowSeconds: list[0]?.windowSeconds ?? windowSecondsForKind(limitType),
});
}
};
@@ -268,6 +280,7 @@ export class AgentQuotaService {
const rows = await this.snapshots.latestPerBucket(accountId);
return rows.map((row) => ({
+ ...readQuotaWindowMetadata(row.raw),
capturedAt: row.capturedAt.getTime(),
isActive: row.isActive ?? undefined,
limitType: row.limitType,
@@ -287,6 +300,7 @@ export class AgentQuotaService {
const rows = await this.snapshots.listRange(accountId, since);
return rows.map((row) => ({
+ ...readQuotaWindowMetadata(row.raw),
capturedAt: row.capturedAt.getTime(),
isActive: row.isActive ?? undefined,
limitType: row.limitType,
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index 6b760d61026..08cb0e5c95a 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -9,7 +9,10 @@ import {
type GatewayMcpParams,
} from '@lobechat/device-gateway-client';
import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
-import type { ClaudeCodeQuotaSnapshot } from '@lobechat/heterogeneous-agents/quota';
+import type {
+ ClaudeCodeQuotaSnapshot,
+ CodexQuotaSnapshot,
+} from '@lobechat/heterogeneous-agents/quota';
import type {
DeviceCopyAssetForPublishResult,
DeviceDirectoryBrowseResult,
@@ -561,6 +564,22 @@ export class DeviceGateway {
});
}
+ /** Codex subscription quota sampled from the login on a remote device. */
+ codexQuota(params: {
+ command?: string;
+ deviceId: string;
+ env?: Record<string, string>;
+ force?: boolean;
+ userId: string;
+ workspaceId?: string;
+ }) {
+ return this.invokeDeviceRead<CodexQuotaSnapshot>('getCodexQuota', params, {
+ command: params.command,
+ env: params.env,
+ force: params.force,
+ });
+ }
+
/** Git worktrees attached to the same repository as a directory on a remote device. */
listGitWorktrees(params: {
deviceId: string;
diff --git a/packages/device-control/src/__tests__/codexQuota.test.ts b/packages/device-control/src/__tests__/codexQuota.test.ts
new file mode 100644
index 00000000000..610dc4bf78e
--- /dev/null
+++ b/packages/device-control/src/__tests__/codexQuota.test.ts
@@ -0,0 +1,98 @@
+import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+
+import { getCodexQuota } from '../codexQuota';
+
+let fixtureDir: string;
+let fixtureCommand: string;
+
+beforeAll(async () => {
+ fixtureDir = await mkdtemp(path.join(tmpdir(), 'codex-quota-'));
+ fixtureCommand = path.join(fixtureDir, 'codex');
+ await writeFile(
+ fixtureCommand,
+ `#!/usr/bin/env node
+const readline = require('node:readline');
+const input = readline.createInterface({ input: process.stdin });
+(async () => {
+ for await (const line of input) {
+ const message = JSON.parse(line);
+ if (message.method === 'initialize') {
+ process.stdout.write(JSON.stringify({ id: message.id, jsonrpc: '2.0', result: {} }) + '\\n');
+ }
+ if (message.method === 'account/rateLimits/read') {
+ process.stdout.write(JSON.stringify({
+ id: message.id,
+ jsonrpc: '2.0',
+ result: {
+ rateLimits: {
+ limitId: 'codex',
+ primary: { resetsAt: 1800000000, usedPercent: 23, windowDurationMins: 300 },
+ secondary: { resetsAt: 1800604800, usedPercent: 41, windowDurationMins: 10080 },
+ },
+ rateLimitsByLimitId: {
+ codex_other: {
+ limitName: 'Other models',
+ primary: { resetsAt: 1800003600, usedPercent: 9, windowDurationMins: 300 },
+ },
+ },
+ },
+ }) + '\\n');
+ }
+ }
+})();
+`,
+ );
+ await chmod(fixtureCommand, 0o755);
+ await writeFile(
+ path.join(fixtureDir, 'auth.json'),
+ JSON.stringify({ tokens: { account_id: 'fixture-account' } }),
+ );
+});
+
+afterAll(async () => {
+ await rm(fixtureDir, { force: true, recursive: true });
+});
+
+describe('getCodexQuota', () => {
+ it('reads and maps every rate-limit bucket through Codex app-server', async () => {
+ const result = await getCodexQuota({
+ command: fixtureCommand,
+ env: { CODEX_HOME: fixtureDir },
+ force: true,
+ });
+
+ expect(result).toMatchObject({
+ error: null,
+ provider: 'codex',
+ identity: { externalAccountId: 'fixture-account' },
+ session: { resetsAt: 1_800_000_000_000, usedPercent: 23, windowMinutes: 300 },
+ status: 'ok',
+ weekly: { resetsAt: 1_800_604_800_000, usedPercent: 41, windowMinutes: 10_080 },
+ });
+ expect(result.readings).toHaveLength(3);
+ expect(result.readings?.[2]).toMatchObject({
+ scopeKey: 'codex_other',
+ limitName: 'Other models',
+ windowMinutes: 300,
+ utilization: 9,
+ });
+ expect(result.rateLimits).toEqual([
+ {
+ limitId: 'codex',
+ limitName: null,
+ primary: { resetsAt: 1_800_000_000_000, usedPercent: 23, windowMinutes: 300 },
+ secondary: { resetsAt: 1_800_604_800_000, usedPercent: 41, windowMinutes: 10_080 },
+ },
+ {
+ limitId: 'codex_other',
+ limitName: 'Other models',
+ primary: { resetsAt: 1_800_003_600_000, usedPercent: 9, windowMinutes: 300 },
+ secondary: null,
+ },
+ ]);
+ });
+});
diff --git a/packages/device-control/src/codexQuota.ts b/packages/device-control/src/codexQuota.ts
new file mode 100644
index 00000000000..5588f57ee6a
--- /dev/null
+++ b/packages/device-control/src/codexQuota.ts
@@ -0,0 +1,21 @@
+import type { CodexQuotaSnapshot } from '@lobechat/heterogeneous-agents/quota';
+import {
+ createQuotaCacheKey,
+ fetchCodexQuota,
+ QuotaSnapshotCache,
+} from '@lobechat/heterogeneous-agents/quota-sampler';
+
+export interface GetCodexQuotaParams {
+ command?: string;
+ env?: Record<string, string>;
+ force?: boolean;
+}
+
+const quotaCache = new QuotaSnapshotCache<CodexQuotaSnapshot>();
+
+export const getCodexQuota = (params: GetCodexQuotaParams = {}): Promise<CodexQuotaSnapshot> =>
+ quotaCache.get(
+ createQuotaCacheKey('codex', params.command, params.env),
+ () => fetchCodexQuota({ ...params, includeResetCredits: false }),
+ { force: params.force },
+ );
diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.ts
index a6b14893743..e2ea5b82e09 100644
--- a/packages/device-control/src/dispatch.ts
+++ b/packages/device-control/src/dispatch.ts
@@ -26,6 +26,7 @@ import {
} from '@lobechat/local-file-shell/git';
import { getClaudeCodeQuota, type GetClaudeCodeQuotaParams } from './claudeCodeQuota';
+import { getCodexQuota, type GetCodexQuotaParams } from './codexQuota';
import { defaultCopyAssetForPublish, defaultReadExternalAssetForPublish } from './filePreview';
import { defaultListProjectDirectory } from './projectFileIndex';
import { prepareSkillDirectory } from './skillDirectory';
@@ -59,6 +60,7 @@ export const DEVICE_RPC_METHODS = [
'initWorkspace',
'listHeterogeneousAgentModels',
'getClaudeCodeQuota',
+ 'getCodexQuota',
'listProjectSkills',
'prepareSkillDirectory',
'browseDirectory',
@@ -145,6 +147,10 @@ export const executeDeviceRpc = async (
return getClaudeCodeQuota(params as GetClaudeCodeQuotaParams);
}
+ case 'getCodexQuota': {
+ return getCodexQuota(params as GetCodexQuotaParams);
+ }
+
case 'listProjectSkills': {
return listProjectSkills(params as ListProjectSkillsParams, deps);
}
diff --git a/packages/device-control/src/index.ts b/packages/device-control/src/index.ts
index 642c30c478f..02b6dfa5555 100644
--- a/packages/device-control/src/index.ts
+++ b/packages/device-control/src/index.ts
@@ -1,3 +1,4 @@
+export { getCodexQuota, type GetCodexQuotaParams } from './codexQuota';
export { DEVICE_RPC_METHODS, type DeviceRpcMethod, executeDeviceRpc } from './dispatch';
export {
defaultCopyAssetForPublish,
diff --git a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
index a165badab83..1909a3dc98d 100644
--- a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
+++ b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
@@ -1,4 +1,7 @@
-import type { HeteroQuotaWindow } from '@lobechat/heterogeneous-agents/quota';
+import type {
+ CodexQuotaSnapshot,
+ CodexRateLimitResetOutcome,
+} from '@lobechat/heterogeneous-agents/quota';
import type { HeterogeneousCliAgentType } from './binary';
@@ -65,51 +68,14 @@ export type {
ClaudeCodeScopedWeekly,
HeteroQuotaWindow,
} from '@lobechat/heterogeneous-agents/quota';
-
-export type CodexQuotaWindow = HeteroQuotaWindow;
-
-export interface CodexRateLimitSnapshot {
- /** Canonical metered limit identifier, for example `codex` or `codex_other`. */
- limitId: string;
- limitName: string | null;
- primary: CodexQuotaWindow | null;
- secondary: CodexQuotaWindow | null;
-}
-
-export interface CodexRateLimitResetCredit {
- expiresAt: number | null;
- grantedAt: number | null;
- /** Opaque backend identifier used only when redeeming this specific credit. */
- id: string | null;
- redeemedAt?: number | null;
- redeemStartedAt?: number | null;
- resetType: string | null;
- status: string;
- title: string | null;
-}
-
-export interface CodexRateLimitResetCredits {
- availableCount: number;
- /** Detailed rows when supported by the installed Codex CLI/backend. */
- credits?: CodexRateLimitResetCredit[];
- nextExpiresAt?: number | null;
- totalEarnedCount?: number;
-}
-
-export interface CodexQuotaSnapshot {
- error: string | null;
- provider: 'codex';
- rateLimitResetCredits?: CodexRateLimitResetCredits | null;
- /** Complete multi-bucket view when supported by the installed Codex app-server. */
- rateLimits?: CodexRateLimitSnapshot[];
- session: CodexQuotaWindow | null;
- status: 'error' | 'ok' | 'unavailable';
- updatedAt: number;
- weekly: CodexQuotaWindow | null;
-}
-
-export type CodexRateLimitResetOutcome =
- 'alreadyRedeemed' | 'noCredit' | 'nothingToReset' | 'reset';
+export type {
+ CodexQuotaSnapshot,
+ CodexQuotaWindow,
+ CodexRateLimitResetCredit,
+ CodexRateLimitResetCredits,
+ CodexRateLimitResetOutcome,
+ CodexRateLimitSnapshot,
+} from '@lobechat/heterogeneous-agents/quota';
export interface CodexRateLimitResetResult {
outcome: CodexRateLimitResetOutcome;
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/codexQuota.test.ts b/packages/heterogeneous-agents/src/quota-sampler/codexQuota.test.ts
similarity index 100%
rename from apps/desktop/src/main/modules/heterogeneousAgent/codexQuota.test.ts
rename to packages/heterogeneous-agents/src/quota-sampler/codexQuota.test.ts
diff --git a/packages/heterogeneous-agents/src/quota-sampler/codexQuota.ts b/packages/heterogeneous-agents/src/quota-sampler/codexQuota.ts
new file mode 100644
index 00000000000..6ab577061e2
--- /dev/null
+++ b/packages/heterogeneous-agents/src/quota-sampler/codexQuota.ts
@@ -0,0 +1,670 @@
+import type { ChildProcess } from 'node:child_process';
+import { spawn } from 'node:child_process';
+import { readFile } from 'node:fs/promises';
+import { homedir } from 'node:os';
+import path from 'node:path';
+
+import type {
+ CodexQuotaSnapshot,
+ CodexQuotaWindow,
+ CodexRateLimitResetCredit,
+ CodexRateLimitResetCredits,
+ CodexRateLimitResetOutcome,
+ CodexRateLimitSnapshot,
+} from '../quota';
+import { codexQuotaReadings } from '../quota/codex';
+import { parseCodexAccountIdentity } from '../quota/identity';
+import { buildCodexAppServerArgs, resolveCliSpawnPlan } from '../spawn';
+
+const RPC_TIMEOUT_MS = 10_000;
+const CODEX_PRIMARY_WINDOW_MINUTES = 5 * 60;
+const CODEX_SECONDARY_WINDOW_MINUTES = 7 * 24 * 60;
+const RESET_CONSUME_TIMEOUT_MS = 30_000;
+const RESET_CREDITS_TIMEOUT_MS = 5_000;
+const CODEX_RATE_LIMIT_RESET_CREDITS_URL =
+ 'https://chatgpt.com/backend-api/wham/rate-limit-reset-credits';
+const CODEX_RATE_LIMIT_RESET_CONSUME_URL = `${CODEX_RATE_LIMIT_RESET_CREDITS_URL}/consume`;
+
+export interface FetchCodexQuotaOptions {
+ codexHomePath?: string | null;
+ command?: string;
+ env?: Record<string, string | undefined>;
+ includeResetCredits?: boolean;
+}
+
+export interface ConsumeCodexRateLimitResetCreditOptions extends FetchCodexQuotaOptions {
+ creditId?: string;
+ idempotencyKey: string;
+}
+
+interface RpcResponse {
+ error?: { message?: string };
+ id?: number;
+ result?: unknown;
+}
+
+interface RpcRateWindow {
+ resetsAt?: number;
+ usedPercent?: number;
+ windowDurationMins?: number;
+}
+
+interface RpcRateLimitSnapshot {
+ limitId?: string | null;
+ limitName?: string | null;
+ primary?: RpcRateWindow;
+ secondary?: RpcRateWindow;
+}
+
+interface RpcRateLimitResetCredit {
+ expiresAt?: number | string | null;
+ grantedAt?: number | string | null;
+ id?: string;
+ redeemedAt?: number | string | null;
+ redeemStartedAt?: number | string | null;
+ resetType?: string;
+ status?: string;
+ title?: string | null;
+}
+
+interface RpcRateLimitsResponse {
+ rateLimitResetCredits?: {
+ availableCount?: number;
+ credits?: RpcRateLimitResetCredit[] | null;
+ nextExpiresAt?: number | string | null;
+ totalEarnedCount?: number;
+ } | null;
+ rateLimits?: RpcRateLimitSnapshot;
+ rateLimitsByLimitId?: Record<string, RpcRateLimitSnapshot> | null;
+}
+
+interface CodexAuthFile {
+ tokens?: {
+ access_token?: string;
+ account_id?: string;
+ };
+}
+
+interface BackendRateLimitResetCreditsResponse {
+ available_count?: number;
+ credits?: {
+ expires_at?: number | string | null;
+ granted_at?: number | string | null;
+ id?: string;
+ redeem_started_at?: number | string | null;
+ redeemed_at?: number | string | null;
+ reset_type?: string;
+ status?: string;
+ title?: string | null;
+ }[];
+ total_earned_count?: number;
+}
+
+interface BackendConsumeRateLimitResetCreditResponse {
+ code?: string;
+}
+
+interface RpcConsumeRateLimitResetCreditResponse {
+ outcome?: string;
+}
+
+interface CodexBackendAuth {
+ headers: Record<string, string>;
+}
+
+const getCodexHomePath = ({ codexHomePath, env }: FetchCodexQuotaOptions) =>
+ codexHomePath ?? env?.CODEX_HOME ?? process.env.CODEX_HOME ?? path.join(homedir(), '.codex');
+
+const errorSnapshot = (message: string): CodexQuotaSnapshot => ({
+ error: message,
+ provider: 'codex',
+ session: null,
+ status: 'error',
+ updatedAt: Date.now(),
+ weekly: null,
+});
+
+const buildRpcMessage = (id: number, method: string, params: unknown = {}) =>
+ `${JSON.stringify({ id, jsonrpc: '2.0', method, params })}\n`;
+
+const parseCreditTimestamp = (value: number | string | null | undefined): number | null => {
+ if (typeof value === 'number' && Number.isFinite(value)) {
+ return value < 10_000_000_000 ? value * 1000 : value;
+ }
+
+ if (typeof value !== 'string' || !value.trim()) return null;
+
+ const numeric = Number(value);
+ if (Number.isFinite(numeric)) {
+ return numeric < 10_000_000_000 ? numeric * 1000 : numeric;
+ }
+
+ const parsed = Date.parse(value);
+ return Number.isFinite(parsed) ? parsed : null;
+};
+
+const normalizeCreditStatus = (status?: string) => status?.toLowerCase() ?? 'unknown';
+
+const normalizeCreditText = (value: string | null | undefined) => {
+ if (typeof value !== 'string') return null;
+ const trimmed = value.trim();
+ return trimmed || null;
+};
+
+const mapRpcResetCredit = (credit: RpcRateLimitResetCredit): CodexRateLimitResetCredit => ({
+ expiresAt: parseCreditTimestamp(credit.expiresAt),
+ grantedAt: parseCreditTimestamp(credit.grantedAt),
+ id: normalizeCreditText(credit.id),
+ redeemStartedAt: parseCreditTimestamp(credit.redeemStartedAt),
+ redeemedAt: parseCreditTimestamp(credit.redeemedAt),
+ resetType: normalizeCreditText(credit.resetType),
+ status: normalizeCreditStatus(credit.status),
+ title: normalizeCreditText(credit.title),
+});
+
+const mapBackendResetCredit = (
+ credit: NonNullable<BackendRateLimitResetCreditsResponse['credits']>[number],
+): CodexRateLimitResetCredit => ({
+ expiresAt: parseCreditTimestamp(credit.expires_at),
+ grantedAt: parseCreditTimestamp(credit.granted_at),
+ id: normalizeCreditText(credit.id),
+ redeemStartedAt: parseCreditTimestamp(credit.redeem_started_at),
+ redeemedAt: parseCreditTimestamp(credit.redeemed_at),
+ resetType: normalizeCreditText(credit.reset_type),
+ status: normalizeCreditStatus(credit.status),
+ title: normalizeCreditText(credit.title),
+});
+
+const getNextAvailableCreditExpiry = (
+ credits: CodexRateLimitResetCredits['credits'] | undefined,
+ now = Date.now(),
+) =>
+ credits
+ ?.filter(
+ (credit) =>
+ credit.status === 'available' &&
+ typeof credit.expiresAt === 'number' &&
+ credit.expiresAt > now,
+ )
+ .map((credit) => credit.expiresAt as number)
+ .sort((a, b) => a - b)[0] ?? null;
+
+const mapRpcResetCredits = (
+ raw: RpcRateLimitsResponse['rateLimitResetCredits'],
+): CodexRateLimitResetCredits | null | undefined => {
+ if (raw === null) return null;
+ if (raw === undefined) return undefined;
+ if (typeof raw.availableCount !== 'number' || !Number.isFinite(raw.availableCount)) return null;
+
+ const credits = Array.isArray(raw.credits) ? raw.credits.map(mapRpcResetCredit) : undefined;
+
+ return {
+ availableCount: Math.max(0, Math.floor(raw.availableCount)),
+ ...(credits ? { credits } : {}),
+ nextExpiresAt: parseCreditTimestamp(raw.nextExpiresAt) ?? getNextAvailableCreditExpiry(credits),
+ ...(typeof raw.totalEarnedCount === 'number' && Number.isFinite(raw.totalEarnedCount)
+ ? { totalEarnedCount: Math.max(0, Math.floor(raw.totalEarnedCount)) }
+ : {}),
+ };
+};
+
+const mapBackendResetCredits = (
+ raw: BackendRateLimitResetCreditsResponse | null | undefined,
+): CodexRateLimitResetCredits | null => {
+ if (!raw) return null;
+
+ const credits = raw.credits?.map(mapBackendResetCredit);
+ const availableCount =
+ typeof raw.available_count === 'number' && Number.isFinite(raw.available_count)
+ ? raw.available_count
+ : (credits?.filter((credit) => credit.status === 'available').length ?? null);
+
+ if (availableCount === null) return null;
+
+ return {
+ availableCount: Math.max(0, Math.floor(availableCount)),
+ ...(credits ? { credits } : {}),
+ nextExpiresAt: getNextAvailableCreditExpiry(credits),
+ ...(typeof raw.total_earned_count === 'number' && Number.isFinite(raw.total_earned_count)
+ ? { totalEarnedCount: Math.max(0, Math.floor(raw.total_earned_count)) }
+ : {}),
+ };
+};
+
+const readCodexBackendAuth = async (
+ options: FetchCodexQuotaOptions,
+): Promise<CodexBackendAuth | null> => {
+ let auth: CodexAuthFile;
+
+ try {
+ const authPath = path.join(getCodexHomePath(options), 'auth.json');
+ auth = JSON.parse(await readFile(authPath, 'utf8')) as CodexAuthFile;
+ } catch {
+ return null;
+ }
+
+ const accessToken = auth.tokens?.access_token;
+ if (!accessToken) return null;
+
+ const headers: Record<string, string> = {
+ 'Authorization': `Bearer ${accessToken}`,
+ 'OpenAI-Beta': 'codex-1',
+ 'User-Agent': 'codex-cli',
+ 'originator': 'LobeHub Desktop',
+ };
+
+ if (auth.tokens?.account_id) {
+ headers['ChatGPT-Account-Id'] = auth.tokens.account_id;
+ }
+
+ return { headers };
+};
+
+const fetchBackendResetCredits = async (
+ auth: CodexBackendAuth,
+): Promise<CodexRateLimitResetCredits | null> => {
+ const controller = new AbortController();
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ const timeoutPromise = new Promise<null>((resolve) => {
+ timeout = setTimeout(() => {
+ controller.abort();
+ resolve(null);
+ }, RESET_CREDITS_TIMEOUT_MS);
+ });
+
+ const fetchPromise = (async () => {
+ const response = await fetch(CODEX_RATE_LIMIT_RESET_CREDITS_URL, {
+ ...auth,
+ signal: controller.signal,
+ });
+ if (!response.ok) return null;
+
+ const payload = (await response.json()) as BackendRateLimitResetCreditsResponse;
+ return mapBackendResetCredits(payload);
+ })();
+
+ try {
+ return await Promise.race([fetchPromise, timeoutPromise]);
+ } finally {
+ if (timeout) clearTimeout(timeout);
+ }
+};
+
+const mapConsumeOutcome = (outcome: string | undefined): CodexRateLimitResetOutcome => {
+ switch (outcome) {
+ case 'already_redeemed':
+ case 'alreadyRedeemed': {
+ return 'alreadyRedeemed';
+ }
+ case 'no_credit':
+ case 'noCredit': {
+ return 'noCredit';
+ }
+ case 'nothing_to_reset':
+ case 'nothingToReset': {
+ return 'nothingToReset';
+ }
+ case 'reset': {
+ return 'reset';
+ }
+ default: {
+ throw new Error(`Unknown Codex rate-limit reset outcome: ${outcome ?? 'missing'}`);
+ }
+ }
+};
+
+const consumeBackendResetCredit = async (
+ auth: CodexBackendAuth,
+ options: ConsumeCodexRateLimitResetCreditOptions,
+): Promise<CodexRateLimitResetOutcome> => {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), RESET_CONSUME_TIMEOUT_MS);
+
+ try {
+ const response = await fetch(CODEX_RATE_LIMIT_RESET_CONSUME_URL, {
+ body: JSON.stringify({
+ ...(options.creditId ? { credit_id: options.creditId } : {}),
+ redeem_request_id: options.idempotencyKey,
+ }),
+ headers: {
+ ...auth.headers,
+ 'Content-Type': 'application/json',
+ },
+ method: 'POST',
+ signal: controller.signal,
+ });
+ if (!response.ok) {
+ throw new Error(`Codex rate-limit reset failed: HTTP ${response.status}`);
+ }
+
+ const payload = (await response.json()) as BackendConsumeRateLimitResetCreditResponse;
+ return mapConsumeOutcome(payload.code);
+ } finally {
+ clearTimeout(timeout);
+ }
+};
+
+const mapRpcWindow = (
+ raw: RpcRateWindow | undefined,
+ fallbackWindowMinutes: number,
+): CodexQuotaWindow | null => {
+ if (!raw || typeof raw.usedPercent !== 'number' || !Number.isFinite(raw.usedPercent)) {
+ return null;
+ }
+
+ const windowMinutes =
+ typeof raw.windowDurationMins === 'number' &&
+ Number.isFinite(raw.windowDurationMins) &&
+ raw.windowDurationMins > 0
+ ? Math.floor(raw.windowDurationMins)
+ : fallbackWindowMinutes;
+
+ return {
+ resetsAt: parseCreditTimestamp(raw.resetsAt),
+ usedPercent: Math.min(100, Math.max(0, raw.usedPercent)),
+ windowMinutes,
+ };
+};
+
+const mapRpcRateLimitSnapshot = (
+ raw: RpcRateLimitSnapshot | undefined,
+ fallbackLimitId: string,
+): CodexRateLimitSnapshot | null => {
+ if (!raw) return null;
+
+ const primary = mapRpcWindow(raw.primary, CODEX_PRIMARY_WINDOW_MINUTES);
+ const secondary = mapRpcWindow(raw.secondary, CODEX_SECONDARY_WINDOW_MINUTES);
+ if (!primary && !secondary) return null;
+
+ return {
+ limitId: normalizeCreditText(raw.limitId) ?? fallbackLimitId,
+ limitName: normalizeCreditText(raw.limitName),
+ primary,
+ secondary,
+ };
+};
+
+const mapRpcRateLimits = (wrapper: RpcRateLimitsResponse): CodexRateLimitSnapshot[] => {
+ const snapshots = new Map<string, CodexRateLimitSnapshot>();
+
+ const addSnapshot = (raw: RpcRateLimitSnapshot | undefined, fallbackLimitId: string) => {
+ const snapshot = mapRpcRateLimitSnapshot(raw, fallbackLimitId);
+ if (!snapshot) return;
+
+ const normalizedId = snapshot.limitId.toLowerCase();
+ if (!snapshots.has(normalizedId)) snapshots.set(normalizedId, snapshot);
+ };
+
+ addSnapshot(wrapper.rateLimits, 'codex');
+
+ const additionalLimits = Object.entries(wrapper.rateLimitsByLimitId ?? {}).sort(
+ ([left], [right]) => left.localeCompare(right),
+ );
+ for (const [limitId, snapshot] of additionalLimits) addSnapshot(snapshot, limitId);
+
+ return [...snapshots.values()];
+};
+
+const cleanupRpcListeners = (
+ child: ChildProcess,
+ listeners: {
+ close: () => void;
+ error: (error: Error) => void;
+ stderrData: (chunk: Buffer) => void;
+ stdoutData: (chunk: Buffer) => void;
+ },
+) => {
+ child.stdout?.off('data', listeners.stdoutData);
+ child.stderr?.off('data', listeners.stderrData);
+ child.off('error', listeners.error);
+ child.off('close', listeners.close);
+};
+
+interface RpcRequestConfig {
+ failureMessage: string;
+ method: string;
+ params?: unknown;
+ timeoutMs?: number;
+}
+
+const requestViaRpc = async <T>(
+ options: FetchCodexQuotaOptions,
+ { failureMessage, method, params, timeoutMs = RPC_TIMEOUT_MS }: RpcRequestConfig,
+): Promise<T> =>
+ new Promise<T>((resolve, reject) => {
+ let buffer = '';
+ let child: ChildProcess | null = null;
+ let initId: number | null = null;
+ let stderr = '';
+ let finished = false;
+ let requestId: number | null = null;
+ let rpcId = 0;
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+
+ // Headless app-server only. TUI flags such as `-a untrusted` are parsed
+ // before the subcommand, and current Codex CLI rejects `untrusted`
+ // (`--ask-for-approval` accepts only `on-request` and `never`).
+ const rpcArgs = buildCodexAppServerArgs();
+
+ const cleanup = (kill: boolean) => {
+ if (finished) return false;
+ finished = true;
+ if (timeout) {
+ clearTimeout(timeout);
+ timeout = undefined;
+ }
+ if (child) {
+ cleanupRpcListeners(child, listeners);
+ if (kill) child.kill();
+ }
+ return true;
+ };
+
+ const settleError = (error: Error, kill = false) => {
+ if (!cleanup(kill)) return;
+ reject(error);
+ };
+
+ const settleResult = (result: T) => {
+ if (!cleanup(true)) return;
+ resolve(result);
+ };
+
+ const sendRpc = (child: ChildProcess, method: string, params?: unknown) => {
+ const id = ++rpcId;
+ child.stdin?.write(buildRpcMessage(id, method, params));
+ return id;
+ };
+
+ const sendNotification = (child: ChildProcess, method: string) => {
+ child.stdin?.write(`${JSON.stringify({ jsonrpc: '2.0', method, params: {} })}\n`);
+ };
+
+ const onStdoutData = (chunk: Buffer) => {
+ buffer += chunk.toString();
+
+ let newlineIndex: number;
+ while ((newlineIndex = buffer.indexOf('\n')) !== -1) {
+ const line = buffer.slice(0, newlineIndex).trim();
+ buffer = buffer.slice(newlineIndex + 1);
+ if (!line) continue;
+
+ try {
+ const message = JSON.parse(line) as RpcResponse;
+ if (message.id === initId) {
+ if (message.error) {
+ settleError(
+ new Error(message.error.message ?? `${failureMessage}: initialize`),
+ true,
+ );
+ return;
+ }
+ if (!child) return;
+ sendNotification(child, 'initialized');
+ requestId = sendRpc(child, method, params);
+ continue;
+ }
+
+ if (requestId !== null && message.id === requestId) {
+ if (message.error) {
+ settleError(new Error(message.error.message ?? failureMessage), true);
+ return;
+ }
+ settleResult(message.result as T);
+ }
+ } catch {
+ // Ignore non-JSON output from the RPC process.
+ }
+ }
+ };
+
+ const onStderrData = (chunk: Buffer) => {
+ stderr += chunk.toString();
+ };
+
+ const listeners = {
+ close: () => settleError(new Error(stderr.trim() || `${failureMessage}: RPC exited`), false),
+ error: (error: Error) => settleError(error, false),
+ stderrData: onStderrData,
+ stdoutData: onStdoutData,
+ };
+
+ timeout = setTimeout(() => {
+ settleError(new Error(`${failureMessage}: RPC timed out`), true);
+ }, timeoutMs);
+
+ void resolveCliSpawnPlan(options.command ?? 'codex', rpcArgs)
+ .then((spawnPlan) => {
+ if (finished) return;
+
+ child = spawn(spawnPlan.command, spawnPlan.args, {
+ env: {
+ ...process.env,
+ ...options.env,
+ ...(options.codexHomePath ? { CODEX_HOME: options.codexHomePath } : {}),
+ },
+ stdio: ['pipe', 'pipe', 'pipe'],
+ windowsHide: true,
+ });
+ child.stdout?.on('data', listeners.stdoutData);
+ child.stderr?.on('data', listeners.stderrData);
+ child.on('error', listeners.error);
+ child.on('close', listeners.close);
+ initId = sendRpc(child, 'initialize', {
+ clientInfo: { name: 'lobehub', version: '1.0.0' },
+ });
+ })
+ .catch((error: unknown) => {
+ const message = error instanceof Error ? error.message : 'Failed to resolve Codex command';
+ settleError(new Error(message), true);
+ });
+ });
+
+const fetchViaRpc = async (
+ options: FetchCodexQuotaOptions,
+ auth: CodexBackendAuth | null,
+): Promise<CodexQuotaSnapshot> => {
+ try {
+ const wrapper = await requestViaRpc<RpcRateLimitsResponse>(options, {
+ failureMessage: 'Codex rate-limit request failed',
+ method: 'account/rateLimits/read',
+ });
+ const rateLimits = mapRpcRateLimits(wrapper);
+ const defaultRateLimit =
+ rateLimits.find(({ limitId }) => limitId.toLowerCase() === 'codex') ?? rateLimits[0];
+ const rateLimitResetCredits = mapRpcResetCredits(wrapper?.rateLimitResetCredits);
+ let backendCredits: CodexRateLimitResetCredits | null = null;
+
+ // Older Codex app-server versions expose only availableCount. Use the same
+ // backend contract as Codex/CodexBar to fill the detail rows when needed.
+ if (
+ options.includeResetCredits !== false &&
+ auth &&
+ rateLimitResetCredits?.credits === undefined
+ ) {
+ try {
+ backendCredits = await fetchBackendResetCredits(auth);
+ } catch {
+ backendCredits = null;
+ }
+ }
+
+ const updatedAt = Date.now();
+ return {
+ error: null,
+ readings: codexQuotaReadings(rateLimits, updatedAt),
+ provider: 'codex',
+ rateLimitResetCredits:
+ backendCredits ?? (rateLimitResetCredits === undefined ? undefined : rateLimitResetCredits),
+ rateLimits,
+ session: defaultRateLimit?.primary ?? null,
+ status: 'ok',
+ updatedAt,
+ weekly: defaultRateLimit?.secondary ?? null,
+ };
+ } catch (error) {
+ return errorSnapshot(
+ error instanceof Error ? error.message : 'Codex rate-limit request failed',
+ );
+ }
+};
+
+const readCodexIdentity = async (options: FetchCodexQuotaOptions) => {
+ try {
+ return parseCodexAccountIdentity(
+ await readFile(path.join(getCodexHomePath(options), 'auth.json'), 'utf8'),
+ );
+ } catch {
+ return null;
+ }
+};
+
+export const fetchCodexQuota = async (
+ options: FetchCodexQuotaOptions = {},
+): Promise<CodexQuotaSnapshot> => {
+ const identityBefore = await readCodexIdentity(options);
+ const auth = await readCodexBackendAuth(options);
+ const snapshot = await fetchViaRpc(options, auth);
+ // Never attribute a sample if the device switched logins while it was read.
+ const identityAfter = await readCodexIdentity(options);
+ return {
+ ...snapshot,
+ identity:
+ identityBefore?.externalAccountId === identityAfter?.externalAccountId ? identityAfter : null,
+ };
+};
+
+export const consumeCodexRateLimitResetCredit = async (
+ options: ConsumeCodexRateLimitResetCreditOptions,
+): Promise<CodexRateLimitResetOutcome> => {
+ const idempotencyKey = options.idempotencyKey.trim();
+ const creditId = options.creditId?.trim();
+ if (!idempotencyKey) throw new Error('Codex reset idempotency key is required');
+ if (options.creditId !== undefined && !creditId) {
+ throw new Error('Codex reset credit ID must not be empty');
+ }
+
+ const normalizedOptions = { ...options, creditId, idempotencyKey };
+ const auth = await readCodexBackendAuth(normalizedOptions);
+
+ try {
+ const response = await requestViaRpc<RpcConsumeRateLimitResetCreditResponse>(
+ normalizedOptions,
+ {
+ failureMessage: 'Codex rate-limit reset failed',
+ method: 'account/rateLimitResetCredit/consume',
+ params: {
+ ...(creditId ? { creditId } : {}),
+ idempotencyKey,
+ },
+ timeoutMs: RESET_CONSUME_TIMEOUT_MS,
+ },
+ );
+ return mapConsumeOutcome(response?.outcome);
+ } catch (rpcError) {
+ // The reset endpoint predates the app-server consume method. Reuse the same
+ // idempotency key so falling back is safe even if the RPC response was lost.
+ if (!auth) throw rpcError;
+ return consumeBackendResetCredit(auth, normalizedOptions);
+ }
+};
diff --git a/packages/heterogeneous-agents/src/quota-sampler/index.ts b/packages/heterogeneous-agents/src/quota-sampler/index.ts
index ea7c7d18d4e..eadecef19a7 100644
--- a/packages/heterogeneous-agents/src/quota-sampler/index.ts
+++ b/packages/heterogeneous-agents/src/quota-sampler/index.ts
@@ -1,2 +1,3 @@
export * from './claudeCodeQuota';
+export * from './codexQuota';
export * from './snapshotCache';
diff --git a/packages/heterogeneous-agents/src/quota/codex.test.ts b/packages/heterogeneous-agents/src/quota/codex.test.ts
new file mode 100644
index 00000000000..36b06b5de3c
--- /dev/null
+++ b/packages/heterogeneous-agents/src/quota/codex.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildCodexRateLimits, codexQuotaReadings } from './codex';
+import { projectWindows } from './windows';
+
+const now = 1_800_000_000_000;
+const limits = [
+ {
+ limitId: 'codex',
+ limitName: null,
+ primary: { resetsAt: now + 60000, usedPercent: 23, windowMinutes: 300 },
+ secondary: null,
+ },
+ {
+ limitId: 'other',
+ limitName: 'Other models',
+ primary: null,
+ secondary: { resetsAt: now + 120000, usedPercent: 41, windowMinutes: 43200 },
+ },
+];
+
+describe('Codex persisted quota projection', () => {
+ it('roundtrips multiple buckets and monthly durations through unified readings', () => {
+ const readings = codexQuotaReadings(limits, now);
+ expect(buildCodexRateLimits(readings, now)).toEqual(limits);
+ expect(projectWindows(readings)[1].windowSeconds).toBe(43200 * 60);
+ });
+ it('selects the latest reading independently per bucket and refills expired windows', () => {
+ const old = codexQuotaReadings(limits, now);
+ const newer = { ...old[0], capturedAt: now + 1, utilization: 55 };
+ expect(buildCodexRateLimits([...old, newer], now)[0].primary?.usedPercent).toBe(55);
+ expect(buildCodexRateLimits(old, now + 120001)[1].secondary?.usedPercent).toBe(0);
+ });
+});
diff --git a/packages/heterogeneous-agents/src/quota/codex.ts b/packages/heterogeneous-agents/src/quota/codex.ts
new file mode 100644
index 00000000000..90f66eaaaee
--- /dev/null
+++ b/packages/heterogeneous-agents/src/quota/codex.ts
@@ -0,0 +1,54 @@
+import { toQuotaWindow } from './readings';
+import type { CodexRateLimitSnapshot } from './snapshot';
+import type { QuotaLimitReading } from './types';
+
+/** Preserve provider bucket ids and window lengths across live and persisted views. */
+export const codexQuotaReadings = (
+ limits: CodexRateLimitSnapshot[],
+ capturedAt: number,
+): QuotaLimitReading[] =>
+ limits.flatMap((limit) => {
+ const readings: QuotaLimitReading[] = [];
+ for (const [slot, window] of [
+ ['primary', limit.primary],
+ ['secondary', limit.secondary],
+ ] as const) {
+ if (!window) continue;
+ readings.push({
+ capturedAt,
+ limitName: limit.limitName,
+ limitType: slot === 'primary' ? 'session' : 'weekly_all',
+ resetsAt: window.resetsAt,
+ scopeKey: limit.limitId.toLowerCase() === 'codex' ? '' : limit.limitId,
+ utilization: Math.round(window.usedPercent),
+ windowMinutes: window.windowMinutes,
+ });
+ }
+ return readings;
+ });
+
+export const buildCodexRateLimits = (
+ readings: QuotaLimitReading[],
+ now: number,
+): CodexRateLimitSnapshot[] => {
+ const newest = new Map<string, QuotaLimitReading>();
+ for (const reading of readings) {
+ if (reading.limitType !== 'session' && reading.limitType !== 'weekly_all') continue;
+ const key = JSON.stringify([reading.limitType, reading.scopeKey]);
+ const previous = newest.get(key);
+ if (!previous || previous.capturedAt < reading.capturedAt) newest.set(key, reading);
+ }
+ const limits = new Map<string, CodexRateLimitSnapshot>();
+ for (const reading of newest.values()) {
+ const id = reading.scopeKey || 'codex';
+ const limit = limits.get(id) ?? {
+ limitId: id,
+ limitName: reading.limitName ?? null,
+ primary: null,
+ secondary: null,
+ };
+ limit[reading.limitType === 'session' ? 'primary' : 'secondary'] = toQuotaWindow(reading, now);
+ limits.set(id, limit);
+ }
+ return [...limits.values()];
+};
diff --git a/packages/heterogeneous-agents/src/quota/index.ts b/packages/heterogeneous-agents/src/quota/index.ts
index 24a5209e91c..79a1c6bf4ee 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 './codex';
export * from './cost';
export * from './identity';
export * from './loadBalancer';
diff --git a/packages/heterogeneous-agents/src/quota/readings.ts b/packages/heterogeneous-agents/src/quota/readings.ts
index 85c58894ca2..d87b0f3b709 100644
--- a/packages/heterogeneous-agents/src/quota/readings.ts
+++ b/packages/heterogeneous-agents/src/quota/readings.ts
@@ -9,7 +9,13 @@ import { windowSecondsForKind } from './types';
*/
export type QuotaDisplayReading = Pick<
QuotaLimitReading,
- 'capturedAt' | 'limitType' | 'resetsAt' | 'scopeKey' | 'utilization'
+ | 'capturedAt'
+ | 'limitType'
+ | 'resetsAt'
+ | 'scopeKey'
+ | 'utilization'
+ | 'windowMinutes'
+ | 'limitName'
>;
const clampPercent = (value: number) => Math.min(100, Math.max(0, Math.round(value)));
@@ -26,7 +32,11 @@ const clampPercent = (value: number) => Math.min(100, Math.max(0, Math.round(val
*/
export const hasWindowRolledOver = (reading: QuotaDisplayReading, now: number): boolean =>
reading.resetsAt == null
- ? now - reading.capturedAt > windowSecondsForKind(reading.limitType) * 1000
+ ? now - reading.capturedAt >
+ (reading.windowMinutes == null
+ ? windowSecondsForKind(reading.limitType)
+ : reading.windowMinutes * 60) *
+ 1000
: reading.resetsAt <= now;
/**
@@ -48,7 +58,7 @@ export const toQuotaWindow = (reading: QuotaDisplayReading, now: number): Hetero
return {
resetsAt: rolledOver ? null : (reading.resetsAt ?? null),
usedPercent: rolledOver ? 0 : clampPercent(reading.utilization),
- windowMinutes: windowSecondsForKind(reading.limitType) / 60,
+ windowMinutes: reading.windowMinutes ?? windowSecondsForKind(reading.limitType) / 60,
};
};
diff --git a/packages/heterogeneous-agents/src/quota/snapshot.ts b/packages/heterogeneous-agents/src/quota/snapshot.ts
index 3b28b91cefc..ff775379b03 100644
--- a/packages/heterogeneous-agents/src/quota/snapshot.ts
+++ b/packages/heterogeneous-agents/src/quota/snapshot.ts
@@ -12,6 +12,53 @@ export interface HeteroQuotaWindow {
windowMinutes: number;
}
+export type CodexQuotaWindow = HeteroQuotaWindow;
+
+export interface CodexRateLimitSnapshot {
+ /** Canonical metered limit identifier, for example `codex` or `codex_other`. */
+ limitId: string;
+ limitName: string | null;
+ primary: CodexQuotaWindow | null;
+ secondary: CodexQuotaWindow | null;
+}
+
+export interface CodexRateLimitResetCredit {
+ expiresAt: number | null;
+ grantedAt: number | null;
+ /** Opaque backend identifier used only when redeeming this specific credit. */
+ id: string | null;
+ redeemedAt?: number | null;
+ redeemStartedAt?: number | null;
+ resetType: string | null;
+ status: string;
+ title: string | null;
+}
+
+export interface CodexRateLimitResetCredits {
+ availableCount: number;
+ /** Detailed rows when supported by the installed Codex CLI/backend. */
+ credits?: CodexRateLimitResetCredit[];
+ nextExpiresAt?: number | null;
+ totalEarnedCount?: number;
+}
+
+export interface CodexQuotaSnapshot {
+ error: string | null;
+ identity?: QuotaAccountIdentity | null;
+ provider: 'codex';
+ rateLimitResetCredits?: CodexRateLimitResetCredits | null;
+ /** Complete multi-bucket view when supported by the installed Codex app-server. */
+ rateLimits?: CodexRateLimitSnapshot[];
+ readings?: QuotaLimitReading[];
+ session: CodexQuotaWindow | null;
+ status: 'error' | 'ok' | 'unavailable';
+ updatedAt: number;
+ weekly: CodexQuotaWindow | null;
+}
+
+export type CodexRateLimitResetOutcome =
+ 'alreadyRedeemed' | 'noCredit' | 'nothingToReset' | 'reset';
+
/**
* Why the quota can't be shown. `external-auth` means the agent is configured
* with an API key / custom base url, so subscription quota does not apply;
diff --git a/packages/heterogeneous-agents/src/quota/types.ts b/packages/heterogeneous-agents/src/quota/types.ts
index 4cf7b64235f..1d084bf7a7d 100644
--- a/packages/heterogeneous-agents/src/quota/types.ts
+++ b/packages/heterogeneous-agents/src/quota/types.ts
@@ -46,6 +46,7 @@ export interface QuotaLimitReading {
/** ms epoch when this reading was captured. */
capturedAt: number;
isActive?: boolean;
+ limitName?: string | null;
/** Raw `limits[].kind`, e.g. `session` / `weekly_all` / `weekly_scoped`. */
limitType: string;
/** True if a real 429 was observed at/around this reading. */
@@ -57,6 +58,8 @@ export interface QuotaLimitReading {
severity?: string;
/** Integer percent 0..100. */
utilization: number;
+ /** Provider-reported duration/name, persisted in the snapshot raw payload. */
+ windowMinutes?: number;
}
/** A projected concrete window, keyed by (limitType, scopeKey, resetsAt). */
diff --git a/packages/heterogeneous-agents/src/quota/windows.ts b/packages/heterogeneous-agents/src/quota/windows.ts
index 72db6bc1bd7..152830b9f14 100644
--- a/packages/heterogeneous-agents/src/quota/windows.ts
+++ b/packages/heterogeneous-agents/src/quota/windows.ts
@@ -29,7 +29,8 @@ export const projectWindows = (
for (const r of readings) {
if (r.resetsAt == null) continue;
const resetsAt = canonicalizeWindowResetAt(r.resetsAt);
- const windowSeconds = windowSecondsFor(r.limitType);
+ const windowSeconds =
+ r.windowMinutes == null ? windowSecondsFor(r.limitType) : r.windowMinutes * 60;
const key = keyOf({ ...r, resetsAt });
const existing = byWindow.get(key);
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/CodexQuotaMenu.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/CodexQuotaMenu.tsx
index c72b7d1560a..7e5f04857b4 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/CodexQuotaMenu.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/CodexQuotaMenu.tsx
@@ -10,12 +10,14 @@ import { Flexbox, Icon } from '@lobehub/ui';
import { Accordion, Button, confirmModal, Text, toast } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { RotateCcwIcon } from 'lucide-react';
-import { memo, useCallback, useEffect, useRef, useState } from 'react';
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
+import { createCodexQuotaReader } from '@/services/codexQuota';
import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';
-import type { FetchQuotaOptions, QuotaMenuHelpers, QuotaWindowItem } from './QuotaMenu';
+import type { QuotaMenuHelpers, QuotaWindowItem } from './QuotaMenu';
import QuotaMenu, { createQuotaSourceKey } from './QuotaMenu';
const FIVE_HOUR_WINDOW_MINUTES = 5 * 60;
@@ -120,6 +122,7 @@ const getAvailableResetCredits = (credits: CodexRateLimitResetCredit[] | undefin
interface CodexQuotaMenuProps {
command?: string;
+ deviceId?: string;
env?: Record<string, string>;
}
@@ -133,9 +136,10 @@ interface ResetFeedback {
text: string;
}
-const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, env }) => {
+const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, deviceId, env }) => {
const { t } = useTranslation('chat');
- const sourceKey = createQuotaSourceKey('codex', command, env);
+ const agentId = useAgentId();
+ const sourceKey = createQuotaSourceKey('codex', agentId, deviceId, command, env);
const activeSourceKeyRef = useRef(sourceKey);
const resetAttemptRef = useRef<ResetAttempt | null>(null);
const [resetFeedback, setResetFeedback] = useState<ResetFeedback>();
@@ -148,14 +152,9 @@ const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, env }) => {
setResetting(false);
}, [sourceKey]);
- const fetchQuota = useCallback(
- (options?: FetchQuotaOptions<CodexQuotaSnapshot>) =>
- heterogeneousAgentService.getCodexQuota({
- command,
- env,
- ...(options?.force ? { force: true } : {}),
- }),
- [command, env],
+ const fetchQuota = useMemo(
+ () => createCodexQuotaReader({ agentId, command, deviceId, env }),
+ [agentId, command, deviceId, env],
);
const getWindowLabel = useCallback(
@@ -216,8 +215,8 @@ const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, env }) => {
);
const hasExtraData = useCallback(
- (quota: CodexQuotaSnapshot) => !!quota.rateLimitResetCredits,
- [],
+ (quota: CodexQuotaSnapshot) => !deviceId && !!quota.rateLimitResetCredits,
+ [deviceId],
);
const getErrorText = useCallback(
@@ -256,6 +255,9 @@ const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, env }) => {
if (activeSourceKeyRef.current !== requestSourceKey) return;
applyQuota(result.quota);
+ void fetchQuota
+ .acceptLocalSnapshot(result.quota)
+ .catch((error) => console.error('[codexQuota:reset-ingest]', error));
resetAttemptRef.current = null;
switch (result.outcome) {
@@ -292,7 +294,7 @@ const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, env }) => {
if (activeSourceKeyRef.current === requestSourceKey) setResetting(false);
}
},
- [command, env, t],
+ [command, env, fetchQuota, t],
);
const confirmReset = useCallback(
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx
index ab6837fa70e..c6d49c435c5 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx
@@ -21,7 +21,7 @@ const mockService = vi.hoisted(() => ({
const effectiveAgencyConfig = vi.hoisted(() => ({
current: {
boundDeviceId: 'personal-device' as string | undefined,
- executionTarget: 'local' as const,
+ executionTarget: 'local' as 'local' | 'device',
heterogeneousProvider: {
command: 'codex',
type: 'codex',
@@ -104,10 +104,17 @@ vi.mock('@/services/electron/heterogeneousAgent', () => ({
// A `deviceId` routes the live sample through the device gateway TRPC instead
// of Electron IPC (see `fetchClaudeCodeQuotaSnapshot`).
-const mockLambdaDeviceQuota = vi.hoisted(() => vi.fn());
+const { mockLambdaClaudeQuota, mockLambdaCodexQuota } = vi.hoisted(() => ({
+ mockLambdaClaudeQuota: vi.fn(),
+ mockLambdaCodexQuota: vi.fn(),
+}));
vi.mock('@/libs/trpc/client', () => ({
- lambdaClient: { device: { getClaudeCodeQuota: { query: mockLambdaDeviceQuota } } },
+ lambdaClient: {
+ device: {
+ getClaudeCodeQuota: { query: mockLambdaClaudeQuota },
+ },
+ },
}));
// The menu reads persisted quota through TRPC before falling back to the live
@@ -117,6 +124,8 @@ vi.mock('@/libs/trpc/client', () => ({
const mockQuotaService = vi.hoisted(() => ({
getLatestReadings: vi.fn(async (): Promise<unknown[]> => []),
ingestClaudeSnapshot: vi.fn(async () => undefined),
+ ingestCodexSnapshot: vi.fn(async () => undefined),
+ refreshCodexQuota: vi.fn(),
listAccounts: vi.fn(async (): Promise<unknown[]> => []),
listBindings: vi.fn(async (): Promise<unknown[]> => []),
}));
@@ -271,6 +280,9 @@ beforeEach(() => {
mockService.consumeCodexRateLimitResetCredit.mockReset();
mockService.getClaudeCodeQuota.mockReset();
mockService.getCodexQuota.mockReset();
+ mockLambdaClaudeQuota.mockReset();
+ mockLambdaCodexQuota.mockReset();
+ mockQuotaService.refreshCodexQuota.mockImplementation(mockLambdaCodexQuota);
toastErrorMock.mockReset();
toastSuccessMock.mockReset();
mockQuotaService.getLatestReadings.mockResolvedValue([]);
@@ -294,17 +306,50 @@ describe('HeteroControlBar', () => {
expect(mockService.getCodexQuota).toHaveBeenCalledWith({ command: 'codex', env: undefined });
});
- it('does not show local quota for a workspace shared-local fallback without an override', () => {
+ it('shows Codex quota sampled by a bound remote device', async () => {
+ effectiveAgencyConfig.current = {
+ boundDeviceId: 'remote-device',
+ executionTarget: 'device',
+ heterogeneousProvider: { command: 'codex', type: 'codex' },
+ };
+ mockLambdaCodexQuota.mockResolvedValue(
+ codexSnapshot({ session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 } }),
+ );
+
+ render(<HeteroControlBar />);
+
+ expect(
+ await screen.findByRole('button', { name: 'heteroAgent.codexQuota.tooltip' }),
+ ).toBeTruthy();
+ expect(mockLambdaCodexQuota).toHaveBeenCalledWith({
+ command: 'codex',
+ deviceId: 'remote-device',
+ env: undefined,
+ });
+ expect(mockService.getCodexQuota).not.toHaveBeenCalled();
+ });
+
+ it('shows remote quota for a workspace shared-device fallback', async () => {
effectiveAgencyConfig.current = {
boundDeviceId: 'workspace-device',
executionTarget: 'local',
heterogeneousProvider: { command: 'codex', type: 'codex' },
};
effectiveAgencyConfig.workspaceScoped = true;
+ mockLambdaCodexQuota.mockResolvedValue(
+ codexSnapshot({ session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 } }),
+ );
render(<HeteroControlBar />);
- expect(screen.queryByRole('button', { name: 'heteroAgent.codexQuota.tooltip' })).toBeNull();
+ expect(
+ await screen.findByRole('button', { name: 'heteroAgent.codexQuota.tooltip' }),
+ ).toBeTruthy();
+ expect(mockLambdaCodexQuota).toHaveBeenCalledWith({
+ command: 'codex',
+ deviceId: 'workspace-device',
+ env: undefined,
+ });
expect(mockService.getCodexQuota).not.toHaveBeenCalled();
});
@@ -798,14 +843,14 @@ describe('ClaudeCodeQuotaMenu', () => {
});
it('samples through the device gateway RPC when a deviceId is provided', async () => {
- mockLambdaDeviceQuota.mockResolvedValue(
+ mockLambdaClaudeQuota.mockResolvedValue(
claudeSnapshot({ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 } }),
);
render(<ClaudeCodeQuotaMenu deviceId="remote-device" />);
await waitFor(() =>
- expect(mockLambdaDeviceQuota).toHaveBeenCalledWith({
+ expect(mockLambdaClaudeQuota).toHaveBeenCalledWith({
deviceId: 'remote-device',
env: undefined,
}),
@@ -819,7 +864,7 @@ describe('ClaudeCodeQuotaMenu', () => {
const account = persistedAccount();
mockQuotaService.listAccounts.mockResolvedValue([account]);
mockQuotaService.getLatestReadings.mockResolvedValue([persistedSessionReading(capturedAt)]);
- mockLambdaDeviceQuota.mockResolvedValueOnce(
+ mockLambdaClaudeQuota.mockResolvedValueOnce(
claudeSnapshot({
identity: { externalAccountId: 'ext-1' },
readings: [liveSessionReading(capturedAt)],
@@ -829,11 +874,11 @@ describe('ClaudeCodeQuotaMenu', () => {
const { rerender } = render(<ClaudeCodeQuotaMenu deviceId="device-a" />);
expect(await screen.findByText('92%')).toBeTruthy();
- mockLambdaDeviceQuota.mockResolvedValueOnce(null);
+ mockLambdaClaudeQuota.mockResolvedValueOnce(null);
rerender(<ClaudeCodeQuotaMenu deviceId="device-b" />);
await waitFor(() =>
- expect(mockLambdaDeviceQuota).toHaveBeenLastCalledWith({
+ expect(mockLambdaClaudeQuota).toHaveBeenLastCalledWith({
deviceId: 'device-b',
env: undefined,
}),
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx
index eeca16cb760..a48a2f87fd3 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx
@@ -164,6 +164,10 @@ const HeteroControlBar = memo(() => {
isSubscriptionAuth &&
heteroProvider?.type === 'claude-code' &&
(isLocalHeteroExecution || !!quotaDeviceId);
+ const shouldShowCodexQuota =
+ isSubscriptionAuth &&
+ heteroProvider?.type === 'codex' &&
+ (isLocalHeteroExecution || !!quotaDeviceId);
if (isAccessLoading) return null;
@@ -191,12 +195,21 @@ const HeteroControlBar = memo(() => {
<Flexbox horizontal align={'center'} className={styles.leftGroup} gap={4}>
<WorkspaceControls alwaysShowWorkspace agentId={agentId} />
</Flexbox>
- {(shouldShowApiCredits || (shouldShowClaudeQuota && quotaDeviceId)) && (
+ {(shouldShowApiCredits ||
+ (shouldShowClaudeQuota && quotaDeviceId) ||
+ (shouldShowCodexQuota && quotaDeviceId)) && (
<Flexbox horizontal align={'center'} className={styles.rightGroup} gap={4}>
{shouldShowApiCredits && <ChatInputCredits />}
{shouldShowClaudeQuota && quotaDeviceId && (
<ClaudeCodeQuotaMenu deviceId={quotaDeviceId} env={heteroProvider?.env} />
)}
+ {shouldShowCodexQuota && quotaDeviceId && (
+ <CodexQuotaMenu
+ command={heteroProvider?.command}
+ deviceId={quotaDeviceId}
+ env={heteroProvider?.env}
+ />
+ )}
</Flexbox>
)}
</Flexbox>
@@ -218,11 +231,6 @@ const HeteroControlBar = memo(() => {
<span className={styles.fullAccessLabel}>{tChat('heteroAgent.fullAccess.label')}</span>
</div>
);
- // Codex quota still needs the local CLI (spawned over IPC), so it stays
- // desktop-local; the SDK runtime badge likewise reports this desktop's own
- // in-process runtime, not a remote device's.
- const shouldShowCodexQuota =
- isSubscriptionAuth && heteroProvider?.type === 'codex' && isLocalHeteroExecution;
const shouldShowSdkRuntime =
heteroProvider?.type === 'claude-code' &&
isLocalHeteroExecution &&
@@ -270,7 +278,11 @@ const HeteroControlBar = memo(() => {
<Flexbox horizontal align={'center'} className={styles.rightGroup} gap={4}>
{shouldShowApiCredits && <ChatInputCredits />}
{shouldShowCodexQuota && (
- <CodexQuotaMenu command={heteroProvider?.command} env={heteroProvider?.env} />
+ <CodexQuotaMenu
+ command={heteroProvider?.command}
+ deviceId={quotaDeviceId}
+ env={heteroProvider?.env}
+ />
)}
{shouldShowClaudeQuota && (
<ClaudeCodeQuotaMenu deviceId={quotaDeviceId} env={heteroProvider?.env} />
diff --git a/src/services/agentQuota.ts b/src/services/agentQuota.ts
index f8ff11f3fea..4dd7283fb45 100644
--- a/src/services/agentQuota.ts
+++ b/src/services/agentQuota.ts
@@ -2,6 +2,11 @@ import type {
ClaudeCodeAccountIdentity,
ClaudeCodeQuotaReading,
} from '@lobechat/electron-client-ipc';
+import type {
+ CodexQuotaSnapshot,
+ QuotaAccountIdentity,
+ QuotaLimitReading,
+} from '@lobechat/heterogeneous-agents/quota';
import { lambdaClient } from '@/libs/trpc/client';
@@ -11,6 +16,19 @@ import { lambdaClient } from '@/libs/trpc/client';
* fetches the *live* quota from the local CLI login over Electron IPC.
*/
class AgentQuotaService {
+ ingestCodexSnapshot = async (params: {
+ identity: QuotaAccountIdentity;
+ readings: QuotaLimitReading[];
+ }) => lambdaClient.agentQuota.ingestSnapshot.mutate({ ...params, provider: 'codex' });
+
+ refreshCodexQuota = async (params: {
+ command?: string;
+ deviceId: string;
+ env?: Record<string, string>;
+ force?: boolean;
+ }): Promise<CodexQuotaSnapshot | null> =>
+ lambdaClient.agentQuota.refreshCodexQuota.mutate(params);
+
/** Persist a live Claude snapshot (identity + readings) captured over IPC. */
ingestClaudeSnapshot = async (params: {
deviceId?: string;
diff --git a/src/services/codexQuota.test.ts b/src/services/codexQuota.test.ts
new file mode 100644
index 00000000000..30378191789
--- /dev/null
+++ b/src/services/codexQuota.test.ts
@@ -0,0 +1,120 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentQuotaService } from './agentQuota';
+import { createCodexQuotaReader } from './codexQuota';
+import { heterogeneousAgentService } from './electron/heterogeneousAgent';
+
+vi.mock('./agentQuota', () => ({
+ agentQuotaService: {
+ listAccounts: vi.fn(),
+ listBindings: vi.fn(),
+ getLatestReadings: vi.fn(),
+ ingestCodexSnapshot: vi.fn(),
+ refreshCodexQuota: vi.fn(),
+ },
+}));
+vi.mock('./electron/heterogeneousAgent', () => ({
+ heterogeneousAgentService: { getCodexQuota: vi.fn() },
+}));
+
+const account = {
+ id: 'account-a',
+ provider: 'codex',
+ externalAccountId: 'external-a',
+ updatedAt: new Date(),
+};
+const reading = {
+ capturedAt: Date.now(),
+ limitType: 'session',
+ resetsAt: Date.now() + 60000,
+ scopeKey: '',
+ utilization: 23,
+ windowMinutes: 300,
+};
+const sample = {
+ error: null,
+ identity: { externalAccountId: 'external-a' },
+ readings: [reading],
+ provider: 'codex' as const,
+ session: { usedPercent: 23, windowMinutes: 300, resetsAt: reading.resetsAt },
+ status: 'ok' as const,
+ updatedAt: reading.capturedAt,
+ weekly: null,
+};
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ vi.mocked(agentQuotaService.listAccounts).mockResolvedValue([account] as never);
+ vi.mocked(agentQuotaService.listBindings).mockResolvedValue([]);
+ vi.mocked(agentQuotaService.getLatestReadings).mockResolvedValue([reading]);
+ vi.mocked(agentQuotaService.ingestCodexSnapshot).mockResolvedValue(account as never);
+ vi.mocked(heterogeneousAgentService.getCodexQuota).mockResolvedValue(sample);
+ vi.mocked(agentQuotaService.refreshCodexQuota).mockResolvedValue(sample);
+});
+
+describe('account-scoped Codex quota', () => {
+ it('renders fresh persisted local quota without probing the CLI', async () => {
+ const result = await createCodexQuotaReader({})({});
+ expect(result.session?.usedPercent).toBe(23);
+ expect(heterogeneousAgentService.getCodexQuota).not.toHaveBeenCalled();
+ });
+
+ it('publishes a fresh local sample to the unified account layer', async () => {
+ vi.mocked(agentQuotaService.listAccounts).mockResolvedValue([]);
+ const result = await createCodexQuotaReader({})({});
+ expect(result.identity?.externalAccountId).toBe('external-a');
+ expect(agentQuotaService.ingestCodexSnapshot).toHaveBeenCalledWith({
+ identity: sample.identity,
+ readings: [reading],
+ });
+ });
+
+ it('keeps local quota usable when the persistence backend is unavailable', async () => {
+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ vi.mocked(agentQuotaService.listAccounts).mockRejectedValue(new Error('offline'));
+ vi.mocked(agentQuotaService.ingestCodexSnapshot).mockRejectedValue(new Error('offline'));
+ const result = await createCodexQuotaReader({})();
+ expect(result.session?.usedPercent).toBe(23);
+ expect(result.status).toBe('ok');
+ } finally {
+ log.mockRestore();
+ }
+ });
+
+ it('does not re-ingest a cached sample on focus', async () => {
+ await createCodexQuotaReader({})({ revalidate: true });
+ expect(agentQuotaService.ingestCodexSnapshot).not.toHaveBeenCalled();
+ });
+
+ it('refreshes remote quota through agentQuota and keeps persisted data while offline', async () => {
+ const reader = createCodexQuotaReader({ deviceId: 'device-a' });
+ expect((await reader()).session?.usedPercent).toBe(23);
+ expect(agentQuotaService.refreshCodexQuota).toHaveBeenCalled();
+ expect(agentQuotaService.ingestCodexSnapshot).not.toHaveBeenCalled();
+ vi.mocked(agentQuotaService.refreshCodexQuota).mockResolvedValue(null);
+ expect((await reader({ revalidate: true })).session?.usedPercent).toBe(23);
+ expect(heterogeneousAgentService.getCodexQuota).not.toHaveBeenCalled();
+ });
+
+ it('does not show another device account while discovering a new source', async () => {
+ vi.mocked(agentQuotaService.refreshCodexQuota).mockResolvedValue(null);
+ const result = await createCodexQuotaReader({ deviceId: 'device-b' })();
+ expect(result.session).toBeNull();
+ expect(result.status).toBe('error');
+ });
+
+ it('does not merge the previous account after the device changes login', async () => {
+ const reader = createCodexQuotaReader({ deviceId: 'device-a' });
+ await reader();
+ vi.mocked(agentQuotaService.refreshCodexQuota).mockResolvedValue({
+ ...sample,
+ identity: { externalAccountId: 'external-b' },
+ readings: [],
+ session: { ...sample.session, usedPercent: 80 },
+ });
+ const result = await reader({ revalidate: true });
+ expect(result.identity?.externalAccountId).toBe('external-b');
+ expect(result.session?.usedPercent).toBe(80);
+ });
+});
diff --git a/src/services/codexQuota.ts b/src/services/codexQuota.ts
new file mode 100644
index 00000000000..21b2caf02e0
--- /dev/null
+++ b/src/services/codexQuota.ts
@@ -0,0 +1,146 @@
+import type { CodexQuotaSnapshot } from '@lobechat/heterogeneous-agents/quota';
+
+import { agentQuotaService } from './agentQuota';
+import { buildCodexPanelSnapshot } from './codexQuotaViewModel';
+import { heterogeneousAgentService } from './electron/heterogeneousAgent';
+
+const REFRESH_MS = 2 * 60_000;
+
+interface CodexQuotaSource {
+ agentId?: string;
+ command?: string;
+ deviceId?: string;
+ env?: Record<string, string>;
+}
+
+interface FetchOptions {
+ force?: boolean;
+ onInterim?: (snapshot: CodexQuotaSnapshot) => void;
+ revalidate?: boolean;
+}
+
+const readPersisted = async <T>(request: Promise<T>, fallback: T): Promise<T> => {
+ try {
+ return await request;
+ } catch (error) {
+ console.error('[codexQuota:read-persisted]', error);
+ return fallback;
+ }
+};
+
+/** Device/profile sources identify their login before reusing persisted data. */
+export const createCodexQuotaReader = (source: CodexQuotaSource) => {
+ let trustedAccountId: string | undefined;
+ let lastLive: CodexQuotaSnapshot | null = null;
+ const readQuota = async (options: FetchOptions = {}): Promise<CodexQuotaSnapshot> => {
+ const [allAccounts, bindings] = await Promise.all([
+ readPersisted(agentQuotaService.listAccounts(), []),
+ source.agentId ? readPersisted(agentQuotaService.listBindings(source.agentId), []) : [],
+ ]);
+ const accounts = allAccounts.filter((account) => account.provider === 'codex');
+ const pinnedId = bindings.find((binding) => binding.role === 'pinned')?.accountId;
+ let account =
+ source.deviceId || source.env?.CODEX_HOME
+ ? accounts.find((item) => item.externalAccountId === trustedAccountId)
+ : (accounts.find((item) => item.externalAccountId === trustedAccountId) ??
+ accounts.find((item) => item.id === pinnedId) ??
+ accounts[0]);
+ let readings = account
+ ? await readPersisted(agentQuotaService.getLatestReadings(account.id), [])
+ : [];
+ const persisted =
+ account && readings.length ? buildCodexPanelSnapshot(account, readings, lastLive) : null;
+ const receivedAt = account?.updatedAt ? new Date(account.updatedAt).getTime() : 0;
+ if (persisted && !options.force && !options.revalidate && Date.now() - receivedAt < REFRESH_MS)
+ return persisted;
+ if (persisted) options.onInterim?.(persisted);
+
+ let live: CodexQuotaSnapshot | null;
+ try {
+ live = source.deviceId
+ ? await agentQuotaService.refreshCodexQuota({
+ command: source.command,
+ env: source.env,
+ deviceId: source.deviceId,
+ ...(options.force ? { force: true } : {}),
+ })
+ : await heterogeneousAgentService.getCodexQuota({
+ command: source.command,
+ env: source.env,
+ ...(options.force ? { force: true } : {}),
+ });
+ } catch (error) {
+ console.error('[codexQuota:refresh]', error);
+ if (persisted) return persisted;
+ throw error;
+ }
+ if (live?.status === 'ok') lastLive = live;
+ const externalAccountId = live?.identity?.externalAccountId;
+ if (live?.status === 'ok' && externalAccountId) {
+ trustedAccountId = externalAccountId;
+ account = accounts.find((item) => item.externalAccountId === externalAccountId);
+ readings = account
+ ? await readPersisted(agentQuotaService.getLatestReadings(account.id), [])
+ : [];
+ const fresh = live.readings?.filter(
+ (reading) =>
+ !readings.some(
+ (previous) =>
+ previous.limitType === reading.limitType &&
+ previous.scopeKey === reading.scopeKey &&
+ previous.capturedAt >= reading.capturedAt,
+ ),
+ );
+ if (!source.deviceId && fresh?.length) {
+ try {
+ account = await agentQuotaService.ingestCodexSnapshot({
+ identity: live.identity!,
+ readings: fresh,
+ });
+ } catch (error) {
+ console.error('[codexQuota:ingest]', error);
+ }
+ }
+ if (source.deviceId && !account) {
+ account = (await readPersisted(agentQuotaService.listAccounts(), [])).find(
+ (item) => item.provider === 'codex' && item.externalAccountId === externalAccountId,
+ );
+ }
+ if (account)
+ readings = await readPersisted(agentQuotaService.getLatestReadings(account.id), []);
+ } else if (live?.status === 'ok') {
+ // A successful but unidentified login must not inherit the previous account.
+ trustedAccountId = undefined;
+ account = undefined;
+ readings = [];
+ }
+ if (account && readings.length) return buildCodexPanelSnapshot(account, readings, live);
+ return (
+ live ??
+ persisted ?? {
+ error: 'Device is unavailable',
+ provider: 'codex',
+ session: null,
+ status: 'error',
+ updatedAt: Date.now(),
+ weekly: null,
+ }
+ );
+ };
+ return Object.assign(readQuota, {
+ acceptLocalSnapshot: async (snapshot: CodexQuotaSnapshot) => {
+ lastLive = snapshot;
+ if (
+ snapshot.status === 'ok' &&
+ snapshot.identity?.externalAccountId &&
+ snapshot.readings?.length
+ ) {
+ trustedAccountId = snapshot.identity.externalAccountId;
+ await agentQuotaService.ingestCodexSnapshot({
+ identity: snapshot.identity,
+ readings: snapshot.readings,
+ });
+ }
+ },
+ });
+};
diff --git a/src/services/codexQuotaViewModel.test.ts b/src/services/codexQuotaViewModel.test.ts
new file mode 100644
index 00000000000..2bb74664ff5
--- /dev/null
+++ b/src/services/codexQuotaViewModel.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildCodexPanelSnapshot } from './codexQuotaViewModel';
+
+const now = 1_800_000_000_000;
+const account = { externalAccountId: 'a', updatedAt: new Date(now) };
+const reading = {
+ capturedAt: now,
+ limitType: 'session',
+ resetsAt: now + 60000,
+ scopeKey: '',
+ utilization: 23,
+ windowMinutes: 300,
+};
+const live = {
+ error: null,
+ identity: { externalAccountId: 'b' },
+ provider: 'codex' as const,
+ readings: [{ ...reading, capturedAt: now + 1, utilization: 90 }],
+ session: null,
+ status: 'ok' as const,
+ updatedAt: now + 1,
+ weekly: null,
+};
+
+describe('Codex account view', () => {
+ it('never merges quota from another account', () => {
+ expect(buildCodexPanelSnapshot(account, [reading], live, now).session?.usedPercent).toBe(23);
+ });
+ it('merges newer live buckets only for the same account', () => {
+ expect(
+ buildCodexPanelSnapshot(
+ account,
+ [reading],
+ { ...live, identity: { externalAccountId: 'a' } },
+ now,
+ ).session?.usedPercent,
+ ).toBe(90);
+ });
+ it('preserves persisted windows after a failed refresh', () => {
+ expect(
+ buildCodexPanelSnapshot(account, [reading], { ...live, status: 'error' }, now).session
+ ?.usedPercent,
+ ).toBe(23);
+ });
+});
diff --git a/src/services/codexQuotaViewModel.ts b/src/services/codexQuotaViewModel.ts
new file mode 100644
index 00000000000..90d87648f8b
--- /dev/null
+++ b/src/services/codexQuotaViewModel.ts
@@ -0,0 +1,53 @@
+import type {
+ CodexQuotaSnapshot,
+ QuotaAccountIdentity,
+ QuotaLimitReading,
+} from '@lobechat/heterogeneous-agents/quota';
+import { buildCodexRateLimits, codexQuotaReadings } from '@lobechat/heterogeneous-agents/quota';
+
+export const buildCodexPanelSnapshot = (
+ account: { externalAccountId?: string | null; updatedAt?: Date | string | null },
+ persisted: QuotaLimitReading[],
+ live: CodexQuotaSnapshot | null,
+ now = Date.now(),
+): CodexQuotaSnapshot => {
+ const sample =
+ live?.status === 'ok' && live.identity?.externalAccountId === account.externalAccountId
+ ? live
+ : null;
+ const liveReadings =
+ sample?.readings ??
+ (sample
+ ? codexQuotaReadings(
+ sample.rateLimits ?? [
+ {
+ limitId: 'codex',
+ limitName: null,
+ primary: sample.session,
+ secondary: sample.weekly,
+ },
+ ],
+ sample.updatedAt,
+ )
+ : []);
+ const rateLimits = buildCodexRateLimits([...persisted, ...liveReadings], now);
+ const primary = rateLimits.find((limit) => limit.limitId === 'codex') ?? rateLimits[0];
+ const identity: QuotaAccountIdentity = {
+ externalAccountId: account.externalAccountId ?? undefined,
+ };
+ return {
+ error: null,
+ identity,
+ provider: 'codex',
+ rateLimitResetCredits: sample?.rateLimitResetCredits,
+ rateLimits,
+ session: primary?.primary ?? null,
+ status: 'ok',
+ updatedAt:
+ Math.max(
+ account.updatedAt ? new Date(account.updatedAt).getTime() : 0,
+ sample?.updatedAt ?? 0,
+ ) || now,
+ weekly: primary?.secondary ?? null,
+ };
+};