Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

merge: reconcile model settings with unified usage cards

Chrisbff9d989158c
diff --cc apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
index 1d473f50c2,2b35c3b281..35ec1ff8b3
--- a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
+++ b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
@@@ -8,50 -8,22 +8,26 @@@
import { describe, expect, it } from 'vitest';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
+ import type { TFunction } from 'i18next';
++import {
++ formatClaudeSubscriptionPlanLabel,
++ formatCodexPlanLabel,
++} from '../lib/subscriptionPlanLabel';
+ import {
+ buildClaudeUsageCard,
+ buildCodexUsageCard,
+ buildXaiUsageCard,
+ } from '../components/status/usageCardModel';
+ const compact = (value: string) => value.replace(/\s+/g, '');
const sourcePath = resolve(__dirname, '..', 'components', 'status', 'TodaySpendChip.tsx');
- const quotaHoverCardPath = resolve(__dirname, '..', 'components', 'status', 'QuotaHoverCard.tsx');
- const preloadPath = resolve(__dirname, '..', '..', 'preload', 'preload.ts');
- const rendererTypesPath = resolve(__dirname, '..', 'vite-env.d.ts');
- // 套餐名的查表与格式化已从这两个组件抽到共享模块(设置页的供应商用量模块是第三个
- // 消费方,再抄一份就成三份必漂)。断言随实现搬家:查表内容断在共享模块上,组件侧只断
- // 「确实调了共享函数」。
- const planLabelPath = resolve(__dirname, '..', 'lib', 'subscriptionPlanLabel.ts');
// Windows CRLF 检出下 \n 字面量断言会失配,统一归一化成 LF 再断言。
const source = readFileSync(sourcePath, 'utf8').replace(/\r\n/g, '\n');
- const quotaHoverCardSource = readFileSync(quotaHoverCardPath, 'utf8').replace(/\r\n/g, '\n');
- const planLabelSource = readFileSync(planLabelPath, 'utf8').replace(/\r\n/g, '\n');
- const preloadSource = readFileSync(preloadPath, 'utf8').replace(/\r\n/g, '\n');
- const rendererTypesSource = readFileSync(rendererTypesPath, 'utf8').replace(/\r\n/g, '\n');
- const localeSources = ['en', 'zh-CN', 'zh-TW', 'ja', 'ko'].map((locale) =>
- readFileSync(resolve(__dirname, '..', 'i18n', 'locales', locale, 'common.json'), 'utf8').replace(
- /\r\n/g,
- '\n',
- ),
- );
-
describe('TodaySpendChip dashboard routing', () => {
- it('keeps the latest user-round total separate while aggregating token/model details', () => {
- expect(source).toContain('message.userTurnMoney?.amount');
- expect(source).toContain('const userTurnCostUsd = typeof message.userTurnCostUsd');
- expect(source).toContain('? { money: userTurnMoney }');
- expect(source).toContain('isUserTurnTotal: Boolean(userTurnMoney || userTurnCostUsd != null)');
- expect(source).toContain("'todaySpend.tooltip.latestUserTurnTitle'");
- expect(source).toContain('aggregateAssistantTurnUsageDetails(messages, message.clientId)');
- expect(source).toContain(
- 'Amount and token/model detail now describe the same visible user turn',
- );
- expect(source).toContain('money: summary.money');
- expect(source).not.toContain('segmentMoney: message.turnMoney');
- expect(source).not.toContain('segmentCostUsd: message.turnCostUsd');
- expect(source).toContain('inputTokensText: formatCompactTokens(details.inputTokens)');
- expect(source).toContain('outputTokensText: formatCompactTokens(details.outputTokens)');
- });
-
it('routes Codex/CC/Pi subscription providers to their account usage pages and keeps gateway routes local', () => {
- expect(source).toContain('https://chatgpt.com/codex/settings/usage');
- expect(source).toContain('https://grok.com');
- expect(source).toContain('https://claude.ai/settings/usage');
+ expect(compact(source)).toContain(compact('https://chatgpt.com/codex/settings/usage'));
+ expect(compact(source)).toContain(compact('https://grok.com'));
+ expect(compact(source)).toContain(compact('https://claude.ai/settings/usage'));
// 网关 / 托管账号这一路 URL 落到 null(点击无跳转);其余三路指向各自公开看板。
expect(source).toMatch(
/usesXaiQuotaForm\s*\?\s*XAI_USAGE_DASHBOARD_URL\s*:\s*isCodexOauth \|\| isChatgptBridge\s*\?\s*CODEX_USAGE_DASHBOARD_URL\s*:\s*isClaudeSubscription\s*\?\s*CLAUDE_USAGE_DASHBOARD_URL\s*:\s*null/,
@@@ -399,69 -188,174 +192,198 @@@
// 悬念期催刷通道必须与 chip 显示的配额槽一致: bridge 形态催 WHAM; Codex CLI
// 形态显示 app-server 槽, WHAM 刷新帮不上它(靠 turn 事件 / 悬念超时兜底),
// 不得催 —— WHAM 桶与 CLI 配额可能不同(账号多限额桶, 2026-07-24 实报 bug)
- expect(source).toContain(
- 'if (isChatgptBridge) {\n' +
- ' requestCodexAccountRefresh();\n' +
- ' } else if (usesXaiQuotaForm) {\n' +
- ' requestXaiSubscriptionRefresh();\n' +
- ' } else if (isClaudeSubscription && !usesCodexQuotaForm) {\n' +
- ' requestClaudeSubscriptionRefresh();\n' +
- ' }',
- );
- expect(source).toContain(
- 'const hasPendingResetWindow = chipWindows.some((window) => window.resetPending);',
- );
- expect(source).toContain('const xaiNeedsWeeklyRefresh = usesXaiQuotaForm');
- expect(source).not.toContain('Boolean(xaiSubscriptionUsage)');
+ expect(compact(source)).toContain(
+ compact(
+ 'if (isChatgptBridge) {\n' +
+ ' requestCodexAccountRefresh();\n' +
+ ' } else if (usesXaiQuotaForm) {\n' +
+ ' requestXaiSubscriptionRefresh();\n' +
+ ' } else if (isClaudeSubscription && !usesCodexQuotaForm) {\n' +
+ ' requestClaudeSubscriptionRefresh();\n' +
+ ' }',
+ ),
+ );
+ expect(compact(source)).toContain(
+ compact('const hasPendingResetWindow = chipWindows.some((window) => window.resetPending);'),
+ );
+ expect(compact(source)).toContain(compact('const xaiNeedsWeeklyRefresh = usesXaiQuotaForm'));
+ expect(compact(source)).not.toContain(compact('Boolean(xaiSubscriptionUsage)'));
});
- it('does not treat missing subscription credits as exhausted usage', () => {
- expect(source).toContain(
- 'function shouldShowCodexLimitReachedReason(snapshot: RateLimitSnapshot): boolean',
- );
- expect(source).toContain("snapshot.rateLimitReachedType.includes('credits_depleted')");
- expect(source).not.toContain('if (snapshot.rateLimitReachedType) return t');
- expect(source).not.toContain('credits.hasCredits\\n ? t');
+ it('no longer exposes the per-key (curApp) tooltip metric', () => {
+ expect(compact(source)).not.toContain(compact('useTodaySpend'));
+ // curApp / currentKeyTodaySpend 指标已于 2026-06-21 移除 (口径冗余 + key 取错桶)。
+ // regression guard: 防止它被重新引入。
+ expect(compact(source)).not.toContain(compact('currentKeyTodaySpend'));
+ expect(compact(source)).not.toContain(compact("t('todaySpend.currentKeyLabel'"));
+ expect(compact(source)).not.toContain(compact("t('todaySpend.tooltip.currentKeyUnavailable')"));
+ expect(compact(source)).not.toContain(compact("'curApp'"));
});
+ });
- it('formats Codex plan labels for display', () => {
- // 查表在共享模块里;两家取值域不同,必须是两张分开的表(合成一张会让任一家的
- // 未知值悄悄命中另一家的条目)。
- expect(planLabelSource).toContain("business: 'Business'");
- expect(planLabelSource).toContain('export function formatCodexPlanLabel');
- expect(planLabelSource).toContain('export function formatClaudeSubscriptionPlanLabel');
- expect(source).toContain('formatCodexPlanLabel(snapshot.planType)');
+ // Presentation contracts use real provider inputs instead of pinning helper names or JSX branches.
+ const t = ((key: string, values?: Record<string, unknown>) =>
+ `${key}${values ? ':' + JSON.stringify(values) : ''}`) as TFunction;
+ const now = Date.UTC(2026, 8, 5);
+ describe('shared usage-card provider projections', () => {
++ it.each([
++ [' ProLite ', 'ProLite', 'Pro Lite'],
++ ['custom_plan', 'Custom_plan', 'Custom Plan'],
++ ['', null, null],
++ ])('keeps settings and usage cards consistent for plan %s', (plan, claudeLabel, codexLabel) => {
++ const claude = buildClaudeUsageCard({ subscriptionType: plan, updatedAt: now }, t);
++ const codex = buildCodexUsageCard({ planType: plan }, null, t, now);
++ expect(claude.planLabel).toBe(claudeLabel);
++ expect(codex.planLabel).toBe(codexLabel);
++ expect(claude.planLabel).toBe(formatClaudeSubscriptionPlanLabel(plan));
++ expect(codex.planLabel).toBe(formatCodexPlanLabel(plan));
+ });
+
- it('drops the internal usage-dashboard domain pre-OSS: gateway / XD accounts get no link and stay non-clickable, other metrics unchanged', () => {
- // 内部用量看板 URL 只活在 PROXY_USAGE_DASHBOARD_URL 常量里 —— 断言该常量已消失
- // + 三元结尾落 null(见上一个用例的正则),即等价于"内部域名已从源码移除";
- // 这里不重新写出被禁的内部域名字面量,否则它又会 grep 命中公开仓。
- expect(source).not.toContain('PROXY_USAGE_DASHBOARD_URL');
- // 网关账号无看板 → url/label 落 null,chip 不可点(点击无跳转)。
- expect(source).toContain('const isDashboardClickable = usageDashboardUrl !== null');
- expect(source).toContain('if (!usageDashboardUrl) return;');
- // tooltip "打开看板" 行经 helper 统一追加,label 为 null(网关账号)时不追加。
- expect(source).toContain(
- 'function pushDashboardLinkLine(lines: string[], label: string | null)',
- );
- // 网关账号仍展示 daily/credit/session 指标 + tooltip(仅去掉"打开看板"链接行)。
- // credit 段服务个人租户的三池账本(LiteLLM 语义的 daily/monthly 对它恒不可用)。
- expect(source).toContain(
- "const PRIMARY_GATEWAY_METRICS: readonly MetricKey[] = ['daily', 'credit', 'session']",
- );
- expect(source).toContain('const chipSegments = getGatewayChipSegments(slots)');
- expect(source).toContain("t('todaySpend.dailyLimitLabel'");
- expect(source).toContain('pushSessionUsageLines(tooltipLines, sessionUsage, null, t)');
++ it('treats malformed plan metadata as absent without dropping quota windows', () => {
++ const card = buildCodexUsageCard(
++ { planType: 123 as unknown as string, primary: { usedPercent: 25 } },
++ null,
++ t,
++ now,
++ );
++ expect(card.planLabel).toBeNull();
++ expect(card.windows[0].window.utilization).toBe(25);
+ });
+
- it('no longer exposes the per-key (curApp) tooltip metric', () => {
- expect(source).not.toContain('useTodaySpend');
- // curApp / currentKeyTodaySpend 指标已于 2026-06-21 移除 (口径冗余 + key 取错桶)。
- // regression guard: 防止它被重新引入。
- expect(source).not.toContain('currentKeyTodaySpend');
- expect(source).not.toContain("t('todaySpend.currentKeyLabel'");
- expect(source).not.toContain("t('todaySpend.tooltip.currentKeyUnavailable')");
- expect(source).not.toContain("'curApp'");
+ it.each(['free', 'plus', 'business', 'enterprise', 'custom_plan'])(
+ 'preserves ChatGPT plan %s without requiring quota windows',
+ (planType) => {
+ const card = buildCodexUsageCard({ planType }, null, t, now, 'en');
+ expect(card.title).toBe('ChatGPT');
+ expect(card.planLabel).toBe(
+ planType
+ .split('_')
+ .map((part) => part[0].toUpperCase() + part.slice(1))
+ .join(' '),
+ );
+ expect(card.windows).toEqual([]);
+ },
+ );
+
+ it('preserves explicit zero reset credits and localizes their expiry', () => {
+ const card = buildCodexUsageCard(
+ null,
+ {
+ rows: [],
+ hasResetCreditCount: true,
+ availableCount: 0,
+ earliestExpiryAt: now / 1000 + 3600,
+ canReset: false,
+ shouldPrompt: false,
+ },
+ t,
+ now,
+ 'en',
+ );
+ expect(card.details).toContain('todaySpend.codex.resetCreditsAvailableLine:{"count":0}');
+ expect(
+ card.details?.some((line) =>
+ line.startsWith('todaySpend.codex.resetCreditEarliestExpiryLine'),
+ ),
+ ).toBe(true);
+ });
+
+ it('does not label a thirty-day window as weekly', () => {
+ const card = buildCodexUsageCard(
+ { primary: { usedPercent: 1, windowMinutes: 43200 } },
+ null,
+ t,
+ now,
+ );
+ expect(card.windows[0].title).toBe('todaySpend.codex.daysWindow:{"days":30}');
+ });
+
+ it('keeps native credits and balance status separate from quota exhaustion', () => {
+ const card = buildCodexUsageCard(
+ {
+ credits: { balance: '1,234.50', hasCredits: false, unlimited: false },
+ primary: { usedPercent: 20, windowMinutes: 90 },
+ rateLimitReachedType: 'workspace_owner_credits_depleted',
+ },
+ null,
+ t,
+ now,
+ 'en',
+ );
+ expect(card.details).toContain('todaySpend.codex.creditsLine:{"credits":"1,234.50"}');
+ expect(card.details).toContain('todaySpend.codex.balanceDepleted');
+ expect(card.notices).toEqual([]);
+ expect(card.windows[0].title).toBe('90m');
+ });
+
+ it('shows rate-limit reasons only when an observed window is exhausted', () => {
+ const snapshot = { primary: { usedPercent: 50 }, rateLimitReachedType: 'rate_limit_reached' };
+ expect(buildCodexUsageCard(snapshot, null, t, now).notices).toEqual([]);
+ snapshot.primary.usedPercent = 100;
+ expect(buildCodexUsageCard(snapshot, null, t, now).notices?.[0].tone).toBe('crit');
+ });
+
+ it('handles missing or malformed percentages without inventing zero quota', () => {
+ const card = buildCodexUsageCard(
+ { primary: { usedPercent: NaN }, secondary: { usedPercent: 12, windowMinutes: 300 } },
+ null,
+ t,
+ now,
+ );
+ expect(card.windows).toHaveLength(1);
+ expect(card.windows[0].window.utilization).toBe(12);
+ expect(buildCodexUsageCard(null, null, t, now).emptyText).toBe('quotaCard.waiting');
+ });
+
+ it('preserves Grok product, prepaid USD, and instantaneous rate-limit details', () => {
+ const card = buildXaiUsageCard(
+ {
+ planLabel: 'SuperGrok',
+ creditUsagePercent: 9,
+ updatedAt: now,
+ resetsAt: now / 1000 + 3600,
+ productUsage: [
+ { product: 'GrokBuild', usagePercent: 2 },
+ { product: 'OtherProduct', usagePercent: 7 },
+ { product: 'InvalidProduct', usagePercent: NaN },
+ ],
+ prepaidBalance: 12.3,
+ },
+ {
+ remainingRequests: 3,
+ limitRequests: 10,
+ remainingTokens: 1000,
+ limitTokens: 5000,
+ updatedAt: now,
+ },
+ t,
+ now,
+ );
+ expect(card.windows.map((window) => window.window.utilization)).toEqual([9]);
+ expect(card.windows[0].breakdown).toEqual([
+ { label: 'quotaCard.includedLabel:{"name":"Grok Build"}', value: '2%' },
+ { label: 'quotaCard.includedLabel:{"name":"Other Product"}', value: '7%' },
+ ]);
+ expect(card.windows[0].detail).toBe('todaySpend.xai.accountWeeklyHint');
+ expect(card.details).toEqual(
+ expect.arrayContaining([
+ 'todaySpend.xai.extraCreditsLine:{"amount":"US$12.30"}',
+ 'todaySpend.xai.requestsLine:{"remaining":"3","limit":"10"}',
+ ]),
+ );
+ expect(card.details?.some((line) => line.startsWith('todaySpend.xai.tokensLine'))).toBe(true);
+ });
+
+ it('filters expired Grok data without borrowing Claude quota', () => {
+ const card = buildXaiUsageCard(
+ { planLabel: 'SuperGrok', creditUsagePercent: 9, updatedAt: now - 31 * 60_000 },
+ null,
+ t,
+ now,
+ );
+ expect(card.planLabel).toBe('SuperGrok');
+ expect(card.windows).toEqual([]);
+ expect(card.emptyText).toBe('todaySpend.xai.noQuotaDetail');
+ expect(buildClaudeUsageCard(null, t).windows).toEqual([]);
});
});
diff --cc apps/desktop/src/renderer/components/status/usageCardModel.ts
index 0000000000,9abc8c94a3..73711a675e
mode 000000,100644..100644
--- a/apps/desktop/src/renderer/components/status/usageCardModel.ts
+++ b/apps/desktop/src/renderer/components/status/usageCardModel.ts
@@@ -1,0 -1,275 +1,254 @@@
+ /** Provider snapshots are adapted here; the card renders only this common presentation model. */
+ import type { TFunction } from 'i18next';
+ import type { CodexRateLimitResetSummary } from '@cindy/maker-shared/session-controls';
+ import type { RateLimitSnapshot } from '@/hooks/useAccountUsage';
+ import type { XaiRateLimitSnapshot } from '@/hooks/useXaiRateLimit';
+ import type { ClaudeSubscriptionUsageSnapshot } from '../../../shared/claudeSubscriptionUsage';
+ import {
+ formatXaiProductLabel,
+ isXaiWeeklyUsageCurrent,
+ type XaiSubscriptionUsageSnapshot,
+ } from '../../../shared/xaiSubscriptionUsage';
+ import { formatCompactTokens } from '@/lib/usageFormat';
++import {
++ formatClaudeSubscriptionPlanLabel,
++ formatCodexPlanLabel,
++} from '@/lib/subscriptionPlanLabel';
+
+ export interface UsageCardWindow {
+ key: string;
+ title: string;
+ window: {
+ utilization: number;
+ /** Epoch seconds, matching provider reset timestamps. */
+ resetsAt?: number | null;
+ severity?: string | null;
+ };
+ /** Only set when the provider supplies a known duration and observation time. */
+ paceWindowMinutes?: number;
+ detail?: string;
+ /** Composition of this window, not independently enforceable quota windows. */
+ breakdown?: ReadonlyArray<{ label: string; value: string }>;
+ }
+
+ export interface UsageCardAccount {
+ title?: string;
+ planLabel?: string | null;
+ windows: UsageCardWindow[];
+ details?: string[];
+ notices?: Array<{ text: string; tone: 'warn' | 'crit' }>;
+ emptyText?: string;
+ updatedAt?: number | null;
+ }
+
-const PLAN_LABELS: Record<string, string> = {
- free: 'Free',
- go: 'Go',
- plus: 'Plus',
- pro: 'Pro',
- prolite: 'Pro Lite',
- max: 'Max',
- team: 'Team',
- business: 'Business',
- enterprise: 'Enterprise',
- edu: 'Edu',
- unknown: 'Unknown',
- self_serve_business_usage_based: 'Self Serve Business Usage Based',
- enterprise_cbp_usage_based: 'Enterprise CBP Usage Based',
-};
-
-function formatPlanType(value: unknown): string | null {
- if (typeof value !== 'string' || !value.trim()) return null;
- const trimmed = value.trim();
- return (
- PLAN_LABELS[trimmed.toLowerCase()] ??
- trimmed.replace(/[_-]+/g, ' ').replace(/\b\w/g, (char) => char.toUpperCase())
- );
-}
-
+ export function formatQuotaResetAt(
+ resetsAt: number | null | undefined,
+ nowMs: number,
+ locale?: string,
+ ): string | null {
+ if (typeof resetsAt !== 'number' || !Number.isFinite(resetsAt) || resetsAt <= 0) return null;
+ const date = new Date(resetsAt * 1000);
+ if (!Number.isFinite(date.getTime())) return null;
+ const now = new Date(nowMs);
+ const sameDay =
+ date.getFullYear() === now.getFullYear() &&
+ date.getMonth() === now.getMonth() &&
+ date.getDate() === now.getDate();
+ const time = new Intl.DateTimeFormat(locale, {
+ hour: '2-digit',
+ minute: '2-digit',
+ hour12: false,
+ }).format(date);
+ return sameDay
+ ? time
+ : `${new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric' }).format(date)} ${time}`;
+ }
+
+ export function buildClaudeUsageCard(
+ snapshot: ClaudeSubscriptionUsageSnapshot | null,
+ t: TFunction,
+ ): UsageCardAccount {
+ if (!snapshot) return { title: 'Claude', windows: [], emptyText: t('quotaCard.waiting') };
+ const windows: UsageCardWindow[] = [];
+ const add = (
+ key: string,
+ title: string,
+ window: UsageCardWindow['window'] | null | undefined,
+ paceWindowMinutes?: number,
+ ) => {
+ if (window && Number.isFinite(window.utilization))
+ windows.push({ key, title, window, paceWindowMinutes });
+ };
+ add('five-hour', t('quotaCard.fiveHourLabel'), snapshot.fiveHour);
+ add('seven-day', t('quotaCard.weeklyLabel'), snapshot.sevenDay, 10_080);
+ for (const [index, scoped] of (Array.isArray(snapshot.scoped) ? snapshot.scoped : []).entries()) {
+ if (!scoped) continue;
+ add(
+ `scoped-${index}`,
+ t('quotaCard.modelWeeklyLabel', { model: scoped.modelDisplayName }),
+ scoped,
+ );
+ }
+ const rawRateLimitStatus = snapshot.rateLimitStatus;
+ const status =
+ typeof rawRateLimitStatus === 'string' ? rawRateLimitStatus.trim().toLowerCase() : undefined;
+ return {
+ title: 'Claude',
- planLabel: formatPlanType(snapshot.subscriptionType),
++ planLabel: formatClaudeSubscriptionPlanLabel(snapshot.subscriptionType),
+ windows,
+ updatedAt: snapshot.updatedAt,
+ emptyText: windows.length ? undefined : t('quotaCard.noWindows'),
+ notices:
+ status === 'rejected'
+ ? [{ text: t('quotaCard.limitRejected'), tone: 'crit' }]
+ : status === 'allowed_warning'
+ ? [{ text: t('quotaCard.limitWarning'), tone: 'warn' }]
+ : [],
+ details: snapshot.extraUsage?.isEnabled === true ? [t('quotaCard.extraUsageEnabled')] : [],
+ };
+ }
+
+ /** Window labels follow the upstream duration, never assume a fixed pair of windows. */
+ export function quotaWindowLabel(minutes: number | null | undefined, t: TFunction): string {
+ if (typeof minutes !== 'number' || !Number.isFinite(minutes) || minutes <= 0)
+ return t('todaySpend.codex.limitWindow');
+ if (minutes === 10_080) return t('quotaCard.weeklyLabel');
+ if (minutes % 1440 === 0) return t('todaySpend.codex.daysWindow', { days: minutes / 1440 });
+ if (minutes === 300) return t('quotaCard.fiveHourLabel');
+ return minutes % 60 === 0 ? `${minutes / 60}h` : `${Math.round(minutes)}m`;
+ }
+
+ export function buildCodexUsageCard(
+ snapshot: RateLimitSnapshot | null,
+ resetSummary: CodexRateLimitResetSummary | null,
+ t: TFunction,
+ nowMs: number,
+ locale?: string,
+ ): UsageCardAccount {
+ const windows: UsageCardWindow[] = [];
+ for (const key of ['primary', 'secondary'] as const) {
+ const window = snapshot?.[key];
+ if (!window || !Number.isFinite(window.usedPercent)) continue;
+ windows.push({
+ key,
+ title: quotaWindowLabel(window.windowMinutes, t),
+ window: { utilization: window.usedPercent, resetsAt: window.resetsAt },
+ paceWindowMinutes: window.windowMinutes === 10_080 ? 10_080 : undefined,
+ });
+ }
+ const details: string[] = [];
+ const credits = snapshot?.credits;
+ const balance =
+ typeof credits?.balance === 'string' ? credits.balance.trim().replace(/,/g, '') : '';
+ const numericBalance = balance ? Number(balance) : NaN;
+ const hasBalance = Number.isFinite(numericBalance);
+ if (hasBalance)
+ details.push(
+ t('todaySpend.codex.creditsLine', {
+ credits: numericBalance.toLocaleString(locale, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ }),
+ }),
+ );
+ if (credits?.unlimited) details.push(t('todaySpend.codex.balanceUnlimited'));
+ else if (credits && !credits.hasCredits) details.push(t('todaySpend.codex.balanceDepleted'));
+ else if (credits?.hasCredits && !hasBalance) details.push(t('todaySpend.codex.balanceAvailable'));
+ if (resetSummary?.hasResetCreditCount)
+ details.push(
+ t('todaySpend.codex.resetCreditsAvailableLine', { count: resetSummary.availableCount }),
+ );
+ const expiryAt = formatQuotaResetAt(resetSummary?.earliestExpiryAt, nowMs, locale);
+ if (expiryAt) details.push(t('todaySpend.codex.resetCreditEarliestExpiryLine', { at: expiryAt }));
+ const reason = snapshot?.rateLimitReachedType;
+ const exhausted = windows.some(({ window }) => window.utilization >= 99.95);
+ return {
+ title: 'ChatGPT',
- planLabel: formatPlanType(snapshot?.planType),
++ planLabel: formatCodexPlanLabel(snapshot?.planType),
+ windows,
+ details,
+ updatedAt: snapshot?.updatedAt,
+ emptyText: windows.length ? undefined : t('quotaCard.noWindows'),
+ notices:
+ exhausted && reason && !reason.includes('credits_depleted')
+ ? [
+ {
+ text: t('todaySpend.codex.limitReached', {
+ reason: reason
+ .replace(/[_-]+/g, ' ')
+ .replace(/\b\w/g, (char) => char.toUpperCase()),
+ }),
+ tone: 'crit',
+ },
+ ]
+ : [],
+ ...(!snapshot ? { emptyText: t('quotaCard.waiting') } : {}),
+ };
+ }
+
+ export function buildXaiUsageCard(
+ usage: XaiSubscriptionUsageSnapshot | null,
+ rateLimit: XaiRateLimitSnapshot | null,
+ t: TFunction,
+ nowMs: number,
+ ): UsageCardAccount {
+ const weekly = isXaiWeeklyUsageCurrent(usage, nowMs) ? usage : null;
+ const windows: UsageCardWindow[] = [];
+ const details: string[] = [];
+ if (weekly && typeof weekly.creditUsagePercent === 'number') {
+ windows.push({
+ key: 'weekly',
+ title: t('quotaCard.weeklyLabel'),
+ window: { utilization: weekly.creditUsagePercent, resetsAt: weekly.resetsAt },
+ paceWindowMinutes: 10_080,
+ detail: t('todaySpend.xai.accountWeeklyHint'),
+ breakdown: (weekly.productUsage ?? [])
+ .filter((product) => Number.isFinite(product.usagePercent))
+ .map((product) => ({
+ label: t('quotaCard.includedLabel', { name: formatXaiProductLabel(product.product) }),
+ value: `${Math.round(Math.min(100, Math.max(0, product.usagePercent)))}%`,
+ })),
+ });
+ if (
+ typeof weekly.prepaidBalance === 'number' &&
+ Number.isFinite(weekly.prepaidBalance) &&
+ weekly.prepaidBalance > 0
+ ) {
+ details.push(
+ t('todaySpend.xai.extraCreditsLine', { amount: `US$${weekly.prepaidBalance.toFixed(2)}` }),
+ );
+ }
+ }
+ if (
+ rateLimit &&
+ typeof rateLimit.remainingRequests === 'number' &&
+ typeof rateLimit.limitRequests === 'number'
+ ) {
+ details.push(
+ t('todaySpend.xai.requestsLine', {
+ remaining: rateLimit.remainingRequests.toLocaleString(),
+ limit: rateLimit.limitRequests.toLocaleString(),
+ }),
+ );
+ }
+ if (
+ rateLimit &&
+ typeof rateLimit.remainingTokens === 'number' &&
+ typeof rateLimit.limitTokens === 'number'
+ ) {
+ details.push(
+ t('todaySpend.xai.tokensLine', {
+ remaining: formatCompactTokens(rateLimit.remainingTokens),
+ limit: formatCompactTokens(rateLimit.limitTokens),
+ }),
+ );
+ }
+ return {
+ title: 'Grok',
+ planLabel: usage?.planLabel,
+ windows,
+ details,
+ updatedAt: usage?.updatedAt,
+ emptyText: windows.length ? undefined : t('todaySpend.xai.noQuotaDetail'),
+ };
+ }
diff --cc apps/desktop/src/renderer/lib/subscriptionPlanLabel.ts
index 7c1d6a73f3,0000000000..0f5e0ff435
mode 100644,000000..100644
--- a/apps/desktop/src/renderer/lib/subscriptionPlanLabel.ts
+++ b/apps/desktop/src/renderer/lib/subscriptionPlanLabel.ts
@@@ -1,53 -1,0 +1,54 @@@
+/**
+ * 订阅套餐名的显示形态 —— 状态栏 chip / 悬停卡与设置页的供应商用量模块共用。
+ *
+ * 抽出来的原因:同一套「已知拼写查表 → 未知就规范化大小写」的逻辑原先在
+ * `QuotaHoverCard`(Claude subscriptionType)与 `TodaySpendChip`(Codex planType)
+ * 各有一份私有副本。设置页要显示第三处,再抄一遍就成三份 —— 三份必然漂,而套餐名是
+ * 用户在两个不同界面里核对同一件事时最容易发现不一致的地方。
+ *
+ * 两个函数分开是因为**两家的取值域不同**,不是同一张表:Anthropic 给 pro / max /
+ * team / enterprise,ChatGPT 还有 go / plus / prolite / *_usage_based 这类。合成一张表
+ * 会让任一家的未知值悄悄命中另一家的条目。
+ */
+
+/** Anthropic 订阅(凭证 blob 的 subscriptionType)。未知套餐保留原始拼写,只补首字母大写。 */
+export function formatClaudeSubscriptionPlanLabel(subscriptionType: unknown): string | null {
+ if (typeof subscriptionType !== 'string') return null;
+ const trimmed = subscriptionType.trim();
+ if (!trimmed) return null;
+
+ const knownPlans: Record<string, string> = {
+ max: 'Max',
+ pro: 'Pro',
+ team: 'Team',
+ enterprise: 'Enterprise',
+ };
+ return (
+ knownPlans[trimmed.toLowerCase()] ?? `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`
+ );
+}
+
+const CODEX_PLAN_TYPE_LABELS: Record<string, string> = {
+ free: 'Free',
+ go: 'Go',
+ plus: 'Plus',
+ pro: 'Pro',
+ prolite: 'Pro Lite',
+ team: 'Team',
+ self_serve_business_usage_based: 'Self Serve Business Usage Based',
+ business: 'Business',
+ enterprise_cbp_usage_based: 'Enterprise CBP Usage Based',
+ enterprise: 'Enterprise',
+ edu: 'Edu',
+ unknown: 'Unknown',
+};
+
+/** ChatGPT / Codex 套餐(app-server 的 planType)。未知值按 snake/kebab → Title Case。 */
- export function formatCodexPlanLabel(planType: string | null | undefined): string | null {
- const trimmed = planType?.trim();
++export function formatCodexPlanLabel(planType: unknown): string | null {
++ if (typeof planType !== 'string') return null;
++ const trimmed = planType.trim();
+ if (!trimmed) return null;
- const known = CODEX_PLAN_TYPE_LABELS[trimmed];
++ const known = CODEX_PLAN_TYPE_LABELS[trimmed.toLowerCase()];
+ if (known) return known;
+ return trimmed.replace(/[_-]+/g, ' ').replace(/\b\w/g, (char) => char.toUpperCase());
+}