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。

fix(desktop): 统一套餐用量卡片并理清配额与明细层级 (#3972)

Dash416b2b793da3
diff --git a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
index b1cfa100ef..2b35c3b281 100644
--- a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
+++ b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
@@ -8,451 +8,354 @@
import { describe, expect, it } from 'vitest';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
+import type { TFunction } from 'i18next';
+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');
// 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 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/,
);
- expect(source).toContain('todaySpend.openCodexUsage');
- expect(source).toContain('todaySpend.openXaiUsage');
- expect(source).toContain('todaySpend.openClaudeUsage');
+ expect(compact(source)).toContain(compact('todaySpend.openCodexUsage'));
+ expect(compact(source)).toContain(compact('todaySpend.openXaiUsage'));
+ expect(compact(source)).toContain(compact('todaySpend.openClaudeUsage'));
// 只有实际 Gateway 会话读取 Model Access quota;自定义供应商只保留本会话统计。
- expect(source).toContain(
- 'const usesGatewayQuota = isClaudeGateway || isCodexGateway || isPiGateway;',
- );
- expect(source).toContain('useClaudeAccountUsage(usesGatewayQuota)');
- });
-
- it('treats CC/Pi chatgpt/ and xai/ bridge sessions as subscription usage', () => {
- expect(source).toContain('modelId.startsWith(CHATGPT_MODEL_PREFIX)');
- expect(source).toContain('modelId.startsWith(XAI_MODEL_PREFIX)');
- expect(source).toContain("(vendorKey === 'cc' || vendorKey === 'pi')");
- expect(source).toContain("providerId === 'openai'");
- expect(source).toContain("providerId === 'xai'");
- expect(source).toContain('const isSubscriptionBridge = isChatgptBridge || isXaiBridge;');
- // ChatGPT 仍要前缀;xAI 显式选中供应商即可(Pi 模型是 grok-4.6,没有 xai/ 前缀)。
- expect(source).toContain("(providerId == null || providerId === 'openai')");
- expect(source).toContain('providerId == null && isXaiPrefixedModel');
- expect(source).toContain('useClaudeAccountUsage(usesGatewayQuota)');
- // gateway quota 对订阅 bridge 会话关闭;device-link 远程同样不读本机网关配额
- expect(source).toContain('&& !isDeviceLinkRemote');
- // chatgpt bridge 复用 codex 订阅 chip 形态;xai 走账号周用量 + 限流 tooltip
- expect(source).toContain('const usesCodexQuotaForm = isCodexOauth || isChatgptBridge;');
- expect(source).toContain('const usesXaiQuotaForm = isCodexXaiProvider || isXaiBridge;');
- expect(source).toContain('tooltipNode = buildXaiTooltipNode(');
- expect(source).toContain('getXaiChipWindows(xaiSubscriptionUsage');
- expect(source).toContain('const weekly = isXaiWeeklyUsageCurrent(usage, nowMs) ? usage : null;');
- expect(source).toContain('useXaiSubscriptionUsage(usesXaiQuotaForm && !isAnyRemoteSession)');
- // 远程会话(SSH / device-link)抑制本机 xAI 限流快照读取
- expect(source).toContain('useXaiRateLimit(usesXaiQuotaForm && !isAnyRemoteSession)');
- expect(source).toContain('todaySpend.xai.noQuotaDetail');
- expect(source).toContain('todaySpend.xai.accountWeeklyHint');
- // bridge 形态优先于 Claude 订阅形态(model 前缀决定实际消耗的额度);device-link 远程不读本机订阅余量
- expect(source).toContain(
- 'isClaudeSubscription && !isSubscriptionBridge && !isDeviceLinkRemote',
+ expect(compact(source)).toContain(
+ compact('const usesGatewayQuota = isClaudeGateway || isCodexGateway || isPiGateway;'),
);
+ expect(compact(source)).toContain(compact('useClaudeAccountUsage(usesGatewayQuota)'));
});
it('treats codex/ budget models + explicit XD selection as API usage on an oauth-bearer spawn', () => {
- expect(source).toContain("modelId.startsWith('codex/')");
- expect(source).toContain("codexAuthInjection === 'oauth-bearer'");
- expect(source).toContain("vendorKey === 'codex' && !isCodexXaiProvider");
- expect(source).toContain('isRemoteCodexSession ||');
- expect(source).toContain("(providerId == null || providerId === 'openai')");
- expect(source).toContain('modelId.startsWith(XAI_MODEL_PREFIX)');
- expect(source).toContain("providerId === 'xai'");
- expect(source).toContain('const isCodexSubscription = isCodexOauth || isCodexXaiProvider;');
- expect(source).toContain("const isCodexApi = vendorKey === 'codex' && !isCodexSubscription");
- expect(source).not.toContain("codexAuthState.authSource === 'oauth'");
+ expect(compact(source)).toContain(compact("modelId.startsWith('codex/')"));
+ expect(compact(source)).toContain(compact("codexAuthInjection === 'oauth-bearer'"));
+ expect(compact(source)).toContain(compact("vendorKey === 'codex' && !isCodexXaiProvider"));
+ expect(compact(source)).toContain(compact('isRemoteCodexSession ||'));
+ expect(compact(source)).toContain(compact("(providerId == null || providerId === 'openai')"));
+ expect(compact(source)).toContain(compact('modelId.startsWith(XAI_MODEL_PREFIX)'));
+ expect(compact(source)).toContain(compact("providerId === 'xai'"));
+ expect(compact(source)).toContain(
+ compact('const isCodexSubscription = isCodexOauth || isCodexXaiProvider;'),
+ );
+ expect(compact(source)).toContain(
+ compact("const isCodexApi = vendorKey === 'codex' && !isCodexSubscription"),
+ );
+ expect(compact(source)).not.toContain(compact("codexAuthState.authSource === 'oauth'"));
});
it('renders device-link remote sessions data-driven without local-account classification', () => {
// device-link 远程会话:计费形态事实在被控端,本机 route 观察 / 账号状态一律不用。
- expect(source).toContain('const isDeviceLinkRemote = Boolean(deviceLinkDeviceId);');
+ expect(compact(source)).toContain(
+ compact('const isDeviceLinkRemote = Boolean(deviceLinkDeviceId);'),
+ );
// 本机 Codex runtime route 观察对 device-link 关闭(否则按控制端账号形态张冠李戴)
- expect(source).toContain("enabled: vendorKey === 'codex' && !isDeviceLinkRemote,");
+ expect(compact(source)).toContain(
+ compact("enabled: vendorKey === 'codex' && !isDeviceLinkRemote,"),
+ );
// Claude 默认路由观察(proxy 观察值 / OAuth / 网关 key 启发式)对 device-link 关闭
- expect(source).toContain(
- "vendorKey === 'cc' && !isRemoteClaudeSession && !isDeviceLinkRemote && providerId == null",
+ expect(compact(source)).toContain(
+ compact(
+ "vendorKey === 'cc' && !isRemoteClaudeSession && !isDeviceLinkRemote && providerId == null",
+ ),
);
// 订阅形态分类整体排除 device-link(专属分支接管渲染)
- expect(source).toContain(
- "|| (vendorKey === 'pi' && !remoteHostId && providerId === 'anthropic')",
+ expect(compact(source)).toContain(
+ compact("(vendorKey === 'pi' && !remoteHostId && providerId === 'anthropic')"),
);
// 渲染走专属分支:估算价值 / 累计 cost 有哪个显哪个,不显示本机限额窗口
- expect(source).toContain('if (isDeviceLinkRemote) {');
+ expect(compact(source)).toContain(compact('if (isDeviceLinkRemote) {'));
// 看板链接对 device-link 落 null(额度属于被控端账号,本机浏览器打开的是控制端账号)
expect(source).toMatch(/usageDashboardUrl: string \| null = isDeviceLinkRemote\s*\?\s*null/);
});
it('does not classify remote Codex sessions from the local runtime route', () => {
- expect(source).toContain('remoteHostId?: string | null');
- expect(source).toContain(
- "const isRemoteCodexSession = vendorKey === 'codex' && Boolean(remoteHostId);",
+ expect(compact(source)).toContain(compact('remoteHostId?: string | null'));
+ expect(compact(source)).toContain(
+ compact("const isRemoteCodexSession = vendorKey === 'codex' && Boolean(remoteHostId);"),
);
// SSH(remoteHostId)与 device-link(deviceLinkDeviceId)远程会话都抑制本机账户快照读取
- expect(source).toContain('deviceLinkDeviceId?: string | null');
- expect(source).toContain(
- 'const isAnyRemoteSession = Boolean(remoteHostId) || Boolean(deviceLinkDeviceId);',
+ expect(compact(source)).toContain(compact('deviceLinkDeviceId?: string | null'));
+ expect(compact(source)).toContain(
+ compact('const isAnyRemoteSession = Boolean(remoteHostId) || Boolean(deviceLinkDeviceId);'),
);
- expect(source).toContain(
- 'const shouldReadLocalCodexAccountUsage = usesCodexQuotaForm && !isAnyRemoteSession;',
+ expect(compact(source)).toContain(
+ compact(
+ 'const shouldReadLocalCodexAccountUsage = usesCodexQuotaForm && !isAnyRemoteSession;',
+ ),
);
// 按会话形态选配额槽: bridge → WHAM(openai-web)槽, CLI → app-server 槽,
// 不跨槽回退(账号多限额桶互相污染, 2026-07-24 实报 bug)
- expect(source).toContain("shouldReadLocalCodexAccountUsage ? 'codex' : undefined,");
- expect(source).toContain("isChatgptBridge ? 'openai-web' : 'app-server',");
- });
-
- it('shows the shared mobile Codex reset-credit summary for local Desktop sessions', () => {
- // 主进程已有 authoritative read;Desktop renderer 需补齐 preload + 类型链路。
- expect(preloadSource).toContain('getCodexRateLimits: (): Promise<MobileCodexRateLimitsResult>');
- expect(preloadSource).toContain("ipcRenderer.invoke('maker:usage:codex-rate-limits')");
- expect(rendererTypesSource).toContain('getCodexRateLimits: () => Promise<');
- // 仅本机 Codex OAuth 会话读取本机账号数据;远程 / bridge 不张冠李戴。
- expect(source).toContain('useCodexRateLimits(isCodexOauth && !isAnyRemoteSession)');
- // 复用 Mobile 的中性汇总字段;Desktop 按当前界面语言渲染 label / 次数 / 本地时间。
- expect(source).toContain('summarizeCodexRateLimitReset');
- // 复用 chip 现有 tick 时间基准,跨日时本地时间文案会重新格式化。
- expect(source).toContain('summarizeCodexRateLimitReset(codexRateLimits, windowLabelNowMs)');
- expect(source).toContain('resetSummary?.hasResetCreditCount');
- expect(source).toContain('resetSummary?.earliestExpiryAt');
- expect(source).toContain("t('todaySpend.codex.resetCreditsAvailableLine'");
- expect(source).toContain("t('todaySpend.codex.resetCreditEarliestExpiryLine'");
- expect(source).toContain('i18n.resolvedLanguage ?? i18n.language');
- expect(source).not.toContain('resetSummary?.resetRows');
- for (const localeSource of localeSources) {
- expect(localeSource).toContain('"resetCreditsAvailableLine"');
- expect(localeSource).toContain('"resetCreditEarliestExpiryLine"');
- }
- // 长时间挂载时每次重新悬停都会刷新,首次瞬态失败与外部消费/授予不会永久陈旧。
- expect(source).toContain('onMouseEnter={refreshCodexRateLimits}');
- });
-
- it('keeps one route-independent session total while provider-specific quota details follow the current model', () => {
- expect(source).not.toContain('CODEX_CREDIT_USD_RATE');
- expect(source).not.toContain('usdFormatted');
- expect(source).not.toContain('function getSessionCostSegment(');
- expect(source).toContain('const cost = formatTurnCostMoney(sessionMoney)');
- expect(source).toContain("tooltipLabel: t('todaySpend.tooltip.sessionUsed'");
- expect(source).toContain('cost: DEFAULT_MONEY_PLACEHOLDER');
- // 会话实际费用与价值估算都无条件读取;当前 provider 只影响配额窗口,
- // 不再决定“本对话”金额取哪一条链路。
- expect(source).toMatch(
- /useSessionUsageMoney\(\s*sessionId,\s*sessionInitialMoney,\s*sessionInitialCostUsd,?\s*\)/,
+ expect(compact(source)).toContain(
+ compact("shouldReadLocalCodexAccountUsage ? 'codex' : undefined,"),
);
- expect(source).toContain('const sessionMoney = sessionUsage.totalMoney;');
- expect(source).toContain('const sessionSegment = sessionMoney?.amount');
- expect(source).toContain('pushSessionUsageLines(lines, sessionUsage, sessionTokens, t);');
- expect(source).toContain('function getCodexChipWindows(');
- expect(source).toContain("'todaySpend.codex.windowSegment'");
- expect(source).toContain('if (sessionSegment) chipSegments.push(sessionSegment);');
- expect(source).toContain('tooltipNode = buildCodexTooltipNode(');
- expect(source).toContain('sessionUsage,');
- expect(source).toContain("t('todaySpend.codex.sessionValueLabel'");
- expect(source).toContain('getCodexWindowUsages(snapshot, t, nowMs)');
- expect(source).toContain('todaySpend.codex.planCreditsLine');
- expect(source).toContain('todaySpend.codex.windowLine');
- // chip 主体 label 统一为距 reset 的剩余时长倒计时 (Claude / Codex 同一函数),
- // tooltip 保留窗口名 + 精确 reset 时间点
- expect(source).toContain('function formatCompactTimeUntilReset(');
- expect(source).toContain('function toCodexChipWindow(');
- expect(source).toContain('todaySpend.codex.resetAt');
- expect(source).toContain('todaySpend.codex.balanceDepleted');
- expect(source).not.toContain('todaySpend.codex.remainingSegment');
- expect(source).not.toContain('todaySpend.codex.sessionTokensSegment');
- expect(source).not.toContain('todaySpend.codex.creditsShort');
+ expect(compact(source)).toContain(compact("isChatgptBridge ? 'openai-web' : 'app-server',"));
});
it('formats gateway quota amounts with the gateway-native currency', () => {
- expect(source).toContain(
- 'formatCompactMoney(gatewayMoney(claudeQuota.spend, claudeQuota.currency))',
+ expect(compact(source)).toContain(
+ compact('formatCompactMoney(gatewayMoney(claudeQuota.spend, claudeQuota.currency))'),
);
- expect(source).toContain(
- 'formatCompactMoney(gatewayMoney(claudeQuota.maxBudget, claudeQuota.currency))',
+ expect(compact(source)).toContain(
+ compact('formatCompactMoney(gatewayMoney(claudeQuota.maxBudget, claudeQuota.currency))'),
);
- expect(source).not.toContain('formatCompactUsd(claudeQuota.');
+ expect(compact(source)).not.toContain(compact('formatCompactUsd(claudeQuota.'));
});
it('uses token and explicit empty-state fallbacks for Codex API sessions', () => {
- expect(source).toContain(
- 'isCodexApi || isCodexSubscription || isSubscriptionBridge || isDeviceLinkRemote',
- );
- expect(source).toContain('function hasPositiveSessionTokens(sessionTokens: number | null)');
- expect(source).toContain('const codexApiHasTokenFallback = isCodexApi');
- expect(source).toContain('const codexApiEmptyState = isCodexApi');
- expect(source.match(/getCodexApiEmptyState\(latestTurnUsage\)/g)).toHaveLength(1);
- expect(source).toContain('todaySpend.codex.sessionTokensLine');
- expect(source).toContain('todaySpend.codex.noUsageLabel');
- expect(source).toContain('todaySpend.codex.unavailableLabel');
- expect(source).toContain('todaySpend.codex.noUsageDetail');
- expect(source).toContain('todaySpend.codex.unavailableDetail');
- });
-
- it('keeps Claude subscription details in the chip and tooltip (plan B: follows current model)', () => {
- // 2026-08 结构化卡片替换纯文本 tooltip(上游 issue 1261),断言迁移至新契约。
- // 方案 B: 第二栏跟随当前模型的 weekly_scoped 窗口, 匹配不到回退总周限
- expect(source).toContain('function getClaudeChipWindows(');
- expect(source).toContain('function resolveClaudeWeeklyWindow(');
- expect(source).toContain('matchScopedWindowForModel(snapshot.scoped, modelId)');
- // bridge 模型形态优先(不消耗 Claude 订阅额度),订阅余量 hook 对 bridge 会话关闭;
- // device-link 远程会话同样不读本机订阅余量
- expect(source).toContain(
- 'isClaudeSubscription && !isSubscriptionBridge && !isDeviceLinkRemote',
- );
- expect(source).toContain(
- 'const usesClaudeSubscriptionPopover = isClaudeSubscription && !isSubscriptionBridge;',
- );
- expect(source).toContain('open={quotaPopoverOpen}');
- expect(source).toContain('onMouseEnter={handleQuotaPopoverTriggerMouseEnter}');
- expect(source).toContain('onMouseLeave={handleQuotaPopoverMouseLeave}');
- expect(source).toContain(
- 'if (quotaPopoverPointerInsideRef.current || quotaPopoverFocusInsideRef.current) return;',
- );
- expect(source).toContain('<QuotaHoverCard');
- expect(source).toContain('snapshot={claudeSubscriptionUsage}');
- expect(source).toContain('sessionUsage={quotaCardSessionUsage}');
- expect(source).toContain('turnUsage={quotaCardTurnUsage}');
- expect(source).toContain("'todaySpend.claude.windowSegment'");
- expect(source).toContain("t('todaySpend.claude.modelWeeklyLabel'");
- expect(source).toContain('todaySpend.claude.weeklyLabel');
- // 窗口详情 / reset 文案已由结构化卡片负责;组件行为另有
- // src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx 直接单测。
- expect(quotaHoverCardSource).toContain("t('quotaCard.usedPercent'");
- expect(quotaHoverCardSource).toContain("t('quotaCard.resetAt'");
- // chip 周限段: scoped 命中时倒计时前带模型名标注口径 (「Fable 7天 剩余 78%」)
- expect(source).toContain(
- 'weekly.modelDisplayName ? `${weekly.modelDisplayName} ${countdown}` : countdown',
- );
- expect(source).toContain('if (sessionSegment) chipSegments.push(sessionSegment);');
- expect(quotaHoverCardSource).toContain(
- 'const planLabel = formatPlanType(snapshot?.subscriptionType);',
- );
- expect(quotaHoverCardSource).toContain('data-testid="quota-plan-badge"');
- // 告警判定是纯数据判定, 统一收在 shared/claudeSubscriptionUsage.ts (有直接单测:
- // main/usage/__tests__/claudeSubscriptionUsage.test.ts), 组件只消费, 不再本地重写。
- expect(source).toContain('isClaudeSubscriptionAlerting,');
- // rateLimitStatus 可能来自脏快照;卡片先做字符串类型守卫再归一化。
- expect(quotaHoverCardSource).toContain(
- "typeof rawRateLimitStatus === 'string' ? rawRateLimitStatus.trim().toLowerCase() : undefined",
- );
- expect(source).not.toContain('function isClaudeSubscriptionAlerting(');
- expect(source).not.toContain('function hasAlertingClaudeSessionWindow(');
- // chip 变红只看当前会话真受限 (rejected / 影响本会话的窗口告警); headers 的
- // allowed_warning 综合了其它模型的分模型周限, 不得单独染红 —— 否则跑 Opus 的
- // 会话会因 Fable 周限吃紧变红, 而 chip 上根本没有那一段。
- expect(source).not.toContain("status === 'rejected' || status === 'allowed_warning'");
- // 卡片比 chip 宽一档:完整 snapshot 把 rateLimitStatus 交给卡片,
- // allowed_warning 仍在全量窗口列表旁以 warning 状态展示。
- expect(quotaHoverCardSource).toContain("normalizedStatus === 'allowed_warning'");
- expect(quotaHoverCardSource).toContain(
- "{ key: 'quotaCard.limitWarning', tone: 'warn' as const }",
- );
- // Claude 订阅 / bridge 订阅不读 gateway quota (不反映订阅花费); 默认路由 key reconcile
- // 完成前形态未定, 同样不放行网关 quota 读 (避免形态闪切)。这些前置条件收敛到
- // isClaudeGateway 里, 由 usesGatewayQuota 统一放行 quota 读取。
- expect(source).toMatch(
- /const isClaudeGateway =\s*vendorKey === 'cc'\s*&& !isAnyRemoteSession\s*&& !isSubscriptionBridge\s*&& !ccBillingFormPending/,
- );
- // 远端 Claude 会话恒走网关, 不显示本机订阅余量 (与 Codex 远端口径一致)
- expect(source).toContain(
- "const isRemoteClaudeSession = vendorKey === 'cc' && Boolean(remoteHostId);",
- );
- // 订阅判定: 显式选 Anthropic; 默认路由优先用 proxy 观察到的会话生效路由
- // (spawn 凭证冻结, 活性重算会发散), 无观察值回落「无网关 key 且连了 Claude
- // OAuth」启发式 (新会话下一次 spawn 恰按当前凭证决定)
- expect(source).toContain('useClaudeSessionRoute(sessionId, isDefaultRouteClaudeSession)');
- expect(source).toMatch(
- /observedClaudeRoute != null\s*\? observedClaudeRoute === 'subscription'\s*: !gatewayKeyReconciling && !hasGatewayKey && claudeOAuthConnected === true/,
- );
- expect(source).toContain(
- 'const { hasSavedKey: hasGatewayKey, isReconciling: gatewayKeyReconciling } = useApiKey()',
+ expect(compact(source)).toContain(
+ compact('isCodexApi || isCodexSubscription || isSubscriptionBridge || isDeviceLinkRemote'),
);
- expect(source).toContain('useClaudeOAuthConnected(isDefaultRouteClaudeSession)');
- // 无观察值且 key reconcile / OAuth 首查未完成时形态未定, 两侧 hook 都不启用
- // (避免形态闪切)
- expect(source).toContain('observedClaudeRoute == null');
- expect(source).toContain(
- '(gatewayKeyReconciling || (!hasGatewayKey && claudeOAuthConnected == null))',
+ expect(compact(source)).toContain(
+ compact('function hasPositiveSessionTokens(sessionTokens: number | null)'),
);
- // extra_usage credits 单位未验证,不得假设 cents 并渲染美元金额
- expect(source).not.toContain('formatExtraUsageCredits');
- expect(quotaHoverCardSource).toContain(
- 'const showExtraUsage = snapshot?.extraUsage?.isEnabled === true;',
- );
- expect(quotaHoverCardSource).toContain("t('quotaCard.extraUsageEnabled')");
- expect(quotaHoverCardSource).not.toContain('usedCredits');
- expect(quotaHoverCardSource).not.toContain('monthlyLimit');
- });
-
- it('labels the Codex chip windows by time until reset while tooltip keeps the window name', () => {
- expect(source).toContain('const DAY_MS = 24 * 60 * 60 * 1000');
- // chip label = 紧凑倒计时 (天级向上取整, 与旧 getDaysUntilReset 口径一致; <1 天
- // 降到小时/分钟, 最后一分钟降到秒)
- expect(source).toContain('Math.ceil(remainMs / DAY_MS)');
- expect(source).toContain('preferResetCountdown: true');
- // 窗口构成不写死, 以上游接口返回为准 (OpenAI 会调整窗口策略, 如 2026-07 曾一度
- // 取消 5h 窗口): 窗口名由 windowMinutes/resetsAt 动态派生, primary/secondary
- // 兜底统一中性「限额」, 不猜 5h / 周等具体窗口名 (Claude 段的 '5h' 是 Anthropic
- // 订阅窗口, 不在此约束内)
- expect(source).not.toContain("formatWindowLabel(snapshot.primary, '5h'");
- expect(source).not.toContain("t('todaySpend.codex.daysWindow', { days: 7 })");
- expect(source).toContain(
- "formatWindowLabel(snapshot.primary, t('todaySpend.codex.limitWindow'), t, nowMs)",
- );
- expect(source).toContain(
- "formatWindowLabel(snapshot.secondary, t('todaySpend.codex.limitWindow'), t, nowMs)",
- );
- expect(source).toContain("t('todaySpend.codex.weekWindow')");
+ expect(compact(source)).toContain(compact('const codexApiHasTokenFallback = isCodexApi'));
+ expect(compact(source)).toContain(compact('const codexApiEmptyState = isCodexApi'));
+ expect(source.match(/getCodexApiEmptyState\(latestTurnUsage\)/g)).toHaveLength(1);
+ expect(compact(source)).toContain(compact('todaySpend.codex.sessionTokensLine'));
+ expect(compact(source)).toContain(compact('todaySpend.codex.noUsageLabel'));
+ expect(compact(source)).toContain(compact('todaySpend.codex.unavailableLabel'));
+ expect(compact(source)).toContain(compact('todaySpend.codex.noUsageDetail'));
+ expect(compact(source)).toContain(compact('todaySpend.codex.unavailableDetail'));
});
it('ticks the reset countdown per second in the last minute and rolls remaining % up after a reset', () => {
// 最后一分钟秒级倒计时: formatCompactTimeUntilReset 落到秒单位, tick 节奏由
// computeCountdownTickDelayMs 决定 (setTimeout 链, 非固定 interval)
- expect(source).toContain("t('todaySpend.unit.second')");
- expect(source).toContain('computeCountdownTickDelayMs(chipResetsAtMsList, Date.now())');
- expect(source).toContain('window.setTimeout(');
- expect(source).not.toContain('window.setInterval(');
+ expect(compact(source)).toContain(compact("t('todaySpend.unit.second')"));
+ expect(compact(source)).toContain(
+ compact('computeCountdownTickDelayMs(chipResetsAtMsList, Date.now())'),
+ );
+ expect(compact(source)).toContain(compact('window.setTimeout('));
+ expect(compact(source)).not.toContain(compact('window.setInterval('));
// 重置滚动动画: chip 最多两个窗口段, 固定两个 slot 无条件调 hook (Rules of Hooks);
// 剩余百分比经 useQuotaResetRollup 后再格式化 (重置时 0% → 100% 快速跳动)
- expect(source).toContain('const rollupA = useQuotaResetRollup(windowSlotA);');
- expect(source).toContain('const rollupB = useQuotaResetRollup(windowSlotB);');
+ expect(compact(source)).toContain(compact('const rollupA = useQuotaResetRollup(windowSlotA);'));
+ expect(compact(source)).toContain(compact('const rollupB = useQuotaResetRollup(windowSlotB);'));
// 揭晓仪式: 重置滚动启动的上升沿放一次撒花 (QuotaResetConfetti, DESIGN §14.4
// 第三类 sanctioned motion); 不再用绿色文字 (2026-07-23 用户反馈效果差已移除)。
// 锚点 = 正在揭晓的窗口段元素 (粒子沿整段文字宽度散布), 兜底 chip 容器
- expect(source).toContain("import { QuotaResetConfetti } from './QuotaResetConfetti';");
- expect(source).toContain('if (celebrating && !prevCelebratingRef.current)');
- expect(source).toContain('segmentElsRef.current[window.key] = el;');
- expect(source).toContain('?? chipRef.current;');
- expect(source).toContain('<QuotaResetConfetti');
- expect(source).toContain('onDone={() => setConfettiBurst(null)}');
- expect(source).not.toContain('card-status-done');
- expect(source).toContain('interface ChipWindowSegment extends ChipWindowSlot');
+ expect(compact(source)).toContain(
+ compact("import { QuotaResetConfetti } from './QuotaResetConfetti';"),
+ );
+ expect(compact(source)).toContain(compact('if (celebrating && !prevCelebratingRef.current)'));
+ expect(compact(source)).toContain(compact('segmentElsRef.current[window.key] = el;'));
+ expect(compact(source)).toContain(compact('?? chipRef.current;'));
+ expect(compact(source)).toContain(compact('<QuotaResetConfetti'));
+ expect(compact(source)).toContain(compact('onDone={() => setConfettiBurst(null)}'));
+ expect(compact(source)).not.toContain(compact('card-status-done'));
+ expect(compact(source)).toContain(
+ compact('interface ChipWindowSegment extends ChipWindowSlot'),
+ );
// 动画身份 key: 上游窗口策略变化 / 周限口径切换只重置基线, 不误触滚动
- expect(source).toContain('`codex-${slotKey}:${window.windowMinutes ?? ');
- expect(source).toContain("'claude-5h'");
- expect(source).toContain('claude-weekly:');
+ expect(compact(source)).toContain(compact('`codex-${slotKey}:${window.windowMinutes ?? '));
+ expect(compact(source)).toContain(compact("'claude-5h'"));
+ expect(compact(source)).toContain(compact('claude-weekly:'));
// tick effect 依赖以值签名 memo 的 reset 时点列表, 动画帧不得重建定时器
- expect(source).toContain('const resetsAtSignature = chipWindows');
+ expect(compact(source)).toContain(compact('const resetsAtSignature = chipWindows'));
});
it('shows a suspense "resetting…" segment while waiting for the post-reset snapshot', () => {
// 悬念期: 倒计时归零、新快照未落地 → 段换成「重置中…」(呼吸省略号), 不再
// 显示已失真的旧百分比; 新快照落地由重置滚动动画揭晓
- expect(source).toContain('function isResetPending(');
- expect(source).toContain('resetPending: isResetPending(resetsAtMs, nowMs)');
+ expect(compact(source)).toContain(compact('function isResetPending('));
+ expect(compact(source)).toContain(compact('resetPending: isResetPending(resetsAtMs, nowMs)'));
// 悬念期必须有界 (催刷是 best-effort, 离线/登出/退避时拿不到新快照); 超时
// 回落旧值 + 窗口名。常量在 quotaResetRollup (tick 节奏踩着超时边界调度,
// 悬念不会因慢 tick 多挂一分钟, Greptile P1 两轮, PR #546)
- expect(source).toContain('RESET_PENDING_MAX_MS,');
+ expect(compact(source)).toContain(compact('RESET_PENDING_MAX_MS,'));
// 超时侧严格小于: 排在超时边界上的 tick 必须当场退出悬念, 含等号会再等一轮
// 慢 tick (Greptile P1 第三轮)
- expect(source).toContain('&& nowMs - resetsAtMs < RESET_PENDING_MAX_MS');
- expect(source).toContain("'todaySpend.resetPendingSegment'");
+ expect(compact(source)).toContain(compact('&& nowMs - resetsAtMs < RESET_PENDING_MAX_MS'));
+ expect(compact(source)).toContain(compact("'todaySpend.resetPendingSegment'"));
// 省略号动画: HTML span + opacity (animate-pulse), 仅悬念期挂载 (动效红线);
// motion-safe = 尊重 prefers-reduced-motion (review P1, PR #546)
- expect(source).toContain('<span className="motion-safe:animate-pulse">…</span>');
- expect(source).not.toContain('"animate-pulse"');
+ expect(compact(source)).toContain(
+ compact('<span className="motion-safe:animate-pulse">…</span>'),
+ );
+ expect(compact(source)).not.toContain(compact('"animate-pulse"'));
// 悬念期催刷通道必须与 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'"));
});
+});
+
+// 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(['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('formats Codex plan labels for display', () => {
- expect(source).toContain("business: 'Business'");
- expect(source).toContain('formatPlanType(snapshot.planType)');
+ 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('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('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('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('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 --git a/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx b/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx
index de672456e3..2d887a4a2f 100644
--- a/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx
+++ b/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx
@@ -1,5 +1,5 @@
/**
- * QuotaHoverCard — Claude 订阅额度的结构化悬浮卡片。
+ * QuotaHoverCard — 所有渠道共用的用量卡片。
*
* 组件只负责展示调用方给出的快照与本轮明细,不读取 store,也不主动获取数据。
*/
@@ -10,10 +10,7 @@ import { useTranslation } from 'react-i18next';
import { computeQuotaPace, type QuotaPace } from '@/lib/quotaPace';
import { cn } from '@/lib/utils';
-import type {
- ClaudeSubscriptionUsageSnapshot,
- ClaudeUsageWindow,
-} from '../../../shared/claudeSubscriptionUsage';
+import { formatQuotaResetAt, type UsageCardAccount, type UsageCardWindow } from './usageCardModel';
import { QuotaBar, quotaSeverity, type QuotaSeverity } from './QuotaBar';
export interface QuotaHoverCardTurnUsage {
@@ -35,14 +32,15 @@ export interface QuotaHoverCardTurnUsage {
}
export interface QuotaHoverCardSessionUsage {
- costText: string;
+ costText?: string | null;
+ tokensText?: string | null;
costIsEstimate?: boolean;
actualCostText?: string | null;
estimatedValueText?: string | null;
}
export interface QuotaHoverCardProps {
- snapshot: ClaudeSubscriptionUsageSnapshot | null;
+ account: UsageCardAccount;
sessionUsage?: QuotaHoverCardSessionUsage | null;
turnUsage?: QuotaHoverCardTurnUsage | null;
dashboardLabel?: string | null;
@@ -51,15 +49,7 @@ export interface QuotaHoverCardProps {
nowMs?: number;
}
-interface DisplayWindow {
- key: string;
- title: string;
- window: ClaudeUsageWindow;
- paceWindowMinutes?: number;
-}
-
const STALE_AFTER_MS = 5 * 60_000;
-const WEEKLY_WINDOW_MINUTES = 10_080;
/** 产品定档:±5 个百分点内视为正常节奏。 */
const PACE_TREND_DELTA_PERCENT = 5;
@@ -68,13 +58,6 @@ function clampPercent(value: number): number {
return Math.min(100, Math.max(0, value));
}
-/** 旧快照可能绕过类型边界;利用率不是有限数值时整窗不展示。 */
-function isDisplayableWindow(value: unknown): value is ClaudeUsageWindow {
- if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
- const utilization = (value as { utilization?: unknown }).utilization;
- return typeof utilization === 'number' && Number.isFinite(utilization);
-}
-
const QUOTA_SEVERITY_RANK: Record<QuotaSeverity, number> = {
normal: 0,
warn: 1,
@@ -96,7 +79,7 @@ function serverQuotaSeverity(value: unknown): QuotaSeverity {
return 'warn';
}
-function effectiveQuotaSeverity(window: ClaudeUsageWindow): QuotaSeverity {
+function effectiveQuotaSeverity(window: UsageCardWindow['window']): QuotaSeverity {
const localSeverity = quotaSeverity(window.utilization);
const serverSeverity = serverQuotaSeverity(window.severity);
return QUOTA_SEVERITY_RANK[serverSeverity] > QUOTA_SEVERITY_RANK[localSeverity]
@@ -104,53 +87,6 @@ function effectiveQuotaSeverity(window: ClaudeUsageWindow): QuotaSeverity {
: localSeverity;
}
-/** 未知套餐保留原始拼写,只补齐首字母大写;非字符串脏值按缺失处理。 */
-function formatPlanType(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)}`
- );
-}
-
-/** reset 时间按本地时区展示:当天仅时分,跨天补月日。 */
-function formatResetAt(
- resetsAt: number | null | undefined,
- nowMs: number,
- locale: string | undefined,
-): string | null {
- if (typeof resetsAt !== 'number' || !Number.isFinite(resetsAt) || resetsAt <= 0) {
- return null;
- }
-
- const resetDate = new Date(resetsAt * 1000);
- const nowDate = new Date(nowMs);
- const sameDay =
- resetDate.getFullYear() === nowDate.getFullYear() &&
- resetDate.getMonth() === nowDate.getMonth() &&
- resetDate.getDate() === nowDate.getDate();
- const time = new Intl.DateTimeFormat(locale, {
- hour: '2-digit',
- minute: '2-digit',
- hour12: false,
- }).format(resetDate);
-
- if (sameDay) return time;
- const monthAndDay = new Intl.DateTimeFormat(locale, {
- month: 'short',
- day: 'numeric',
- }).format(resetDate);
- return `${monthAndDay} ${time}`;
-}
-
function CardDivider() {
return <div aria-hidden="true" className="mx-4 my-1.5 h-px bg-[var(--border-default)]" />;
}
@@ -171,14 +107,18 @@ function WindowBlock({
title,
window,
paceWindowMinutes,
+ detail,
+ breakdown,
nowMs,
paceNowMs,
locale,
t,
}: {
title: string;
- window: ClaudeUsageWindow;
+ window: UsageCardWindow['window'];
paceWindowMinutes?: number;
+ detail?: string;
+ breakdown?: UsageCardWindow['breakdown'];
nowMs: number;
paceNowMs: number | null;
locale: string | undefined;
@@ -189,11 +129,11 @@ function WindowBlock({
const severity = effectiveQuotaSeverity(window);
const severityAnnouncement =
severity === 'crit'
- ? t('quotaCard.limitRejected')
+ ? t('quotaCard.usageCritical')
: severity === 'warn'
- ? t('quotaCard.limitWarning')
+ ? t('quotaCard.usageWarning')
: null;
- const resetAt = formatResetAt(window.resetsAt, nowMs, locale);
+ const resetAt = formatQuotaResetAt(window.resetsAt, nowMs, locale);
// 窗口已过重置点,旧观测的节奏失真,待新快照。
const resetPassed =
typeof window.resetsAt === 'number' &&
@@ -216,7 +156,7 @@ function WindowBlock({
id={titleId}
data-severity={severity}
className={cn(
- 'mb-2 text-sm font-medium tracking-[-0.005em]',
+ 'mb-2 text-14 font-medium tracking-[-0.005em]',
severity === 'crit' ? 'text-[var(--quota-bar-crit)]' : 'text-[var(--text-primary)]',
)}
>
@@ -232,15 +172,29 @@ function WindowBlock({
{t('quotaCard.usedPercent', { percent: Math.round(usedPercent) })}
</span>
{resetAt !== null ? (
- <span className="text-xs text-[var(--text-secondary)]">
+ <span className="text-12 text-[var(--text-secondary)]">
{t('quotaCard.resetAt', { at: resetAt })}
</span>
) : null}
</div>
+ {detail ? <div className="mt-1 text-12 text-[var(--text-secondary)]">{detail}</div> : null}
+ {breakdown?.length ? (
+ <dl
+ data-testid="quota-window-breakdown"
+ className="mt-2 space-y-1 text-12 text-[var(--text-secondary)]"
+ >
+ {breakdown.map(({ label, value }, index) => (
+ <div key={index} className="flex items-baseline justify-between gap-3">
+ <dt className="min-w-0 break-words">{label}</dt>
+ <dd className="shrink-0 tabular-nums">{value}</dd>
+ </div>
+ ))}
+ </dl>
+ ) : null}
{paceLine !== null ? (
<div
data-testid="quota-pace"
- className="mt-[3px] text-xs tabular-nums text-[var(--text-secondary)]"
+ className="mt-[3px] text-12 tabular-nums text-[var(--text-secondary)]"
>
{paceLine}
</div>
@@ -258,7 +212,13 @@ function TurnUsageSection({ turnUsage, t }: { turnUsage: QuotaHoverCardTurnUsage
isEstimate: boolean | undefined,
unavailableKey: string,
) => (
- <div className="text-sm font-medium text-[var(--text-primary)]">
+ <div
+ className={
+ costText != null
+ ? 'text-14 font-medium text-[var(--text-primary)]'
+ : 'text-12 text-[var(--text-secondary)]'
+ }
+ >
{costText != null
? t(isEstimate ? 'quotaCard.valueLine' : 'quotaCard.costLine', { cost: costText })
: t(unavailableKey)}
@@ -268,7 +228,7 @@ function TurnUsageSection({ turnUsage, t }: { turnUsage: QuotaHoverCardTurnUsage
return (
<section data-testid="quota-turn-usage" className="px-4 pb-1 pt-2">
{turnUsage.isUserTurnTotal ? (
- <div className="mb-[3px] text-xs font-medium text-[var(--text-secondary)]">
+ <div className="mb-[3px] text-12 font-medium text-[var(--text-secondary)]">
{t('quotaCard.latestMessageTitle')}
</div>
) : null}
@@ -282,7 +242,7 @@ function TurnUsageSection({ turnUsage, t }: { turnUsage: QuotaHoverCardTurnUsage
{showModelCostBreakdown ? (
<div data-testid="quota-model-cost-breakdown" className="mt-2">
- <div className="mb-[3px] text-xs font-medium text-[var(--text-secondary)]">
+ <div className="mb-[3px] text-12 font-medium text-[var(--text-secondary)]">
{t('usageDetails.costBreakdownHeader')}
</div>
<div className="space-y-0.5 tabular-nums text-[var(--text-primary)]">
@@ -301,7 +261,7 @@ function TurnUsageSection({ turnUsage, t }: { turnUsage: QuotaHoverCardTurnUsage
{turnUsage.totalTokensText != null ? (
<div className="mt-[5px] flex items-baseline justify-between gap-3 tabular-nums">
<span className="text-[var(--text-secondary)]">{t('quotaCard.tokenLabel')}</span>
- <span className="text-right font-medium text-[var(--text-primary)]">
+ <span className="min-w-0 break-words text-right font-medium text-[var(--text-primary)]">
{turnUsage.totalTokensText}
{hasTokenBreakdown ? (
<span className="font-normal text-[var(--text-secondary)]">
@@ -318,30 +278,31 @@ function TurnUsageSection({ turnUsage, t }: { turnUsage: QuotaHoverCardTurnUsage
{turnUsage.cacheLineText != null ? (
<div className="mt-[5px] flex items-baseline justify-between gap-3 tabular-nums">
<span className="text-[var(--text-secondary)]">{t('quotaCard.cacheLabel')}</span>
- <span className="text-right font-medium text-[var(--text-primary)]">
+ <span className="min-w-0 break-words text-right font-medium text-[var(--text-primary)]">
{turnUsage.cacheLineText}
</span>
</div>
) : null}
- {turnUsage.turnDurationText != null ? (
- <div
- data-testid="quota-performance"
- className="mt-[5px] flex items-baseline justify-between gap-3 tabular-nums"
- >
- <span className="text-[var(--text-secondary)]">{t('quotaCard.timeLabel')}</span>
- <span
- data-testid="quota-performance-value"
- className="ml-auto text-right font-medium text-[var(--text-primary)]"
- >
- {turnUsage.outputRateText != null
- ? t('quotaCard.timeAndRateValue', {
- duration: turnUsage.turnDurationText,
- rate: turnUsage.outputRateText,
- })
- : turnUsage.turnDurationText}
- </span>
- </div>
+ {turnUsage.turnDurationText != null || turnUsage.outputRateText != null ? (
+ <dl data-testid="quota-performance" className="mt-[5px] space-y-[5px] tabular-nums">
+ {turnUsage.turnDurationText != null ? (
+ <div className="flex items-baseline justify-between gap-3">
+ <dt className="text-[var(--text-secondary)]">{t('quotaCard.timeLabel')}</dt>
+ <dd className="min-w-0 break-words text-right font-medium text-[var(--text-primary)]">
+ {turnUsage.turnDurationText}
+ </dd>
+ </div>
+ ) : null}
+ {turnUsage.outputRateText != null ? (
+ <div className="flex items-baseline justify-between gap-3">
+ <dt className="text-[var(--text-secondary)]">{t('quotaCard.speedLabel')}</dt>
+ <dd className="min-w-0 break-words text-right font-medium text-[var(--text-primary)]">
+ {t('quotaCard.rateValue', { rate: turnUsage.outputRateText })}
+ </dd>
+ </div>
+ ) : null}
+ </dl>
) : null}
{!showModelCostBreakdown && turnUsage.model != null ? (
@@ -356,7 +317,7 @@ function TurnUsageSection({ turnUsage, t }: { turnUsage: QuotaHoverCardTurnUsage
{turnUsage.suggestionText != null ? (
<div
data-testid="quota-suggestion"
- className="mt-2.5 flex items-start gap-[7px] rounded-lg bg-[var(--warning-bg-soft)] px-2.5 py-[7px] text-xs text-[var(--text-primary)]"
+ className="mt-2.5 flex items-start gap-[7px] rounded-lg bg-[var(--warning-bg-soft)] px-2.5 py-[7px] text-12 text-[var(--text-primary)]"
>
<span aria-hidden="true" className="shrink-0 text-[var(--quota-bar-warn)]">
●
@@ -385,11 +346,24 @@ function SessionUsageSection({
return (
<section data-testid="quota-session-usage" className="px-4 pb-1 pt-2 tabular-nums">
- <div className="text-sm font-medium text-[var(--text-primary)]">
- {t(totalKey, { cost: sessionUsage.costText })}
- </div>
+ {sessionUsage.costText ? (
+ <div className="text-14 font-medium text-[var(--text-primary)]">
+ {t(totalKey, { cost: sessionUsage.costText })}
+ </div>
+ ) : null}
+ {sessionUsage.tokensText ? (
+ <div
+ className={
+ sessionUsage.costText
+ ? 'mt-1 text-12 text-[var(--text-secondary)]'
+ : 'text-14 font-medium text-[var(--text-primary)]'
+ }
+ >
+ {t('todaySpend.codex.sessionTokensLine', { tokens: sessionUsage.tokensText })}
+ </div>
+ ) : null}
{hasMixedBreakdown ? (
- <div className="mt-1 space-y-0.5 text-xs text-[var(--text-secondary)]">
+ <div className="mt-1 space-y-0.5 text-12 text-[var(--text-secondary)]">
<div>{t('todaySpend.tooltip.sessionUsed', { cost: sessionUsage.actualCostText })}</div>
<div>
{t('todaySpend.codex.sessionValueLabel', {
@@ -402,9 +376,9 @@ function SessionUsageSection({
);
}
-/** 按冻结的 v6 信息层级渲染 Claude 额度卡片。 */
+/** 套餐、配额、任务合计与本轮明细按同一信息层级渲染;供应商差异只来自 account。 */
export function QuotaHoverCard({
- snapshot,
+ account,
sessionUsage = null,
turnUsage = null,
dashboardLabel = null,
@@ -415,64 +389,18 @@ export function QuotaHoverCard({
const { t, i18n } = useTranslation();
// 测试可只注入 t;运行时再优先跟随应用当前语言格式化日期。
const locale = i18n?.resolvedLanguage ?? i18n?.language;
- const planLabel = formatPlanType(snapshot?.subscriptionType);
- // utilization 是 updatedAt 时刻的观测值,用观测时刻算节奏,避免旧快照随渲染时间自漂移;
- // 缺有效观测时刻则不算节奏——回退渲染时刻会让趋势随倒计时重渲染无新数据自跳档。
- const paceNowMs = snapshot
- && typeof snapshot.updatedAt === 'number'
- && Number.isFinite(snapshot.updatedAt)
- ? snapshot.updatedAt
- : null;
-
- const windows: DisplayWindow[] = [];
- if (isDisplayableWindow(snapshot?.fiveHour)) {
- windows.push({
- key: 'five-hour',
- title: t('quotaCard.fiveHourLabel'),
- window: snapshot.fiveHour,
- });
- }
- if (isDisplayableWindow(snapshot?.sevenDay)) {
- windows.push({
- key: 'seven-day',
- title: t('quotaCard.weeklyLabel'),
- window: snapshot.sevenDay,
- paceWindowMinutes: WEEKLY_WINDOW_MINUTES,
- });
- }
- // 持久化旧快照可能把 scoped 写成非数组;脏容器按缺失处理,避免 .entries() 崩溃。
- const scopedWindows = Array.isArray(snapshot?.scoped) ? snapshot.scoped : [];
- for (const [index, scoped] of scopedWindows.entries()) {
- if (!isDisplayableWindow(scoped)) continue;
- windows.push({
- key: `scoped-${scoped.modelId ?? scoped.modelDisplayName}-${index}`,
- title: t('quotaCard.modelWeeklyLabel', { model: scoped.modelDisplayName }),
- window: scoped,
- });
- }
-
- const rawRateLimitStatus = snapshot?.rateLimitStatus;
- const normalizedStatus =
- typeof rawRateLimitStatus === 'string' ? rawRateLimitStatus.trim().toLowerCase() : undefined;
- const status =
- normalizedStatus === 'rejected'
- ? { key: 'quotaCard.limitRejected', tone: 'crit' as const }
- : normalizedStatus === 'allowed_warning'
- ? { key: 'quotaCard.limitWarning', tone: 'warn' as const }
- : null;
- const showExtraUsage = snapshot?.extraUsage?.isEnabled === true;
+ const { title, planLabel, windows, details = [], notices = [], emptyText, updatedAt } = account;
+ // Use observation time for pace so a stale snapshot cannot drift as the card renders.
+ const paceNowMs = typeof updatedAt === 'number' && Number.isFinite(updatedAt) ? updatedAt : null;
const staleMinutes =
- snapshot &&
- typeof snapshot.updatedAt === 'number' &&
- Number.isFinite(snapshot.updatedAt) &&
- nowMs - snapshot.updatedAt > STALE_AFTER_MS
- ? Math.floor((nowMs - snapshot.updatedAt) / 60_000)
+ paceNowMs !== null && nowMs - paceNowMs > STALE_AFTER_MS
+ ? Math.floor((nowMs - paceNowMs) / 60_000)
: null;
return (
<div
data-testid="quota-hover-card"
- className="flex max-h-[calc(100vh-16px)] w-[340px] select-none flex-col overflow-hidden rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] pb-2 text-13 leading-5 text-[var(--text-primary)]"
+ className="flex max-h-[min(calc(100vh-16px),var(--radix-popover-content-available-height,100vh))] w-[340px] max-w-[calc(100vw-16px)] select-none flex-col overflow-hidden rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] pb-2 text-13 leading-5 text-[var(--text-primary)]"
style={{ boxShadow: 'var(--shadow-menu)' }}
>
<div
@@ -482,72 +410,61 @@ export function QuotaHoverCard({
tabIndex={0}
className="min-h-0 overflow-y-auto pt-[6px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus-ring)]"
>
- {snapshot ? (
+ {title ? (
<>
- <div className="flex items-center gap-2 px-4 pb-2 pt-3 text-xs text-[var(--text-secondary)]">
- <span className="font-medium">Claude</span>
+ <div className="flex items-center gap-2 px-4 pb-2 pt-3 text-12 text-[var(--text-secondary)]">
+ <span className="min-w-0 break-words font-medium">{title}</span>
{planLabel ? (
<span
data-testid="quota-plan-badge"
- className="ml-auto rounded-full border border-[var(--border-default)] px-[7px] py-px text-11 font-medium"
+ className="ml-auto max-w-[65%] break-words rounded-full border border-[var(--border-default)] px-[7px] py-px text-11 font-medium"
>
{planLabel}
</span>
) : null}
</div>
-
+ </>
+ ) : null}
+ {title && (windows.length > 0 || emptyText) ? <CardDivider /> : null}
+ {windows.map(({ key, ...displayWindow }) => (
+ <WindowBlock
+ key={key}
+ {...displayWindow}
+ nowMs={nowMs}
+ paceNowMs={paceNowMs}
+ locale={locale}
+ t={t}
+ />
+ ))}
+ {emptyText ? (
+ <div className="px-4 py-2 text-[var(--text-secondary)]">{emptyText}</div>
+ ) : null}
+ {notices.map((notice, index) => (
+ <React.Fragment key={index}>
<CardDivider />
-
- {windows.length > 0 ? (
- <div>
- {windows.map((displayWindow) => (
- <WindowBlock
- key={displayWindow.key}
- title={displayWindow.title}
- window={displayWindow.window}
- paceWindowMinutes={displayWindow.paceWindowMinutes}
- nowMs={nowMs}
- paceNowMs={paceNowMs}
- locale={locale}
- t={t}
- />
- ))}
- </div>
- ) : (
- <div className="px-4 py-2 text-[var(--text-secondary)]">
- {t('quotaCard.noWindows')}
- </div>
- )}
-
- {status ? (
- <>
- <CardDivider />
- <div
- data-testid="quota-status"
- className={cn(
- 'px-4 py-2 font-medium',
- status.tone === 'crit'
- ? 'text-[var(--quota-bar-crit)]'
- : 'text-[var(--quota-bar-warn)]',
- )}
- >
- {t(status.key)}
- </div>
- </>
- ) : null}
-
- {showExtraUsage ? (
- <>
- <CardDivider />
- <div className="px-4 py-2 text-[var(--text-secondary)]">
- {t('quotaCard.extraUsageEnabled')}
- </div>
- </>
- ) : null}
+ <div
+ data-testid="quota-status"
+ className={cn(
+ 'px-4 py-2 font-medium',
+ notice.tone === 'crit'
+ ? 'text-[var(--quota-bar-crit)]'
+ : 'text-[var(--quota-bar-warn)]',
+ )}
+ >
+ {notice.text}
+ </div>
+ </React.Fragment>
+ ))}
+ {details.length ? (
+ <>
+ <CardDivider />
+ <section className="space-y-1 px-4 py-2 text-12 tabular-nums text-[var(--text-secondary)]">
+ {details.map((detail, index) => (
+ <div key={index}>{detail}</div>
+ ))}
+ </section>
</>
- ) : (
- <div className="px-4 py-2 text-[var(--text-secondary)]">{t('quotaCard.waiting')}</div>
- )}
+ ) : null}
{sessionUsage ? (
<>
@@ -571,7 +488,7 @@ export function QuotaHoverCard({
ref={dashboardButtonRef}
type="button"
onClick={onOpenDashboard}
- className="mx-2 mt-0.5 flex w-[calc(100%_-_16px)] items-center gap-[9px] rounded-full px-2 py-[7px] text-left font-medium transition-colors hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--surface-elevated)] active:scale-[0.98]"
+ className="mx-2 mt-0.5 flex w-[calc(100%_-_16px)] items-center gap-[9px] rounded-full px-2 py-[7px] text-left font-medium text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--surface-elevated)] active:scale-[0.98]"
>
<svg
aria-hidden="true"
@@ -594,7 +511,7 @@ export function QuotaHoverCard({
{staleMinutes !== null ? (
<>
<CardDivider />
- <div className="px-4 py-1.5 text-xs tabular-nums text-[var(--text-secondary)]">
+ <div className="px-4 py-1.5 text-12 tabular-nums text-[var(--text-secondary)]">
{t('quotaCard.staleData', { minutes: staleMinutes })}
</div>
</>
diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
index 9ec3195ed6..e2de2fdc76 100644
--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
@@ -1,43 +1,15 @@
/**
- * TodaySpendChip — 与 ContextCapacityRing 同行的极简用量指示器。
+ * TodaySpendChip — 右下角用量指示器与所有渠道共用的悬浮卡片入口。
*
- * 设计意图(用户拍板的方向):
- * - 不在 desktop 重做完整看板(点击 chip 跳到对应供应商的 web 用量看板)
- * - 仅在右下角与 Context 同行显示区域币种的今日 / 本会话金额
- * - 点击 → 在系统默认浏览器打开对应 vendor 的用量看板
- * (XD 网关 / 托管账号暂无看板可跳,点击无反应,详见 usageDashboardUrl)
- *
- * Claude / gateway 形态: 主 chip 固定显示 daily + session, monthly 进 tooltip。
- * - daily: 今日跨客户端已用 / 软日限额 (maxBudget/30*4.5, 与 web 看板同公式)
- * - monthly: 本月度周期已用 / 月度上限 (LiteLLM /v2/user/info 原值)
- * - session: 当前会话终身累计 (跨 resume 持久化, 有 sessionId 才显示)
- *
- * Codex 订阅形态主 chip 显示服务端下发的各限额窗口剩余 / 当前会话区域金额。
- * 窗口构成不做任何假设,完全以上游接口返回为准 —— OpenAI 会调整窗口策略
- * (典型:5h + 周双窗;2026-07 曾一度取消 5h 窗口,且可能随时恢复)。
- * 订阅模式下金额是 token 价值,API / codex/ 折扣 GPT 下是 gateway API 单价折算 cost。
- * credits / token 明细只放 tooltip,不占主 chip。
- *
- * Codex tooltip 按当前会话实际 runtime route + 当前模型分两种:
- * - oauth 模式 + 当前 app-server 以 OAuth bearer 启动 + 普通模型: 显示各限额窗口
- * 剩余额度、当前会话 token 累计、credits 明细。订阅没有单一 per-token 余额。
- * - api 模式、app-server 以 gateway key 启动、或当前模型是 codex/ 折扣 GPT:
- * 与 cc 同一把 XD key、同一套 LiteLLM 计费,直接复用 cc 的 daily/monthly/key
- * cost 形态(session 显示当前 region 的累计金额)。
- *
- * 数据可用性:
- * - daily / monthly 依赖 claudeQuota (LiteLLM 在线): 拉不到时这俩 metric 都隐藏,
- * tooltip 顶部加 ⚠️ 提示降级
- * - session 需实际费用或价值估算大于 0(没跑过 turn 时隐藏)
+ * 主指标显示当前渠道的配额与任务累计金额,详情统一交给 QuotaHoverCard。
+ * 供应商快照在 usageCardModel 中投影;实际费用、订阅价值估算与 Token 保持各自语义。
+ * 订阅点击打开对应看板;无看板的渠道点击查看卡片。远程任务不借用本机账号配额。
*/
import React from 'react';
import { useTranslation } from 'react-i18next';
import type { TFunction } from 'i18next';
-import {
- summarizeCodexRateLimitReset,
- type CodexRateLimitResetSummary,
-} from '@cindy/maker-shared/session-controls';
+import { summarizeCodexRateLimitReset } from '@cindy/maker-shared/session-controls';
import { cn } from '@/lib/utils';
import {
@@ -48,19 +20,11 @@ import {
formatTurnCostMoney,
formatTurnCostUsd,
} from '@/lib/usageFormat';
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from '@/components/ui/popover';
-import { Tip } from '@/components/ui/tooltip';
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { useApiKey } from '@/hooks/useApiKey';
import { useClaudeOAuthConnected } from '@/hooks/useClaudeOAuthConnected';
import { useClaudeSessionRoute } from '@/hooks/useClaudeSessionRoute';
-import {
- useSessionUsageMoney,
- type SessionUsageMoney,
-} from '@/hooks/useSessionUsageMoney';
+import { useSessionUsageMoney, type SessionUsageMoney } from '@/hooks/useSessionUsageMoney';
import { useSessionTokens } from '@/hooks/useSessionTokens';
import { useChatDisplaySnapshot } from '@/components/chat/ChatDisplaySnapshotContext';
import {
@@ -86,20 +50,18 @@ import {
} from '../../../shared/claudeSubscriptionUsage';
import { useCodexRuntimeRoute } from '@/hooks/useCodexRuntimeRoute';
import { useCodexRateLimits } from '@/hooks/useCodexRateLimits';
-import { useXaiRateLimit, type XaiRateLimitSnapshot } from '@/hooks/useXaiRateLimit';
+import { useXaiRateLimit } from '@/hooks/useXaiRateLimit';
import {
requestXaiSubscriptionRefresh,
useXaiSubscriptionUsage,
type XaiSubscriptionUsageSnapshot,
} from '@/hooks/useXaiSubscriptionUsage';
import {
- formatXaiProductLabel,
isXaiSubscriptionAlerting,
isXaiWeeklyUsageCurrent,
} from '../../../shared/xaiSubscriptionUsage';
import { makerChatStore, type ChatMessage } from '@/lib/makerChatStore';
import {
- buildTurnUsageTooltipLines,
formatOutputTokenRate,
formatTurnDuration,
getTurnUsageSuggestion,
@@ -124,6 +86,12 @@ import {
type QuotaHoverCardTurnUsage,
} from './QuotaHoverCard';
import { QuotaResetConfetti } from './QuotaResetConfetti';
+import {
+ buildClaudeUsageCard,
+ buildCodexUsageCard,
+ buildXaiUsageCard,
+ type UsageCardAccount,
+} from './usageCardModel';
// XD 网关 / 托管账号之前会跳到内部用量看板(内部域名)—— 开源前移除该硬编码。
// 登录随凭据只下发 { endpoint, apiKey }(见 main/model-access/credentialsSync.ts),不含
@@ -136,8 +104,7 @@ const CODEX_USAGE_DASHBOARD_URL = 'https://chatgpt.com/codex/settings/usage';
const XAI_USAGE_DASHBOARD_URL = 'https://grok.com';
const CLAUDE_USAGE_DASHBOARD_URL = 'https://claude.ai/settings/usage';
-const METRIC_KEYS = ['daily', 'monthly', 'credit', 'session'] as const;
-type MetricKey = (typeof METRIC_KEYS)[number];
+type MetricKey = 'daily' | 'monthly' | 'credit' | 'session';
// credit 排在 session 左边 —— 账号额度是"还能用多少"的前提, 本对话花费是它的增量。
// daily / monthly 与 credit 来自服务端两种不同的额度语义(周期配额 vs 额度池账本),
// 按账号所属租户二选一下发, 两组互斥, 同一形态下不会都占位。
@@ -148,21 +115,6 @@ const QUOTA_POPOVER_CLOSE_GRACE_MS = 200;
const DEFAULT_MONEY_SYMBOL = DEFAULT_USAGE_CURRENCY === 'CNY' ? '¥' : '$';
const DEFAULT_MONEY_PLACEHOLDER = `${DEFAULT_MONEY_SYMBOL}—`;
-const 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',
-};
-
// 软日限额系数 + 紧凑金额格式化已抽到 lib/usageFormat.ts (与首页仪表盘共用同口径)。
/** chip / tooltip 共用: 一个 metric 的最终展示形态。 */
@@ -190,10 +142,31 @@ function computeMetricSlots(
t: TFunction,
): Record<MetricKey, MetricSlot> {
const slots: Record<MetricKey, MetricSlot> = {
- daily: { label: t('todaySpend.dailyLimitLabel', { spend: DEFAULT_MONEY_PLACEHOLDER, limit: DEFAULT_MONEY_PLACEHOLDER }), available: false },
- monthly: { label: t('todaySpend.monthlyLimitLabel', { spend: DEFAULT_MONEY_PLACEHOLDER, limit: DEFAULT_MONEY_PLACEHOLDER }), available: false },
- credit: { label: t('todaySpend.creditLabel', { used: DEFAULT_MONEY_PLACEHOLDER, total: DEFAULT_MONEY_PLACEHOLDER }), available: false },
- session: { label: t('todaySpend.sessionCostLabel', { cost: DEFAULT_MONEY_PLACEHOLDER }), available: false },
+ daily: {
+ label: t('todaySpend.dailyLimitLabel', {
+ spend: DEFAULT_MONEY_PLACEHOLDER,
+ limit: DEFAULT_MONEY_PLACEHOLDER,
+ }),
+ available: false,
+ },
+ monthly: {
+ label: t('todaySpend.monthlyLimitLabel', {
+ spend: DEFAULT_MONEY_PLACEHOLDER,
+ limit: DEFAULT_MONEY_PLACEHOLDER,
+ }),
+ available: false,
+ },
+ credit: {
+ label: t('todaySpend.creditLabel', {
+ used: DEFAULT_MONEY_PLACEHOLDER,
+ total: DEFAULT_MONEY_PLACEHOLDER,
+ }),
+ available: false,
+ },
+ session: {
+ label: t('todaySpend.sessionCostLabel', { cost: DEFAULT_MONEY_PLACEHOLDER }),
+ available: false,
+ },
};
// 额度池账本没有周期概念(订阅发放 + 充值 + 赠送), 所以不派生日均软限额。
@@ -226,9 +199,7 @@ function computeMetricSlots(
const softLimit = (claudeQuota.maxBudget / 30) * DAILY_SOFT_LIMIT_FACTOR;
slots.daily = {
label: t('todaySpend.dailyLimitLabel', {
- spend: formatCompactMoney(
- gatewayMoney(claudeQuota.todaySpend, claudeQuota.currency),
- ),
+ spend: formatCompactMoney(gatewayMoney(claudeQuota.todaySpend, claudeQuota.currency)),
limit: formatCompactMoney(gatewayMoney(softLimit, claudeQuota.currency)),
}),
available: true,
@@ -248,30 +219,6 @@ function computeMetricSlots(
return slots;
}
-function parseCreditBalance(balance: string | null | undefined): {
- formatted: string;
-} | null {
- const trimmed = balance?.trim();
- if (!trimmed) return null;
- const numeric = Number(trimmed.replace(/,/g, ''));
- if (!Number.isFinite(numeric)) return null;
- const formatted = numeric.toLocaleString(undefined, {
- minimumFractionDigits: 2,
- maximumFractionDigits: 2,
- });
- return { formatted };
-}
-
-function formatPlanType(planType: string | null | undefined): string | null {
- const trimmed = planType?.trim();
- if (!trimmed) return null;
- const knownLabel = PLAN_TYPE_LABELS[trimmed];
- if (knownLabel) return knownLabel;
- return trimmed
- .replace(/[_-]+/g, ' ')
- .replace(/\b\w/g, (char) => char.toUpperCase());
-}
-
function clampPercent(value: number): number {
if (!Number.isFinite(value)) return 0;
return Math.min(100, Math.max(0, value));
@@ -283,44 +230,6 @@ function formatPercent(value: number): string {
return `${clamped.toFixed(1).replace(/\.0$/, '')}%`;
}
-/** tooltip 用的精确 reset 时间点(当天只显时分, 跨天带月日)。 */
-function formatResetAt(epochSeconds: number | null | undefined): string | null {
- if (typeof epochSeconds !== 'number' || !Number.isFinite(epochSeconds) || epochSeconds <= 0) {
- return null;
- }
- const date = new Date(epochSeconds * 1000);
- const now = new Date();
- const sameDay = date.toDateString() === now.toDateString();
- return new Intl.DateTimeFormat(
- undefined,
- sameDay
- ? { hour: 'numeric', minute: '2-digit' }
- : { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' },
- ).format(date);
-}
-
-/** Codex 重置卡到期时间:沿用产品的“当天时分、跨天月日+时分”,按界面语言本地化。 */
-function formatResetCreditExpiryAt(
- epochSeconds: number | null | undefined,
- nowMs: number,
- locale: string,
-): string | null {
- if (typeof epochSeconds !== 'number' || !Number.isFinite(epochSeconds) || epochSeconds <= 0) {
- return null;
- }
- const date = new Date(epochSeconds * 1000);
- const now = new Date(nowMs);
- const sameDay = date.getFullYear() === now.getFullYear()
- && date.getMonth() === now.getMonth()
- && date.getDate() === now.getDate();
- return new Intl.DateTimeFormat(
- locale,
- sameDay
- ? { hour: 'numeric', minute: '2-digit' }
- : { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' },
- ).format(date);
-}
-
/**
* chip 主体用的紧凑剩余时长(距 reset 还有多久): 单级精度 + 向上取整 ——
* 「7天」/「3小时」/「45分钟」/「41秒」。Codex 与 Claude 订阅两种形态统一用它当窗口
@@ -383,9 +292,11 @@ interface ChipWindowSegment extends ChipWindowSlot {
* 含等号会让它再等一轮慢 tick(多挂最长一分钟)。
*/
function isResetPending(resetsAtMs: number | null, nowMs: number): boolean {
- return typeof resetsAtMs === 'number'
- && resetsAtMs <= nowMs
- && nowMs - resetsAtMs < RESET_PENDING_MAX_MS;
+ return (
+ typeof resetsAtMs === 'number' &&
+ resetsAtMs <= nowMs &&
+ nowMs - resetsAtMs < RESET_PENDING_MAX_MS
+ );
}
function formatWindowLabel(
@@ -417,58 +328,6 @@ function formatWindowLabel(
return `${Math.round(minutes)}m`;
}
-interface CodexWindowUsage {
- label: string;
- used: string;
- remaining: string;
- /** tooltip 用的精确 reset 时间点;无数据 → null。 */
- resetAt: string | null;
-}
-
-function toCodexWindowUsage(
- label: string,
- window: RateLimitSnapshot['primary'],
-): CodexWindowUsage | null {
- if (!window || typeof window.usedPercent !== 'number' || !Number.isFinite(window.usedPercent)) {
- return null;
- }
- const usedPercent = clampPercent(window.usedPercent);
- return {
- label,
- used: formatPercent(usedPercent),
- remaining: formatPercent(100 - usedPercent),
- resetAt: formatResetAt(window.resetsAt),
- };
-}
-
-function formatRateLimitReason(reason: string): string {
- return reason
- .replace(/[_-]+/g, ' ')
- .replace(/\b\w/g, (char) => char.toUpperCase());
-}
-
-function getCodexWindowUsages(
- snapshot: RateLimitSnapshot | null,
- t: TFunction,
- nowMs: number,
-): CodexWindowUsage[] {
- if (!snapshot) return [];
- // tooltip 形态: 窗口名 + resetAt 精确时间(chip 段见 getCodexChipWindows)。
- // 窗口名一律由服务端下发的 windowMinutes / resetsAt 动态派生,不对窗口构成做
- // 任何假设(OpenAI 会调整策略:2026-07 曾一度取消 5h 窗口,且可能随时恢复)。
- // 两项数据都缺时兜底中性「限额」,不猜具体窗口名。
- return [
- toCodexWindowUsage(
- formatWindowLabel(snapshot.primary, t('todaySpend.codex.limitWindow'), t, nowMs),
- snapshot.primary,
- ),
- toCodexWindowUsage(
- formatWindowLabel(snapshot.secondary, t('todaySpend.codex.limitWindow'), t, nowMs),
- snapshot.secondary,
- ),
- ].filter((v): v is CodexWindowUsage => Boolean(v));
-}
-
/** Codex 订阅 chip 的单个窗口段素材;窗口缺失 / 百分比不可解析 → null。 */
function toCodexChipWindow(
slotKey: 'primary' | 'secondary',
@@ -503,33 +362,28 @@ function getCodexChipWindows(
return [
toCodexChipWindow('primary', snapshot.primary, t, nowMs),
toCodexChipWindow('secondary', snapshot.secondary, t, nowMs),
- ].filter((v): v is ChipWindowSegment => Boolean(v)).map((window) => ({
- ...window,
- // 相同长度的窗口也可能属于不同账号、数据源或模型桶,不能跨额度比较。
- key: JSON.stringify([window.key, snapshot.accountId ?? null, snapshot.source ?? null, snapshot.limitId ?? null]),
- }));
-}
-
-function isCodexWindowExhausted(window: RateLimitSnapshot['primary']): boolean {
- return Boolean(window && clampPercent(window.usedPercent) >= 99.95);
-}
-
-function shouldShowCodexLimitReachedReason(snapshot: RateLimitSnapshot): boolean {
- if (!snapshot.rateLimitReachedType) return false;
- if (snapshot.rateLimitReachedType.includes('credits_depleted')) return false;
- return isCodexWindowExhausted(snapshot.primary) || isCodexWindowExhausted(snapshot.secondary);
+ ]
+ .filter((v): v is ChipWindowSegment => Boolean(v))
+ .map((window) => ({
+ ...window,
+ // 相同长度的窗口也可能属于不同账号、数据源或模型桶,不能跨额度比较。
+ key: JSON.stringify([
+ window.key,
+ snapshot.accountId ?? null,
+ snapshot.source ?? null,
+ snapshot.limitId ?? null,
+ ]),
+ }));
}
function getGatewayChipSegments(slots: Record<MetricKey, MetricSlot>): string[] {
- return PRIMARY_GATEWAY_METRICS
- .filter((key) => slots[key].available)
- .map((key) => slots[key].label);
+ return PRIMARY_GATEWAY_METRICS.filter((key) => slots[key].available).map(
+ (key) => slots[key].label,
+ );
}
function hasPositiveSessionTokens(sessionTokens: number | null): boolean {
- return typeof sessionTokens === 'number'
- && Number.isFinite(sessionTokens)
- && sessionTokens > 0;
+ return typeof sessionTokens === 'number' && Number.isFinite(sessionTokens) && sessionTokens > 0;
}
function getCodexApiEmptyState(
@@ -540,82 +394,6 @@ function getCodexApiEmptyState(
return latestTurnUsage ? 'unavailable' : 'no-usage';
}
-function buildCodexTooltipNode(
- snapshot: RateLimitSnapshot | null,
- sessionTokens: number | null,
- sessionUsage: SessionUsageMoney,
- resetSummary: CodexRateLimitResetSummary | null,
- t: TFunction,
- locale: string,
- usageDashboardLabel: string | null,
- nowMs: number,
- latestTurnUsage: LatestTurnUsageSummary | null,
-): React.ReactNode {
- const lines: string[] = [];
- pushSessionUsageLines(lines, sessionUsage, sessionTokens, t);
- if (!snapshot) {
- lines.push(t('todaySpend.codex.waitingDetail'));
- pushCodexResetCreditLines(lines, resetSummary, t, locale, nowMs);
- appendLatestTurnUsageLines(lines, latestTurnUsage, t);
- pushDashboardLinkLine(lines, usageDashboardLabel);
- return buildTooltipNode(lines);
- }
-
- const planLabel = formatPlanType(snapshot.planType);
- const credits = snapshot.credits;
- const parsedCredits = parseCreditBalance(credits?.balance);
-
- if (planLabel && parsedCredits) {
- lines.push(t('todaySpend.codex.planCreditsLine', {
- plan: planLabel,
- credits: parsedCredits.formatted,
- }));
- } else if (planLabel) {
- lines.push(t('todaySpend.codex.planLine', { plan: planLabel }));
- } else if (parsedCredits) {
- lines.push(t('todaySpend.codex.creditsLine', {
- credits: parsedCredits.formatted,
- }));
- }
-
- if (credits?.unlimited) {
- lines.push(t('todaySpend.codex.balanceUnlimited'));
- } else if (credits && !credits.hasCredits) {
- lines.push(t('todaySpend.codex.balanceDepleted'));
- } else if (credits?.hasCredits && !parsedCredits) {
- lines.push(t('todaySpend.codex.balanceAvailable'));
- }
- pushCodexResetCreditLines(lines, resetSummary, t, locale, nowMs);
-
- for (const window of getCodexWindowUsages(snapshot, t, nowMs)) {
- const base = t('todaySpend.codex.windowLine', {
- label: window.label,
- remaining: window.remaining,
- used: window.used,
- });
- lines.push(window.resetAt
- ? `${base} · ${t('todaySpend.codex.resetAt', { at: window.resetAt })}`
- : base,
- );
- }
-
- const limitReachedReason = shouldShowCodexLimitReachedReason(snapshot)
- ? snapshot.rateLimitReachedType
- : null;
- if (limitReachedReason) {
- lines.push(t('todaySpend.codex.limitReached', {
- reason: formatRateLimitReason(limitReachedReason),
- }));
- }
-
- if (lines.length === 0) {
- lines.push(t('todaySpend.codex.waitingDetail'));
- }
- appendLatestTurnUsageLines(lines, latestTurnUsage, t);
- pushDashboardLinkLine(lines, usageDashboardLabel);
- return buildTooltipNode(lines);
-}
-
// ── Claude 订阅 (Anthropic OAuth) 形态 ───────────────────────────────────────
// 主 chip 方案 B: 5h 剩余% · 当前模型周限剩余% (weekly_scoped 按模型家族匹配, 匹配
// 不到回退总周限并标注口径) · 本会话价值 $。utilization 语义 = 已用百分比 (0-100)。
@@ -659,7 +437,11 @@ function getClaudeChipWindows(
if (!snapshot) return [];
const windows: ChipWindowSegment[] = [];
const fiveHour = snapshot.fiveHour;
- if (fiveHour && typeof fiveHour.utilization === 'number' && Number.isFinite(fiveHour.utilization)) {
+ if (
+ fiveHour &&
+ typeof fiveHour.utilization === 'number' &&
+ Number.isFinite(fiveHour.utilization)
+ ) {
const countdown = formatCompactTimeUntilReset(fiveHour.resetsAt, nowMs, t);
const resetsAtMs = toEpochMs(fiveHour.resetsAt);
windows.push({
@@ -672,18 +454,22 @@ function getClaudeChipWindows(
}
const weekly = resolveClaudeWeeklyWindow(snapshot, modelId, t);
if (
- weekly
- && typeof weekly.window.utilization === 'number'
- && Number.isFinite(weekly.window.utilization)
+ weekly &&
+ typeof weekly.window.utilization === 'number' &&
+ Number.isFinite(weekly.window.utilization)
) {
const countdown = formatCompactTimeUntilReset(weekly.window.resetsAt, nowMs, t);
const label = countdown
- ? (weekly.modelDisplayName ? `${weekly.modelDisplayName} ${countdown}` : countdown)
+ ? weekly.modelDisplayName
+ ? `${weekly.modelDisplayName} ${countdown}`
+ : countdown
: weekly.label;
const resetsAtMs = toEpochMs(weekly.window.resetsAt);
windows.push({
// 身份 key 区分总周限与各 scoped 周限: 切模型导致窗口切换时只重置动画基线。
- key: weekly.modelDisplayName ? `claude-weekly:${weekly.modelDisplayName}` : 'claude-weekly:total',
+ key: weekly.modelDisplayName
+ ? `claude-weekly:${weekly.modelDisplayName}`
+ : 'claude-weekly:total',
label,
remainingPercent: 100 - clampPercent(weekly.window.utilization),
resetsAtMs,
@@ -784,20 +570,22 @@ function toQuotaHoverCardTurnUsage(
/** 把会话金额投影成卡片数据;混合合计保留实际费用与价值估算两条构成。 */
function toQuotaHoverCardSessionUsage(
sessionUsage: SessionUsageMoney,
+ sessionTokens: number | null,
): QuotaHoverCardSessionUsage | null {
const { actualMoney, estimatedValueMoney, totalMoney } = sessionUsage;
- if (!totalMoney?.amount) return null;
+ if (!totalMoney?.amount && !hasPositiveSessionTokens(sessionTokens)) return null;
return {
- costText: formatTurnCostMoney(totalMoney),
+ costText: totalMoney?.amount ? formatTurnCostMoney(totalMoney) : null,
+ tokensText: hasPositiveSessionTokens(sessionTokens)
+ ? formatCompactTokens(Math.floor(sessionTokens!))
+ : null,
// approximate 只说明金额精度,不能把第三方参考价的实际费用改成订阅价值语义。
// 纯价值估算优先信任 kind;兼容旧投影时再以唯一存在的估值分量兜底。
costIsEstimate:
- totalMoney.kind === 'value-estimate'
- || Boolean(!actualMoney?.amount && estimatedValueMoney?.amount),
- ...(actualMoney?.amount
- ? { actualCostText: formatTurnCostMoney(actualMoney) }
- : {}),
+ totalMoney?.kind === 'value-estimate' ||
+ Boolean(!actualMoney?.amount && estimatedValueMoney?.amount),
+ ...(actualMoney?.amount ? { actualCostText: formatTurnCostMoney(actualMoney) } : {}),
...(estimatedValueMoney?.amount
? { estimatedValueText: formatTurnCostMoney(estimatedValueMoney) }
: {}),
@@ -808,13 +596,11 @@ function findLatestTurnUsageSummary(messages: ChatMessage[]): LatestTurnUsageSum
for (let i = messages.length - 1; i >= 0; i--) {
const message = messages[i];
if (message.role !== 'assistant' || !message.turnUsageDetails) continue;
- const userTurnMoney =
- message.userTurnMoney?.amount
- ? message.userTurnMoney
+ const userTurnMoney = message.userTurnMoney?.amount ? message.userTurnMoney : undefined;
+ const userTurnCostUsd =
+ typeof message.userTurnCostUsd === 'number' && message.userTurnCostUsd > 0
+ ? message.userTurnCostUsd
: undefined;
- const userTurnCostUsd = typeof message.userTurnCostUsd === 'number' && message.userTurnCostUsd > 0
- ? message.userTurnCostUsd
- : undefined;
const displayedMoney = userTurnMoney ?? message.turnMoney;
return {
...(userTurnMoney
@@ -823,13 +609,12 @@ function findLatestTurnUsageSummary(messages: ChatMessage[]): LatestTurnUsageSum
? { costUsd: userTurnCostUsd }
: message.turnMoney?.amount
? { money: message.turnMoney }
- : typeof message.turnCostUsd === 'number' && message.turnCostUsd > 0
- ? { costUsd: message.turnCostUsd }
- : {}),
+ : typeof message.turnCostUsd === 'number' && message.turnCostUsd > 0
+ ? { costUsd: message.turnCostUsd }
+ : {}),
...((userTurnMoney || userTurnCostUsd != null
? message.userTurnCostIsEstimate
- : message.turnCostIsEstimate) === true
- || displayedMoney?.kind === 'value-estimate'
+ : message.turnCostIsEstimate) === true || displayedMoney?.kind === 'value-estimate'
? { isEstimate: true }
: {}),
isUserTurnTotal: Boolean(userTurnMoney || userTurnCostUsd != null),
@@ -837,8 +622,7 @@ function findLatestTurnUsageSummary(messages: ChatMessage[]): LatestTurnUsageSum
// Raw segment costs remain persisted for billing and analytics, but are
// an implementation detail rather than a second user-facing total.
details:
- aggregateAssistantTurnUsageDetails(messages, message.clientId) ??
- message.turnUsageDetails,
+ aggregateAssistantTurnUsageDetails(messages, message.clientId) ?? message.turnUsageDetails,
};
}
return null;
@@ -847,7 +631,7 @@ function findLatestTurnUsageSummary(messages: ChatMessage[]): LatestTurnUsageSum
function useLatestTurnUsageSummary(sessionId: string | undefined): LatestTurnUsageSummary | null {
const displaySnapshot = useChatDisplaySnapshot(sessionId);
const displaySummary = React.useMemo(
- () => displaySnapshot ? findLatestTurnUsageSummary(displaySnapshot.messages) : null,
+ () => (displaySnapshot ? findLatestTurnUsageSummary(displaySnapshot.messages) : null),
[displaySnapshot],
);
const [summary, setSummary] = React.useState<LatestTurnUsageSummary | null>(() => {
@@ -871,160 +655,6 @@ function useLatestTurnUsageSummary(sessionId: string | undefined): LatestTurnUsa
return displaySnapshot ? displaySummary : summary;
}
-function appendLatestTurnUsageLines(
- lines: string[],
- summary: LatestTurnUsageSummary | null,
- t: TFunction,
-): void {
- if (!summary) return;
- if (lines.length > 0) lines.push('');
- lines.push(...buildTurnUsageTooltipLines({
- details: summary.details,
- t,
- money: summary.money,
- costUsd: summary.costUsd,
- isEstimate: summary.isEstimate,
- title: t(
- summary.isUserTurnTotal
- ? 'todaySpend.tooltip.latestUserTurnTitle'
- : 'todaySpend.tooltip.latestTurnTitle',
- ),
- }));
-}
-
-function buildTooltipNode(lines: string[]): React.ReactNode {
- return <span className="whitespace-pre-line">{lines.join('\n')}</span>;
-}
-
-/**
- * 在 tooltip 末尾追加"打开看板"链接行(前置空行与正文隔开)。
- * label 为 null(如 XD 网关账号暂无看板可跳)时不追加任何内容。
- */
-function pushDashboardLinkLine(lines: string[], label: string | null): void {
- if (!label) return;
- if (lines.length > 0) lines.push('');
- lines.push(label);
-}
-
-/**
- * 会话金额 tooltip 的统一投影:纯实际费用或纯价值估算各显示自己的语义;
- * 两者并存时先显示合计,再列出构成,避免把估算值伪装成真实扣费。
- */
-function pushSessionUsageLines(
- lines: string[],
- sessionUsage: SessionUsageMoney,
- sessionTokens: number | null,
- t: TFunction,
-): void {
- const { actualMoney, estimatedValueMoney, totalMoney } = sessionUsage;
- if (actualMoney?.amount && estimatedValueMoney?.amount && totalMoney?.amount) {
- lines.push(t('todaySpend.sessionCostLabel', {
- cost: formatTurnCostMoney(totalMoney),
- }));
- }
- if (actualMoney?.amount) {
- lines.push(t('todaySpend.tooltip.sessionUsed', {
- cost: formatTurnCostMoney(actualMoney),
- }));
- }
- if (estimatedValueMoney?.amount) {
- lines.push(t('todaySpend.codex.sessionValueLabel', {
- cost: formatTurnCostMoney(estimatedValueMoney),
- }));
- }
- if (typeof sessionTokens === 'number' && Number.isFinite(sessionTokens) && sessionTokens > 0) {
- lines.push(t('todaySpend.codex.sessionTokensLine', {
- tokens: formatCompactTokens(Math.floor(sessionTokens)),
- }));
- }
-}
-
-/** 与 Mobile 共用中性汇总字段;Desktop label、次数和时间按当前界面语言展示。 */
-function pushCodexResetCreditLines(
- lines: string[],
- resetSummary: CodexRateLimitResetSummary | null,
- t: TFunction,
- locale: string,
- nowMs: number,
-): void {
- if (resetSummary?.hasResetCreditCount) {
- lines.push(t('todaySpend.codex.resetCreditsAvailableLine', {
- count: resetSummary.availableCount,
- }));
- }
- const expiryAt = formatResetCreditExpiryAt(
- resetSummary?.earliestExpiryAt,
- nowMs,
- locale,
- );
- if (expiryAt) {
- lines.push(t('todaySpend.codex.resetCreditEarliestExpiryLine', { at: expiryAt }));
- }
-}
-
-/**
- * xAI(SuperGrok bridge)tooltip —— 尽力档:有限流快照(bridge 抓到 x-ratelimit-* 头)就
- * 显示剩余请求/tokens,拿不到诚实标注「无订阅额度明细」,只显示价值估算 + token 累计。
- */
-function buildXaiTooltipNode(
- usage: XaiSubscriptionUsageSnapshot | null,
- rateLimit: XaiRateLimitSnapshot | null,
- sessionTokens: number | null,
- sessionUsage: SessionUsageMoney,
- t: TFunction,
- usageDashboardLabel: string | null,
- latestTurnUsage: LatestTurnUsageSummary | null,
- nowMs: number,
-): React.ReactNode {
- const lines: string[] = [];
- pushSessionUsageLines(lines, sessionUsage, sessionTokens, t);
- if (usage?.planLabel) {
- lines.push(t('todaySpend.xai.planLine', { plan: usage.planLabel }));
- }
- const weekly = isXaiWeeklyUsageCurrent(usage, nowMs) ? usage : null;
- if (weekly && typeof weekly.creditUsagePercent === 'number') {
- lines.push(t('todaySpend.xai.windowLine', {
- label: t('todaySpend.xai.weeklyLabel'),
- remaining: formatPercent(100 - clampPercent(weekly.creditUsagePercent)),
- used: formatPercent(clampPercent(weekly.creditUsagePercent)),
- }));
- lines.push(t('todaySpend.xai.accountWeeklyHint'));
- }
- if (weekly?.resetsAt) {
- const resetAt = formatResetAt(weekly.resetsAt);
- if (resetAt) lines.push(t('todaySpend.xai.resetAt', { at: resetAt }));
- }
- for (const product of weekly?.productUsage ?? []) {
- lines.push(t('todaySpend.xai.productLine', {
- product: formatXaiProductLabel(product.product),
- percent: formatPercent(product.usagePercent),
- }));
- }
- if (weekly && typeof weekly.prepaidBalance === 'number' && weekly.prepaidBalance > 0) {
- lines.push(t('todaySpend.xai.extraCreditsLine', {
- amount: `US$${weekly.prepaidBalance.toFixed(2)}`,
- }));
- }
- if (rateLimit && typeof rateLimit.remainingRequests === 'number' && typeof rateLimit.limitRequests === 'number') {
- lines.push(t('todaySpend.xai.requestsLine', {
- remaining: rateLimit.remainingRequests.toLocaleString(),
- limit: rateLimit.limitRequests.toLocaleString(),
- }));
- }
- if (rateLimit && typeof rateLimit.remainingTokens === 'number' && typeof rateLimit.limitTokens === 'number') {
- lines.push(t('todaySpend.xai.tokensLine', {
- remaining: formatCompactTokens(rateLimit.remainingTokens),
- limit: formatCompactTokens(rateLimit.limitTokens),
- }));
- }
- if (!usage && !rateLimit) {
- lines.push(t('todaySpend.xai.noQuotaDetail'));
- }
- appendLatestTurnUsageLines(lines, latestTurnUsage, t);
- pushDashboardLinkLine(lines, usageDashboardLabel);
- return buildTooltipNode(lines);
-}
-
function getXaiChipWindows(
snapshot: XaiSubscriptionUsageSnapshot | null,
t: TFunction,
@@ -1034,23 +664,22 @@ function getXaiChipWindows(
const used = snapshot.creditUsagePercent ?? 0;
const countdown = formatCompactTimeUntilReset(snapshot.resetsAt ?? undefined, nowMs, t);
const resetsAtMs = toEpochMs(snapshot.resetsAt ?? undefined);
- return [{
- key: JSON.stringify(['xai-weekly', snapshot.accountFingerprint ?? null]),
- label: countdown ?? t('todaySpend.xai.weeklyLabel'),
- remainingPercent: 100 - clampPercent(used),
- resetsAtMs,
- resetPending: isResetPending(resetsAtMs, nowMs),
- }];
+ return [
+ {
+ key: JSON.stringify(['xai-weekly', snapshot.accountFingerprint ?? null]),
+ label: countdown ?? t('todaySpend.xai.weeklyLabel'),
+ remainingPercent: 100 - clampPercent(used),
+ resetsAtMs,
+ resetPending: isResetPending(resetsAtMs, nowMs),
+ },
+ ];
}
function renderSegmentedLabel(segments: React.ReactNode[]): React.ReactNode {
return segments.map((seg, i) => (
<React.Fragment key={i}>
{i > 0 && (
- <span
- aria-hidden="true"
- className="mx-2 inline-block h-3 w-px bg-current opacity-30"
- />
+ <span aria-hidden="true" className="mx-2 inline-block h-3 w-px bg-current opacity-30" />
)}
<span className="tabular-nums">{seg}</span>
</React.Fragment>
@@ -1129,128 +758,103 @@ export function TodaySpendChip({
const { hasSavedKey: hasGatewayKey, isReconciling: gatewayKeyReconciling } = useApiKey();
const claudeOAuthConnected = useClaudeOAuthConnected(isDefaultRouteClaudeSession);
const observedClaudeRoute = useClaudeSessionRoute(sessionId, isDefaultRouteClaudeSession);
- const ccBillingFormPending = isDefaultRouteClaudeSession && observedClaudeRoute == null
- && (gatewayKeyReconciling || (!hasGatewayKey && claudeOAuthConnected == null));
- const isClaudeSubscription = !isDeviceLinkRemote && (
- (
- vendorKey === 'cc'
- && !isRemoteClaudeSession
- && (
- providerId === 'anthropic'
- || (providerId == null && (
- observedClaudeRoute != null
+ const ccBillingFormPending =
+ isDefaultRouteClaudeSession &&
+ observedClaudeRoute == null &&
+ (gatewayKeyReconciling || (!hasGatewayKey && claudeOAuthConnected == null));
+ const isClaudeSubscription =
+ !isDeviceLinkRemote &&
+ ((vendorKey === 'cc' &&
+ !isRemoteClaudeSession &&
+ (providerId === 'anthropic' ||
+ (providerId == null &&
+ (observedClaudeRoute != null
? observedClaudeRoute === 'subscription'
- : !gatewayKeyReconciling && !hasGatewayKey && claudeOAuthConnected === true
- ))
- )
- )
- // Pi 的 provider 在创建会话时已经显式固化,不需要再从 CC proxy route 猜。
- || (vendorKey === 'pi' && !remoteHostId && providerId === 'anthropic')
- );
+ : !gatewayKeyReconciling && !hasGatewayKey && claudeOAuthConnected === true)))) ||
+ // Pi 的 provider 在创建会话时已经显式固化,不需要再从 CC proxy route 猜。
+ (vendorKey === 'pi' && !remoteHostId && providerId === 'anthropic'));
// cc 走「订阅直连 bridge」= model 带 chatgpt/ / xai/ 前缀(经本地 responses-bridge 打用户个人
// 订阅额度,真实计费恒 0,gateway quota 与之无关):
// - chatgpt/ → 与 codex 同一 ChatGPT 账户,复用 codex 订阅 chip 形态(限额窗口 + 价值估算);
// - xai/ → SuperGrok 账号周用量(cli-chat-proxy billing) + 尽力显示限流头。
// 优先级高于 Claude 订阅形态(model 前缀决定实际消耗的额度)。
const isChatgptBridge =
- (vendorKey === 'cc' || vendorKey === 'pi')
- && (providerId == null || providerId === 'openai')
- && typeof modelId === 'string'
- && modelId.startsWith(CHATGPT_MODEL_PREFIX);
+ (vendorKey === 'cc' || vendorKey === 'pi') &&
+ (providerId == null || providerId === 'openai') &&
+ typeof modelId === 'string' &&
+ modelId.startsWith(CHATGPT_MODEL_PREFIX);
// SuperGrok 周用量是账号级。Pi catalog 的模型 id 是 grok-4.6,没有 xai/ 前缀,
// 只靠前缀会漏掉「显式选了 xAI」的 Pi/CC 会话(设置页看得到、chip 没有)。
- const isXaiPrefixedModel =
- typeof modelId === 'string' && modelId.startsWith(XAI_MODEL_PREFIX);
+ const isXaiPrefixedModel = typeof modelId === 'string' && modelId.startsWith(XAI_MODEL_PREFIX);
const isXaiBridge =
- (vendorKey === 'cc' || vendorKey === 'pi')
- && (
- providerId === 'xai'
- || (providerId == null && isXaiPrefixedModel)
- );
+ (vendorKey === 'cc' || vendorKey === 'pi') &&
+ (providerId === 'xai' || (providerId == null && isXaiPrefixedModel));
const isSubscriptionBridge = isChatgptBridge || isXaiBridge;
const isRemoteCodexSession = vendorKey === 'codex' && Boolean(remoteHostId);
const isCodexBudgetModel = typeof modelId === 'string' && modelId.startsWith('codex/');
const isCodexGatewayBudgetModel =
isCodexBudgetModel && (providerId == null || providerId === 'xd');
const isCodexXaiProvider =
- vendorKey === 'codex'
- && (
- providerId === 'xai'
- || (providerId == null && isXaiPrefixedModel)
- );
+ vendorKey === 'codex' && (providerId === 'xai' || (providerId == null && isXaiPrefixedModel));
// codex 走订阅价值估算:ChatGPT 订阅需要 oauth-bearer + OpenAI 来源;xAI 由 proxy 注入
// SuperGrok OAuth。显式自定义供应商优先于共享 host 的 authInjection 和模型名前缀。
// 远端 Codex 的事实在远端 daemon 上,本机只记录 token 价值估算,不写本地 gateway cost。
- const isCodexOauth = vendorKey === 'codex' && !isCodexXaiProvider && (
- isRemoteCodexSession ||
- (
- codexAuthInjection === 'oauth-bearer'
- && !isCodexGatewayBudgetModel
- && (providerId == null || providerId === 'openai')
- )
- );
+ const isCodexOauth =
+ vendorKey === 'codex' &&
+ !isCodexXaiProvider &&
+ (isRemoteCodexSession ||
+ (codexAuthInjection === 'oauth-bearer' &&
+ !isCodexGatewayBudgetModel &&
+ (providerId == null || providerId === 'openai')));
const isCodexSubscription = isCodexOauth || isCodexXaiProvider;
const isCodexApi = vendorKey === 'codex' && !isCodexSubscription;
const isPiGateway =
- vendorKey === 'pi'
- && !remoteHostId
- && !isDeviceLinkRemote
- && (providerId == null || providerId === 'xd')
- && !isClaudeSubscription
- && !isChatgptBridge
- && !isXaiBridge;
+ vendorKey === 'pi' &&
+ !remoteHostId &&
+ !isDeviceLinkRemote &&
+ (providerId == null || providerId === 'xd') &&
+ !isClaudeSubscription &&
+ !isChatgptBridge &&
+ !isXaiBridge;
// codex-oauth 与 cc+chatgpt/ bridge 共用同一 ChatGPT 账户 → 同一套限额窗口 chip 渲染。
const usesCodexQuotaForm = isCodexOauth || isChatgptBridge;
const usesXaiQuotaForm = isCodexXaiProvider || isXaiBridge;
- const usesClaudeSubscriptionPopover = isClaudeSubscription && !isSubscriptionBridge;
// 远程会话不读本机账户快照 —— 额度事实在远端:SSH 用 remoteHostId 判,device-link 用
// deviceLinkDeviceId 判(两者互斥,任一非空即远程,turn 消耗的是远端账号的额度)。
const isAnyRemoteSession = Boolean(remoteHostId) || Boolean(deviceLinkDeviceId);
// Model Access 配额只属于实际走 XD/Cindy AI Gateway 的本地会话。显式自定义供应商即使
// 复用了 env-key / oauth-bearer host,也不能据 host 的启动凭证把 /v2/user/info 串进来。
const isClaudeGateway =
- vendorKey === 'cc'
- && !isAnyRemoteSession
- && !isSubscriptionBridge
- && !ccBillingFormPending
- && (
- providerId === 'xd'
- || (
- providerId == null
- && (
- observedClaudeRoute != null
- ? observedClaudeRoute === 'gateway'
- : !gatewayKeyReconciling && hasGatewayKey
- )
- )
- );
+ vendorKey === 'cc' &&
+ !isAnyRemoteSession &&
+ !isSubscriptionBridge &&
+ !ccBillingFormPending &&
+ (providerId === 'xd' ||
+ (providerId == null &&
+ (observedClaudeRoute != null
+ ? observedClaudeRoute === 'gateway'
+ : !gatewayKeyReconciling && hasGatewayKey)));
const isCodexGateway =
- vendorKey === 'codex'
- && !isAnyRemoteSession
- && !isCodexSubscription
- && (
- providerId === 'xd'
- || (
- providerId == null
- && (
- codexAuthInjection === 'env-key'
- || isCodexGatewayBudgetModel
- || (codexAuthInjection === 'provider-oauth' && hasGatewayKey)
- )
- )
- );
+ vendorKey === 'codex' &&
+ !isAnyRemoteSession &&
+ !isCodexSubscription &&
+ (providerId === 'xd' ||
+ (providerId == null &&
+ (codexAuthInjection === 'env-key' ||
+ isCodexGatewayBudgetModel ||
+ (codexAuthInjection === 'provider-oauth' && hasGatewayKey))));
const usesGatewayQuota = isClaudeGateway || isCodexGateway || isPiGateway;
const shouldReadLocalCodexAccountUsage = usesCodexQuotaForm && !isAnyRemoteSession;
// 会话金额只由已发生的 turn 决定,不由当前选中的 provider/模型决定。实际费用从
// session ledger 读取,订阅价值从消息明细重建,再统一汇总成“本对话”投影。
- const sessionUsage = useSessionUsageMoney(
- sessionId,
- sessionInitialMoney,
- sessionInitialCostUsd,
- );
+ const sessionUsage = useSessionUsageMoney(sessionId, sessionInitialMoney, sessionInitialCostUsd);
const sessionMoney = sessionUsage.totalMoney;
const sessionTokens = useSessionTokens(
- vendorKey === 'pi' || isCodexApi || isCodexSubscription || isSubscriptionBridge || isDeviceLinkRemote
+ vendorKey === 'pi' ||
+ isCodexApi ||
+ isCodexSubscription ||
+ isSubscriptionBridge ||
+ isDeviceLinkRemote
? sessionId
: undefined,
sessionInitialTokens,
@@ -1266,10 +870,9 @@ export function TodaySpendChip({
// 促销桶, 见 useAccountUsage.matchCodexBucketForModel)。
modelId,
);
- const {
- snapshot: codexRateLimits,
- refresh: refreshCodexRateLimits,
- } = useCodexRateLimits(isCodexOauth && !isAnyRemoteSession);
+ const { snapshot: codexRateLimits, refresh: refreshCodexRateLimits } = useCodexRateLimits(
+ isCodexOauth && !isAnyRemoteSession,
+ );
// xAI 限流快照同为本机 main 抓的 —— 远程会话(SSH / device-link)同样抑制,回落价值估算。
const xaiRateLimit = useXaiRateLimit(usesXaiQuotaForm && !isAnyRemoteSession);
const xaiSubscriptionUsage = useXaiSubscriptionUsage(usesXaiQuotaForm && !isAnyRemoteSession);
@@ -1286,7 +889,7 @@ export function TodaySpendChip({
isClaudeSubscription && !isSubscriptionBridge && !isDeviceLinkRemote,
);
const latestTurnUsage = useLatestTurnUsageSummary(sessionId);
- const quotaCardSessionUsage = toQuotaHoverCardSessionUsage(sessionUsage);
+ const quotaCardSessionUsage = toQuotaHoverCardSessionUsage(sessionUsage, sessionTokens);
const quotaCardTurnUsage = toQuotaHoverCardTurnUsage(latestTurnUsage, t);
const [quotaPopoverOpen, setQuotaPopoverOpen] = React.useState(false);
const quotaPopoverOpenTimerRef = React.useRef<number | null>(null);
@@ -1297,6 +900,7 @@ export function TodaySpendChip({
const quotaPopoverFocusTakenRef = React.useRef(false);
const quotaPopoverRestoringFocusRef = React.useRef(false);
const quotaPopoverTriggerRef = React.useRef<HTMLElement>(null);
+ const quotaPopoverContentRef = React.useRef<HTMLDivElement>(null);
const quotaPopoverDashboardButtonRef = React.useRef<HTMLButtonElement>(null);
const setQuotaPopoverFocusTarget = React.useCallback((node: HTMLElement | null) => {
quotaPopoverTriggerRef.current = node;
@@ -1328,6 +932,7 @@ export function TodaySpendChip({
const openQuotaPopoverImmediately = React.useCallback(() => {
keepQuotaPopoverOpen();
quotaPopoverOpenSourceRef.current = 'focus';
+ setWindowLabelNowMs(Date.now());
setQuotaPopoverOpen(true);
}, [keepQuotaPopoverOpen]);
const closeQuotaPopoverImmediately = React.useCallback(() => {
@@ -1342,6 +947,7 @@ export function TodaySpendChip({
quotaPopoverOpenTimerRef.current = window.setTimeout(() => {
quotaPopoverOpenTimerRef.current = null;
quotaPopoverOpenSourceRef.current = 'hover';
+ setWindowLabelNowMs(Date.now());
setQuotaPopoverOpen(true);
}, QUOTA_POPOVER_OPEN_DELAY_MS);
}, [clearQuotaPopoverCloseTimer, clearQuotaPopoverOpenTimer]);
@@ -1373,16 +979,36 @@ export function TodaySpendChip({
}, [scheduleQuotaPopoverOpen]);
const quotaPopoverContextRef = React.useRef({
- enabled: usesClaudeSubscriptionPopover,
- sessionId,
+ identity: JSON.stringify([
+ sessionId,
+ providerId,
+ modelId,
+ vendorKey,
+ remoteHostId,
+ deviceLinkDeviceId,
+ usesCodexQuotaForm,
+ usesXaiQuotaForm,
+ isClaudeSubscription,
+ usesGatewayQuota,
+ ]),
});
React.useLayoutEffect(() => {
const previousContext = quotaPopoverContextRef.current;
- const contextInvalidated = previousContext.enabled
- && (!usesClaudeSubscriptionPopover || previousContext.sessionId !== sessionId);
- quotaPopoverContextRef.current = {
- enabled: usesClaudeSubscriptionPopover,
+ const identity = JSON.stringify([
sessionId,
+ providerId,
+ modelId,
+ vendorKey,
+ remoteHostId,
+ deviceLinkDeviceId,
+ usesCodexQuotaForm,
+ usesXaiQuotaForm,
+ isClaudeSubscription,
+ usesGatewayQuota,
+ ]);
+ const contextInvalidated = previousContext.identity !== identity;
+ quotaPopoverContextRef.current = {
+ identity,
};
if (!contextInvalidated) return;
@@ -1391,12 +1017,27 @@ export function TodaySpendChip({
quotaPopoverPointerInsideRef.current = false;
quotaPopoverFocusInsideRef.current = false;
closeQuotaPopoverImmediately();
- }, [closeQuotaPopoverImmediately, sessionId, usesClaudeSubscriptionPopover]);
-
- React.useEffect(() => () => {
- clearQuotaPopoverOpenTimer();
- clearQuotaPopoverCloseTimer();
- }, [clearQuotaPopoverCloseTimer, clearQuotaPopoverOpenTimer]);
+ }, [
+ closeQuotaPopoverImmediately,
+ sessionId,
+ providerId,
+ modelId,
+ vendorKey,
+ remoteHostId,
+ deviceLinkDeviceId,
+ usesCodexQuotaForm,
+ usesXaiQuotaForm,
+ isClaudeSubscription,
+ usesGatewayQuota,
+ ]);
+
+ React.useEffect(
+ () => () => {
+ clearQuotaPopoverOpenTimer();
+ clearQuotaPopoverCloseTimer();
+ },
+ [clearQuotaPopoverCloseTimer, clearQuotaPopoverOpenTimer],
+ );
const sessionSegment = sessionMoney?.amount
? t('todaySpend.sessionCostLabel', {
@@ -1438,9 +1079,9 @@ export function TodaySpendChip({
? getCodexChipWindows(accountUsage, t, windowLabelNowMs)
: usesXaiQuotaForm
? getXaiChipWindows(xaiSubscriptionUsage, t, windowLabelNowMs)
- : isClaudeSubscription
- ? getClaudeChipWindows(claudeSubscriptionUsage, modelId, t, windowLabelNowMs)
- : [];
+ : isClaudeSubscription
+ ? getClaudeChipWindows(claudeSubscriptionUsage, modelId, t, windowLabelNowMs)
+ : [];
// chip 最多两个窗口段, 固定两个 slot 无条件调 hook(Rules of Hooks)。
// 重置滚动: 快照刷新中同窗口剩余百分比大幅回升(典型: 窗口到点重置 0% → 100%)
// 时, 显示值从 0% 快速滚动到新值。
@@ -1494,19 +1135,20 @@ export function TodaySpendChip({
// 锚点取正在揭晓的窗口段元素(兜底 chip 容器)。
const chipRef = React.useRef<HTMLDivElement | null>(null);
const celebratingKey = rollupA?.celebrating
- ? windowSlotA?.key ?? null
+ ? (windowSlotA?.key ?? null)
: rollupB?.celebrating
- ? windowSlotB?.key ?? null
+ ? (windowSlotB?.key ?? null)
: null;
const prevCelebratingRef = React.useRef(false);
- const [confettiBurst, setConfettiBurst] = React.useState<
- { nonce: number; anchor: HTMLElement } | null
- >(null);
+ const [confettiBurst, setConfettiBurst] = React.useState<{
+ nonce: number;
+ anchor: HTMLElement;
+ } | null>(null);
React.useEffect(() => {
const celebrating = celebratingKey !== null;
if (celebrating && !prevCelebratingRef.current) {
- const anchor = (celebratingKey ? segmentElsRef.current[celebratingKey] : null)
- ?? chipRef.current;
+ const anchor =
+ (celebratingKey ? segmentElsRef.current[celebratingKey] : null) ?? chipRef.current;
if (anchor) {
setConfettiBurst((prev) => ({ nonce: (prev?.nonce ?? 0) + 1, anchor }));
}
@@ -1518,9 +1160,10 @@ export function TodaySpendChip({
// (含滚动动画的每一帧), 直接进 tick effect 依赖会让定时器反复重建。
const resetsAtSignature = chipWindows.map((window) => window.resetsAtMs ?? 'na').join(',');
const chipResetsAtMsList = React.useMemo(
- () => resetsAtSignature === ''
- ? []
- : resetsAtSignature.split(',').map((value) => (value === 'na' ? null : Number(value))),
+ () =>
+ resetsAtSignature === ''
+ ? []
+ : resetsAtSignature.split(',').map((value) => (value === 'na' ? null : Number(value))),
[resetsAtSignature],
);
@@ -1528,13 +1171,21 @@ export function TodaySpendChip({
// 订阅形态 (codex-oauth / cc+chatgpt bridge / claude 订阅) 的 reset 倒计时文案
// 需要随时间走动: 常态分钟级 tick 足够; 任一窗口进入最后一分钟切秒级 tick,
// 让「59秒 → 1秒」逐秒跳动。setTimeout 链每次 tick 后按最新窗口重估下一次延迟。
- if (!usesCodexQuotaForm && !usesXaiQuotaForm && !isClaudeSubscription) return undefined;
+ if (!usesCodexQuotaForm && !usesXaiQuotaForm && !isClaudeSubscription && !quotaPopoverOpen)
+ return undefined;
const delay = computeCountdownTickDelayMs(chipResetsAtMsList, Date.now());
const timer = window.setTimeout(() => {
setWindowLabelNowMs(Date.now());
}, delay);
return () => window.clearTimeout(timer);
- }, [usesCodexQuotaForm, usesXaiQuotaForm, isClaudeSubscription, windowLabelNowMs, chipResetsAtMsList]);
+ }, [
+ usesCodexQuotaForm,
+ usesXaiQuotaForm,
+ isClaudeSubscription,
+ quotaPopoverOpen,
+ windowLabelNowMs,
+ chipResetsAtMsList,
+ ]);
// 悬念期主动催一次余量刷新, 让「重置揭晓」尽快到来 —— main read 都是
// cached-first + 节流(Claude 订阅端点 180s + 退避; Codex WHAM 10s + in-flight
@@ -1545,8 +1196,8 @@ export function TodaySpendChip({
// 且无空闲期 app-server 催刷通道, 靠下一个 turn 事件或悬念超时回落兜底;
// - Claude 订阅形态催订阅端点。
const hasPendingResetWindow = chipWindows.some((window) => window.resetPending);
- const xaiNeedsWeeklyRefresh = usesXaiQuotaForm
- && !isXaiWeeklyUsageCurrent(xaiSubscriptionUsage, windowLabelNowMs);
+ const xaiNeedsWeeklyRefresh =
+ usesXaiQuotaForm && !isXaiWeeklyUsageCurrent(xaiSubscriptionUsage, windowLabelNowMs);
React.useEffect(() => {
if (!hasPendingResetWindow && !xaiNeedsWeeklyRefresh) return;
if (isChatgptBridge) {
@@ -1556,7 +1207,15 @@ export function TodaySpendChip({
} else if (isClaudeSubscription && !usesCodexQuotaForm) {
requestClaudeSubscriptionRefresh();
}
- }, [hasPendingResetWindow, xaiNeedsWeeklyRefresh, isChatgptBridge, isClaudeSubscription, usesCodexQuotaForm, usesXaiQuotaForm, windowLabelNowMs]);
+ }, [
+ hasPendingResetWindow,
+ xaiNeedsWeeklyRefresh,
+ isChatgptBridge,
+ isClaudeSubscription,
+ usesCodexQuotaForm,
+ usesXaiQuotaForm,
+ windowLabelNowMs,
+ ]);
const isDashboardClickable = usageDashboardUrl !== null;
const handleClick = () => {
@@ -1565,119 +1224,108 @@ export function TodaySpendChip({
};
let labelNode: React.ReactNode;
- let tooltipNode: React.ReactNode = usageDashboardLabel;
+ let account: UsageCardAccount = { title: t('quotaCard.usageTitle'), windows: [] };
if (isDeviceLinkRemote) {
// device-link 远程会话不读取本机账号形态;金额仍使用同一个会话合计投影。
const chipSegments = sessionSegment ? [sessionSegment] : [];
- labelNode = chipSegments.length > 0
- ? renderSegmentedLabel(chipSegments)
- : <span className="tabular-nums opacity-60">{DEFAULT_MONEY_SYMBOL}</span>;
- const tooltipLines: string[] = [];
- pushSessionUsageLines(tooltipLines, sessionUsage, sessionTokens, t);
- appendLatestTurnUsageLines(tooltipLines, latestTurnUsage, t);
- tooltipNode = tooltipLines.length > 0 ? buildTooltipNode(tooltipLines) : null;
- } else if (usesCodexQuotaForm) {
- // 配额窗口跟随当前渠道;会话金额独立汇总历史上所有已发生的 turn。
- const chipSegments = [...windowSegments];
- if (sessionSegment) chipSegments.push(sessionSegment);
- labelNode = chipSegments.length > 0
- ? renderSegmentedLabel(chipSegments)
- : <span className="tabular-nums opacity-60">{DEFAULT_MONEY_SYMBOL}</span>;
- tooltipNode = buildCodexTooltipNode(
- accountUsage,
- sessionTokens,
- sessionUsage,
- codexResetSummary,
- t,
- formatterLocale,
- usageDashboardLabel,
- windowLabelNowMs,
- latestTurnUsage,
- );
- } else if (usesXaiQuotaForm) {
- // 账号周用量进 chip;限流头与额外点数只在 tooltip。文案是账号级,不是本任务配额。
- const chipSegments = [...windowSegments];
- if (sessionSegment) chipSegments.push(sessionSegment);
- labelNode = chipSegments.length > 0
- ? renderSegmentedLabel(chipSegments)
- : <span className="tabular-nums opacity-60">{DEFAULT_MONEY_SYMBOL}</span>;
- tooltipNode = buildXaiTooltipNode(
- xaiSubscriptionUsage,
- xaiRateLimit,
- sessionTokens,
- sessionUsage,
- t,
- usageDashboardLabel,
- latestTurnUsage,
- windowLabelNowMs,
- );
- } else if (isClaudeSubscription) {
- // Claude 订阅形态 (方案 B): chip 显示「剩余时长 剩余%」倒计时段 + 本会话合计,
- // 倒计时由 windowLabelNowMs 驱动 (常态 60s tick, 最后一分钟逐秒)。
+ labelNode =
+ chipSegments.length > 0 ? (
+ renderSegmentedLabel(chipSegments)
+ ) : (
+ <span className="tabular-nums opacity-60">{DEFAULT_MONEY_SYMBOL}</span>
+ );
+ } else if (usesCodexQuotaForm || usesXaiQuotaForm || isClaudeSubscription) {
const chipSegments = [...windowSegments];
if (sessionSegment) chipSegments.push(sessionSegment);
- labelNode = chipSegments.length > 0
- ? renderSegmentedLabel(chipSegments)
- : <span className="tabular-nums opacity-60">{DEFAULT_MONEY_SYMBOL}</span>;
+ labelNode =
+ chipSegments.length > 0 ? (
+ renderSegmentedLabel(chipSegments)
+ ) : (
+ <span className="tabular-nums opacity-60">{DEFAULT_MONEY_SYMBOL}</span>
+ );
+ if (!isAnyRemoteSession) {
+ account = usesCodexQuotaForm
+ ? buildCodexUsageCard(accountUsage, codexResetSummary, t, windowLabelNowMs, formatterLocale)
+ : usesXaiQuotaForm
+ ? buildXaiUsageCard(xaiSubscriptionUsage, xaiRateLimit, t, windowLabelNowMs)
+ : buildClaudeUsageCard(claudeSubscriptionUsage, t);
+ }
} else {
const slots = computeMetricSlots(claudeQuota, creditTotals, sessionMoney, t);
const chipSegments = getGatewayChipSegments(slots);
- const codexApiHasTokenFallback = isCodexApi
- && !slots.session.available
- && hasPositiveSessionTokens(sessionTokens);
- const codexApiEmptyState = isCodexApi
- && !slots.session.available
- && !hasPositiveSessionTokens(sessionTokens)
- ? getCodexApiEmptyState(latestTurnUsage)
- : null;
+ const codexApiHasTokenFallback =
+ isCodexApi && !slots.session.available && hasPositiveSessionTokens(sessionTokens);
+ const codexApiEmptyState =
+ isCodexApi && !slots.session.available && !hasPositiveSessionTokens(sessionTokens)
+ ? getCodexApiEmptyState(latestTurnUsage)
+ : null;
if (codexApiHasTokenFallback) {
- chipSegments.push(t('todaySpend.codex.sessionTokensLine', {
- tokens: formatCompactTokens(Math.floor(sessionTokens ?? 0)),
- }));
- }
- // tooltip 主体: 主 chip 未显示且可用的 metric, 同样按固定顺序
- const tooltipMetricLines = METRIC_KEYS.filter(
- (k) => !PRIMARY_GATEWAY_METRICS.includes(k) && slots[k].available,
- ).map((k) => slots[k].tooltipLabel ?? slots[k].label);
-
- const tooltipLines: string[] = [];
- // server-side endpoint 独立可能失败, 各自挂掉时都加一行 ⚠️ 提示, 让用户知道
- // 那段是端点降级而非数据为 0
- // 个人租户没有"月度配额"这回事(三池账本是买断 + 赠送制), 拿到 credit 就不该再
- // 提示月度降级 —— 只有两种语义都拿不到(未开户 / 网关不可用)才是真降级。
- if (usesGatewayQuota && !claudeQuota && !creditTotals) {
- tooltipLines.push(t('todaySpend.tooltip.monthlyUnavailable'));
- } else if (claudeQuota?.todaySpend === null) {
- tooltipLines.push(t('todaySpend.tooltip.dailyUnavailable'));
- }
- if (slots.session.available) {
- pushSessionUsageLines(tooltipLines, sessionUsage, null, t);
+ chipSegments.push(
+ t('todaySpend.codex.sessionTokensLine', {
+ tokens: formatCompactTokens(Math.floor(sessionTokens ?? 0)),
+ }),
+ );
}
- if (codexApiHasTokenFallback) {
- tooltipLines.push(t('todaySpend.codex.sessionTokensLine', {
- tokens: formatCompactTokens(Math.floor(sessionTokens ?? 0)),
- }));
+ // Account quota is separate from lifetime task cost. API and remote routes never borrow it.
+ if (usesGatewayQuota) {
+ account.title = t('quotaCard.gatewayTitle');
+ if (creditTotals) {
+ account.windows.push({
+ key: 'balance',
+ title: t('quotaCard.balanceLabel'),
+ window: {
+ utilization:
+ creditTotals.total > 0 ? (creditTotals.used / creditTotals.total) * 100 : 0,
+ },
+ detail: slots.credit.tooltipLabel ?? slots.credit.label,
+ });
+ }
+ if (claudeQuota && claudeQuota.maxBudget > 0) {
+ if (typeof claudeQuota.todaySpend === 'number') {
+ const softLimit = (claudeQuota.maxBudget / 30) * DAILY_SOFT_LIMIT_FACTOR;
+ account.windows.push({
+ key: 'daily',
+ title: t('quotaCard.dailyLabel'),
+ window: { utilization: (claudeQuota.todaySpend / softLimit) * 100 },
+ detail: slots.daily.label,
+ });
+ }
+ account.windows.push({
+ key: 'monthly',
+ title: t('quotaCard.monthlyLabel'),
+ window: {
+ utilization: (claudeQuota.spend / claudeQuota.maxBudget) * 100,
+ resetsAt: claudeQuota.budgetResetAt
+ ? Date.parse(claudeQuota.budgetResetAt) / 1000
+ : null,
+ },
+ detail: slots.monthly.label,
+ });
+ account.updatedAt = claudeQuota.fetchedAt;
+ }
+ if (!claudeQuota && !creditTotals) {
+ account.emptyText = t('todaySpend.tooltip.monthlyUnavailable');
+ } else if (claudeQuota?.todaySpend === null) {
+ account.details = [t('todaySpend.tooltip.dailyUnavailable')];
+ }
}
- tooltipLines.push(...tooltipMetricLines);
- appendLatestTurnUsageLines(tooltipLines, latestTurnUsage, t);
if (codexApiEmptyState) {
- tooltipLines.unshift(t(
+ account.emptyText = t(
codexApiEmptyState === 'no-usage'
? 'todaySpend.codex.noUsageDetail'
: 'todaySpend.codex.unavailableDetail',
- ));
+ );
}
- // 链接行在最底(用空行隔开);网关账号 label 为 null → 不追加(见 usageDashboardUrl)。
- pushDashboardLinkLine(tooltipLines, usageDashboardLabel);
- tooltipNode = buildTooltipNode(tooltipLines);
if (chipSegments.length === 0) {
if (codexApiEmptyState) {
labelNode = (
<span className="tabular-nums opacity-60">
- {t(codexApiEmptyState === 'no-usage'
- ? 'todaySpend.codex.noUsageLabel'
- : 'todaySpend.codex.unavailableLabel')}
+ {t(
+ codexApiEmptyState === 'no-usage'
+ ? 'todaySpend.codex.noUsageLabel'
+ : 'todaySpend.codex.unavailableLabel',
+ )}
</span>
);
} else {
@@ -1692,14 +1340,23 @@ export function TodaySpendChip({
}
}
+ if (
+ !account.emptyText &&
+ !account.windows.length &&
+ !quotaCardSessionUsage &&
+ !quotaCardTurnUsage
+ ) {
+ account.emptyText = t('todaySpend.codex.noUsageDetail');
+ }
+
// Claude 订阅告警态: 影响当前会话的窗口 (5h / 总周限 / 当前模型 scoped) 任一逼近 /
// 打满, 或 headers 报 rejected → chip 变 error 色 (语义豁免色, 跨主题一致)。
// 其它模型的周限吃紧不染红 —— chip 上没有那一段, 红了也无从解释 (见
// isClaudeSubscriptionAlerting 对 allowed_warning 的取舍)。
- const claudeSubscriptionAlerting = isClaudeSubscription
- && isClaudeSubscriptionAlerting(claudeSubscriptionUsage, modelId);
- const xaiSubscriptionAlerting = usesXaiQuotaForm
- && isXaiSubscriptionAlerting(xaiSubscriptionUsage);
+ const claudeSubscriptionAlerting =
+ isClaudeSubscription && isClaudeSubscriptionAlerting(claudeSubscriptionUsage, modelId);
+ const xaiSubscriptionAlerting =
+ usesXaiQuotaForm && isXaiSubscriptionAlerting(xaiSubscriptionUsage);
// 与 ContextCapacityRing 视觉对齐 (h-5 = 20px) + reset button UA 默认 padding/border。
// tabular-nums 让 "$306 / $1.2k" 这类数字段的字符宽度等宽, 段间数字落点对齐。
@@ -1708,11 +1365,10 @@ export function TodaySpendChip({
'text-12 font-medium leading-none tabular-nums',
claudeSubscriptionAlerting || xaiSubscriptionAlerting
? 'text-[var(--error-fg)] hover:text-[var(--error-fg-strong)]'
- // 不可点(网关账号)时不加 hover 变色,避免暗示可交互。
- : cn('text-[var(--msg-tool-card-chevron)]', isDashboardClickable && 'hover:text-foreground'),
+ : 'text-[var(--msg-tool-card-chevron)] hover:text-foreground',
'border-0 bg-transparent p-0 m-0',
'transition-colors',
- 'focus:outline-none',
+ 'focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] rounded-full',
);
return (
@@ -1722,131 +1378,101 @@ export function TodaySpendChip({
onMouseEnter={refreshCodexRateLimits}
onFocusCapture={refreshCodexRateLimits}
>
- {usesClaudeSubscriptionPopover ? (
- <Popover
- open={quotaPopoverOpen}
- onOpenChange={(open) => {
- // 打开只由 hover / focus 驱动;Radix 的 outside / Escape 仍可请求关闭。
- if (!open) closeQuotaPopoverImmediately();
- }}
- modal={false}
- >
- <PopoverTrigger asChild>
- {isDashboardClickable ? (
- <button
- ref={setQuotaPopoverFocusTarget}
- type="button"
- onClick={(event) => {
- // 阻止 Radix 把 dashboard 点击解释成开关,chip 原动作保持不变。
- event.preventDefault();
- handleClick();
- }}
- onMouseEnter={handleQuotaPopoverTriggerMouseEnter}
- onMouseLeave={handleQuotaPopoverMouseLeave}
- onFocus={() => {
- if (quotaPopoverRestoringFocusRef.current) return;
- quotaPopoverFocusInsideRef.current = true;
- openQuotaPopoverImmediately();
- }}
- onBlur={() => {
- quotaPopoverFocusInsideRef.current = false;
- scheduleQuotaPopoverClose();
- }}
- onKeyDown={(event) => {
- if (event.key !== 'Escape') return;
- event.preventDefault();
- closeQuotaPopoverImmediately();
- }}
- className={buttonClass}
- aria-label={usageDashboardLabel ?? undefined}
- >
- {labelNode}
- </button>
- ) : (
- <span
- ref={setQuotaPopoverFocusTarget}
- tabIndex={-1}
- className={cn(buttonClass, 'cursor-default')}
- onMouseEnter={handleQuotaPopoverTriggerMouseEnter}
- onMouseLeave={handleQuotaPopoverMouseLeave}
- >
- {labelNode}
- </span>
- )}
- </PopoverTrigger>
- <PopoverContent
- side="top"
- align="end"
- sideOffset={8}
- collisionPadding={8}
- onOpenAutoFocus={(event) => {
- event.preventDefault();
- if (quotaPopoverOpenSourceRef.current !== 'focus') return;
- const dashboardButton = quotaPopoverDashboardButtonRef.current;
- dashboardButton?.focus({ preventScroll: true });
- quotaPopoverFocusTakenRef.current = document.activeElement === dashboardButton;
- }}
- onCloseAutoFocus={(event) => {
+ <Popover
+ open={quotaPopoverOpen}
+ onOpenChange={(open) => {
+ // 打开只由 hover / focus 驱动;Radix 的 outside / Escape 仍可请求关闭。
+ if (!open) closeQuotaPopoverImmediately();
+ }}
+ modal={false}
+ >
+ <PopoverTrigger asChild>
+ <button
+ ref={setQuotaPopoverFocusTarget}
+ type="button"
+ onClick={(event) => {
+ // 阻止 Radix 把 dashboard 点击解释成开关,chip 原动作保持不变。
event.preventDefault();
- restoreQuotaPopoverFocus();
+ if (isDashboardClickable) handleClick();
+ else openQuotaPopoverImmediately();
}}
- onEscapeKeyDown={closeQuotaPopoverImmediately}
- onMouseEnter={handleQuotaPopoverMouseEnter}
+ onMouseEnter={handleQuotaPopoverTriggerMouseEnter}
onMouseLeave={handleQuotaPopoverMouseLeave}
- onFocusCapture={() => {
+ onFocus={() => {
+ if (quotaPopoverRestoringFocusRef.current) return;
quotaPopoverFocusInsideRef.current = true;
- // 内容无论因键盘还是鼠标获得焦点,都算卡片已接管焦点;关闭时统一归还 trigger。
- quotaPopoverFocusTakenRef.current = true;
- keepQuotaPopoverOpen();
+ openQuotaPopoverImmediately();
}}
- onBlurCapture={(event) => {
- const nextTarget = event.relatedTarget;
- if (nextTarget instanceof Node && event.currentTarget.contains(nextTarget)) return;
- if (quotaPopoverRestoringFocusRef.current) return;
- // Tab 已将焦点交给卡片外的控件;自然离开只关闭卡片,
- // 不让延时器或 close-autofocus 再把焦点抢回 trigger。
+ onBlur={() => {
quotaPopoverFocusInsideRef.current = false;
- quotaPopoverFocusTakenRef.current = false;
- quotaPopoverOpenSourceRef.current = null;
scheduleQuotaPopoverClose();
}}
- className="w-[340px] border-0 bg-transparent p-0 shadow-none"
+ onKeyDown={(event) => {
+ if (event.key !== 'Escape') return;
+ event.preventDefault();
+ closeQuotaPopoverImmediately();
+ }}
+ className={buttonClass}
+ aria-label={usageDashboardLabel ?? t('quotaCard.usageTitle')}
>
- <QuotaHoverCard
- snapshot={claudeSubscriptionUsage}
- sessionUsage={quotaCardSessionUsage}
- turnUsage={quotaCardTurnUsage}
- dashboardLabel={usageDashboardLabel}
- onOpenDashboard={handleClick}
- dashboardButtonRef={quotaPopoverDashboardButtonRef}
- />
- </PopoverContent>
- </Popover>
- ) : (
- <Tip text={tooltipNode}>
- {isDashboardClickable ? (
- <button
- ref={setQuotaPopoverFocusTarget}
- type="button"
- onClick={handleClick}
- className={buttonClass}
- aria-label={usageDashboardLabel ?? undefined}
- >
- {labelNode}
- </button>
- ) : (
- // 网关 / 托管账号暂无看板可跳(见 usageDashboardUrl):渲染为非交互文本,
- // 点击无反应、不显示手型 / hover 态;用量指标与 tooltip 仍照常展示。
- <span
- ref={setQuotaPopoverFocusTarget}
- tabIndex={-1}
- className={cn(buttonClass, 'cursor-default')}
- >
- {labelNode}
- </span>
- )}
- </Tip>
- )}
+ {labelNode}
+ </button>
+ </PopoverTrigger>
+ <PopoverContent
+ ref={quotaPopoverContentRef}
+ side="top"
+ align="end"
+ sideOffset={8}
+ collisionPadding={8}
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ if (quotaPopoverOpenSourceRef.current !== 'focus') return;
+ const dashboardButton = quotaPopoverDashboardButtonRef.current;
+ const focusTarget =
+ dashboardButton ??
+ quotaPopoverContentRef.current?.querySelector<HTMLElement>('[role=region]');
+ focusTarget?.focus({ preventScroll: true });
+ quotaPopoverFocusTakenRef.current = Boolean(
+ focusTarget && document.activeElement === focusTarget,
+ );
+ }}
+ onCloseAutoFocus={(event) => {
+ event.preventDefault();
+ restoreQuotaPopoverFocus();
+ }}
+ onEscapeKeyDown={closeQuotaPopoverImmediately}
+ onMouseEnter={handleQuotaPopoverMouseEnter}
+ onMouseLeave={handleQuotaPopoverMouseLeave}
+ onFocusCapture={() => {
+ quotaPopoverFocusInsideRef.current = true;
+ // 内容无论因键盘还是鼠标获得焦点,都算卡片已接管焦点;关闭时统一归还 trigger。
+ quotaPopoverFocusTakenRef.current = true;
+ keepQuotaPopoverOpen();
+ }}
+ onBlurCapture={(event) => {
+ const nextTarget = event.relatedTarget;
+ if (nextTarget instanceof Node && event.currentTarget.contains(nextTarget)) return;
+ if (quotaPopoverRestoringFocusRef.current) return;
+ // Tab 已将焦点交给卡片外的控件;自然离开只关闭卡片,
+ // 不让延时器或 close-autofocus 再把焦点抢回 trigger。
+ quotaPopoverFocusInsideRef.current = false;
+ quotaPopoverFocusTakenRef.current = false;
+ quotaPopoverOpenSourceRef.current = null;
+ scheduleQuotaPopoverClose();
+ }}
+ className="w-[340px] max-w-[calc(100vw-16px)] border-0 bg-transparent p-0 shadow-none"
+ >
+ <QuotaHoverCard
+ account={account}
+ nowMs={windowLabelNowMs}
+ sessionUsage={quotaCardSessionUsage}
+ turnUsage={quotaCardTurnUsage}
+ dashboardLabel={usageDashboardLabel}
+ onOpenDashboard={handleClick}
+ dashboardButtonRef={quotaPopoverDashboardButtonRef}
+ />
+ </PopoverContent>
+ </Popover>
{confettiBurst && (
<QuotaResetConfetti
key={confettiBurst.nonce}
diff --git a/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx b/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx
index b6c343d59e..16cd15a9ec 100644
--- a/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx
+++ b/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx
@@ -14,6 +14,8 @@ vi.mock('react-i18next', () => ({
if (key === 'quotaCard.modelWeeklyLabel') return `${options.model} 周限`;
if (key === 'quotaCard.windowsRegionLabel') return '配额窗口列表';
if (key === 'quotaCard.usedPercent') return `已用 ${options.percent}%`;
+ if (key === 'quotaCard.usageCritical') return '用量较高';
+ if (key === 'quotaCard.usageWarning') return '用量偏高';
if (key === 'quotaCard.limitRejected') return '已触发套餐限额,请求可能被拒绝';
if (key === 'quotaCard.limitWarning') return '接近套餐限额';
if (key === 'quotaCard.resetAt') return `${options.at} 重置`;
@@ -23,8 +25,11 @@ vi.mock('react-i18next', () => ({
if (key === 'quotaCard.tokenBreakdown') {
return `(输入 ${options.input} · 输出 ${options.output})`;
}
+ if (key === 'quotaCard.speedLabel') return '速度';
+ if (key === 'quotaCard.rateValue') return `${options.rate} tokens/秒`;
if (key === 'quotaCard.timeLabel') return '耗时';
- if (key === 'quotaCard.timeAndRateValue') return `${options.duration} 速度:${options.rate} token/秒`;
+ if (key === 'quotaCard.timeAndRateValue')
+ return `${options.duration} 速度:${options.rate} token/秒`;
if (key === 'todaySpend.sessionCostLabel') return `本任务 ${options.cost}`;
if (key === 'todaySpend.tooltip.sessionUsed') return `本任务已用 ${options.cost}`;
if (key === 'todaySpend.codex.sessionValueLabel') return `本任务价值 ${options.cost}`;
@@ -34,7 +39,7 @@ vi.mock('react-i18next', () => ({
if (key === 'usageDetails.costBreakdownHeader') return '按模型拆分:';
if (key === 'usageDetails.modelCostLine') return `· ${options.model} ${options.cost}`;
if (key === 'quotaCard.turnCostUnavailable') return '本轮费用暂无法估算';
- if (key === 'quotaCard.latestMessageTitle') return '最近一轮用户请求累计';
+ if (key === 'quotaCard.latestMessageTitle') return '最近一轮';
if (key === 'chat.messageActionBar.userTurnCostDetailsTitle') return '本轮明细';
if (key === 'quotaCard.staleData') return `quotaCard.staleData:${options.minutes}`;
return key;
@@ -42,7 +47,18 @@ vi.mock('react-i18next', () => ({
}),
}));
-import { QuotaHoverCard } from '../QuotaHoverCard';
+import { useTranslation } from 'react-i18next';
+import { QuotaHoverCard as UsageCard, type QuotaHoverCardProps } from '../QuotaHoverCard';
+import { buildClaudeUsageCard } from '../usageCardModel';
+
+// Exercise the Claude adapter and the shared card together, retaining all existing edge cases.
+function QuotaHoverCard({
+ snapshot,
+ ...props
+}: Omit<QuotaHoverCardProps, 'account'> & { snapshot: ClaudeSubscriptionUsageSnapshot | null }) {
+ const { t } = useTranslation();
+ return <UsageCard {...props} account={buildClaudeUsageCard(snapshot, t)} />;
+}
const NOW_MS = new Date(2026, 7, 1, 10, 0, 0).getTime();
const WEEKLY_WINDOW_MS = 7 * 24 * 60 * 60_000;
@@ -69,7 +85,7 @@ function weeklyAtProgress(utilization: number, progress: number) {
}
describe('QuotaHoverCard', () => {
- it('renders only the waiting branch when snapshot is null', () => {
+ it('keeps the provider header while waiting for quota data', () => {
render(<QuotaHoverCard snapshot={null} nowMs={NOW_MS} />);
const card = screen.getByTestId('quota-hover-card');
@@ -80,7 +96,7 @@ describe('QuotaHoverCard', () => {
expect(card.classList.contains('text-[var(--text-primary)]')).toBe(true);
expect(card.style.boxShadow).toBe('var(--shadow-menu)');
expect(screen.getByText('quotaCard.waiting')).toBeTruthy();
- expect(screen.queryByText('Claude')).toBeNull();
+ expect(screen.getByText('Claude')).toBeTruthy();
expect(screen.queryAllByRole('progressbar')).toHaveLength(0);
});
@@ -117,7 +133,7 @@ describe('QuotaHoverCard', () => {
expect(screen.getByRole('progressbar', { name: '5 小时' })).toBeTruthy();
expect(screen.getByRole('progressbar', { name: '周限' })).toBeTruthy();
expect(screen.getByRole('progressbar', { name: 'Fable 周限' })).toBeTruthy();
- expect(screen.getByRole('progressbar', { name: /Opus 周限.*接近套餐限额/ })).toBeTruthy();
+ expect(screen.getByRole('progressbar', { name: /Opus 周限.*用量偏高/ })).toBeTruthy();
expect(screen.getByText('5 小时')).toBeTruthy();
expect(screen.getByText('周限')).toBeTruthy();
expect(screen.getByText('Fable 周限')).toBeTruthy();
@@ -355,7 +371,7 @@ describe('QuotaHoverCard', () => {
expect(screen.getByText('本任务价值 $0.50')).toBeTruthy();
});
- it('订阅卡用固定耗时标题和右对齐组合值,缺速度时结构保持不变', () => {
+ it('耗时与速度使用独立明细行,缺失时分别隐藏', () => {
const { rerender } = render(
<QuotaHoverCard
snapshot={makeSnapshot()}
@@ -366,10 +382,9 @@ describe('QuotaHoverCard', () => {
const performance = screen.getByTestId('quota-performance');
expect(within(performance).getByText('耗时')).toBeTruthy();
- const combinedValue = within(performance).getByTestId('quota-performance-value');
- expect(combinedValue.textContent).toBe('12.3s 速度:40 token/秒');
- expect(combinedValue.classList.contains('ml-auto')).toBe(true);
- expect(combinedValue.classList.contains('text-right')).toBe(true);
+ expect(within(performance).getByText('12.3s')).toBeTruthy();
+ expect(within(performance).getByText('速度')).toBeTruthy();
+ expect(within(performance).getByText('40 tokens/秒')).toBeTruthy();
rerender(
<QuotaHoverCard
@@ -380,9 +395,8 @@ describe('QuotaHoverCard', () => {
);
const timeOnlyPerformance = screen.getByTestId('quota-performance');
expect(within(timeOnlyPerformance).getByText('耗时')).toBeTruthy();
- const timeOnlyValue = within(timeOnlyPerformance).getByTestId('quota-performance-value');
- expect(timeOnlyValue.textContent).toBe('12.3s');
- expect(timeOnlyValue.classList.contains('ml-auto')).toBe(true);
+ expect(within(timeOnlyPerformance).getByText('12.3s')).toBeTruthy();
+ expect(within(timeOnlyPerformance).queryByText('速度')).toBeNull();
rerender(
<QuotaHoverCard
@@ -391,7 +405,8 @@ describe('QuotaHoverCard', () => {
turnUsage={{ outputRateText: '40', turnDurationText: null }}
/>,
);
- expect(screen.queryByTestId('quota-performance')).toBeNull();
+ expect(within(screen.getByTestId('quota-performance')).getByText('40 tokens/秒')).toBeTruthy();
+ expect(within(screen.getByTestId('quota-performance')).queryByText('耗时')).toBeNull();
rerender(
<QuotaHoverCard
@@ -431,7 +446,7 @@ describe('QuotaHoverCard', () => {
/>,
);
- expect(screen.getByText('最近一轮用户请求累计')).toBeTruthy();
+ expect(screen.getByText('最近一轮')).toBeTruthy();
expect(screen.getByText('本轮消耗:$0.70')).toBeTruthy();
expect(screen.queryByText('本轮明细')).toBeNull();
});
@@ -531,7 +546,11 @@ describe('QuotaHoverCard', () => {
const card = screen.getByTestId('quota-hover-card');
const scrollContent = screen.getByTestId('quota-hover-card-scroll-content');
const dashboardButton = screen.getByRole('button', { name: '打开 Claude 用量页面' });
- expect(card.classList.contains('max-h-[calc(100vh-16px)]')).toBe(true);
+ expect(
+ card.classList.contains(
+ 'max-h-[min(calc(100vh-16px),var(--radix-popover-content-available-height,100vh))]',
+ ),
+ ).toBe(true);
expect(scrollContent.classList.contains('min-h-0')).toBe(true);
expect(scrollContent.classList.contains('overflow-y-auto')).toBe(true);
expect(scrollContent.contains(dashboardButton)).toBe(false);
@@ -651,11 +670,11 @@ describe('QuotaHoverCard', () => {
/>,
);
- const criticalHint = screen.getByText(/已触发套餐限额,请求可能被拒绝/);
+ const criticalHint = screen.getByText(/用量较高/);
expect(criticalHint.classList.contains('sr-only')).toBe(true);
expect(
screen.getByRole('progressbar', {
- name: /5 小时.*已触发套餐限额,请求可能被拒绝/,
+ name: /5 小时.*用量较高/,
}),
).toBeTruthy();
@@ -666,9 +685,9 @@ describe('QuotaHoverCard', () => {
/>,
);
- const warningHint = screen.getByText(/接近套餐限额/);
+ const warningHint = screen.getByText(/用量偏高/);
expect(warningHint.classList.contains('sr-only')).toBe(true);
- expect(screen.getByRole('progressbar', { name: /5 小时.*接近套餐限额/ })).toBeTruthy();
+ expect(screen.getByRole('progressbar', { name: /5 小时.*用量偏高/ })).toBeTruthy();
});
it('marks a critical window title with the critical styling hook', () => {
@@ -717,7 +736,10 @@ describe('QuotaHoverCard', () => {
])('renders the $label weekly pace trend', ({ utilization, expected }) => {
render(
<QuotaHoverCard
- snapshot={makeSnapshot({ updatedAt: NOW_MS, sevenDay: weeklyAtProgress(utilization, 0.25) })}
+ snapshot={makeSnapshot({
+ updatedAt: NOW_MS,
+ sevenDay: weeklyAtProgress(utilization, 0.25),
+ })}
nowMs={NOW_MS}
/>,
);
@@ -760,9 +782,7 @@ describe('QuotaHoverCard', () => {
const { rerender } = render(<QuotaHoverCard snapshot={snapshot} nowMs={NOW_MS} />);
const originalText = screen.getByTestId('quota-pace').textContent;
- rerender(
- <QuotaHoverCard snapshot={snapshot} nowMs={NOW_MS + 30 * 60_000} />,
- );
+ rerender(<QuotaHoverCard snapshot={snapshot} nowMs={NOW_MS + 30 * 60_000} />);
expect(originalText).toBe('按当前平均速度偏快(粗略趋势)');
expect(screen.getByTestId('quota-pace').textContent).toBe(originalText);
@@ -791,10 +811,12 @@ describe('QuotaHoverCard', () => {
render(
<QuotaHoverCard
snapshot={makeSnapshot({
- scoped: [{
- modelDisplayName: 'Opus',
- ...weeklyAtProgress(93, 0.25),
- }],
+ scoped: [
+ {
+ modelDisplayName: 'Opus',
+ ...weeklyAtProgress(93, 0.25),
+ },
+ ],
})}
nowMs={NOW_MS}
/>,
diff --git a/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx b/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx
index 5b33f7c61b..c71934ba86 100644
--- a/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx
+++ b/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx
@@ -5,12 +5,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { ClaudeSubscriptionUsageSnapshot } from '../../../../shared/claudeSubscriptionUsage';
import type { RateLimitSnapshot } from '@/hooks/useAccountUsage';
+import type { XaiSubscriptionUsageSnapshot } from '../../../../shared/xaiSubscriptionUsage';
+import type { ClaudeAccountUsageSnapshot } from '@/hooks/useClaudeAccountUsage';
import type { RegionalMoney } from '../../../../shared/regionalMoney';
import type { SessionUsageMoney } from '@/hooks/useSessionUsageMoney';
const mocks = vi.hoisted(() => ({
claudeSnapshot: null as ClaudeSubscriptionUsageSnapshot | null,
codexSnapshot: null as RateLimitSnapshot | null,
+ xaiSnapshot: null as XaiSubscriptionUsageSnapshot | null,
+ gatewaySnapshot: null as ClaudeAccountUsageSnapshot | null,
+ sessionTokens: null as number | null,
codexAuthInjection: null as string | null,
displaySnapshot: {
messages: [] as Array<Record<string, unknown>>,
@@ -29,6 +34,11 @@ vi.mock('react-i18next', () => ({
i18n: { language: 'zh-CN', resolvedLanguage: 'zh-CN' },
t: (key: string, options: Record<string, string | number> = {}) => {
const templates: Record<string, string> = {
+ 'quotaCard.usageTitle': '用量明细',
+ 'todaySpend.openXaiUsage': '打开 Grok 用量页面',
+ 'todaySpend.codex.sessionTokensLine': '本任务 Token {{tokens}}',
+ 'quotaCard.speedLabel': '速度',
+ 'quotaCard.rateValue': '{{rate}} tokens/秒',
'todaySpend.openClaudeUsage': '打开 Claude 用量页面',
'todaySpend.openCodexUsage': '打开 Codex 用量页面',
'todaySpend.claude.weeklyLabel': '周限',
@@ -47,6 +57,7 @@ vi.mock('react-i18next', () => ({
'todaySpend.unit.second': '秒',
'quotaCard.fiveHourLabel': '5 小时',
'quotaCard.weeklyLabel': '周限',
+ 'quotaCard.includedLabel': '其中 {{name}}',
'quotaCard.modelWeeklyLabel': '{{model}} 周限',
'quotaCard.usedPercent': '已用 {{percent}}%',
'quotaCard.resetAt': '{{at}} 重置',
@@ -58,7 +69,7 @@ vi.mock('react-i18next', () => ({
'quotaCard.timeAndRateValue': '{{duration}} 速度:{{rate}} token/秒',
'quotaCard.modelLabel': '模型',
'quotaCard.waiting': '等待额度数据',
- 'quotaCard.latestMessageTitle': '最近一轮用户请求累计',
+ 'quotaCard.latestMessageTitle': '最近一轮',
'chat.messageActionBar.userTurnCostDetailsTitle': '本轮明细',
'quotaCard.costLine': '本轮消耗:{{cost}}',
'quotaCard.valueLine': '本轮 token 价值:{{cost}}',
@@ -91,12 +102,14 @@ vi.mock('@/hooks/useClaudeSessionRoute', () => ({
vi.mock('@/hooks/useSessionUsageMoney', () => ({
useSessionUsageMoney: () => mocks.sessionUsage,
}));
-vi.mock('@/hooks/useSessionTokens', () => ({ useSessionTokens: () => null }));
+vi.mock('@/hooks/useSessionTokens', () => ({ useSessionTokens: () => mocks.sessionTokens }));
vi.mock('@/hooks/useAccountUsage', () => ({
requestCodexAccountRefresh: vi.fn(),
- useAccountUsage: () => mocks.codexSnapshot,
+ useAccountUsage: (_: unknown, kind: unknown) => (kind ? mocks.codexSnapshot : null),
+}));
+vi.mock('@/hooks/useClaudeAccountUsage', () => ({
+ useClaudeAccountUsage: (enabled: boolean) => (enabled ? mocks.gatewaySnapshot : null),
}));
-vi.mock('@/hooks/useClaudeAccountUsage', () => ({ useClaudeAccountUsage: () => null }));
vi.mock('@/hooks/useModelAccessCreditUsage', () => ({ useModelAccessCreditUsage: () => null }));
vi.mock('@/hooks/useClaudeSubscriptionUsage', () => ({
requestClaudeSubscriptionRefresh: vi.fn(),
@@ -111,6 +124,10 @@ vi.mock('@/hooks/useCodexRateLimits', () => ({
refresh: mocks.refreshCodexRateLimits,
}),
}));
+vi.mock('@/hooks/useXaiSubscriptionUsage', () => ({
+ useXaiSubscriptionUsage: (enabled: boolean) => (enabled ? mocks.xaiSnapshot : null),
+ requestXaiSubscriptionRefresh: vi.fn(),
+}));
vi.mock('@/hooks/useXaiRateLimit', () => ({ useXaiRateLimit: () => null }));
vi.mock('../QuotaResetConfetti', () => ({
QuotaResetConfetti: () => <span data-testid="quota-reset-confetti" />,
@@ -196,6 +213,9 @@ beforeEach(() => {
sevenDay: { utilization: 34, resetsAt: Date.now() / 1000 + 86_400 },
};
mocks.codexSnapshot = null;
+ mocks.xaiSnapshot = null;
+ mocks.gatewaySnapshot = null;
+ mocks.sessionTokens = null;
mocks.codexAuthInjection = null;
Object.defineProperty(window, 'electronAPI', {
configurable: true,
@@ -216,7 +236,9 @@ describe('TodaySpendChip Claude subscription popover', () => {
(field) => {
mocks.codexAuthInjection = 'oauth-bearer';
mocks.codexSnapshot = {
- accountId: 'account-a', source: 'codex-app-server', limitId: 'codex',
+ accountId: 'account-a',
+ source: 'codex-app-server',
+ limitId: 'codex',
primary: { usedPercent: 40, windowMinutes: 300, resetsAt: Date.now() / 1000 - 1 },
};
const chip = <TodaySpendChip vendorKey="codex" providerId="openai" sessionId="codex" />;
@@ -227,27 +249,43 @@ describe('TodaySpendChip Claude subscription popover', () => {
primary: { usedPercent: 2, windowMinutes: 300, resetsAt: Date.now() / 1000 + 18_000 },
};
view.rerender(<TodaySpendChip vendorKey="codex" providerId="openai" sessionId="codex" />);
- expect(screen.getByRole('button', { name: '打开 Codex 用量页面' }).textContent).toContain('98%');
+ expect(screen.getByRole('button', { name: '打开 Codex 用量页面' }).textContent).toContain(
+ '98%',
+ );
expect(screen.queryByTestId('quota-reset-confetti')).toBeNull();
},
);
- it.each([false, true])('only celebrates a Claude reset for the same account (changed: %s)', (changed) => {
- mocks.claudeSnapshot = {
- accountFingerprint: 'account-a', source: 'unified-headers',
- fiveHour: { utilization: 40, resetsAt: Date.now() / 1000 - 1 },
- };
- const view = renderClaudeSubscriptionChip();
- mocks.claudeSnapshot = {
- accountFingerprint: changed ? 'account-b' : 'account-a', source: 'oauth-endpoint',
- fiveHour: { utilization: 2, resetsAt: Date.now() / 1000 + 18_000 },
- };
- view.rerender(<TodaySpendChip vendorKey="cc" providerId="anthropic" modelId="claude-opus-5[1m]" sessionId="session-1" />);
- expect(screen.queryByTestId('quota-reset-confetti') !== null).toBe(!changed);
- if (changed) {
- expect(screen.getByRole('button', { name: '打开 Claude 用量页面' }).textContent).toContain('98%');
- }
- });
+ it.each([false, true])(
+ 'only celebrates a Claude reset for the same account (changed: %s)',
+ (changed) => {
+ mocks.claudeSnapshot = {
+ accountFingerprint: 'account-a',
+ source: 'unified-headers',
+ fiveHour: { utilization: 40, resetsAt: Date.now() / 1000 - 1 },
+ };
+ const view = renderClaudeSubscriptionChip();
+ mocks.claudeSnapshot = {
+ accountFingerprint: changed ? 'account-b' : 'account-a',
+ source: 'oauth-endpoint',
+ fiveHour: { utilization: 2, resetsAt: Date.now() / 1000 + 18_000 },
+ };
+ view.rerender(
+ <TodaySpendChip
+ vendorKey="cc"
+ providerId="anthropic"
+ modelId="claude-opus-5[1m]"
+ sessionId="session-1"
+ />,
+ );
+ expect(screen.queryByTestId('quota-reset-confetti') !== null).toBe(!changed);
+ if (changed) {
+ expect(screen.getByRole('button', { name: '打开 Claude 用量页面' }).textContent).toContain(
+ '98%',
+ );
+ }
+ },
+ );
it('完整渲染 Claude 的 5h 与当前模型周窗口', () => {
mocks.claudeSnapshot = {
@@ -304,7 +342,9 @@ describe('TodaySpendChip Claude subscription popover', () => {
expect(screen.getByText('读 0 · 写 74.0k · 命中 0%')).toBeTruthy();
const performance = screen.getByTestId('quota-performance');
expect(within(performance).getByText('耗时')).toBeTruthy();
- expect(within(performance).getByText('12.3秒 速度:40 token/秒')).toBeTruthy();
+ expect(within(performance).getByText('12.3秒')).toBeTruthy();
+ expect(within(performance).getByText('速度')).toBeTruthy();
+ expect(within(performance).getByText('40 tokens/秒')).toBeTruthy();
expect(screen.getByText('claude-opus-5[1m]')).toBeTruthy();
expect(screen.getByText('缓存命中率偏低,本轮较多上下文重新计费')).toBeTruthy();
expect(document.activeElement).toBe(document.body);
@@ -423,7 +463,7 @@ describe('TodaySpendChip Claude subscription popover', () => {
);
expect(screen.queryByTestId('quota-hover-card')).toBeNull();
- const gatewayChip = document.querySelector<HTMLElement>('[tabindex="-1"]');
+ const gatewayChip = screen.getByRole('button', { name: '用量明细' });
expect(gatewayChip).toBeTruthy();
expect(document.activeElement).toBe(gatewayChip);
@@ -547,7 +587,7 @@ describe('TodaySpendChip Claude subscription popover', () => {
it('把混合会话合计及实际费用和价值估算拆分传入卡片', () => {
mocks.sessionUsage = {
actualMoney: usdMoney(0.25),
- estimatedValueMoney: usdMoney(0.50, 'value-estimate'),
+ estimatedValueMoney: usdMoney(0.5, 'value-estimate'),
totalMoney: {
...usdMoney(0.75),
approximate: true,
@@ -586,7 +626,7 @@ describe('TodaySpendChip Claude subscription popover', () => {
});
it('纯订阅价值估算仍标为本任务价值', () => {
- const estimatedValueMoney = usdMoney(0.50, 'value-estimate');
+ const estimatedValueMoney = usdMoney(0.5, 'value-estimate');
mocks.sessionUsage = {
actualMoney: null,
estimatedValueMoney,
@@ -610,21 +650,21 @@ describe('TodaySpendChip Claude subscription popover', () => {
});
const equalAmount = renderClaudeSubscriptionChip();
openCardFromHover();
- expect(screen.getByText('最近一轮用户请求累计')).toBeTruthy();
+ expect(screen.getByText('最近一轮')).toBeTruthy();
expect(screen.queryByText('最后一个 SDK 分段')).toBeNull();
expect(screen.getAllByText('本轮 token 价值:$0.46')).toHaveLength(1);
equalAmount.unmount();
vi.clearAllTimers();
setLatestUsageMessage({
- turnMoney: usdMoney(0.20),
- userTurnMoney: usdMoney(0.70),
+ turnMoney: usdMoney(0.2),
+ userTurnMoney: usdMoney(0.7),
turnCostIsEstimate: false,
userTurnCostIsEstimate: false,
});
renderClaudeSubscriptionChip();
openCardFromHover();
- expect(screen.getByText('最近一轮用户请求累计')).toBeTruthy();
+ expect(screen.getByText('最近一轮')).toBeTruthy();
expect(screen.getByText('本轮消耗:$0.70')).toBeTruthy();
expect(screen.queryByText('最后一个 SDK 分段')).toBeNull();
expect(screen.getByText(/^74\.0k/)).toBeTruthy();
@@ -683,7 +723,7 @@ describe('TodaySpendChip Claude subscription popover', () => {
renderClaudeSubscriptionChip();
openCardFromHover();
- expect(screen.getByText('最近一轮用户请求累计')).toBeTruthy();
+ expect(screen.getByText('最近一轮')).toBeTruthy();
expect(screen.getByText('本轮消耗:$0.70')).toBeTruthy();
expect(screen.getByText(/^197/)).toBeTruthy();
expect(screen.getByText('按模型拆分:')).toBeTruthy();
@@ -723,19 +763,124 @@ describe('TodaySpendChip Claude subscription popover', () => {
expect(screen.queryByText('claude-opus-5[1m]')).toBeNull();
});
- it('非 Claude 订阅形态继续使用旧 Tip,不挂载额度卡片', () => {
+ it.each([
+ ['codex', 'openai', 'gpt-5.6-sol', '打开 Codex 用量页面'],
+ ['cc', 'openai', 'chatgpt/gpt-5.6-sol', '打开 Codex 用量页面'],
+ ['pi', 'xai', 'grok-4.6', '打开 Grok 用量页面'],
+ ['cc', 'xd', 'claude-opus-5', '用量明细'],
+ ['codex', 'custom', 'custom-model', '用量明细'],
+ ] as const)('共用卡片和本轮明细:%s / %s', (vendorKey, providerId, modelId, label) => {
+ mocks.codexAuthInjection = 'oauth-bearer';
render(
<TodaySpendChip
- vendorKey="cc"
- providerId="xd"
+ vendorKey={vendorKey}
+ providerId={providerId}
+ modelId={modelId}
sessionId="session-1"
/>,
);
+ const trigger = screen.getByRole('button', { name: label });
+ fireEvent.mouseEnter(trigger);
+ act(() => vi.advanceTimersByTime(300));
+ const card = screen.getByTestId('quota-hover-card');
+ expect(within(card).getByText('本轮消耗:$0.46')).toBeTruthy();
+ expect(screen.queryByRole('tooltip')).toBeNull();
+ fireEvent.mouseLeave(trigger);
+ fireEvent.mouseEnter(card);
+ act(() => vi.advanceTimersByTime(250));
+ expect(screen.getByTestId('quota-hover-card')).toBeTruthy();
+ });
- const legacyChip = document.querySelector('.inline-flex.h-5.shrink-0.items-center');
- expect(legacyChip).toBeTruthy();
- fireEvent.mouseEnter(legacyChip as HTMLElement);
- act(() => vi.advanceTimersByTime(1_000));
+ it('ChatGPT 动态窗口和套餐渲染为与 Claude 相同的进度条', () => {
+ mocks.codexAuthInjection = 'oauth-bearer';
+ mocks.codexSnapshot = {
+ planType: 'plus',
+ primary: { usedPercent: 22, windowMinutes: 120 },
+ secondary: { usedPercent: 48, windowMinutes: 10080 },
+ };
+ render(<TodaySpendChip vendorKey="codex" providerId="openai" sessionId="session-1" />);
+ act(() => screen.getByRole('button', { name: '打开 Codex 用量页面' }).focus());
+ const card = screen.getByTestId('quota-hover-card');
+ expect(within(card).getByText('ChatGPT')).toBeTruthy();
+ expect(within(card).getByText('Plus')).toBeTruthy();
+ expect(within(card).getByText('2h')).toBeTruthy();
+ expect(
+ within(card)
+ .getAllByRole('progressbar')
+ .map((bar) => bar.getAttribute('aria-valuenow')),
+ ).toEqual(['22', '48']);
+ });
+
+ it('Grok 产品用量属于周限明细,不重复进度条或重置时间,过期后移除旧百分比', () => {
+ mocks.xaiSnapshot = {
+ planLabel: 'SuperGrok Heavy',
+ creditUsagePercent: 8,
+ updatedAt: Date.now(),
+ resetsAt: Date.now() / 1000 + 100,
+ productUsage: [{ product: 'GrokBuild', usagePercent: 8 }],
+ };
+ const view = render(
+ <TodaySpendChip vendorKey="pi" providerId="xai" modelId="grok-4.6" sessionId="session-1" />,
+ );
+ act(() => screen.getByRole('button', { name: '打开 Grok 用量页面' }).focus());
+ expect(screen.getAllByRole('progressbar')).toHaveLength(1);
+ const breakdown = screen.getByTestId('quota-window-breakdown');
+ expect(within(breakdown).getByText('其中 Grok Build')).toBeTruthy();
+ expect(within(breakdown).getByText('8%')).toBeTruthy();
+ expect(screen.getAllByText(/重置$/)).toHaveLength(1);
+ mocks.xaiSnapshot = { ...mocks.xaiSnapshot, updatedAt: Date.now() - 31 * 60_000 };
+ view.rerender(
+ <TodaySpendChip vendorKey="pi" providerId="xai" modelId="grok-4.6" sessionId="session-1" />,
+ );
+ expect(screen.queryAllByRole('progressbar')).toHaveLength(0);
+ expect(screen.getByText('SuperGrok Heavy')).toBeTruthy();
+ });
+
+ it('没有看板按钮时键盘进入滚动区并在 Escape 后归还焦点', () => {
+ render(<TodaySpendChip vendorKey="cc" providerId="xd" sessionId="session-1" />);
+ const trigger = screen.getByRole('button', { name: '用量明细' });
+ act(() => trigger.focus());
+ const card = screen.getByTestId('quota-hover-card');
+ expect(document.activeElement).toBe(within(card).getByRole('region'));
+ expect(within(card).queryByRole('button')).toBeNull();
+ fireEvent.keyDown(document, { key: 'Escape' });
expect(screen.queryByTestId('quota-hover-card')).toBeNull();
+ expect(document.activeElement).toBe(trigger);
+ expect(mocks.openExternal).not.toHaveBeenCalled();
+ });
+
+ it('远程任务只显示任务用量,不混入本机配额', () => {
+ mocks.codexAuthInjection = 'oauth-bearer';
+ mocks.codexSnapshot = { primary: { usedPercent: 99 } };
+ mocks.sessionTokens = 123_000;
+ render(
+ <TodaySpendChip
+ vendorKey="codex"
+ providerId="openai"
+ sessionId="session-1"
+ deviceLinkDeviceId="remote"
+ />,
+ );
+ act(() => screen.getByRole('button', { name: '用量明细' }).focus());
+ const card = screen.getByTestId('quota-hover-card');
+ expect(within(card).queryByRole('progressbar')).toBeNull();
+ expect(within(card).queryByRole('button')).toBeNull();
+ expect(within(card).getByText('本任务 Token 123.0k')).toBeTruthy();
+ expect(within(card).getByText('本轮消耗:$0.46')).toBeTruthy();
+ });
+
+ it('网关月预算与日软限额共用进度条,保留原生币种', () => {
+ mocks.gatewaySnapshot = {
+ spend: 40,
+ maxBudget: 100,
+ currency: 'CNY',
+ todaySpend: 3,
+ fetchedAt: Date.now(),
+ };
+ render(<TodaySpendChip vendorKey="cc" providerId="xd" sessionId="session-1" />);
+ act(() => screen.getByRole('button', { name: '用量明细' }).focus());
+ expect(
+ screen.getAllByRole('progressbar').map((bar) => bar.getAttribute('aria-valuenow')),
+ ).toEqual(['20', '40']);
});
});
diff --git a/apps/desktop/src/renderer/components/status/usageCardModel.ts b/apps/desktop/src/renderer/components/status/usageCardModel.ts
new file mode 100644
index 0000000000..9abc8c94a3
--- /dev/null
+++ b/apps/desktop/src/renderer/components/status/usageCardModel.ts
@@ -0,0 +1,275 @@
+/** 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';
+
+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),
+ 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),
+ 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 --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index ae13ecd8bd..7889d477f7 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -5677,9 +5677,9 @@
"openProxyUsage": "Open the full usage dashboard in your browser",
"openXaiUsage": "Open Grok usage page",
"xai": {
- "requestsLine": "Rate limit (requests): {{remaining}}/{{limit}} left",
- "tokensLine": "Rate limit (tokens): {{remaining}}/{{limit}} left",
- "noQuotaDetail": "SuperGrok weekly usage is unavailable; only the estimated value is shown",
+ "requestsLine": "Last response · requests left: {{remaining}}/{{limit}}",
+ "tokensLine": "Last response · tokens left: {{remaining}}/{{limit}}",
+ "noQuotaDetail": "SuperGrok weekly usage is currently unavailable",
"weeklyLabel": "Weekly",
"windowSegment": "{{label}} {{remaining}} left",
"windowLine": "{{label}} {{remaining}} left ({{used}} used)",
@@ -5687,7 +5687,7 @@
"resetAt": "Resets {{at}}",
"productLine": "{{product}} {{percent}}",
"extraCreditsLine": "Extra credits {{amount}}",
- "accountWeeklyHint": "Account weekly usage, not this session's quota"
+ "accountWeeklyHint": "Account weekly usage"
},
"dailyLimitLabel": "Today {{spend}}/{{limit}}",
"monthlyLimitLabel": "Cycle {{spend}}/{{limit}}",
@@ -5748,10 +5748,20 @@
}
},
"quotaCard": {
+ "usageCritical": "High usage",
+ "usageWarning": "Elevated usage",
+ "usageTitle": "Usage details",
+ "gatewayTitle": "Cindy AI Gateway",
+ "balanceLabel": "Balance usage",
+ "dailyLabel": "Daily soft limit",
+ "monthlyLabel": "Monthly quota",
+ "speedLabel": "Speed",
+ "rateValue": "{{rate}} tokens/s",
+ "waiting": "Waiting for quota data.",
+ "windowsRegionLabel": "Usage details",
"fiveHourLabel": "5 hours",
"weeklyLabel": "Weekly",
"modelWeeklyLabel": "{{model}} weekly",
- "windowsRegionLabel": "Quota Windows",
"usedPercent": "Used {{percent}}%",
"resetAt": "Resets {{at}}",
"noWindows": "No quota window data available",
@@ -5761,7 +5771,7 @@
"costLine": "Cost this message: {{cost}}",
"valueLine": "Token value this message: {{cost}}",
"noBilledCost": "Cost unavailable for this message; showing usage only",
- "latestMessageTitle": "Latest message total",
+ "latestMessageTitle": "Latest message",
"turnCostUnavailable": "Cost unavailable for this message",
"tokenLabel": "Tokens",
"tokenBreakdown": "(input {{input}} · output {{output}})",
@@ -5773,7 +5783,7 @@
"paceTrendFast": "Trending fast at the current average pace (rough estimate)",
"paceTrendNormal": "Trending normally at the current average pace (rough estimate)",
"paceTrendSlow": "Trending slowly at the current average pace (rough estimate)",
- "waiting": "Claude subscription usage will update after the next request completes."
+ "includedLabel": "Including {{name}}"
},
"usageDetails": {
"durationSeconds": "{{value}}s",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 85b2d4238b..d9347d3aed 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -5675,9 +5675,9 @@
"openProxyUsage": "ブラウザで完全な使用量ダッシュボードを開く",
"openXaiUsage": "Grok の使用量ページを開く",
"xai": {
- "requestsLine": "レート制限(リクエスト): 残り {{remaining}}/{{limit}}",
- "tokensLine": "レート制限(トークン): 残り {{remaining}}/{{limit}}",
- "noQuotaDetail": "SuperGrok の週間使用量を取得できないため、価値の推定のみ表示します",
+ "requestsLine": "前回の応答時 · リクエストの残り: {{remaining}}/{{limit}}",
+ "tokensLine": "前回の応答時 · トークンの残り: {{remaining}}/{{limit}}",
+ "noQuotaDetail": "SuperGrok の週間使用量は現在取得できません",
"weeklyLabel": "週間",
"windowSegment": "{{label}} 残り {{remaining}}",
"windowLine": "{{label}} 残り {{remaining}}(使用 {{used}})",
@@ -5685,7 +5685,7 @@
"resetAt": "{{at}} にリセット",
"productLine": "{{product}} {{percent}}",
"extraCreditsLine": "追加クレジット {{amount}}",
- "accountWeeklyHint": "アカウントの週間使用量であり、このセッションのクォータではありません"
+ "accountWeeklyHint": "アカウントの週間使用量"
},
"dailyLimitLabel": "本日 {{spend}}/{{limit}}",
"monthlyLimitLabel": "周期 {{spend}}/{{limit}}",
@@ -5746,10 +5746,20 @@
}
},
"quotaCard": {
+ "usageCritical": "使用量が高い状態です",
+ "usageWarning": "使用量がやや高い状態です",
+ "usageTitle": "使用量の詳細",
+ "gatewayTitle": "Cindy AI Gateway",
+ "balanceLabel": "残高の使用量",
+ "dailyLabel": "1日のソフト上限",
+ "monthlyLabel": "月間クォータ",
+ "speedLabel": "速度",
+ "rateValue": "{{rate}} トークン/秒",
+ "waiting": "クォータデータの更新を待っています。",
+ "windowsRegionLabel": "使用量の詳細",
"fiveHourLabel": "5 時間",
"weeklyLabel": "週間",
"modelWeeklyLabel": "{{model}} 週間",
- "windowsRegionLabel": "クォータ期間の一覧",
"usedPercent": "使用済み {{percent}}%",
"resetAt": "{{at}} にリセット",
"noWindows": "クォータ期間のデータはありません",
@@ -5759,7 +5769,7 @@
"costLine": "このメッセージの消費: {{cost}}",
"valueLine": "このメッセージの token 価値: {{cost}}",
"noBilledCost": "このメッセージの料金は現在取得できないため、使用量のみ表示しています",
- "latestMessageTitle": "直近のメッセージ合計",
+ "latestMessageTitle": "直近のメッセージ",
"turnCostUnavailable": "このメッセージの料金は現在見積もれません",
"tokenLabel": "Token",
"tokenBreakdown": "(入力 {{input}} · 出力 {{output}})",
@@ -5771,7 +5781,7 @@
"paceTrendFast": "現在の平均使用ペースは速めです(おおよその傾向)",
"paceTrendNormal": "現在の平均使用ペースは通常です(おおよその傾向)",
"paceTrendSlow": "現在の平均使用ペースは遅めです(おおよその傾向)",
- "waiting": "Claude サブスクリプションの使用量は次のリクエスト完了後に更新されます。"
+ "includedLabel": "うち {{name}}"
},
"usageDetails": {
"durationSeconds": "{{value}}秒",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 5e2675bd85..b5aa2826e4 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -5675,9 +5675,9 @@
"openProxyUsage": "브라우저에서 전체 사용량 대시보드 열기",
"openXaiUsage": "Grok 사용량 페이지 열기",
"xai": {
- "requestsLine": "속도 제한(요청): 남음 {{remaining}}/{{limit}}",
- "tokensLine": "속도 제한(토큰): 남음 {{remaining}}/{{limit}}",
- "noQuotaDetail": "SuperGrok 주간 사용량을 가져오지 못해 가치 추정치만 표시됩니다",
+ "requestsLine": "마지막 응답 시 요청 잔여량: {{remaining}}/{{limit}}",
+ "tokensLine": "마지막 응답 시 토큰 잔여량: {{remaining}}/{{limit}}",
+ "noQuotaDetail": "현재 SuperGrok 주간 사용량을 가져올 수 없습니다",
"weeklyLabel": "주간",
"windowSegment": "{{label}} 남음 {{remaining}}",
"windowLine": "{{label}} 남음 {{remaining}}(사용 {{used}})",
@@ -5685,7 +5685,7 @@
"resetAt": "{{at}} 초기화",
"productLine": "{{product}} {{percent}}",
"extraCreditsLine": "추가 크레딧 {{amount}}",
- "accountWeeklyHint": "계정 주간 사용량이며 이 작업의 할당량이 아닙니다"
+ "accountWeeklyHint": "계정 주간 사용량"
},
"dailyLimitLabel": "오늘 {{spend}}/{{limit}}",
"monthlyLimitLabel": "주기 {{spend}}/{{limit}}",
@@ -5746,10 +5746,20 @@
}
},
"quotaCard": {
+ "usageCritical": "사용량이 높습니다",
+ "usageWarning": "사용량이 다소 높습니다",
+ "usageTitle": "사용량 상세",
+ "gatewayTitle": "Cindy AI Gateway",
+ "balanceLabel": "잔액 사용량",
+ "dailyLabel": "일일 소프트 한도",
+ "monthlyLabel": "월간 할당량",
+ "speedLabel": "속도",
+ "rateValue": "{{rate}} 토큰/초",
+ "waiting": "할당량 데이터 업데이트를 기다리는 중입니다.",
+ "windowsRegionLabel": "사용량 상세",
"fiveHourLabel": "5시간",
"weeklyLabel": "주간",
"modelWeeklyLabel": "{{model}} 주간",
- "windowsRegionLabel": "할당량 구간 목록",
"usedPercent": "사용 {{percent}}%",
"resetAt": "{{at}} 재설정",
"noWindows": "할당량 구간 데이터가 없습니다",
@@ -5759,7 +5769,7 @@
"costLine": "이번 메시지 비용: {{cost}}",
"valueLine": "이번 메시지 토큰 가치: {{cost}}",
"noBilledCost": "이번 메시지의 비용을 현재 확인할 수 없어 사용량만 표시합니다",
- "latestMessageTitle": "최근 메시지 합계",
+ "latestMessageTitle": "최근 메시지",
"turnCostUnavailable": "이 메시지의 비용을 현재 추정할 수 없습니다",
"tokenLabel": "Token",
"tokenBreakdown": "(입력 {{input}} · 출력 {{output}})",
@@ -5771,7 +5781,7 @@
"paceTrendFast": "현재 평균 사용 속도는 빠른 편입니다(대략적인 추세)",
"paceTrendNormal": "현재 평균 사용 속도는 보통입니다(대략적인 추세)",
"paceTrendSlow": "현재 평균 사용 속도는 느린 편입니다(대략적인 추세)",
- "waiting": "Claude 구독 사용량은 다음 요청이 완료된 후 업데이트됩니다."
+ "includedLabel": "그중 {{name}}"
},
"usageDetails": {
"durationSeconds": "{{value}}초",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index dd251ae7f6..3c30f1bf4c 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -5675,9 +5675,9 @@
"openProxyUsage": "打开浏览器查看完整用量看板",
"openXaiUsage": "打开 Grok 用量页面",
"xai": {
- "requestsLine": "限流(请求):剩余 {{remaining}}/{{limit}}",
- "tokensLine": "限流(token):剩余 {{remaining}}/{{limit}}",
- "noQuotaDetail": "暂未获取到 SuperGrok 周用量,此处仅显示价值估算",
+ "requestsLine": "上次响应请求余量:{{remaining}}/{{limit}}",
+ "tokensLine": "上次响应 Token 余量:{{remaining}}/{{limit}}",
+ "noQuotaDetail": "暂未获取到 SuperGrok 周用量",
"weeklyLabel": "周限",
"windowSegment": "{{label}} 剩余 {{remaining}}",
"windowLine": "{{label}} 剩余 {{remaining}}(已用 {{used}})",
@@ -5685,7 +5685,7 @@
"resetAt": "{{at}} 重置",
"productLine": "{{product}} {{percent}}",
"extraCreditsLine": "额外点数 {{amount}}",
- "accountWeeklyHint": "账号周用量,不是本任务配额"
+ "accountWeeklyHint": "账号周用量"
},
"dailyLimitLabel": "今日 {{spend}}/{{limit}}",
"monthlyLimitLabel": "本周期 {{spend}}/{{limit}}",
@@ -5746,10 +5746,20 @@
}
},
"quotaCard": {
+ "usageCritical": "用量较高",
+ "usageWarning": "用量偏高",
+ "usageTitle": "用量明细",
+ "gatewayTitle": "Cindy AI Gateway",
+ "balanceLabel": "余额用量",
+ "dailyLabel": "每日软限额",
+ "monthlyLabel": "月度配额",
+ "speedLabel": "速度",
+ "rateValue": "{{rate}} tokens/秒",
+ "waiting": "等待配额数据更新。",
+ "windowsRegionLabel": "用量明细",
"fiveHourLabel": "5 小时",
"weeklyLabel": "周限",
"modelWeeklyLabel": "{{model}} 周限",
- "windowsRegionLabel": "配额窗口列表",
"usedPercent": "已用 {{percent}}%",
"resetAt": "{{at}} 重置",
"noWindows": "暂无配额窗口数据",
@@ -5759,7 +5769,7 @@
"costLine": "本轮消耗:{{cost}}",
"valueLine": "本轮 token 价值:{{cost}}",
"noBilledCost": "本轮费用暂不可用,仅显示用量",
- "latestMessageTitle": "最近一轮用户请求累计",
+ "latestMessageTitle": "最近一轮",
"turnCostUnavailable": "本轮费用暂无法估算",
"tokenLabel": "Token",
"tokenBreakdown": "(输入 {{input}} · 输出 {{output}})",
@@ -5771,7 +5781,7 @@
"paceTrendFast": "按当前平均速度偏快(粗略趋势)",
"paceTrendNormal": "按当前平均速度正常(粗略趋势)",
"paceTrendSlow": "按当前平均速度偏慢(粗略趋势)",
- "waiting": "Claude 订阅余量会在下一轮完成后更新。"
+ "includedLabel": "其中 {{name}}"
},
"usageDetails": {
"durationSeconds": "{{value}}秒",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 6f0f3c1e13..7c8e8110ba 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -5675,9 +5675,9 @@
"openProxyUsage": "開啟瀏覽器檢視完整用量看板",
"openXaiUsage": "開啟 Grok 用量頁面",
"xai": {
- "requestsLine": "限流(請求):剩餘 {{remaining}}/{{limit}}",
- "tokensLine": "限流(token):剩餘 {{remaining}}/{{limit}}",
- "noQuotaDetail": "暫未取得 SuperGrok 週用量,此處僅顯示價值估算",
+ "requestsLine": "上次回應請求餘量:{{remaining}}/{{limit}}",
+ "tokensLine": "上次回應 Token 餘量:{{remaining}}/{{limit}}",
+ "noQuotaDetail": "暫未取得 SuperGrok 週用量",
"weeklyLabel": "週限",
"windowSegment": "{{label}} 剩餘 {{remaining}}",
"windowLine": "{{label}} 剩餘 {{remaining}}(已用 {{used}})",
@@ -5685,7 +5685,7 @@
"resetAt": "{{at}} 重設",
"productLine": "{{product}} {{percent}}",
"extraCreditsLine": "額外點數 {{amount}}",
- "accountWeeklyHint": "帳號週用量,不是本任務配額"
+ "accountWeeklyHint": "帳號週用量"
},
"dailyLimitLabel": "今日 {{spend}}/{{limit}}",
"monthlyLimitLabel": "本週期 {{spend}}/{{limit}}",
@@ -5746,10 +5746,20 @@
}
},
"quotaCard": {
+ "usageCritical": "用量較高",
+ "usageWarning": "用量偏高",
+ "usageTitle": "用量明細",
+ "gatewayTitle": "Cindy AI Gateway",
+ "balanceLabel": "餘額用量",
+ "dailyLabel": "每日軟限額",
+ "monthlyLabel": "月度配額",
+ "speedLabel": "速度",
+ "rateValue": "{{rate}} tokens/秒",
+ "waiting": "等待配額資料更新。",
+ "windowsRegionLabel": "用量明細",
"fiveHourLabel": "5 小時",
"weeklyLabel": "週限",
"modelWeeklyLabel": "{{model}} 週限",
- "windowsRegionLabel": "配額視窗列表",
"usedPercent": "已用 {{percent}}%",
"resetAt": "{{at}} 重置",
"noWindows": "暫無配額視窗資料",
@@ -5759,7 +5769,7 @@
"costLine": "本輪消耗:{{cost}}",
"valueLine": "本輪 token 價值:{{cost}}",
"noBilledCost": "本輪費用暫不可用,僅顯示用量",
- "latestMessageTitle": "最近一輪使用者請求累計",
+ "latestMessageTitle": "最近一輪",
"turnCostUnavailable": "本輪費用暫無法估算",
"tokenLabel": "Token",
"tokenBreakdown": "(輸入 {{input}} · 輸出 {{output}})",
@@ -5771,7 +5781,7 @@
"paceTrendFast": "按目前平均速度偏快(粗略趨勢)",
"paceTrendNormal": "按目前平均速度正常(粗略趨勢)",
"paceTrendSlow": "按目前平均速度偏慢(粗略趨勢)",
- "waiting": "Claude 訂閱餘量會在下一輪完成後更新。"
+ "includedLabel": "其中 {{name}}"
},
"usageDetails": {
"durationSeconds": "{{value}}秒",