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(codex): show credit balance and USD estimate (#23757)

Mochaf604751aa883
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index c542bc7d535..682bbe3284f 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1581,6 +1581,9 @@
"heteroAgent.cloudRepo.notSet": "No repo selected",
"heteroAgent.cloudRepo.sectionTitle": "Repositories",
"heteroAgent.codexQuota.calendar.title": "Codex usage calendar",
+ "heteroAgent.codexQuota.creditsBalance": "Credits balance",
+ "heteroAgent.codexQuota.creditsUnlimited": "Unlimited",
+ "heteroAgent.codexQuota.creditsUsdEstimate": "≈ {{amount}}",
"heteroAgent.codexQuota.doesNotExpire": "Does not expire",
"heteroAgent.codexQuota.errorConnection": "Couldn't reach the Codex quota endpoint. Check your network or LobeHub proxy settings.",
"heteroAgent.codexQuota.errorGeneric": "Couldn't load Codex quota. Try again later.",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 14ce2f37c0f..4509128cb71 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1581,6 +1581,9 @@
"heteroAgent.cloudRepo.notSet": "未选择仓库",
"heteroAgent.cloudRepo.sectionTitle": "代码仓库",
"heteroAgent.codexQuota.calendar.title": "Codex 用量日历",
+ "heteroAgent.codexQuota.creditsBalance": "Credits 余额",
+ "heteroAgent.codexQuota.creditsUnlimited": "无限",
+ "heteroAgent.codexQuota.creditsUsdEstimate": "约 {{amount}}",
"heteroAgent.codexQuota.doesNotExpire": "永不过期",
"heteroAgent.codexQuota.errorConnection": "无法访问 Codex 额度接口,请检查网络或 LobeHub 代理设置。",
"heteroAgent.codexQuota.errorGeneric": "无法获取 Codex 额度,请稍后重试。",
diff --git a/packages/heterogeneous-agents/src/quota-sampler/codexQuota.test.ts b/packages/heterogeneous-agents/src/quota-sampler/codexQuota.test.ts
index 2654a48f1db..f674a3883ac 100644
--- a/packages/heterogeneous-agents/src/quota-sampler/codexQuota.test.ts
+++ b/packages/heterogeneous-agents/src/quota-sampler/codexQuota.test.ts
@@ -78,6 +78,42 @@ describe('fetchCodexQuota', () => {
vi.useRealTimers();
});
+ it.each([
+ {
+ expected: { balance: '1250.75', unlimited: false },
+ rateLimits: { credits: { balance: '1250.75', hasCredits: true, unlimited: false } },
+ },
+ {
+ expected: { balance: '0', unlimited: false },
+ rateLimits: { credits: { balance: '0', hasCredits: false, unlimited: false } },
+ },
+ {
+ expected: { balance: null, unlimited: true },
+ rateLimits: {},
+ rateLimitsByLimitId: {
+ codex: { credits: { balance: null, hasCredits: true, unlimited: true } },
+ },
+ },
+ {
+ expected: undefined,
+ rateLimits: { credits: { balance: null, hasCredits: true, unlimited: false } },
+ rateLimitsByLimitId: {
+ other: { credits: { balance: '99', hasCredits: true, unlimited: false } },
+ },
+ },
+ ])('reads the account credit balance from the Codex quota RPC (%#)', async (fixture) => {
+ const child = new RpcChild();
+ spawnMock.mockReturnValue(child);
+ vi.mocked(readFile).mockRejectedValue(new Error('ENOENT'));
+ const { expected, ...response } = fixture;
+ mockRpcRateLimits(child, response);
+
+ const result = fetchCodexQuota({ includeResetCredits: false });
+ await vi.advanceTimersByTimeAsync(2);
+
+ expect((await result).credits).toEqual(expected);
+ });
+
it('fills reset-credit metadata from the Codex backend when RPC omits it', async () => {
const child = new RpcChild();
spawnMock.mockReturnValue(child);
diff --git a/packages/heterogeneous-agents/src/quota-sampler/codexQuota.ts b/packages/heterogeneous-agents/src/quota-sampler/codexQuota.ts
index 09259e3fb73..ac2b3beafe4 100644
--- a/packages/heterogeneous-agents/src/quota-sampler/codexQuota.ts
+++ b/packages/heterogeneous-agents/src/quota-sampler/codexQuota.ts
@@ -50,6 +50,7 @@ interface RpcRateWindow {
}
interface RpcRateLimitSnapshot {
+ credits?: { balance?: string | null; unlimited?: boolean } | null;
limitId?: string | null;
limitName?: string | null;
primary?: RpcRateWindow;
@@ -151,6 +152,12 @@ const normalizeCreditText = (value: string | null | undefined) => {
return trimmed || null;
};
+const mapRpcCredits = (raw: RpcRateLimitSnapshot['credits']): CodexQuotaSnapshot['credits'] => {
+ const balance = normalizeCreditText(raw?.balance);
+ const unlimited = raw?.unlimited === true;
+ return balance === null && !unlimited ? undefined : { balance, unlimited };
+};
+
const mapRpcResetCredit = (credit: RpcRateLimitResetCredit): CodexRateLimitResetCredit => ({
expiresAt: parseCreditTimestamp(credit.expiresAt),
grantedAt: parseCreditTimestamp(credit.grantedAt),
@@ -573,6 +580,9 @@ const fetchViaRpc = async (
const rateLimits = mapRpcRateLimits(wrapper);
const defaultRateLimit =
rateLimits.find(({ limitId }) => limitId.toLowerCase() === 'codex') ?? rateLimits[0];
+ const credits =
+ mapRpcCredits(wrapper.rateLimitsByLimitId?.codex?.credits) ??
+ mapRpcCredits(wrapper.rateLimits?.credits);
const rateLimitResetCredits = mapRpcResetCredits(wrapper?.rateLimitResetCredits);
let backendCredits: CodexRateLimitResetCredits | null = null;
@@ -592,6 +602,7 @@ const fetchViaRpc = async (
const updatedAt = Date.now();
return {
+ credits,
error: null,
readings: codexQuotaReadings(rateLimits, updatedAt),
provider: 'codex',
diff --git a/packages/heterogeneous-agents/src/quota/snapshot.ts b/packages/heterogeneous-agents/src/quota/snapshot.ts
index 69987b70af4..9db77a8a339 100644
--- a/packages/heterogeneous-agents/src/quota/snapshot.ts
+++ b/packages/heterogeneous-agents/src/quota/snapshot.ts
@@ -43,6 +43,8 @@ export interface CodexRateLimitResetCredits {
}
export interface CodexQuotaSnapshot {
+ /** Credit balance reported by Codex, independent of rate-limit reset credits. */
+ credits?: { balance: string | null; unlimited: boolean };
error: string | null;
identity?: QuotaAccountIdentity | null;
provider: 'codex';
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index e1705a9e668..6b4acec754f 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -815,6 +815,9 @@ export default {
'heteroAgent.claudeSdkRuntime.state.starting': 'SDK starting',
'heteroAgent.claudeSdkRuntime.tooltip': '{{state}}. Active background tasks: {{count}}.',
'heteroAgent.codexQuota.calendar.title': 'Codex usage calendar',
+ 'heteroAgent.codexQuota.creditsBalance': 'Credits balance',
+ 'heteroAgent.codexQuota.creditsUnlimited': 'Unlimited',
+ 'heteroAgent.codexQuota.creditsUsdEstimate': '≈ {{amount}}',
'heteroAgent.codexQuota.doesNotExpire': 'Does not expire',
'heteroAgent.codexQuota.errorConnection':
"Couldn't reach the Codex quota endpoint. Check your network or LobeHub proxy settings.",
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/CodexQuotaMenu.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/CodexQuotaMenu.tsx
index 4251193a333..60e7e2512f9 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/CodexQuotaMenu.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/CodexQuotaMenu.tsx
@@ -9,7 +9,7 @@ import { uuid } from '@lobechat/utils';
import { Accordion, Button, confirmModal, Flexbox, Icon, Text, toast } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
-import { RotateCcwIcon } from 'lucide-react';
+import { RotateCcwIcon, WalletIcon } from 'lucide-react';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -26,6 +26,26 @@ const WEEKLY_WINDOW_MINUTES = 7 * 24 * 60;
const MONTHLY_WINDOW_MIN_MINUTES = 28 * 24 * 60;
const MONTHLY_WINDOW_MAX_MINUTES = 31 * 24 * 60;
+// Reference API usage value from the published Codex token rates.
+// https://learn.chatgpt.com/docs/pricing#token-rates
+const ESTIMATED_USD_PER_CODEX_CREDIT = 0.04;
+
+const formatCreditsUsdEstimate = (credits: CodexQuotaSnapshot['credits'], locale: string) => {
+ if (credits?.unlimited || !credits?.balance?.trim()) return;
+
+ const balance = Number(credits.balance);
+ if (!Number.isFinite(balance) || balance < 0) return;
+
+ const estimate = balance * ESTIMATED_USD_PER_CODEX_CREDIT;
+ return new Intl.NumberFormat(locale, {
+ currency: 'USD',
+ currencyDisplay: 'narrowSymbol',
+ maximumFractionDigits: estimate < 1 ? 2 : 0,
+ minimumFractionDigits: 0,
+ style: 'currency',
+ }).format(estimate);
+};
+
const isConnectionError = (quota: CodexQuotaSnapshot) =>
/error sending request for url|fetch failed|\b(?:ECONNREFUSED|ENOTFOUND|ETIMEDOUT)\b/i.test(
quota.error ?? '',
@@ -90,7 +110,7 @@ const styles = stylex.create({
backgroundColor: cssVar.colorSuccessBg,
backgroundImage: 'none',
},
- resetCredits: {
+ footerSection: {
paddingBlockStart: '8px',
borderBlockStartWidth: '1px',
borderBlockStartStyle: 'solid',
@@ -139,7 +159,7 @@ interface ResetFeedback {
}
const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, deviceId, env }) => {
- const { t } = useTranslation('chat');
+ const { i18n, t } = useTranslation('chat');
const agentId = useAgentId();
const sourceKey = createQuotaSourceKey('codex', agentId, deviceId, command, env);
const activeSourceKeyRef = useRef(sourceKey);
@@ -217,7 +237,7 @@ const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, deviceId, env }) =>
);
const hasExtraData = useCallback(
- (quota: CodexQuotaSnapshot) => !deviceId && !!quota.rateLimitResetCredits,
+ (quota: CodexQuotaSnapshot) => !!quota.credits || (!deviceId && !!quota.rateLimitResetCredits),
[deviceId],
);
@@ -313,7 +333,7 @@ const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, deviceId, env }) =>
[consumeReset, sourceKey, t],
);
- const renderFooter = useCallback(
+ const renderResetCredits = useCallback(
(
quota: CodexQuotaSnapshot,
{ applyQuota, formatDuration, now }: QuotaMenuHelpers<CodexQuotaSnapshot>,
@@ -322,7 +342,7 @@ const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, deviceId, env }) =>
if (!resetCredits) {
return (
- <Flexbox className={stylex.props(styles.resetCredits).className} gap={4}>
+ <Flexbox className={stylex.props(styles.footerSection).className} gap={4}>
<Flexbox horizontal align={'center'} gap={4}>
<Icon icon={RotateCcwIcon} size={14} />
<Text style={{ fontSize: 12 }} type="secondary">
@@ -345,7 +365,7 @@ const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, deviceId, env }) =>
}));
return (
- <Flexbox className={stylex.props(styles.resetCredits).className}>
+ <Flexbox className={stylex.props(styles.footerSection).className}>
<Accordion
className={stylex.props(styles.creditCollapse).className}
defaultValue={[]}
@@ -470,13 +490,50 @@ const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, deviceId, env }) =>
createErrorSnapshot={createErrorSnapshot}
fetchQuota={fetchQuota}
getErrorText={getErrorText}
- getRefreshErrorText={getErrorText}
getWindows={getWindows}
hasExtraData={hasExtraData}
- renderFooter={renderFooter}
+ retainLastSnapshotOnError={false}
sourceKey={sourceKey}
title={t('heteroAgent.codexQuota.title')}
tooltip={t('heteroAgent.codexQuota.tooltip')}
+ renderFooter={(quota, helpers) => {
+ const { credits } = quota;
+ const usdEstimate = formatCreditsUsdEstimate(credits, i18n.language);
+
+ return (
+ <>
+ {renderResetCredits(quota, helpers)}
+ {credits && (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.footerSection).className}
+ gap={8}
+ justify={'space-between'}
+ >
+ <Flexbox horizontal align={'center'} gap={4}>
+ <Icon icon={WalletIcon} size={14} />
+ <Text style={{ fontSize: 12 }} type="secondary">
+ {t('heteroAgent.codexQuota.creditsBalance')}
+ </Text>
+ </Flexbox>
+ <Flexbox horizontal align={'center'} gap={8} justify={'flex-end'} wrap={'wrap'}>
+ <Text style={{ fontSize: 12 }}>
+ {credits.unlimited
+ ? t('heteroAgent.codexQuota.creditsUnlimited')
+ : credits.balance}
+ </Text>
+ {usdEstimate && (
+ <Text style={{ fontSize: 12, whiteSpace: 'nowrap' }} type="secondary">
+ {t('heteroAgent.codexQuota.creditsUsdEstimate', { amount: usdEstimate })}
+ </Text>
+ )}
+ </Flexbox>
+ </Flexbox>
+ )}
+ </>
+ );
+ }}
renderHeader={(quota) => (
<QuotaAccountSwitcher placement="top" provider="codex" snapshot={quota} />
)}
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx
index 9fc6c894b8c..a831ca74589 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx
@@ -97,6 +97,7 @@ vi.mock('@/services/agentQuota', () => ({ agentQuotaService: mockQuotaService })
// target the exact i18n key + params a snapshot should produce.
vi.mock('react-i18next', () => ({
useTranslation: () => ({
+ i18n: { language: 'en-US' },
t: translate,
}),
}));
@@ -443,6 +444,44 @@ describe('KimiCodeQuotaMenu', () => {
});
describe('CodexQuotaMenu', () => {
+ it('shows a stale warning for the confirmed account and clears its quota when the login changes', async () => {
+ mockService.getCodexQuota
+ .mockResolvedValueOnce(
+ codexSnapshot({
+ credits: { balance: '1250.75', unlimited: false },
+ identity: { externalAccountId: 'a' },
+ session: { resetsAt: null, usedPercent: 19, windowMinutes: 300 },
+ }),
+ )
+ .mockResolvedValueOnce(
+ codexSnapshot({
+ error: 'Codex RPC timed out',
+ identity: { externalAccountId: 'a' },
+ status: 'error',
+ }),
+ )
+ .mockResolvedValueOnce(
+ codexSnapshot({
+ error: 'Codex RPC timed out',
+ identity: { externalAccountId: 'b' },
+ status: 'error',
+ }),
+ );
+
+ render(<CodexQuotaMenu />);
+ expect(await screen.findByText('1250.75')).toBeTruthy();
+
+ fireEvent.click(screen.getByRole('button', { name: 'heteroAgent.quota.refresh' }));
+ expect(await screen.findByText('heteroAgent.quota.refreshFailed')).toBeTruthy();
+ expect(screen.getByText('81%')).toBeTruthy();
+ expect(screen.getByText('1250.75')).toBeTruthy();
+
+ fireEvent.click(screen.getByRole('button', { name: 'heteroAgent.quota.refresh' }));
+ expect(await screen.findByText('heteroAgent.codexQuota.errorGeneric')).toBeTruthy();
+ expect(screen.queryByText('81%')).toBeNull();
+ expect(screen.queryByText('1250.75')).toBeNull();
+ });
+
it('opens the usage calendar for the codex account from the header switcher', async () => {
mockService.getCodexQuota.mockResolvedValue(
codexSnapshot({
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx
index 1c51e1b1c56..dfcd9f433c7 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx
@@ -205,6 +205,8 @@ interface QuotaMenuProps<S extends QuotaSnapshotBase> {
renderFooter?: (quota: S, helpers: QuotaMenuHelpers<S>) => ReactNode;
/** Agent-specific content rendered above the quota windows (e.g. account switcher). */
renderHeader?: (quota: S, helpers: QuotaMenuHelpers<S>) => ReactNode;
+ /** Disable the generic fallback when the reader supplies account-scoped failure data. */
+ retainLastSnapshotOnError?: boolean;
sourceKey?: string;
title: string;
tooltip: string;
@@ -243,6 +245,7 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
hasExtraData,
renderFooter,
renderHeader,
+ retainLastSnapshotOnError = true,
alwaysRenderHeader,
sourceKey = 'default',
title,
@@ -337,7 +340,7 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
}
// A failed refresh keeps the last good snapshot on screen (and in storage).
- if (hasQuotaDataForSnapshot(readQuota(requestSourceKey))) {
+ if (retainLastSnapshotOnError && hasQuotaDataForSnapshot(readQuota(requestSourceKey))) {
if (options.manual) setRefreshError(nextQuota);
return;
}
@@ -348,7 +351,13 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
setRefreshError(null);
setQuotaSnapshot(nextQuota, requestSourceKey, requestContext);
},
- [hasQuotaDataForSnapshot, isCurrentRequest, readQuota, setQuotaSnapshot],
+ [
+ hasQuotaDataForSnapshot,
+ isCurrentRequest,
+ readQuota,
+ retainLastSnapshotOnError,
+ setQuotaSnapshot,
+ ],
);
const loadQuota = useCallback(
diff --git a/src/services/codexQuota.test.ts b/src/services/codexQuota.test.ts
index cc94218d481..900990bb0f1 100644
--- a/src/services/codexQuota.test.ts
+++ b/src/services/codexQuota.test.ts
@@ -35,6 +35,7 @@ const reading = {
windowMinutes: 300,
};
const sample = {
+ credits: { balance: '1250.75', unlimited: false },
error: null,
identity: { externalAccountId: 'external-a' },
readings: [reading],
@@ -59,10 +60,11 @@ beforeEach(() => {
});
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('reads credits on first load even when persisted windows are fresh', async () => {
+ const reader = createCodexQuotaReader({});
+ expect((await reader()).credits).toEqual(sample.credits);
+ expect((await reader()).credits).toEqual(sample.credits);
+ expect(heterogeneousAgentService.getCodexQuota).toHaveBeenCalledTimes(1);
});
it('publishes a fresh local sample to the unified account layer', async () => {
@@ -95,11 +97,17 @@ describe('account-scoped Codex quota', () => {
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(await reader()).toMatchObject({
+ credits: sample.credits,
+ session: { usedPercent: 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(await reader({ revalidate: true })).toMatchObject({
+ credits: sample.credits,
+ session: { usedPercent: 23 },
+ });
expect(heterogeneousAgentService.getCodexQuota).not.toHaveBeenCalled();
});
@@ -110,11 +118,54 @@ describe('account-scoped Codex quota', () => {
expect(result.status).toBe('error');
});
+ it('returns stale saved windows and credits when the confirmed account refresh fails', async () => {
+ const reader = createCodexQuotaReader({ deviceId: 'device-a' });
+ await reader();
+ vi.mocked(agentQuotaService.refreshCodexQuota).mockResolvedValue({
+ error: 'Codex RPC timed out',
+ identity: sample.identity,
+ provider: 'codex',
+ session: null,
+ status: 'error',
+ updatedAt: sample.updatedAt + 1,
+ weekly: null,
+ });
+
+ expect(await reader({ force: true })).toMatchObject({
+ credits: sample.credits,
+ error: 'Codex RPC timed out',
+ identity: sample.identity,
+ session: { usedPercent: 23 },
+ status: 'error',
+ });
+ });
+
+ it.each([null, { externalAccountId: 'external-b' }])(
+ 'does not reuse cached credits after an error for a different or unidentified account (%j)',
+ async (identity) => {
+ const reader = createCodexQuotaReader({ deviceId: 'device-a' });
+ await reader();
+ vi.mocked(agentQuotaService.refreshCodexQuota).mockResolvedValue({
+ error: 'Codex RPC timed out',
+ identity,
+ provider: 'codex',
+ session: null,
+ status: 'error',
+ updatedAt: sample.updatedAt + 1,
+ weekly: null,
+ });
+
+ expect((await reader({ force: true })).credits).toBeUndefined();
+ expect((await reader()).session).toBeNull();
+ },
+ );
+
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,
+ credits: undefined,
identity: { externalAccountId: 'external-b' },
readings: [],
session: { ...sample.session, usedPercent: 80 },
@@ -122,6 +173,7 @@ describe('account-scoped Codex quota', () => {
const result = await reader({ revalidate: true });
expect(result.identity?.externalAccountId).toBe('external-b');
expect(result.session?.usedPercent).toBe(80);
+ expect(result.credits).toBeUndefined();
});
it('refreshes the quota replica after accepting a local snapshot', async () => {
diff --git a/src/services/codexQuota.ts b/src/services/codexQuota.ts
index ac3708947d5..ee8d889946b 100644
--- a/src/services/codexQuota.ts
+++ b/src/services/codexQuota.ts
@@ -55,7 +55,14 @@ export const createCodexQuotaReader = (source: CodexQuotaSource) => {
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)
+ // Persisted limit readings omit the live account's credit balance.
+ if (
+ lastLive &&
+ persisted &&
+ !options.force &&
+ !options.revalidate &&
+ Date.now() - receivedAt < REFRESH_MS
+ )
return persisted;
if (persisted) options.onInterim?.(persisted);
@@ -78,9 +85,22 @@ export const createCodexQuotaReader = (source: CodexQuotaSource) => {
if (persisted) return persisted;
throw error;
}
+ const externalAccountId = live?.identity?.externalAccountId;
+ if (live?.status === 'error') {
+ const fallback = externalAccountId
+ ? [persisted, lastLive].find(
+ (snapshot) => snapshot?.identity?.externalAccountId === externalAccountId,
+ )
+ : null;
+ if (!externalAccountId || externalAccountId !== trustedAccountId) {
+ trustedAccountId = undefined;
+ lastLive = null;
+ }
+ return fallback ? { ...fallback, error: live.error, status: 'error' } : live;
+ }
+
if (live?.status === 'ok') lastLive = live;
let ingested = false;
- const externalAccountId = live?.identity?.externalAccountId;
if (live?.status === 'ok' && externalAccountId) {
trustedAccountId = externalAccountId;
account = accounts.find((item) => item.externalAccountId === externalAccountId);
@@ -125,7 +145,8 @@ export const createCodexQuotaReader = (source: CodexQuotaSource) => {
account = undefined;
readings = [];
}
- if (account && readings.length) return buildCodexPanelSnapshot(account, readings, live);
+ if (account && readings.length)
+ return buildCodexPanelSnapshot(account, readings, live ?? lastLive);
return (
live ??
persisted ?? {
diff --git a/src/services/codexQuotaViewModel.test.ts b/src/services/codexQuotaViewModel.test.ts
index 2bb74664ff5..b28e5708f18 100644
--- a/src/services/codexQuotaViewModel.test.ts
+++ b/src/services/codexQuotaViewModel.test.ts
@@ -13,6 +13,7 @@ const reading = {
windowMinutes: 300,
};
const live = {
+ credits: { balance: '1250.75', unlimited: false },
error: null,
identity: { externalAccountId: 'b' },
provider: 'codex' as const,
@@ -25,17 +26,19 @@ const live = {
describe('Codex account view', () => {
it('never merges quota from another account', () => {
- expect(buildCodexPanelSnapshot(account, [reading], live, now).session?.usedPercent).toBe(23);
+ const result = buildCodexPanelSnapshot(account, [reading], live, now);
+ expect(result.session?.usedPercent).toBe(23);
+ expect(result.credits).toBeUndefined();
});
- it('merges newer live buckets only for the same account', () => {
- expect(
- buildCodexPanelSnapshot(
- account,
- [reading],
- { ...live, identity: { externalAccountId: 'a' } },
- now,
- ).session?.usedPercent,
- ).toBe(90);
+ it('merges newer live buckets and credits only for the same account', () => {
+ const result = buildCodexPanelSnapshot(
+ account,
+ [reading],
+ { ...live, identity: { externalAccountId: 'a' } },
+ now,
+ );
+ expect(result.session?.usedPercent).toBe(90);
+ expect(result.credits).toEqual(live.credits);
});
it('preserves persisted windows after a failed refresh', () => {
expect(
diff --git a/src/services/codexQuotaViewModel.ts b/src/services/codexQuotaViewModel.ts
index 90d87648f8b..b8a1a810df9 100644
--- a/src/services/codexQuotaViewModel.ts
+++ b/src/services/codexQuotaViewModel.ts
@@ -36,6 +36,7 @@ export const buildCodexPanelSnapshot = (
externalAccountId: account.externalAccountId ?? undefined,
};
return {
+ credits: sample?.credits,
error: null,
identity,
provider: 'codex',