Skip to content

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

✨ feat(desktop): improve Codex quota reset controls (#17230)

AmAzing-eae74fe70b9a
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
index 9f8c6b2b545..5e239250623 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
@@ -11,6 +11,7 @@ import { finished as streamFinished } from 'node:stream/promises';
import type {
ClaudeCodeQuotaSnapshot,
CodexQuotaSnapshot,
+ CodexRateLimitResetResult,
HeterogeneousAgentSessionError,
} from '@lobechat/electron-client-ipc';
import {
@@ -47,7 +48,10 @@ import { detectHeterogeneousCliCommand } from '@/modules/binaries';
import { getHeterogeneousAgentDriver } from '@/modules/heterogeneousAgent';
import { buildBrowserMcpTools } from '@/modules/heterogeneousAgent/browserMcpTools';
import { fetchClaudeCodeQuota } from '@/modules/heterogeneousAgent/claudeCodeQuota';
-import { fetchCodexQuota } from '@/modules/heterogeneousAgent/codexQuota';
+import {
+ consumeCodexRateLimitResetCredit as consumeCodexRateLimitResetCreditRequest,
+ fetchCodexQuota,
+} from '@/modules/heterogeneousAgent/codexQuota';
import { createLambdaFileStorePort } from '@/modules/heterogeneousAgent/fileStorePort';
import {
createQuotaCacheKey,
@@ -215,6 +219,13 @@ interface GetCodexQuotaParams {
force?: boolean;
}
+interface ConsumeCodexRateLimitResetCreditParams {
+ command?: string;
+ creditId?: string;
+ env?: Record<string, string>;
+ idempotencyKey: string;
+}
+
interface GetClaudeCodeQuotaParams {
env?: Record<string, string>;
force?: boolean;
@@ -1598,6 +1609,43 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
);
}
+ /**
+ * Redeem one earned Codex rate-limit reset, then bypass the quota cache so
+ * every renderer receives the post-reset windows and remaining inventory.
+ */
+ @IpcMethod()
+ async consumeCodexRateLimitResetCredit(
+ params: ConsumeCodexRateLimitResetCreditParams,
+ ): Promise<CodexRateLimitResetResult> {
+ const command = params.command?.trim() || 'codex';
+ const sourceEnv = {
+ ...buildProxyEnv(this.app.storeManager.get('networkProxy')),
+ ...params.env,
+ };
+ const sourceKey = createQuotaCacheKey('codex', command, sourceEnv);
+ const status = await detectHeterogeneousCliCommand('codex', command);
+ const env = {
+ ...(status.resolvedPathEnv ? { PATH: status.resolvedPathEnv } : {}),
+ ...sourceEnv,
+ };
+ const requestOptions = {
+ command: status.available && status.path ? status.path : command,
+ env: Object.keys(env).length > 0 ? env : undefined,
+ };
+
+ const outcome = await consumeCodexRateLimitResetCreditRequest({
+ ...requestOptions,
+ creditId: params.creditId,
+ idempotencyKey: params.idempotencyKey,
+ });
+ this.codexQuotaCache.invalidate(sourceKey);
+ const quota = await this.codexQuotaCache.get(sourceKey, () => fetchCodexQuota(requestOptions), {
+ force: true,
+ });
+
+ return { outcome, quota };
+ }
+
/**
* Read the Claude Code subscription quota. No CLI is spawned: the quota
* comes from Anthropic's OAuth usage API using the local `claude` login,
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index c5d11b91ccf..0aacd195c22 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -4,6 +4,7 @@ import * as os from 'node:os';
import path from 'node:path';
import { PassThrough } from 'node:stream';
+import type { CodexQuotaSnapshot } from '@lobechat/electron-client-ipc';
import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';
// `electron` is mocked below; this binding is the mock object so tests can
// flip `isPackaged` to exercise the packaged-build tracing gate.
@@ -103,11 +104,13 @@ vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {
};
});
-const { fetchCodexQuotaMock } = vi.hoisted(() => ({
+const { consumeCodexRateLimitResetCreditMock, fetchCodexQuotaMock } = vi.hoisted(() => ({
+ consumeCodexRateLimitResetCreditMock: vi.fn(),
fetchCodexQuotaMock: vi.fn(),
}));
vi.mock('@/modules/heterogeneousAgent/codexQuota', () => ({
+ consumeCodexRateLimitResetCredit: consumeCodexRateLimitResetCreditMock,
fetchCodexQuota: fetchCodexQuotaMock,
}));
@@ -190,6 +193,7 @@ describe('HeterogeneousAgentCtr', () => {
beforeEach(async () => {
originalClaudeSdkLabEnv = process.env.LOBE_CLAUDE_CODE_SDK;
appStoragePath = await mkdtemp(path.join(os.tmpdir(), 'lobehub-hetero-'));
+ consumeCodexRateLimitResetCreditMock.mockReset();
fetchCodexQuotaMock.mockReset();
claudeSdkSessionCloseMock.mockReset();
claudeSdkSessionConstructMock.mockReset();
@@ -376,6 +380,128 @@ describe('HeterogeneousAgentCtr', () => {
expect(fetchCodexQuotaMock).toHaveBeenCalledTimes(2);
});
+
+ it('consumes a reset credit and replaces the cached quota with a fresh snapshot', async () => {
+ execFileMock.mockImplementation(
+ (
+ _file: string,
+ _args: string[],
+ optionsOrCallback: unknown,
+ callback?: (error: Error | null, result: { stderr: string; stdout: string }) => void,
+ ) => {
+ const resolvedCallback =
+ typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
+ resolvedCallback?.(null, { stderr: '', stdout: 'codex-cli 0.99.0' });
+ },
+ );
+ const initialQuota = {
+ error: null,
+ provider: 'codex',
+ rateLimitResetCredits: { availableCount: 2 },
+ session: { resetsAt: null, usedPercent: 96, windowMinutes: 300 },
+ status: 'ok',
+ updatedAt: 1,
+ weekly: null,
+ };
+ const refreshedQuota = {
+ ...initialQuota,
+ rateLimitResetCredits: { availableCount: 1 },
+ session: { resetsAt: null, usedPercent: 0, windowMinutes: 300 },
+ updatedAt: 2,
+ };
+ fetchCodexQuotaMock.mockResolvedValueOnce(initialQuota).mockResolvedValueOnce(refreshedQuota);
+ consumeCodexRateLimitResetCreditMock.mockResolvedValue('reset');
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const source = {
+ command: '/custom/bin/codex',
+ env: { CODEX_HOME: '/tmp/codex-home' },
+ };
+
+ await ctr.getCodexQuota(source);
+ await expect(
+ ctr.consumeCodexRateLimitResetCredit({
+ ...source,
+ creditId: 'credit-first',
+ idempotencyKey: 'redeem-request-1',
+ }),
+ ).resolves.toEqual({ outcome: 'reset', quota: refreshedQuota });
+
+ expect(consumeCodexRateLimitResetCreditMock).toHaveBeenCalledWith({
+ command: '/custom/bin/codex',
+ creditId: 'credit-first',
+ env: { CODEX_HOME: '/tmp/codex-home' },
+ idempotencyKey: 'redeem-request-1',
+ });
+ expect(fetchCodexQuotaMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('bypasses an in-flight pre-reset quota read after consuming a credit', async () => {
+ execFileMock.mockImplementation(
+ (
+ _file: string,
+ _args: string[],
+ optionsOrCallback: unknown,
+ callback?: (error: Error | null, result: { stderr: string; stdout: string }) => void,
+ ) => {
+ const resolvedCallback =
+ typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
+ resolvedCallback?.(null, { stderr: '', stdout: 'codex-cli 0.99.0' });
+ },
+ );
+ const refreshedAt = Date.now();
+ const staleQuota = {
+ error: null,
+ provider: 'codex',
+ rateLimitResetCredits: { availableCount: 2 },
+ session: { resetsAt: null, usedPercent: 96, windowMinutes: 300 },
+ status: 'ok',
+ updatedAt: refreshedAt - 1,
+ weekly: null,
+ } satisfies CodexQuotaSnapshot;
+ const refreshedQuota = {
+ ...staleQuota,
+ rateLimitResetCredits: { availableCount: 1 },
+ session: { resetsAt: null, usedPercent: 0, windowMinutes: 300 },
+ updatedAt: refreshedAt,
+ } satisfies CodexQuotaSnapshot;
+ let resolveStaleQuota: ((quota: CodexQuotaSnapshot) => void) | undefined;
+ fetchCodexQuotaMock
+ .mockImplementationOnce(
+ () =>
+ new Promise<CodexQuotaSnapshot>((resolve) => {
+ resolveStaleQuota = resolve;
+ }),
+ )
+ .mockResolvedValueOnce(refreshedQuota);
+ consumeCodexRateLimitResetCreditMock.mockResolvedValue('reset');
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const source = {
+ command: '/custom/bin/codex',
+ env: { CODEX_HOME: '/tmp/codex-home' },
+ };
+
+ const staleRequest = ctr.getCodexQuota(source);
+ await vi.waitFor(() => expect(fetchCodexQuotaMock).toHaveBeenCalledTimes(1));
+
+ await expect(
+ ctr.consumeCodexRateLimitResetCredit({
+ ...source,
+ creditId: 'credit-first',
+ idempotencyKey: 'redeem-request-2',
+ }),
+ ).resolves.toEqual({ outcome: 'reset', quota: refreshedQuota });
+
+ resolveStaleQuota?.(staleQuota);
+ await expect(staleRequest).resolves.toEqual(staleQuota);
+ await expect(ctr.getCodexQuota(source)).resolves.toEqual(refreshedQuota);
+ expect(fetchCodexQuotaMock).toHaveBeenCalledTimes(2);
+ });
});
describe('sendPrompt (claude-code)', () => {
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/codexQuota.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/codexQuota.test.ts
index 99f80c2c1b6..e99af6b2ab6 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/codexQuota.test.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/codexQuota.test.ts
@@ -3,7 +3,7 @@ import { readFile } from 'node:fs/promises';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { fetchCodexQuota } from './codexQuota';
+import { consumeCodexRateLimitResetCredit, fetchCodexQuota } from './codexQuota';
vi.mock('node:fs/promises', () => ({
readFile: vi.fn(),
@@ -25,7 +25,10 @@ class RpcChild extends EventEmitter {
kill = vi.fn();
}
-const mockRpcRateLimits = (child: RpcChild, result: unknown) => {
+const mockRpcMethods = (
+ child: RpcChild,
+ methods: Record<string, { error?: string; result?: unknown }>,
+) => {
child.stdin.write.mockImplementation((line: string) => {
const message = JSON.parse(line) as { id?: number; method?: string };
@@ -38,15 +41,17 @@ const mockRpcRateLimits = (child: RpcChild, result: unknown) => {
}, 0);
}
- if (message.method === 'account/rateLimits/read') {
+ const response = message.method ? methods[message.method] : undefined;
+ if (response) {
setTimeout(() => {
child.stdout.emit(
'data',
Buffer.from(
`${JSON.stringify({
+ ...(response.error ? { error: { message: response.error } } : {}),
jsonrpc: '2.0',
id: message.id,
- result,
+ ...(!response.error ? { result: response.result } : {}),
})}\n`,
),
);
@@ -55,6 +60,9 @@ const mockRpcRateLimits = (child: RpcChild, result: unknown) => {
});
};
+const mockRpcRateLimits = (child: RpcChild, result: unknown) =>
+ mockRpcMethods(child, { 'account/rateLimits/read': { result } });
+
describe('fetchCodexQuota', () => {
beforeEach(() => {
vi.useFakeTimers();
@@ -87,19 +95,30 @@ describe('fetchCodexQuota', () => {
total_earned_count: 3,
credits: [
{
+ description: 'Use this when a Codex limit is exhausted.',
status: 'available',
expires_at: '2026-06-25T12:00:00Z',
granted_at: '2026-06-18T12:00:00Z',
+ id: 'credit-later',
+ reset_type: 'codex_all_limits',
+ title: 'Codex reset',
},
{
+ description: 'Expires first.',
status: 'available',
expires_at: '2026-06-24T12:00:00Z',
granted_at: '2026-06-17T12:00:00Z',
+ id: 'credit-first',
+ reset_type: 'codex_all_limits',
+ title: 'Early reset',
},
{
status: 'redeemed',
expires_at: '2026-06-23T12:00:00Z',
granted_at: '2026-06-16T12:00:00Z',
+ id: 'credit-used',
+ redeem_started_at: '2026-06-19T10:00:00Z',
+ redeemed_at: '2026-06-19T10:01:00Z',
},
],
}),
@@ -135,10 +154,32 @@ describe('fetchCodexQuota', () => {
},
rateLimitResetCredits: {
availableCount: 2,
+ credits: [
+ expect.objectContaining({
+ expiresAt: Date.parse('2026-06-25T12:00:00Z'),
+ grantedAt: Date.parse('2026-06-18T12:00:00Z'),
+ id: 'credit-later',
+ resetType: 'codex_all_limits',
+ status: 'available',
+ title: 'Codex reset',
+ }),
+ expect.objectContaining({
+ expiresAt: Date.parse('2026-06-24T12:00:00Z'),
+ id: 'credit-first',
+ title: 'Early reset',
+ }),
+ expect.objectContaining({
+ id: 'credit-used',
+ redeemStartedAt: Date.parse('2026-06-19T10:00:00Z'),
+ redeemedAt: Date.parse('2026-06-19T10:01:00Z'),
+ status: 'redeemed',
+ }),
+ ],
totalEarnedCount: 3,
nextExpiresAt: Date.parse('2026-06-24T12:00:00Z'),
},
});
+ expect(result.rateLimitResetCredits?.credits?.[0]).not.toHaveProperty('description');
expect(readFile).toHaveBeenCalledWith('/tmp/codex-home/auth.json', 'utf8');
expect(spawnMock).toHaveBeenCalledWith(
'/custom/bin/codex',
@@ -154,7 +195,7 @@ describe('fetchCodexQuota', () => {
'https://chatgpt.com/backend-api/wham/rate-limit-reset-credits',
expect.objectContaining({
headers: expect.objectContaining({
- Authorization: 'Bearer access-token',
+ 'Authorization': 'Bearer access-token',
'ChatGPT-Account-Id': 'account-id',
'OpenAI-Beta': 'codex-1',
}),
@@ -173,6 +214,17 @@ describe('fetchCodexQuota', () => {
},
rateLimitResetCredits: {
availableCount: 1,
+ credits: [
+ {
+ description: 'RPC detail',
+ expiresAt: '2026-06-27T12:00:00Z',
+ grantedAt: '2026-06-20T10:00:00Z',
+ id: 'rpc-credit',
+ resetType: 'codex_all_limits',
+ status: 'AVAILABLE',
+ title: 'RPC reset',
+ },
+ ],
},
});
@@ -196,8 +248,84 @@ describe('fetchCodexQuota', () => {
},
rateLimitResetCredits: {
availableCount: 1,
+ credits: [
+ expect.objectContaining({
+ expiresAt: Date.parse('2026-06-27T12:00:00Z'),
+ grantedAt: Date.parse('2026-06-20T10:00:00Z'),
+ id: 'rpc-credit',
+ resetType: 'codex_all_limits',
+ status: 'available',
+ title: 'RPC reset',
+ }),
+ ],
+ nextExpiresAt: Date.parse('2026-06-27T12:00:00Z'),
+ },
+ });
+ expect(result.rateLimitResetCredits?.credits?.[0]).not.toHaveProperty('description');
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it('maps and deduplicates every app-server rate-limit bucket', async () => {
+ const child = new RpcChild();
+ spawnMock.mockReturnValue(child);
+ vi.mocked(readFile).mockRejectedValue(new Error('ENOENT'));
+ mockRpcRateLimits(child, {
+ rateLimits: {
+ limitId: 'codex',
+ limitName: 'Codex',
+ primary: { resetsAt: 1_718_800_000, usedPercent: 12, windowDurationMins: 300 },
+ secondary: { resetsAt: 1_719_300_000, usedPercent: 24, windowDurationMins: 10_080 },
+ },
+ rateLimitsByLimitId: {
+ codex: {
+ limitId: 'codex',
+ primary: { resetsAt: 1_718_800_100, usedPercent: 99, windowDurationMins: 300 },
+ },
+ codex_other: {
+ limitName: 'Codex Other',
+ primary: { resetsAt: 1_718_900_000, usedPercent: 98, windowDurationMins: 60 },
+ secondary: { resetsAt: 1_721_400_000, usedPercent: 40, windowDurationMins: 43_200 },
+ },
},
});
+
+ const resultPromise = fetchCodexQuota({ command: '/custom/bin/codex' });
+ await vi.advanceTimersByTimeAsync(1);
+ await vi.advanceTimersByTimeAsync(1);
+ const result = await resultPromise;
+
+ expect(result.rateLimits).toEqual([
+ {
+ limitId: 'codex',
+ limitName: 'Codex',
+ primary: {
+ resetsAt: 1_718_800_000 * 1000,
+ usedPercent: 12,
+ windowMinutes: 300,
+ },
+ secondary: {
+ resetsAt: 1_719_300_000 * 1000,
+ usedPercent: 24,
+ windowMinutes: 10_080,
+ },
+ },
+ {
+ limitId: 'codex_other',
+ limitName: 'Codex Other',
+ primary: {
+ resetsAt: 1_718_900_000 * 1000,
+ usedPercent: 98,
+ windowMinutes: 60,
+ },
+ secondary: {
+ resetsAt: 1_721_400_000 * 1000,
+ usedPercent: 40,
+ windowMinutes: 43_200,
+ },
+ },
+ ]);
+ expect(result.session).toEqual(result.rateLimits?.[0].primary);
+ expect(result.weekly).toEqual(result.rateLimits?.[0].secondary);
expect(fetch).not.toHaveBeenCalled();
});
@@ -225,7 +353,7 @@ describe('fetchCodexQuota', () => {
const resultPromise = fetchCodexQuota({ command: '/custom/bin/codex' });
await vi.advanceTimersByTimeAsync(1);
await vi.advanceTimersByTimeAsync(1);
- await vi.advanceTimersByTimeAsync(2000);
+ await vi.advanceTimersByTimeAsync(5001);
const result = await resultPromise;
expect(result).toMatchObject({
@@ -256,4 +384,78 @@ describe('fetchCodexQuota', () => {
}),
);
});
+
+ it('consumes a specific reset credit through the Codex app-server', async () => {
+ const child = new RpcChild();
+ spawnMock.mockReturnValue(child);
+ vi.mocked(readFile).mockRejectedValue(new Error('ENOENT'));
+ mockRpcMethods(child, {
+ 'account/rateLimitResetCredit/consume': { result: { outcome: 'reset' } },
+ });
+
+ const resultPromise = consumeCodexRateLimitResetCredit({
+ command: '/custom/bin/codex',
+ creditId: 'credit-first',
+ idempotencyKey: 'redeem-request-1',
+ });
+ await vi.advanceTimersByTimeAsync(1);
+ await vi.advanceTimersByTimeAsync(1);
+
+ await expect(resultPromise).resolves.toBe('reset');
+ const consumeMessage = child.stdin.write.mock.calls
+ .map(([line]) => JSON.parse(line as string))
+ .find((message) => message.method === 'account/rateLimitResetCredit/consume');
+ expect(consumeMessage).toMatchObject({
+ params: {
+ creditId: 'credit-first',
+ idempotencyKey: 'redeem-request-1',
+ },
+ });
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it('falls back to the backend consume endpoint with the same idempotency key', async () => {
+ const child = new RpcChild();
+ spawnMock.mockReturnValue(child);
+ vi.mocked(readFile).mockResolvedValue(
+ JSON.stringify({
+ tokens: {
+ access_token: 'access-token',
+ account_id: 'account-id',
+ },
+ }),
+ );
+ mockRpcMethods(child, {
+ 'account/rateLimitResetCredit/consume': { error: 'Method not found' },
+ });
+ vi.mocked(fetch).mockResolvedValue({
+ json: async () => ({ code: 'already_redeemed' }),
+ ok: true,
+ } as Response);
+
+ const resultPromise = consumeCodexRateLimitResetCredit({
+ command: '/custom/bin/codex',
+ creditId: 'credit-first',
+ idempotencyKey: 'redeem-request-2',
+ });
+ await vi.advanceTimersByTimeAsync(1);
+ await vi.advanceTimersByTimeAsync(1);
+
+ await expect(resultPromise).resolves.toBe('alreadyRedeemed');
+ expect(fetch).toHaveBeenCalledWith(
+ 'https://chatgpt.com/backend-api/wham/rate-limit-reset-credits/consume',
+ expect.objectContaining({
+ body: JSON.stringify({
+ credit_id: 'credit-first',
+ redeem_request_id: 'redeem-request-2',
+ }),
+ headers: expect.objectContaining({
+ 'Authorization': 'Bearer access-token',
+ 'ChatGPT-Account-Id': 'account-id',
+ 'Content-Type': 'application/json',
+ }),
+ method: 'POST',
+ }),
+ );
+ });
});
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/codexQuota.ts b/apps/desktop/src/main/modules/heterogeneousAgent/codexQuota.ts
index 7868d655401..b0296caa002 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/codexQuota.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/codexQuota.ts
@@ -4,39 +4,24 @@ 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 { resolveCliSpawnPlan } from '@lobechat/heterogeneous-agents/spawn';
const RPC_TIMEOUT_MS = 10_000;
-const RESET_CREDITS_TIMEOUT_MS = 1_500;
+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';
-
-export interface CodexQuotaWindow {
- resetsAt: number | null;
- usedPercent: number;
- windowMinutes: number;
-}
-
-export interface CodexRateLimitResetCredits {
- availableCount: number;
- credits?: {
- expiresAt: number | null;
- grantedAt: number | null;
- status: string;
- }[];
- nextExpiresAt?: number | null;
- totalEarnedCount?: number;
-}
-
-export interface CodexQuotaSnapshot {
- error: string | null;
- provider: 'codex';
- rateLimitResetCredits?: CodexRateLimitResetCredits | null;
- session: CodexQuotaWindow | null;
- status: 'error' | 'ok' | 'unavailable';
- updatedAt: number;
- weekly: CodexQuotaWindow | null;
-}
+const CODEX_RATE_LIMIT_RESET_CONSUME_URL = `${CODEX_RATE_LIMIT_RESET_CREDITS_URL}/consume`;
export interface FetchCodexQuotaOptions {
codexHomePath?: string | null;
@@ -44,6 +29,11 @@ export interface FetchCodexQuotaOptions {
env?: NodeJS.ProcessEnv;
}
+export interface ConsumeCodexRateLimitResetCreditOptions extends FetchCodexQuotaOptions {
+ creditId?: string;
+ idempotencyKey: string;
+}
+
interface RpcResponse {
error?: { message?: string };
id?: number;
@@ -56,21 +46,33 @@ interface RpcRateWindow {
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?: {
- expiresAt?: number | string | null;
- grantedAt?: number | string | null;
- status?: string;
- }[];
+ credits?: RpcRateLimitResetCredit[] | null;
nextExpiresAt?: number | string | null;
totalEarnedCount?: number;
} | null;
- rateLimits?: {
- primary?: RpcRateWindow;
- secondary?: RpcRateWindow;
- };
+ rateLimits?: RpcRateLimitSnapshot;
+ rateLimitsByLimitId?: Record<string, RpcRateLimitSnapshot> | null;
}
interface CodexAuthFile {
@@ -85,11 +87,24 @@ interface BackendRateLimitResetCreditsResponse {
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>;
}
@@ -127,11 +142,47 @@ const parseCreditTimestamp = (value: number | string | null | undefined): number
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')
+ ?.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;
@@ -142,11 +193,7 @@ const mapRpcResetCredits = (
if (raw === undefined) return undefined;
if (typeof raw.availableCount !== 'number' || !Number.isFinite(raw.availableCount)) return null;
- const credits = raw.credits?.map((credit) => ({
- expiresAt: parseCreditTimestamp(credit.expiresAt),
- grantedAt: parseCreditTimestamp(credit.grantedAt),
- status: normalizeCreditStatus(credit.status),
- }));
+ const credits = Array.isArray(raw.credits) ? raw.credits.map(mapRpcResetCredit) : undefined;
return {
availableCount: Math.max(0, Math.floor(raw.availableCount)),
@@ -163,11 +210,7 @@ const mapBackendResetCredits = (
): CodexRateLimitResetCredits | null => {
if (!raw) return null;
- const credits = raw.credits?.map((credit) => ({
- expiresAt: parseCreditTimestamp(credit.expires_at),
- grantedAt: parseCreditTimestamp(credit.granted_at),
- status: normalizeCreditStatus(credit.status),
- }));
+ const credits = raw.credits?.map(mapBackendResetCredit);
const availableCount =
typeof raw.available_count === 'number' && Number.isFinite(raw.available_count)
? raw.available_count
@@ -201,10 +244,10 @@ const readCodexBackendAuth = async (
if (!accessToken) return null;
const headers: Record<string, string> = {
- Authorization: `Bearer ${accessToken}`,
+ 'Authorization': `Bearer ${accessToken}`,
'OpenAI-Beta': 'codex-1',
'User-Agent': 'codex-cli',
- originator: 'LobeHub Desktop',
+ 'originator': 'LobeHub Desktop',
};
if (auth.tokens?.account_id) {
@@ -244,6 +287,60 @@ const fetchBackendResetCredits = async (
}
};
+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,
@@ -260,15 +357,51 @@ const mapRpcWindow = (
: fallbackWindowMinutes;
return {
- resetsAt:
- typeof raw.resetsAt === 'number' && Number.isFinite(raw.resetsAt)
- ? raw.resetsAt * 1000
- : null,
+ 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: {
@@ -284,25 +417,32 @@ const cleanupRpcListeners = (
child.off('close', listeners.close);
};
-const fetchViaRpc = async (
+interface RpcRequestConfig {
+ failureMessage: string;
+ method: string;
+ params?: unknown;
+ timeoutMs?: number;
+}
+
+const requestViaRpc = async <T>(
options: FetchCodexQuotaOptions,
- auth: CodexBackendAuth | null,
-): Promise<CodexQuotaSnapshot> =>
- new Promise<CodexQuotaSnapshot>((resolve) => {
+ { failureMessage, method, params, timeoutMs = RPC_TIMEOUT_MS }: RpcRequestConfig,
+): Promise<T> =>
+ new Promise<T>((resolve, reject) => {
let buffer = '';
let child: ChildProcess | null = null;
- let initId = 0;
+ let initId: number | null = null;
let stderr = '';
- let resolved = false;
+ let finished = false;
+ let requestId: number | null = null;
let rpcId = 0;
- let rateLimitsId: number | null = null;
let timeout: ReturnType<typeof setTimeout> | undefined;
const rpcArgs = ['-s', 'read-only', '-a', 'untrusted', 'app-server'];
- const settle = (result: CodexQuotaSnapshot, kill = false) => {
- if (resolved) return;
- resolved = true;
+ const cleanup = (kill: boolean) => {
+ if (finished) return false;
+ finished = true;
if (timeout) {
clearTimeout(timeout);
timeout = undefined;
@@ -311,6 +451,16 @@ const fetchViaRpc = async (
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);
};
@@ -324,41 +474,7 @@ const fetchViaRpc = async (
child.stdin?.write(`${JSON.stringify({ jsonrpc: '2.0', method, params: {} })}\n`);
};
- const handleRateLimitsResponse = async (message: RpcResponse) => {
- if (message.error) {
- settle(errorSnapshot(message.error.message ?? 'Codex rate-limit RPC failed'), true);
- return;
- }
-
- const wrapper = message.result as RpcRateLimitsResponse | undefined;
- const rateLimitResetCredits = mapRpcResetCredits(wrapper?.rateLimitResetCredits);
- let backendCredits: CodexRateLimitResetCredits | null = null;
-
- if (auth && rateLimitResetCredits?.nextExpiresAt == null) {
- try {
- backendCredits = await fetchBackendResetCredits(auth);
- } catch {
- backendCredits = null;
- }
- }
-
- settle(
- {
- error: null,
- provider: 'codex',
- rateLimitResetCredits:
- backendCredits ??
- (rateLimitResetCredits === undefined ? undefined : rateLimitResetCredits),
- session: mapRpcWindow(wrapper?.rateLimits?.primary, 300),
- status: 'ok',
- updatedAt: Date.now(),
- weekly: mapRpcWindow(wrapper?.rateLimits?.secondary, 10_080),
- },
- true,
- );
- };
-
- const onStdoutData = (child: ChildProcess) => (chunk: Buffer) => {
+ const onStdoutData = (chunk: Buffer) => {
buffer += chunk.toString();
let newlineIndex: number;
@@ -370,14 +486,25 @@ const fetchViaRpc = async (
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');
- rateLimitsId = sendRpc(child, 'account/rateLimits/read');
+ requestId = sendRpc(child, method, params);
continue;
}
- if (rateLimitsId !== null && message.id === rateLimitsId) {
- void handleRateLimitsResponse(message);
+ 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.
@@ -390,21 +517,19 @@ const fetchViaRpc = async (
};
const listeners = {
- close: () => settle(errorSnapshot(stderr || 'Codex rate-limit RPC exited'), false),
- error: (error: Error) => settle(errorSnapshot(error.message), false),
+ close: () => settleError(new Error(stderr.trim() || `${failureMessage}: RPC exited`), false),
+ error: (error: Error) => settleError(error, false),
stderrData: onStderrData,
- stdoutData: (chunk: Buffer) => {
- if (child) onStdoutData(child)(chunk);
- },
+ stdoutData: onStdoutData,
};
timeout = setTimeout(() => {
- settle(errorSnapshot('Codex rate-limit RPC timed out'), true);
- }, RPC_TIMEOUT_MS);
+ settleError(new Error(`${failureMessage}: RPC timed out`), true);
+ }, timeoutMs);
void resolveCliSpawnPlan(options.command ?? 'codex', rpcArgs)
.then((spawnPlan) => {
- if (resolved) return;
+ if (finished) return;
child = spawn(spawnPlan.command, spawnPlan.args, {
env: {
@@ -425,13 +550,91 @@ const fetchViaRpc = async (
})
.catch((error: unknown) => {
const message = error instanceof Error ? error.message : 'Failed to resolve Codex command';
- settle(errorSnapshot(message), true);
+ 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);
+ }
+};
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/quotaSnapshotCache.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/quotaSnapshotCache.test.ts
index ce011634207..2fb347de1b7 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/quotaSnapshotCache.test.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/quotaSnapshotCache.test.ts
@@ -75,6 +75,32 @@ describe('QuotaSnapshotCache', () => {
expect(fetchSnapshot).toHaveBeenCalledTimes(2);
});
+ it('starts a new read after invalidating an in-flight entry', async () => {
+ const cache = new QuotaSnapshotCache<TestQuotaSnapshot>();
+ const requests: Array<(value: TestQuotaSnapshot) => void> = [];
+ const fetchSnapshot = vi.fn(
+ () =>
+ new Promise<TestQuotaSnapshot>((resolve) => {
+ requests.push(resolve);
+ }),
+ );
+
+ const staleRequest = cache.get('source', fetchSnapshot);
+ cache.invalidate('source');
+ const freshRequest = cache.get('source', fetchSnapshot);
+
+ expect(fetchSnapshot).toHaveBeenCalledTimes(2);
+
+ requests[1](snapshot({ session: 90 }));
+ await expect(freshRequest).resolves.toMatchObject({ session: 90 });
+
+ requests[0](snapshot({ session: 10 }));
+ await expect(staleRequest).resolves.toMatchObject({ session: 10 });
+
+ await expect(cache.get('source', fetchSnapshot)).resolves.toMatchObject({ session: 90 });
+ expect(fetchSnapshot).toHaveBeenCalledTimes(2);
+ });
+
it('evicts entries after their inactivity TTL expires', async () => {
const cache = new QuotaSnapshotCache<TestQuotaSnapshot>({
entryTtlMs: 1_000,
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/quotaSnapshotCache.ts b/apps/desktop/src/main/modules/heterogeneousAgent/quotaSnapshotCache.ts
index bc66d840ad1..b2b106c8ee7 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/quotaSnapshotCache.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/quotaSnapshotCache.ts
@@ -68,6 +68,15 @@ export class QuotaSnapshotCache<S extends CacheableQuotaSnapshot> {
this.staleMs = config.staleMs ?? DEFAULT_STALE_MS;
}
+ /**
+ * Detach the current entry so the next read cannot join an older in-flight
+ * request. Any detached request may still settle for its original caller,
+ * but it can no longer update or replace the active cache entry.
+ */
+ invalidate(key: string) {
+ this.entries.delete(key);
+ }
+
async get(
key: string,
fetchSnapshot: () => Promise<S>,
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 70a689abc49..ea6009414d3 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -317,14 +317,29 @@
"heteroAgent.cloudRepo.noRepos": "No repositories configured. Add them in agent settings.",
"heteroAgent.cloudRepo.notSet": "No repo selected",
"heteroAgent.cloudRepo.sectionTitle": "Repositories",
+ "heteroAgent.codexQuota.doesNotExpire": "Does not expire",
"heteroAgent.codexQuota.expiresIn": "Expires in {{duration}}",
- "heteroAgent.codexQuota.nextExpiresIn": "Next expires in {{duration}}",
+ "heteroAgent.codexQuota.expiresSoon": "Expires soon",
+ "heteroAgent.codexQuota.fiveHour": "5-hour",
+ "heteroAgent.codexQuota.monthly": "Monthly",
+ "heteroAgent.codexQuota.resetConfirmDescription": "This uses one reset credit and immediately resets every eligible Codex usage window.",
+ "heteroAgent.codexQuota.resetConfirmTitle": "Reset Codex limits?",
+ "heteroAgent.codexQuota.resetCreditDetailsUnavailable": "Details unavailable",
+ "heteroAgent.codexQuota.resetCreditTitle": "Codex usage reset",
"heteroAgent.codexQuota.resetCreditsUnavailable": "Reset credits unavailable",
"heteroAgent.codexQuota.resetCredits_one": "1 rate-limit reset available",
"heteroAgent.codexQuota.resetCredits_other": "{{count}} rate-limit resets available",
"heteroAgent.codexQuota.resetCredits_zero": "No rate-limit resets available",
+ "heteroAgent.codexQuota.resetFailed": "Couldn't reset Codex usage. Try again.",
+ "heteroAgent.codexQuota.resetNoCredit": "No reset credits are available. Quota has been refreshed.",
+ "heteroAgent.codexQuota.resetNothingToReset": "No Codex usage window needs a reset right now. No reset was used.",
+ "heteroAgent.codexQuota.resetNow": "Reset Codex limits",
+ "heteroAgent.codexQuota.resetSuccess": "Codex usage limits reset.",
+ "heteroAgent.codexQuota.resetting": "Resetting…",
"heteroAgent.codexQuota.title": "Codex quota",
"heteroAgent.codexQuota.tooltip": "View Codex quota",
+ "heteroAgent.codexQuota.totalEarned_one": "{{count}} earned in total",
+ "heteroAgent.codexQuota.totalEarned_other": "{{count}} earned in total",
"heteroAgent.executionTarget.ampSandboxUnsupported": "Amp currently runs only on a local or connected device",
"heteroAgent.executionTarget.auto": "Auto",
"heteroAgent.executionTarget.autoDesc": "Use an online device automatically, picking one when several are available",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 3ac4bf8b83c..f71d838c5f1 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -317,14 +317,29 @@
"heteroAgent.cloudRepo.noRepos": "未配置仓库,请在助理设置中添加。",
"heteroAgent.cloudRepo.notSet": "未选择仓库",
"heteroAgent.cloudRepo.sectionTitle": "代码仓库",
+ "heteroAgent.codexQuota.doesNotExpire": "永不过期",
"heteroAgent.codexQuota.expiresIn": "{{duration}}后过期",
- "heteroAgent.codexQuota.nextExpiresIn": "下一次将在 {{duration}}后过期",
+ "heteroAgent.codexQuota.expiresSoon": "即将过期",
+ "heteroAgent.codexQuota.fiveHour": "5 小时",
+ "heteroAgent.codexQuota.monthly": "每月",
+ "heteroAgent.codexQuota.resetConfirmDescription": "这会消耗 1 次额度重置,并立即重置所有符合条件的 Codex 使用周期。",
+ "heteroAgent.codexQuota.resetConfirmTitle": "重置 Codex 使用限额?",
+ "heteroAgent.codexQuota.resetCreditDetailsUnavailable": "暂无详细信息",
+ "heteroAgent.codexQuota.resetCreditTitle": "Codex 额度重置",
"heteroAgent.codexQuota.resetCreditsUnavailable": "额度重置次数不可用",
"heteroAgent.codexQuota.resetCredits_one": "1 次可用额度重置",
"heteroAgent.codexQuota.resetCredits_other": "{{count}} 次可用额度重置",
"heteroAgent.codexQuota.resetCredits_zero": "暂无可用额度重置",
+ "heteroAgent.codexQuota.resetFailed": "无法重置 Codex 额度,请重试。",
+ "heteroAgent.codexQuota.resetNoCredit": "暂无可用额度重置,额度信息已刷新。",
+ "heteroAgent.codexQuota.resetNothingToReset": "当前没有需要重置的 Codex 使用周期,未消耗重置次数。",
+ "heteroAgent.codexQuota.resetNow": "重置 Codex 限额",
+ "heteroAgent.codexQuota.resetSuccess": "Codex 使用限额已重置。",
+ "heteroAgent.codexQuota.resetting": "正在重置…",
"heteroAgent.codexQuota.title": "Codex 额度",
"heteroAgent.codexQuota.tooltip": "查看 Codex 额度",
+ "heteroAgent.codexQuota.totalEarned_one": "累计获得 {{count}} 次",
+ "heteroAgent.codexQuota.totalEarned_other": "累计获得 {{count}} 次",
"heteroAgent.executionTarget.ampSandboxUnsupported": "Amp 目前仅支持在本地设备或已连接设备上运行",
"heteroAgent.executionTarget.auto": "自动",
"heteroAgent.executionTarget.autoDesc": "自动使用在线设备,有多台时择一使用",
diff --git a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
index e48c652a916..4ae46f5857c 100644
--- a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
+++ b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
@@ -50,13 +50,30 @@ export interface HeteroQuotaWindow {
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;
- credits?: {
- expiresAt: number | null;
- grantedAt: number | null;
- status: string;
- }[];
+ /** Detailed rows when supported by the installed Codex CLI/backend. */
+ credits?: CodexRateLimitResetCredit[];
nextExpiresAt?: number | null;
totalEarnedCount?: number;
}
@@ -65,12 +82,22 @@ 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 interface CodexRateLimitResetResult {
+ outcome: CodexRateLimitResetOutcome;
+ quota: CodexQuotaSnapshot;
+}
+
/**
* Why the quota can't be shown. `external-auth` means the agent is configured
* with an API key / custom base url, so subscription quota does not apply;
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 124087e1e87..d7c5303eb52 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -298,13 +298,31 @@ export default {
'heteroAgent.claudeSdkRuntime.state.stale': 'SDK stale',
'heteroAgent.claudeSdkRuntime.state.starting': 'SDK starting',
'heteroAgent.claudeSdkRuntime.tooltip': '{{state}}. Active background tasks: {{count}}.',
+ 'heteroAgent.codexQuota.doesNotExpire': 'Does not expire',
'heteroAgent.codexQuota.expiresIn': 'Expires in {{duration}}',
- 'heteroAgent.codexQuota.nextExpiresIn': 'Next expires in {{duration}}',
+ 'heteroAgent.codexQuota.expiresSoon': 'Expires soon',
+ 'heteroAgent.codexQuota.fiveHour': '5-hour',
+ 'heteroAgent.codexQuota.monthly': 'Monthly',
+ 'heteroAgent.codexQuota.resetConfirmDescription':
+ 'This uses one reset credit and immediately resets every eligible Codex usage window.',
+ 'heteroAgent.codexQuota.resetConfirmTitle': 'Reset Codex limits?',
+ 'heteroAgent.codexQuota.resetCreditDetailsUnavailable': 'Details unavailable',
+ 'heteroAgent.codexQuota.resetCreditTitle': 'Codex usage reset',
'heteroAgent.codexQuota.resetCredits_one': '1 rate-limit reset available',
'heteroAgent.codexQuota.resetCredits_other': '{{count}} rate-limit resets available',
'heteroAgent.codexQuota.resetCredits_zero': 'No rate-limit resets available',
'heteroAgent.codexQuota.resetCreditsUnavailable': 'Reset credits unavailable',
+ 'heteroAgent.codexQuota.resetFailed': "Couldn't reset Codex usage. Try again.",
+ 'heteroAgent.codexQuota.resetNoCredit':
+ 'No reset credits are available. Quota has been refreshed.',
+ 'heteroAgent.codexQuota.resetNothingToReset':
+ 'No Codex usage window needs a reset right now. No reset was used.',
+ 'heteroAgent.codexQuota.resetNow': 'Reset Codex limits',
+ 'heteroAgent.codexQuota.resetSuccess': 'Codex usage limits reset.',
+ 'heteroAgent.codexQuota.resetting': 'Resetting…',
'heteroAgent.codexQuota.title': 'Codex quota',
+ 'heteroAgent.codexQuota.totalEarned_one': '{{count}} earned in total',
+ 'heteroAgent.codexQuota.totalEarned_other': '{{count}} earned in total',
'heteroAgent.codexQuota.tooltip': 'View Codex quota',
'heteroAgent.quota.compactLeft': '{{percent}}%',
'heteroAgent.quota.exhausted': 'Exhausted',
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/CodexQuotaMenu.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/CodexQuotaMenu.tsx
index c83a9aeb9b8..b4f4fc25b27 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/CodexQuotaMenu.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/CodexQuotaMenu.tsx
@@ -1,10 +1,17 @@
'use client';
-import type { CodexQuotaSnapshot } from '@lobechat/electron-client-ipc';
+import type {
+ CodexQuotaSnapshot,
+ CodexQuotaWindow,
+ CodexRateLimitResetCredit,
+ CodexRateLimitSnapshot,
+} from '@lobechat/electron-client-ipc';
+import { uuid } from '@lobechat/utils';
import { Flexbox, Icon, Text } from '@lobehub/ui';
+import { Button, confirmModal, toast } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { RotateCcwIcon } from 'lucide-react';
-import { memo, useCallback } from 'react';
+import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';
@@ -12,7 +19,68 @@ import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgen
import type { FetchQuotaOptions, QuotaMenuHelpers, QuotaWindowItem } from './QuotaMenu';
import QuotaMenu, { createQuotaSourceKey } from './QuotaMenu';
+const FIVE_HOUR_WINDOW_MINUTES = 5 * 60;
+const WEEKLY_WINDOW_MINUTES = 7 * 24 * 60;
+const MONTHLY_WINDOW_MIN_MINUTES = 28 * 24 * 60;
+const MONTHLY_WINDOW_MAX_MINUTES = 31 * 24 * 60;
+
const styles = createStaticStyles(({ css }) => ({
+ credit: css`
+ min-width: 0;
+ padding-block: 8px;
+ padding-inline: 10px;
+
+ &:not(:last-child) {
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ }
+ `,
+ creditExpiry: css`
+ flex: none;
+ text-align: end;
+ white-space: nowrap;
+ `,
+ creditIndex: css`
+ flex: 0 0 20px;
+ font-variant-numeric: tabular-nums;
+ color: ${cssVar.colorTextTertiary};
+ text-align: center;
+ `,
+ creditList: css`
+ overflow: hidden;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadius};
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ creditTitle: css`
+ overflow: hidden;
+ flex: 1;
+
+ min-width: 0;
+
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ feedback: css`
+ padding: 8px;
+ border: 1px solid ${cssVar.colorInfoBorder};
+ border-radius: ${cssVar.borderRadius};
+
+ color: ${cssVar.colorInfoText};
+
+ background: ${cssVar.colorInfoBg};
+
+ &[data-kind='error'] {
+ border-color: ${cssVar.colorErrorBorder};
+ color: ${cssVar.colorErrorText};
+ background: ${cssVar.colorErrorBg};
+ }
+
+ &[data-kind='success'] {
+ border-color: ${cssVar.colorSuccessBorder};
+ color: ${cssVar.colorSuccessText};
+ background: ${cssVar.colorSuccessBg};
+ }
+ `,
resetCredits: css`
padding-block-start: 8px;
border-block-start: 1px solid ${cssVar.colorBorderSecondary};
@@ -29,14 +97,49 @@ const createErrorSnapshot = (error: unknown): CodexQuotaSnapshot => ({
weekly: null,
});
+const getAvailableResetCredits = (credits: CodexRateLimitResetCredit[] | undefined, now: number) =>
+ [...(credits ?? [])]
+ .filter(
+ (credit) =>
+ credit.status === 'available' && (credit.expiresAt === null || credit.expiresAt > now),
+ )
+ .sort((left, right) => {
+ const expiryDifference =
+ (left.expiresAt ?? Number.POSITIVE_INFINITY) -
+ (right.expiresAt ?? Number.POSITIVE_INFINITY);
+ if (expiryDifference !== 0) return expiryDifference;
+ return (left.id ?? '').localeCompare(right.id ?? '');
+ });
+
interface CodexQuotaMenuProps {
command?: string;
env?: Record<string, string>;
}
+interface ResetAttempt {
+ creditId?: string;
+ idempotencyKey: string;
+}
+
+interface ResetFeedback {
+ kind: 'error' | 'info' | 'success';
+ text: string;
+}
+
const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, env }) => {
const { t } = useTranslation('chat');
const sourceKey = createQuotaSourceKey('codex', command, env);
+ const activeSourceKeyRef = useRef(sourceKey);
+ const resetAttemptRef = useRef<ResetAttempt | null>(null);
+ const [resetFeedback, setResetFeedback] = useState<ResetFeedback>();
+ const [resetting, setResetting] = useState(false);
+
+ useEffect(() => {
+ activeSourceKeyRef.current = sourceKey;
+ resetAttemptRef.current = null;
+ setResetFeedback(undefined);
+ setResetting(false);
+ }, [sourceKey]);
const fetchQuota = useCallback(
(options?: FetchQuotaOptions) =>
@@ -48,68 +151,291 @@ const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, env }) => {
[command, env],
);
- const getWindows = useCallback(
- (quota: CodexQuotaSnapshot): QuotaWindowItem[] => [
- { key: 'session', label: t('heteroAgent.quota.session'), window: quota.session },
- { key: 'weekly', label: t('heteroAgent.quota.weekly'), window: quota.weekly },
- ],
+ const getWindowLabel = useCallback(
+ (window: CodexQuotaWindow | null, fallback: string) => {
+ if (!window) return fallback;
+ if (window.windowMinutes === FIVE_HOUR_WINDOW_MINUTES) {
+ return t('heteroAgent.codexQuota.fiveHour');
+ }
+ if (window.windowMinutes === WEEKLY_WINDOW_MINUTES) {
+ return t('heteroAgent.quota.weekly');
+ }
+ if (
+ window.windowMinutes >= MONTHLY_WINDOW_MIN_MINUTES &&
+ window.windowMinutes <= MONTHLY_WINDOW_MAX_MINUTES
+ ) {
+ return t('heteroAgent.codexQuota.monthly');
+ }
+ return fallback;
+ },
[t],
);
+ const getRateLimitWindowLabel = useCallback(
+ (rateLimit: CodexRateLimitSnapshot, window: CodexQuotaWindow, fallback: string) => {
+ const windowLabel = getWindowLabel(window, fallback);
+ if (rateLimit.limitId.toLowerCase() === 'codex') return windowLabel;
+
+ return `${rateLimit.limitName || rateLimit.limitId} · ${windowLabel}`;
+ },
+ [getWindowLabel],
+ );
+
+ const getWindows = useCallback(
+ (quota: CodexQuotaSnapshot): QuotaWindowItem[] => {
+ if (!quota.rateLimits?.length) {
+ return [
+ {
+ key: 'primary',
+ label: getWindowLabel(quota.session, t('heteroAgent.quota.session')),
+ window: quota.session,
+ },
+ {
+ key: 'secondary',
+ label: getWindowLabel(quota.weekly, t('heteroAgent.quota.weekly')),
+ window: quota.weekly,
+ },
+ ];
+ }
+
+ return quota.rateLimits.flatMap((rateLimit) => {
+ const windows: QuotaWindowItem[] = [];
+
+ if (rateLimit.primary) {
+ windows.push({
+ key: `${rateLimit.limitId}:primary`,
+ label: getRateLimitWindowLabel(
+ rateLimit,
+ rateLimit.primary,
+ t('heteroAgent.quota.session'),
+ ),
+ window: rateLimit.primary,
+ });
+ }
+
+ if (rateLimit.secondary) {
+ windows.push({
+ key: `${rateLimit.limitId}:secondary`,
+ label: getRateLimitWindowLabel(
+ rateLimit,
+ rateLimit.secondary,
+ t('heteroAgent.quota.weekly'),
+ ),
+ window: rateLimit.secondary,
+ });
+ }
+
+ return windows;
+ });
+ },
+ [getRateLimitWindowLabel, getWindowLabel, t],
+ );
+
const hasExtraData = useCallback(
(quota: CodexQuotaSnapshot) => !!quota.rateLimitResetCredits,
[],
);
+ const consumeReset = useCallback(
+ async (
+ creditId: string | undefined,
+ applyQuota: (quota: CodexQuotaSnapshot) => void,
+ requestSourceKey: string,
+ ) => {
+ const previousAttempt = resetAttemptRef.current;
+ const attempt =
+ previousAttempt && previousAttempt.creditId === creditId
+ ? previousAttempt
+ : {
+ ...(creditId ? { creditId } : {}),
+ idempotencyKey: uuid(),
+ };
+ resetAttemptRef.current = attempt;
+ setResetFeedback(undefined);
+ setResetting(true);
+
+ try {
+ const result = await heterogeneousAgentService.consumeCodexRateLimitResetCredit({
+ command,
+ ...(attempt.creditId ? { creditId: attempt.creditId } : {}),
+ env,
+ idempotencyKey: attempt.idempotencyKey,
+ });
+ if (activeSourceKeyRef.current !== requestSourceKey) return;
+
+ applyQuota(result.quota);
+ resetAttemptRef.current = null;
+
+ switch (result.outcome) {
+ case 'alreadyRedeemed':
+ case 'reset': {
+ const text = t('heteroAgent.codexQuota.resetSuccess');
+ setResetFeedback({ kind: 'success', text });
+ toast.success(text);
+ break;
+ }
+ case 'nothingToReset': {
+ setResetFeedback({
+ kind: 'info',
+ text: t('heteroAgent.codexQuota.resetNothingToReset'),
+ });
+ break;
+ }
+ case 'noCredit': {
+ setResetFeedback({
+ kind: 'error',
+ text: t('heteroAgent.codexQuota.resetNoCredit'),
+ });
+ break;
+ }
+ }
+ } catch (error) {
+ console.error('Failed to consume Codex rate-limit reset credit:', error);
+ if (activeSourceKeyRef.current !== requestSourceKey) return;
+
+ const text = t('heteroAgent.codexQuota.resetFailed');
+ setResetFeedback({ kind: 'error', text });
+ toast.error(text);
+ } finally {
+ if (activeSourceKeyRef.current === requestSourceKey) setResetting(false);
+ }
+ },
+ [command, env, t],
+ );
+
+ const confirmReset = useCallback(
+ (creditId: string | undefined, applyQuota: (quota: CodexQuotaSnapshot) => void) => {
+ const requestSourceKey = sourceKey;
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('heteroAgent.codexQuota.resetConfirmDescription'),
+ okText: t('heteroAgent.codexQuota.resetNow'),
+ onOk: () => consumeReset(creditId, applyQuota, requestSourceKey),
+ title: t('heteroAgent.codexQuota.resetConfirmTitle'),
+ });
+ },
+ [consumeReset, sourceKey, t],
+ );
+
const renderFooter = useCallback(
- (quota: CodexQuotaSnapshot, { formatDuration, now }: QuotaMenuHelpers) => {
- const resetCreditCount = quota.rateLimitResetCredits?.availableCount;
- const resetCreditExpiry = quota.rateLimitResetCredits?.nextExpiresAt;
+ (
+ quota: CodexQuotaSnapshot,
+ { applyQuota, formatDuration, now }: QuotaMenuHelpers<CodexQuotaSnapshot>,
+ ) => {
+ const resetCredits = quota.rateLimitResetCredits;
- if (resetCreditCount === undefined)
+ if (!resetCredits) {
return (
<Flexbox className={styles.resetCredits} gap={4}>
- <Flexbox horizontal align={'center'} gap={6}>
- <Icon icon={RotateCcwIcon} size={13} />
+ <Flexbox horizontal align={'center'} gap={4}>
+ <Icon icon={RotateCcwIcon} size={14} />
<Text style={{ fontSize: 12 }} type="secondary">
{t('heteroAgent.codexQuota.resetCreditsUnavailable')}
</Text>
</Flexbox>
</Flexbox>
);
-
- let expiryLabel: string | undefined;
- if (resetCreditExpiry) {
- const duration = formatDuration(resetCreditExpiry - now);
- if (duration) {
- expiryLabel =
- resetCreditCount > 1
- ? t('heteroAgent.codexQuota.nextExpiresIn', { duration })
- : t('heteroAgent.codexQuota.expiresIn', { duration });
- }
}
+ const resetCreditCount = resetCredits.availableCount;
+ const availableCredits = getAvailableResetCredits(resetCredits.credits, now).slice(
+ 0,
+ resetCreditCount,
+ );
+ const nextCredit = availableCredits[0];
+ const resetCreditItems = Array.from({ length: resetCreditCount }, (_, index) => ({
+ credit: availableCredits[index],
+ index: index + 1,
+ }));
+
return (
- <Flexbox className={styles.resetCredits} gap={4}>
- <Flexbox horizontal align={'center'} gap={6}>
- <Icon icon={RotateCcwIcon} size={13} />
- <Text strong style={{ fontSize: 12 }}>
- {t('heteroAgent.codexQuota.resetCredits', { count: resetCreditCount })}
- </Text>
+ <Flexbox className={styles.resetCredits} gap={8}>
+ <Flexbox gap={2}>
+ <Flexbox horizontal align={'center'} gap={4}>
+ <Icon icon={RotateCcwIcon} size={14} />
+ <Text strong style={{ fontSize: 12 }}>
+ {t('heteroAgent.codexQuota.resetCredits', { count: resetCreditCount })}
+ </Text>
+ </Flexbox>
+ {resetCredits.totalEarnedCount !== undefined && (
+ <Text color={cssVar.colorTextTertiary} style={{ fontSize: 12 }}>
+ {t('heteroAgent.codexQuota.totalEarned', {
+ count: resetCredits.totalEarnedCount,
+ })}
+ </Text>
+ )}
</Flexbox>
- {expiryLabel && (
- <Text style={{ fontSize: 12 }} type="secondary">
- {expiryLabel}
- </Text>
+
+ {resetCreditItems.length > 0 && (
+ <Flexbox className={styles.creditList}>
+ {resetCreditItems.map(({ credit, index }) => {
+ const fallbackExpiry = index === 1 ? resetCredits.nextExpiresAt : undefined;
+ const expiresAt = credit ? credit.expiresAt : fallbackExpiry;
+ const expiresIn = expiresAt ? formatDuration(expiresAt - now) : undefined;
+
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.credit}
+ gap={8}
+ key={credit?.id ?? `reset-credit-${index}`}
+ >
+ <Text className={styles.creditIndex} style={{ fontSize: 12 }}>
+ {`#${index}`}
+ </Text>
+ <Text strong className={styles.creditTitle} style={{ fontSize: 12 }}>
+ {credit?.title || t('heteroAgent.codexQuota.resetCreditTitle')}
+ </Text>
+ <Text className={styles.creditExpiry} style={{ fontSize: 12 }} type="secondary">
+ {expiresAt
+ ? expiresIn
+ ? t('heteroAgent.codexQuota.expiresIn', { duration: expiresIn })
+ : t('heteroAgent.codexQuota.expiresSoon')
+ : credit
+ ? t('heteroAgent.codexQuota.doesNotExpire')
+ : t('heteroAgent.codexQuota.resetCreditDetailsUnavailable')}
+ </Text>
+ </Flexbox>
+ );
+ })}
+ </Flexbox>
+ )}
+
+ {resetFeedback && (
+ <div
+ aria-live="polite"
+ className={styles.feedback}
+ data-kind={resetFeedback.kind}
+ role={resetFeedback.kind === 'error' ? 'alert' : 'status'}
+ >
+ {resetFeedback.text}
+ </div>
+ )}
+
+ {resetCreditCount > 0 && (
+ <Button
+ block
+ icon={RotateCcwIcon}
+ loading={resetting}
+ size={'small'}
+ type={'primary'}
+ onClick={() => confirmReset(nextCredit?.id ?? undefined, applyQuota)}
+ >
+ {resetting
+ ? t('heteroAgent.codexQuota.resetting')
+ : t('heteroAgent.codexQuota.resetNow')}
+ </Button>
)}
</Flexbox>
);
},
- [t],
+ [confirmReset, resetFeedback, resetting, t],
);
return (
<QuotaMenu
+ contentWidth={360}
createErrorSnapshot={createErrorSnapshot}
fetchQuota={fetchQuota}
getWindows={getWindows}
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.test.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.test.tsx
index cf7887de0a1..6cfc6fd860e 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.test.tsx
@@ -10,10 +10,22 @@ import ClaudeCodeQuotaMenu from './ClaudeCodeQuotaMenu';
import CodexQuotaMenu from './CodexQuotaMenu';
const mockService = vi.hoisted(() => ({
+ consumeCodexRateLimitResetCredit: vi.fn(),
getClaudeCodeQuota: vi.fn(),
getCodexQuota: vi.fn(),
}));
+const { confirmModalMock, toastErrorMock, toastSuccessMock } = vi.hoisted(() => ({
+ confirmModalMock: vi.fn(),
+ toastErrorMock: vi.fn(),
+ toastSuccessMock: vi.fn(),
+}));
+
+const translate = vi.hoisted(() => (key: string, opts?: Record<string, unknown>) => {
+ const values = opts ? Object.values(opts) : [];
+ return values.length > 0 ? `${key}:${values.join(',')}` : key;
+});
+
vi.mock('@/services/electron/heterogeneousAgent', () => ({
heterogeneousAgentService: mockService,
}));
@@ -22,10 +34,7 @@ vi.mock('@/services/electron/heterogeneousAgent', () => ({
// target the exact i18n key + params a snapshot should produce.
vi.mock('react-i18next', () => ({
useTranslation: () => ({
- t: (key: string, opts?: Record<string, unknown>) => {
- const values = opts ? Object.values(opts) : [];
- return values.length > 0 ? `${key}:${values.join(',')}` : key;
- },
+ t: translate,
}),
}));
@@ -68,6 +77,29 @@ vi.mock('@lobehub/ui', () => ({
Tooltip: ({ children }: { children?: ReactNode }) => <>{children}</>,
}));
+vi.mock('@lobehub/ui/base-ui', () => ({
+ Button: ({
+ children,
+ disabled,
+ loading,
+ onClick,
+ }: {
+ children?: ReactNode;
+ disabled?: boolean;
+ loading?: boolean;
+ onClick?: () => void;
+ }) => (
+ <button disabled={disabled || loading} type="button" onClick={onClick}>
+ {children}
+ </button>
+ ),
+ confirmModal: confirmModalMock,
+ toast: {
+ error: toastErrorMock,
+ success: toastSuccessMock,
+ },
+}));
+
const claudeSnapshot = (
overrides: Partial<ClaudeCodeQuotaSnapshot> = {},
): ClaudeCodeQuotaSnapshot => ({
@@ -93,8 +125,12 @@ const codexSnapshot = (overrides: Partial<CodexQuotaSnapshot> = {}): CodexQuotaS
});
beforeEach(() => {
+ confirmModalMock.mockReset();
+ mockService.consumeCodexRateLimitResetCredit.mockReset();
mockService.getClaudeCodeQuota.mockReset();
mockService.getCodexQuota.mockReset();
+ toastErrorMock.mockReset();
+ toastSuccessMock.mockReset();
});
describe('ClaudeCodeQuotaMenu', () => {
@@ -115,9 +151,9 @@ describe('ClaudeCodeQuotaMenu', () => {
expect(await screen.findByText('heteroAgent.quota.session')).toBeTruthy();
expect(screen.getByText('heteroAgent.quota.weekly')).toBeTruthy();
expect(screen.getByText('heteroAgent.claudeQuota.scopedWeekly:Fable')).toBeTruthy();
- // 100 - usedPercent, session drives the compact trigger label
+ // The compact trigger surfaces the most binding window.
expect(screen.getByText('heteroAgent.quota.left:92')).toBeTruthy();
- expect(screen.getByText('heteroAgent.quota.compactLeft:92')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.quota.compactLeft:76')).toBeTruthy();
expect(mockService.getClaudeCodeQuota).toHaveBeenCalledWith({
env: { CLAUDE_CONFIG_DIR: '/custom' },
});
@@ -334,17 +370,36 @@ describe('ClaudeCodeQuotaMenu', () => {
describe('CodexQuotaMenu', () => {
it('renders windows and the reset-credits footer', async () => {
+ const resetsAt = Date.now() + 60 * 60_000;
mockService.getCodexQuota.mockResolvedValue(
codexSnapshot({
rateLimitResetCredits: { availableCount: 4, nextExpiresAt: null },
- session: { resetsAt: null, usedPercent: 19, windowMinutes: 300 },
+ session: { resetsAt, usedPercent: 19, windowMinutes: 300 },
+ weekly: { resetsAt: resetsAt + 60 * 60_000, usedPercent: 88, windowMinutes: 10_080 },
}),
);
render(<CodexQuotaMenu command="codex" />);
expect(await screen.findByText('heteroAgent.quota.left:81')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.quota.left:12')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.quota.compactLeft:12')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.codexQuota.fiveHour')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.quota.weekly')).toBeTruthy();
+ expect(
+ screen.getAllByText((content) => content.startsWith('heteroAgent.quota.resetsIn:')),
+ ).toHaveLength(2);
+ expect(
+ screen.queryAllByText((content) => content.startsWith('heteroAgent.quota.resetAt:')),
+ ).toHaveLength(0);
expect(screen.getByText('heteroAgent.codexQuota.resetCredits:4')).toBeTruthy();
+ expect(screen.getByText('#1')).toBeTruthy();
+ expect(screen.getByText('#2')).toBeTruthy();
+ expect(screen.getByText('#3')).toBeTruthy();
+ expect(screen.getByText('#4')).toBeTruthy();
+ expect(
+ screen.getAllByText('heteroAgent.codexQuota.resetCreditDetailsUnavailable'),
+ ).toHaveLength(4);
expect(mockService.getCodexQuota).toHaveBeenCalledWith({ command: 'codex', env: undefined });
fireEvent.click(screen.getByTestId('refresh'));
@@ -356,6 +411,41 @@ describe('CodexQuotaMenu', () => {
});
});
+ it('renders every Codex rate-limit bucket and uses the tightest window in the trigger', async () => {
+ mockService.getCodexQuota.mockResolvedValue(
+ codexSnapshot({
+ rateLimits: [
+ {
+ limitId: 'codex',
+ limitName: 'Codex',
+ primary: { resetsAt: null, usedPercent: 10, windowMinutes: 300 },
+ secondary: { resetsAt: null, usedPercent: 20, windowMinutes: 10_080 },
+ },
+ {
+ limitId: 'codex_other',
+ limitName: 'Codex Other',
+ primary: { resetsAt: null, usedPercent: 98, windowMinutes: 60 },
+ secondary: { resetsAt: null, usedPercent: 40, windowMinutes: 43_200 },
+ },
+ ],
+ session: { resetsAt: null, usedPercent: 10, windowMinutes: 300 },
+ weekly: { resetsAt: null, usedPercent: 20, windowMinutes: 10_080 },
+ }),
+ );
+
+ render(<CodexQuotaMenu />);
+
+ expect(await screen.findByText('heteroAgent.quota.compactLeft:2')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.codexQuota.fiveHour')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.quota.weekly')).toBeTruthy();
+ expect(screen.getByText('Codex Other · heteroAgent.quota.session')).toBeTruthy();
+ expect(screen.getByText('Codex Other · heteroAgent.codexQuota.monthly')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.quota.left:90')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.quota.left:80')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.quota.left:2')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.quota.left:60')).toBeTruthy();
+ });
+
it('renders the credits-unavailable footer when the RPC omits credits', async () => {
mockService.getCodexQuota.mockResolvedValue(
codexSnapshot({ session: { resetsAt: null, usedPercent: 5, windowMinutes: 300 } }),
@@ -365,4 +455,175 @@ describe('CodexQuotaMenu', () => {
expect(await screen.findByText('heteroAgent.codexQuota.resetCreditsUnavailable')).toBeTruthy();
});
+
+ it('renders every available reset with relative expiry only', async () => {
+ const now = Date.now();
+ mockService.getCodexQuota.mockResolvedValue(
+ codexSnapshot({
+ rateLimitResetCredits: {
+ availableCount: 3,
+ credits: [
+ {
+ expiresAt: now + 3 * 24 * 60 * 60_000,
+ grantedAt: now - 24 * 60 * 60_000,
+ id: 'credit-later',
+ resetType: 'codex_all_limits',
+ status: 'available',
+ title: 'Weekly rescue',
+ },
+ {
+ expiresAt: now + 24 * 60 * 60_000,
+ grantedAt: now - 2 * 24 * 60 * 60_000,
+ id: 'credit-first',
+ resetType: 'codex_all_limits',
+ status: 'available',
+ title: 'Early reset',
+ },
+ ],
+ nextExpiresAt: now + 24 * 60 * 60_000,
+ totalEarnedCount: 5,
+ },
+ session: { resetsAt: null, usedPercent: 95, windowMinutes: 300 },
+ }),
+ );
+
+ render(<CodexQuotaMenu />);
+
+ expect(await screen.findByText('Early reset')).toBeTruthy();
+ expect(screen.getByText('Weekly rescue')).toBeTruthy();
+ expect(screen.getByText('#1')).toBeTruthy();
+ expect(screen.getByText('#2')).toBeTruthy();
+ expect(screen.getByText('#3')).toBeTruthy();
+ expect(
+ screen.getAllByText((text) => text.startsWith('heteroAgent.codexQuota.expiresIn:')),
+ ).toHaveLength(2);
+ expect(
+ screen.queryAllByText((text) => text.startsWith('heteroAgent.codexQuota.expiresAt:')),
+ ).toHaveLength(0);
+ expect(
+ screen.queryAllByText((text) => text.startsWith('heteroAgent.codexQuota.grantedAt:')),
+ ).toHaveLength(0);
+ expect(screen.getByText('heteroAgent.codexQuota.totalEarned:5')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.codexQuota.resetCreditDetailsUnavailable')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.codexQuota.resetCreditTitle')).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'heteroAgent.codexQuota.resetNow' })).toBeTruthy();
+ });
+
+ it('confirms and consumes the earliest-expiring credit, then applies refreshed quota', async () => {
+ const now = Date.now();
+ mockService.getCodexQuota.mockResolvedValue(
+ codexSnapshot({
+ rateLimitResetCredits: {
+ availableCount: 2,
+ credits: [
+ {
+ expiresAt: now + 2 * 24 * 60 * 60_000,
+ grantedAt: now,
+ id: 'credit-later',
+ resetType: 'codex_all_limits',
+ status: 'available',
+ title: 'Later reset',
+ },
+ {
+ expiresAt: now + 60 * 60_000,
+ grantedAt: now,
+ id: 'credit-first',
+ resetType: 'codex_all_limits',
+ status: 'available',
+ title: 'First reset',
+ },
+ ],
+ },
+ session: { resetsAt: null, usedPercent: 96, windowMinutes: 300 },
+ }),
+ );
+ mockService.consumeCodexRateLimitResetCredit.mockResolvedValue({
+ outcome: 'reset',
+ quota: codexSnapshot({
+ rateLimitResetCredits: { availableCount: 1 },
+ session: { resetsAt: null, usedPercent: 0, windowMinutes: 300 },
+ }),
+ });
+
+ render(<CodexQuotaMenu command="codex" env={{ CODEX_HOME: '/custom' }} />);
+
+ fireEvent.click(await screen.findByRole('button', { name: 'heteroAgent.codexQuota.resetNow' }));
+ expect(confirmModalMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: 'heteroAgent.codexQuota.resetConfirmDescription',
+ title: 'heteroAgent.codexQuota.resetConfirmTitle',
+ }),
+ );
+
+ await act(async () => {
+ await confirmModalMock.mock.calls[0][0].onOk();
+ });
+
+ await waitFor(() =>
+ expect(mockService.consumeCodexRateLimitResetCredit).toHaveBeenCalledWith({
+ command: 'codex',
+ creditId: 'credit-first',
+ env: { CODEX_HOME: '/custom' },
+ idempotencyKey: expect.any(String),
+ }),
+ );
+ expect(await screen.findByText('heteroAgent.quota.left:100')).toBeTruthy();
+ expect(screen.getByText('heteroAgent.codexQuota.resetSuccess')).toBeTruthy();
+ expect(toastSuccessMock).toHaveBeenCalledWith('heteroAgent.codexQuota.resetSuccess');
+ });
+
+ it('clears refresh loading when a reset supersedes an in-flight quota request', async () => {
+ const requests: Array<(snapshot: CodexQuotaSnapshot) => void> = [];
+ mockService.getCodexQuota
+ .mockResolvedValueOnce(
+ codexSnapshot({
+ rateLimitResetCredits: { availableCount: 1 },
+ session: { resetsAt: null, usedPercent: 96, windowMinutes: 300 },
+ }),
+ )
+ .mockImplementationOnce(
+ () =>
+ new Promise<CodexQuotaSnapshot>((resolve) => {
+ requests.push(resolve);
+ }),
+ );
+ mockService.consumeCodexRateLimitResetCredit.mockResolvedValue({
+ outcome: 'reset',
+ quota: codexSnapshot({
+ rateLimitResetCredits: { availableCount: 0 },
+ session: { resetsAt: null, usedPercent: 0, windowMinutes: 300 },
+ }),
+ });
+
+ render(<CodexQuotaMenu />);
+
+ expect(await screen.findByText('heteroAgent.quota.left:4')).toBeTruthy();
+
+ fireEvent.click(screen.getByTestId('refresh'));
+
+ await waitFor(() => expect(requests).toHaveLength(1));
+ expect((screen.getByTestId('refresh') as HTMLButtonElement).disabled).toBe(true);
+
+ fireEvent.click(screen.getByRole('button', { name: 'heteroAgent.codexQuota.resetNow' }));
+
+ await act(async () => {
+ await confirmModalMock.mock.calls[0][0].onOk();
+ });
+
+ expect(await screen.findByText('heteroAgent.quota.left:100')).toBeTruthy();
+ expect((screen.getByTestId('refresh') as HTMLButtonElement).disabled).toBe(false);
+
+ await act(async () => {
+ requests[0](
+ codexSnapshot({
+ rateLimitResetCredits: { availableCount: 1 },
+ session: { resetsAt: null, usedPercent: 80, windowMinutes: 300 },
+ }),
+ );
+ });
+
+ expect(screen.getByText('heteroAgent.quota.left:100')).toBeTruthy();
+ expect(screen.queryByText('heteroAgent.quota.left:20')).toBeNull();
+ expect((screen.getByTestId('refresh') as HTMLButtonElement).disabled).toBe(false);
+ });
});
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.tsx
index 8fa6bcbf8fe..dbaf8e467b5 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.tsx
@@ -137,7 +137,8 @@ export interface QuotaWindowItem {
window: HeteroQuotaWindow | null;
}
-export interface QuotaMenuHelpers {
+export interface QuotaMenuHelpers<S> {
+ applyQuota: (quota: S) => void;
formatDuration: (ms: number) => string | undefined;
now: number;
}
@@ -147,6 +148,7 @@ export interface FetchQuotaOptions {
}
interface QuotaMenuProps<S extends QuotaSnapshotBase> {
+ contentWidth?: number;
createErrorSnapshot: (error: unknown) => S;
fetchQuota: (options?: FetchQuotaOptions) => Promise<S>;
/** Localized explanation for `status: 'error'`; falls back to `error`. */
@@ -158,7 +160,7 @@ interface QuotaMenuProps<S extends QuotaSnapshotBase> {
getWindows: (quota: S) => QuotaWindowItem[];
/** Extra agent-specific data (beyond windows) that makes the body worth rendering. */
hasExtraData?: (quota: S) => boolean;
- renderFooter?: (quota: S, helpers: QuotaMenuHelpers) => ReactNode;
+ renderFooter?: (quota: S, helpers: QuotaMenuHelpers<S>) => ReactNode;
sourceKey?: string;
title: string;
tooltip: string;
@@ -174,6 +176,7 @@ interface LoadQuotaOptions {
* reset countdowns. Agent specifics come in through the props.
*/
const QuotaMenu = <S extends QuotaSnapshotBase>({
+ contentWidth,
createErrorSnapshot,
fetchQuota,
getErrorText,
@@ -211,6 +214,20 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
setQuota(nextQuota);
}, []);
+ const applyQuota = useCallback(
+ (nextQuota: S) => {
+ if (sourceKeyRef.current !== sourceKey) return;
+
+ // A completed mutation owns the newest snapshot. Invalidate any older
+ // read still in flight so it cannot repaint pre-mutation quota data.
+ requestIdRef.current += 1;
+ setLoading(false);
+ setRefreshError(null);
+ setQuotaSnapshot(nextQuota);
+ },
+ [setQuotaSnapshot, sourceKey],
+ );
+
const isCurrentRequest = useCallback(
(requestId: number, requestSourceKey: string) =>
requestId === requestIdRef.current && requestSourceKey === sourceKeyRef.current,
@@ -332,8 +349,11 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
);
const windows = quota ? getWindows(quota) : [];
- const firstWindow = windows.find((item) => item.window)?.window;
- const compactLeftPercent = firstWindow ? clampPercent(100 - firstWindow.usedPercent) : undefined;
+ const compactLeftPercent = windows.reduce<number | undefined>((mostBinding, item) => {
+ if (!item.window) return mostBinding;
+ const leftPercent = clampPercent(100 - item.window.usedPercent);
+ return mostBinding === undefined ? leftPercent : Math.min(mostBinding, leftPercent);
+ }, undefined);
const hasQuotaData = hasQuotaDataForSnapshot(quota);
const manualRefreshErrorText =
refreshError && (getRefreshErrorText?.(refreshError) || t('heteroAgent.quota.refreshFailed'));
@@ -396,7 +416,7 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
};
const content = (
- <Flexbox className={styles.popover} gap={10}>
+ <Flexbox className={styles.popover} gap={10} style={{ width: contentWidth }}>
<Flexbox horizontal align={'center'} className={styles.header} justify={'space-between'}>
<Flexbox gap={2}>
<Text strong>{title}</Text>
@@ -433,7 +453,7 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
) : hasQuotaData ? (
<>
<Flexbox gap={10}>{windows.map((item) => renderQuotaWindow(item))}</Flexbox>
- {quota && renderFooter?.(quota, { formatDuration, now })}
+ {quota && renderFooter?.(quota, { applyQuota, formatDuration, now })}
{refreshErrorText && <div className={styles.refreshNotice}>{refreshErrorText}</div>}
</>
) : (
diff --git a/src/services/electron/heterogeneousAgent.test.ts b/src/services/electron/heterogeneousAgent.test.ts
index 965e5d8a033..3ea16234057 100644
--- a/src/services/electron/heterogeneousAgent.test.ts
+++ b/src/services/electron/heterogeneousAgent.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
const mockHeterogeneousAgent = vi.hoisted(() => ({
cancelSession: vi.fn(),
+ consumeCodexRateLimitResetCredit: vi.fn(),
getClaudeCodeQuota: vi.fn(),
getCodexQuota: vi.fn(),
getSessionInfo: vi.fn(),
@@ -59,6 +60,34 @@ describe('heterogeneousAgentService', () => {
expect(mockHeterogeneousAgent.getCodexQuota).toHaveBeenCalledWith(params);
});
+ it('forwards Codex reset-credit consumption over IPC', async () => {
+ const { heterogeneousAgentService } = await import('./heterogeneousAgent');
+ const result = {
+ outcome: 'reset',
+ quota: {
+ error: null,
+ provider: 'codex',
+ rateLimitResetCredits: { availableCount: 0 },
+ session: { resetsAt: null, usedPercent: 0, windowMinutes: 300 },
+ status: 'ok',
+ updatedAt: 2,
+ weekly: null,
+ },
+ };
+ mockHeterogeneousAgent.consumeCodexRateLimitResetCredit.mockResolvedValue(result);
+ const params = {
+ command: '/usr/local/bin/codex',
+ creditId: 'credit-first',
+ env: { CODEX_HOME: '/tmp/codex' },
+ idempotencyKey: 'redeem-request-1',
+ };
+
+ await expect(
+ heterogeneousAgentService.consumeCodexRateLimitResetCredit(params),
+ ).resolves.toEqual(result);
+ expect(mockHeterogeneousAgent.consumeCodexRateLimitResetCredit).toHaveBeenCalledWith(params);
+ });
+
it('forwards session lifecycle calls over IPC', async () => {
const { heterogeneousAgentService } = await import('./heterogeneousAgent');
diff --git a/src/services/electron/heterogeneousAgent.ts b/src/services/electron/heterogeneousAgent.ts
index ad95176eb56..d76e3f797d2 100644
--- a/src/services/electron/heterogeneousAgent.ts
+++ b/src/services/electron/heterogeneousAgent.ts
@@ -1,4 +1,8 @@
-import type { ClaudeCodeQuotaSnapshot, CodexQuotaSnapshot } from '@lobechat/electron-client-ipc';
+import type {
+ ClaudeCodeQuotaSnapshot,
+ CodexQuotaSnapshot,
+ CodexRateLimitResetResult,
+} from '@lobechat/electron-client-ipc';
import { ensureElectronIpc } from '@/utils/electron/ipc';
@@ -54,6 +58,15 @@ class HeterogeneousAgentService {
return this.ipc.heterogeneousAgent.getCodexQuota(params);
}
+ async consumeCodexRateLimitResetCredit(params: {
+ command?: string;
+ creditId?: string;
+ env?: Record<string, string>;
+ idempotencyKey: string;
+ }): Promise<CodexRateLimitResetResult> {
+ return this.ipc.heterogeneousAgent.consumeCodexRateLimitResetCredit(params);
+ }
+
async getClaudeCodeQuota(params?: {
env?: Record<string, string>;
force?: boolean;