Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): Claude 订阅额度 hover 提示升级为结构化用量卡片 (#1300)
Mario69651271c6f0
diff --git a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.tsindex ff38ce1992..a732901f35 100644--- a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts+++ b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts@@ -10,10 +10,12 @@ import { readFileSync } from 'node:fs';import { resolve } from 'node:path';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', 'ja', 'ko'].map((locale) =>@@ -34,6 +36,8 @@ describe('TodaySpendChip dashboard routing', () => {expect(source).toContain('segmentCostUsd: message.turnCostUsd');expect(source).toContain('money: summary.isUserTurnTotal ? summary.segmentMoney : summary.money');expect(source).toContain("'chat.messageActionBar.userTurnCostDetailsTitle'");+ 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', () => {@@ -218,6 +222,7 @@ describe('TodaySpendChip dashboard routing', () => {});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(');@@ -225,30 +230,48 @@ describe('TodaySpendChip dashboard routing', () => {// bridge 模型形态优先(不消耗 Claude 订阅额度),订阅余量 hook 对 bridge 会话关闭;// device-link 远程会话同样不读本机订阅余量expect(source).toContain('isClaudeSubscription && !isSubscriptionBridge && !isDeviceLinkRemote');- expect(source).toContain('tooltipNode = buildClaudeSubscriptionTooltipNode(');+ 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');- expect(source).toContain('todaySpend.claude.windowLine');- expect(source).toContain('todaySpend.claude.resetAt');+ // 窗口详情 / 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(source).toContain('todaySpend.claude.planLine');+ 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,');- expect(source).toContain('hasAlertingClaudeSessionWindow,');+ // 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'");- // tooltip 比 chip 宽一档: allowed_warning 仍提示 (紧邻全量窗口列表, 有上下文)- expect(source).toContain(- "status === 'allowed_warning' || hasAlertingClaudeSessionWindow(snapshot, modelId)",- );+ // 卡片比 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 读取。@@ -272,7 +295,10 @@ describe('TodaySpendChip dashboard routing', () => {expect(source).toContain('(gatewayKeyReconciling || (!hasGatewayKey && claudeOAuthConnected == null))');// extra_usage credits 单位未验证,不得假设 cents 并渲染美元金额expect(source).not.toContain('formatExtraUsageCredits');- expect(source).toContain('不能假设 cents 并渲染美元金额');+ 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', () => {diff --git a/apps/desktop/src/renderer/components/status/QuotaBar.tsx b/apps/desktop/src/renderer/components/status/QuotaBar.tsxnew file mode 100644index 0000000000..faa8f7a418--- /dev/null+++ b/apps/desktop/src/renderer/components/status/QuotaBar.tsx@@ -0,0 +1,78 @@+/**+ * QuotaBar — 额度进度条,统一展示当前额度使用比例及预警等级。+ */++import React from 'react';++import { cn } from '@/lib/utils';++export type QuotaSeverity = 'normal' | 'warn' | 'crit';++export interface QuotaBarProps {+ usedPercent: number;+ size?: 'regular' | 'mini';+ /** 调用方已合并本地阈值与上游信号后的展示级别。 */+ severity?: QuotaSeverity;+ /** 进度条的可访问名称;也可由 aria-labelledby 指向可见标题。 */+ ariaLabel?: string;+ 'aria-labelledby'?: string;+ className?: string;+}++function clampPercent(usedPercent: number): number {+ if (!Number.isFinite(usedPercent)) return 0;+ return Math.min(100, Math.max(0, usedPercent));+}++/** 将上游用量统一归一化后判定额度预警等级。 */+export function quotaSeverity(usedPercent: number): QuotaSeverity {+ const clampedPercent = clampPercent(usedPercent);+ if (clampedPercent >= 90) return 'crit';+ if (clampedPercent > 70) return 'warn';+ return 'normal';+}++const FILL_COLOR_CLASSES: Record<QuotaSeverity, string> = {+ normal: 'bg-[var(--quota-bar-fill)]',+ warn: 'bg-[var(--quota-bar-warn)]',+ crit: 'bg-[var(--quota-bar-crit)]',+};++export function QuotaBar({+ usedPercent,+ size = 'regular',+ severity: severityOverride,+ ariaLabel,+ 'aria-labelledby': ariaLabelledBy,+ className,+}: QuotaBarProps) {+ const clampedPercent = clampPercent(usedPercent);+ const severity = severityOverride ?? quotaSeverity(clampedPercent);+ const isMini = size === 'mini';++ return (+ <div+ role="progressbar"+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={Math.round(clampedPercent)}+ aria-label={ariaLabel}+ aria-labelledby={ariaLabelledBy}+ data-severity={severity}+ className={cn(+ 'overflow-hidden rounded-full bg-[var(--quota-bar-track)]',+ isMini ? 'inline-flex h-[5px] w-[32px]' : 'flex h-[7px] w-full',+ className,+ )}+ >+ <div+ className={cn(+ 'h-full rounded-full transition-[width] duration-[var(--motion-base)] ease-[var(--motion-ease-move)] motion-reduce:transition-none',+ clampedPercent > 0 && (isMini ? 'min-w-[4px]' : 'min-w-[7px]'),+ FILL_COLOR_CLASSES[severity],+ )}+ style={{ width: `${clampedPercent}%` }}+ />+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx b/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsxnew file mode 100644index 0000000000..e03e05afe6--- /dev/null+++ b/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx@@ -0,0 +1,547 @@+/**+ * QuotaHoverCard — Claude 订阅额度的结构化悬浮卡片。+ *+ * 组件只负责展示调用方给出的快照与本轮明细,不读取 store,也不主动获取数据。+ */++import React from 'react';+import type { TFunction } from 'i18next';+import { useTranslation } from 'react-i18next';++import { cn } from '@/lib/utils';+import type {+ ClaudeSubscriptionUsageSnapshot,+ ClaudeUsageWindow,+} from '../../../shared/claudeSubscriptionUsage';+import { QuotaBar, quotaSeverity, type QuotaSeverity } from './QuotaBar';++export interface QuotaHoverCardTurnUsage {+ costText?: string | null;+ costIsEstimate?: boolean;+ isUserTurnTotal?: boolean;+ finalSegment?: {+ costText?: string | null;+ costIsEstimate?: boolean;+ } | null;+ totalTokensText?: string | null;+ inputTokensText?: string | null;+ outputTokensText?: string | null;+ cacheLineText?: string | null;+ model?: string | null;+ perModelCost?: ReadonlyArray<{+ model: string;+ costText: string;+ }> | null;+ suggestionText?: string | null;+}++export interface QuotaHoverCardSessionUsage {+ costText: string;+ costIsEstimate?: boolean;+ actualCostText?: string | null;+ estimatedValueText?: string | null;+}++export interface QuotaHoverCardProps {+ snapshot: ClaudeSubscriptionUsageSnapshot | null;+ sessionUsage?: QuotaHoverCardSessionUsage | null;+ turnUsage?: QuotaHoverCardTurnUsage | null;+ dashboardLabel?: string | null;+ onOpenDashboard?: () => void;+ dashboardButtonRef?: React.Ref<HTMLButtonElement>;+ nowMs?: number;+}++interface DisplayWindow {+ key: string;+ title: string;+ window: ClaudeUsageWindow;+}++const STALE_AFTER_MS = 5 * 60_000;++function clampPercent(value: number): number {+ if (!Number.isFinite(value)) return 0;+ 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,+ crit: 2,+};++/**+ * 非字符串按缺失处理;字符串空值或 normal 才是无告警,未知非空值至少保留为 warn。+ * 这与共享告警谓词“任何非 normal severity 均告警”保持一致,+ * 避免新增的上游级别在卡片里被静默降成正常。+ */+function serverQuotaSeverity(value: unknown): QuotaSeverity {+ if (typeof value !== 'string') return 'normal';+ const normalized = value.trim().toLowerCase();+ if (!normalized || normalized === 'normal') return 'normal';+ if (normalized === 'warning') return 'warn';+ const parts = normalized.split(/[^a-z]+/).filter(Boolean);+ if (parts.includes('exceeded') || parts.includes('critical')) return 'crit';+ return 'warn';+}++function effectiveQuotaSeverity(window: ClaudeUsageWindow): QuotaSeverity {+ const localSeverity = quotaSeverity(window.utilization);+ const serverSeverity = serverQuotaSeverity(window.severity);+ return QUOTA_SEVERITY_RANK[serverSeverity] > QUOTA_SEVERITY_RANK[localSeverity]+ ? serverSeverity+ : 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)]" />;+}++function WindowBlock({+ title,+ window,+ nowMs,+ locale,+ t,+}: {+ title: string;+ window: ClaudeUsageWindow;+ nowMs: number;+ locale: string | undefined;+ t: TFunction;+}) {+ const titleId = React.useId();+ const usedPercent = clampPercent(window.utilization);+ const severity = effectiveQuotaSeverity(window);+ const severityAnnouncement =+ severity === 'crit'+ ? t('quotaCard.limitRejected')+ : severity === 'warn'+ ? t('quotaCard.limitWarning')+ : null;+ const resetAt = formatResetAt(window.resetsAt, nowMs, locale);++ return (+ <section data-testid="quota-window" className="px-4 pb-1 pt-2">+ <div+ id={titleId}+ data-severity={severity}+ className={cn(+ 'mb-2 text-sm font-medium tracking-[-0.005em]',+ severity === 'crit' ? 'text-[var(--quota-bar-crit)]' : 'text-[var(--text-primary)]',+ )}+ >+ {title}+ {severityAnnouncement !== null ? (+ // 告警不能只依赖颜色;标题与进度条共用对应级别的屏幕阅读器文案。+ <span className="sr-only">,{severityAnnouncement}</span>+ ) : null}+ </div>+ <QuotaBar usedPercent={window.utilization} severity={severity} aria-labelledby={titleId} />+ <div className="mt-[7px] flex items-baseline justify-between gap-3 tabular-nums">+ <span className="font-medium text-[var(--text-primary)]">+ {t('quotaCard.usedPercent', { percent: Math.round(usedPercent) })}+ </span>+ {resetAt !== null ? (+ <span className="text-xs text-[var(--text-secondary)]">+ {t('quotaCard.resetAt', { at: resetAt })}+ </span>+ ) : null}+ </div>+ </section>+ );+}++function TurnUsageSection({ turnUsage, t }: { turnUsage: QuotaHoverCardTurnUsage; t: TFunction }) {+ const hasTokenBreakdown = turnUsage.inputTokensText != null && turnUsage.outputTokensText != null;+ const showModelCostBreakdown = (turnUsage.perModelCost?.length ?? 0) >= 2;++ const renderCostLine = (+ costText: string | null | undefined,+ isEstimate: boolean | undefined,+ unavailableKey: string,+ ) => (+ <div className="text-sm font-medium text-[var(--text-primary)]">+ {costText != null+ ? t(isEstimate ? 'quotaCard.valueLine' : 'quotaCard.costLine', { cost: costText })+ : t(unavailableKey)}+ </div>+ );++ 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)]">+ {t('quotaCard.latestMessageTitle')}+ </div>+ ) : null}+ <div className="tabular-nums">+ {renderCostLine(+ turnUsage.costText,+ turnUsage.costIsEstimate,+ 'quotaCard.turnCostUnavailable',+ )}+ </div>++ {turnUsage.finalSegment ? (+ <div className="mt-2">+ <div className="mb-[3px] text-xs font-medium text-[var(--text-secondary)]">+ {t('chat.messageActionBar.userTurnCostDetailsTitle')}+ </div>+ <div className="tabular-nums">+ {renderCostLine(+ turnUsage.finalSegment.costText,+ turnUsage.finalSegment.costIsEstimate,+ 'quotaCard.noBilledCost',+ )}+ </div>+ </div>+ ) : null}++ {showModelCostBreakdown ? (+ <div data-testid="quota-model-cost-breakdown" className="mt-2">+ <div className="mb-[3px] text-xs font-medium text-[var(--text-secondary)]">+ {t('usageDetails.costBreakdownHeader')}+ </div>+ <div className="space-y-0.5 tabular-nums text-[var(--text-primary)]">+ {turnUsage.perModelCost?.map((entry, index) => (+ <div key={`${entry.model}-${index}`}>+ {t('usageDetails.modelCostLine', {+ model: entry.model,+ cost: entry.costText,+ })}+ </div>+ ))}+ </div>+ </div>+ ) : null}++ {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)]">+ {turnUsage.totalTokensText}+ {hasTokenBreakdown ? (+ <span className="font-normal text-[var(--text-secondary)]">+ {t('quotaCard.tokenBreakdown', {+ input: turnUsage.inputTokensText,+ output: turnUsage.outputTokensText,+ })}+ </span>+ ) : null}+ </span>+ </div>+ ) : null}++ {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)]">+ {turnUsage.cacheLineText}+ </span>+ </div>+ ) : null}++ {!showModelCostBreakdown && turnUsage.model != null ? (+ <div className="mt-[5px] flex items-baseline justify-between gap-3">+ <span className="text-[var(--text-secondary)]">{t('quotaCard.modelLabel')}</span>+ <span className="min-w-0 break-words text-right font-medium text-[var(--text-primary)]">+ {turnUsage.model}+ </span>+ </div>+ ) : null}++ {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)]"+ >+ <span aria-hidden="true" className="shrink-0 text-[var(--quota-bar-warn)]">+ ●+ </span>+ <span>{turnUsage.suggestionText}</span>+ </div>+ ) : null}+ </section>+ );+}++/** 会话合计含真实费用与价值估算时,保留两条构成供用户核对。 */+function SessionUsageSection({+ sessionUsage,+ t,+}: {+ sessionUsage: QuotaHoverCardSessionUsage;+ t: TFunction;+}) {+ const hasMixedBreakdown = Boolean(sessionUsage.actualCostText && sessionUsage.estimatedValueText);+ const totalKey = hasMixedBreakdown+ ? 'todaySpend.sessionCostLabel'+ : sessionUsage.costIsEstimate+ ? 'todaySpend.codex.sessionValueLabel'+ : 'todaySpend.tooltip.sessionUsed';++ 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>+ {hasMixedBreakdown ? (+ <div className="mt-1 space-y-0.5 text-xs text-[var(--text-secondary)]">+ <div>{t('todaySpend.tooltip.sessionUsed', { cost: sessionUsage.actualCostText })}</div>+ <div>+ {t('todaySpend.codex.sessionValueLabel', {+ cost: sessionUsage.estimatedValueText,+ })}+ </div>+ </div>+ ) : null}+ </section>+ );+}++/** 按冻结的 v6 信息层级渲染 Claude 额度卡片。 */+export function QuotaHoverCard({+ snapshot,+ sessionUsage = null,+ turnUsage = null,+ dashboardLabel = null,+ onOpenDashboard,+ dashboardButtonRef,+ nowMs = Date.now(),+}: QuotaHoverCardProps) {+ const { t, i18n } = useTranslation();+ // 测试可只注入 t;运行时再优先跟随应用当前语言格式化日期。+ const locale = i18n?.resolvedLanguage ?? i18n?.language;+ const planLabel = formatPlanType(snapshot?.subscriptionType);++ 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,+ });+ }+ // 持久化旧快照可能把 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 staleMinutes =+ snapshot &&+ typeof snapshot.updatedAt === 'number' &&+ Number.isFinite(snapshot.updatedAt) &&+ nowMs - snapshot.updatedAt > STALE_AFTER_MS+ ? Math.floor((nowMs - snapshot.updatedAt) / 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-[13px] leading-5 text-[var(--text-primary)]"+ style={{ boxShadow: 'var(--shadow-menu)' }}+ >+ <div+ data-testid="quota-hover-card-scroll-content"+ role="region"+ aria-label={t('quotaCard.windowsRegionLabel')}+ 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 ? (+ <>+ <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>+ {planLabel ? (+ <span+ data-testid="quota-plan-badge"+ className="ml-auto rounded-full border border-[var(--border-default)] px-[7px] py-px text-[11px] font-medium"+ >+ {planLabel}+ </span>+ ) : null}+ </div>++ <CardDivider />++ {windows.length > 0 ? (+ <div>+ {windows.map((displayWindow) => (+ <WindowBlock+ key={displayWindow.key}+ title={displayWindow.title}+ window={displayWindow.window}+ nowMs={nowMs}+ 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 className="px-4 py-2 text-[var(--text-secondary)]">{t('quotaCard.waiting')}</div>+ )}++ {sessionUsage ? (+ <>+ <CardDivider />+ <SessionUsageSection sessionUsage={sessionUsage} t={t} />+ </>+ ) : null}++ {turnUsage ? (+ <>+ <CardDivider />+ <TurnUsageSection turnUsage={turnUsage} t={t} />+ </>+ ) : null}+ </div>++ {dashboardLabel ? (+ <>+ <CardDivider />+ <button+ 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]"+ >+ <svg+ aria-hidden="true"+ width="14"+ height="14"+ viewBox="0 0 14 14"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.5"+ strokeLinecap="round"+ className="shrink-0 opacity-75"+ >+ <path d="M2 12V7M7 12V2M12 12V5" />+ </svg>+ <span>{dashboardLabel}</span>+ </button>+ </>+ ) : null}++ {staleMinutes !== null ? (+ <>+ <CardDivider />+ <div className="px-4 py-1.5 text-xs tabular-nums text-[var(--text-secondary)]">+ {t('quotaCard.staleData', { minutes: staleMinutes })}+ </div>+ </>+ ) : null}+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsxindex dd8ca3e23a..0708968f55 100644--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx@@ -44,9 +44,15 @@ import {DAILY_SOFT_LIMIT_FACTOR,formatCompactMoney,formatCompactTokens,+ formatModelShort,formatTurnCostMoney,formatTurnCostUsd,} from '@/lib/usageFormat';+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '@/components/ui/popover';import { Tip } from '@/components/ui/tooltip';import { useApiKey } from '@/hooks/useApiKey';import { useClaudeOAuthConnected } from '@/hooks/useClaudeOAuthConnected';@@ -74,7 +80,6 @@ import {type ClaudeSubscriptionUsageSnapshot,} from '@/hooks/useClaudeSubscriptionUsage';import {- hasAlertingClaudeSessionWindow,isClaudeSubscriptionAlerting,matchScopedWindowForModel,type ClaudeUsageWindow,@@ -83,7 +88,10 @@ import { useCodexRuntimeRoute } from '@/hooks/useCodexRuntimeRoute';import { useCodexRateLimits } from '@/hooks/useCodexRateLimits';import { useXaiRateLimit, type XaiRateLimitSnapshot } from '@/hooks/useXaiRateLimit';import { makerChatStore, type ChatMessage } from '@/lib/makerChatStore';-import { buildTurnUsageTooltipLines } from '@/lib/turnUsageTooltip';+import {+ buildTurnUsageTooltipLines,+ getTurnUsageSuggestion,+} from '@/lib/turnUsageTooltip';import type { TurnUsageDetails } from '../../../shared/turnUsageDetails';import {DEFAULT_USAGE_CURRENCY,@@ -97,6 +105,11 @@ import {useQuotaResetRollup,type ChipWindowSlot,} from './quotaResetRollup';+import {+ QuotaHoverCard,+ type QuotaHoverCardSessionUsage,+ type QuotaHoverCardTurnUsage,+} from './QuotaHoverCard';import { QuotaResetConfetti } from './QuotaResetConfetti';// XD 网关 / 托管账号之前会跳到内部用量看板(内部域名)—— 开源前移除该硬编码。@@ -117,6 +130,8 @@ type MetricKey = (typeof METRIC_KEYS)[number];// 按账号所属租户二选一下发, 两组互斥, 同一形态下不会都占位。const PRIMARY_GATEWAY_METRICS: readonly MetricKey[] = ['daily', 'credit', 'session'];const DAY_MS = 24 * 60 * 60 * 1000;+const QUOTA_POPOVER_OPEN_DELAY_MS = 300;+const QUOTA_POPOVER_CLOSE_GRACE_MS = 200;const DEFAULT_MONEY_SYMBOL = DEFAULT_USAGE_CURRENCY === 'CNY' ? '¥' : '$';const DEFAULT_MONEY_PLACEHOLDER = `${DEFAULT_MONEY_SYMBOL}—`;@@ -586,37 +601,7 @@ function buildCodexTooltipNode(// ── Claude 订阅 (Anthropic OAuth) 形态 ───────────────────────────────────────// 主 chip 方案 B: 5h 剩余% · 当前模型周限剩余% (weekly_scoped 按模型家族匹配, 匹配-// 不到回退总周限并标注口径) · 本会话价值 $。tooltip 列全量窗口 (含非当前模型的-// scoped 条目) + 套餐 + extra usage。utilization 语义 = 已用百分比 (0-100)。--/**- * Claude 窗口 → tooltip 行素材;窗口缺失 / 数据不可解析 → null (调用方过滤)。- * tooltip 的窗口行不做逐行高亮 (纯文本 tooltip), 告警只体现在 chip 配色与末尾的- * 「接近限额」行 —— 故这里不带 alerting 标记。- */-interface ClaudeWindowUsage {- label: string;- used: string;- remaining: string;- /** tooltip 用的精确 reset 时间点;无数据 → null。 */- resetAt: string | null;-}--function toClaudeWindowUsage(- label: string,- window: ClaudeUsageWindow | null | undefined,-): ClaudeWindowUsage | null {- if (!window || typeof window.utilization !== 'number' || !Number.isFinite(window.utilization)) {- return null;- }- const usedPercent = clampPercent(window.utilization);- return {- label,- used: formatPercent(usedPercent),- remaining: formatPercent(100 - usedPercent),- resetAt: formatResetAt(window.resetsAt),- };-}+// 不到回退总周限并标注口径) · 本会话价值 $。utilization 语义 = 已用百分比 (0-100)。/*** 当前会话生效的周限窗口: 命中当前模型的 weekly_scoped 条目优先 (label 带模型名,@@ -692,82 +677,8 @@ function getClaudeChipWindows(}// 告警判定 (chip 变红的口径 + allowed_warning 为何不染红、为何不用 representativeClaim-// 的取舍) 已收进 shared/claudeSubscriptionUsage.ts: isClaudeUsageWindowAlerting /-// hasAlertingClaudeSessionWindow / isClaudeSubscriptionAlerting (纯数据判定, 有直接单测)。-// tooltip 不逐行高亮, 它比 chip 宽一档的那一档在 buildClaudeSubscriptionTooltipNode 里-// (整体 status 的 allowed_warning 也出「接近限额」行)。--function buildClaudeSubscriptionTooltipNode(- snapshot: ClaudeSubscriptionUsageSnapshot | null,- modelId: string | null | undefined,- sessionUsage: SessionUsageMoney,- t: TFunction,- usageDashboardLabel: string | null,- latestTurnUsage: LatestTurnUsageSummary | null,-): React.ReactNode {- const lines: string[] = [];- pushSessionUsageLines(lines, sessionUsage, null, t);- if (!snapshot) {- lines.push(t('todaySpend.claude.waitingDetail'));- appendLatestTurnUsageLines(lines, latestTurnUsage, t);- pushDashboardLinkLine(lines, usageDashboardLabel);- return buildTooltipNode(lines);- }-- const planLabel = formatPlanType(snapshot.subscriptionType);- if (planLabel) {- lines.push(t('todaySpend.claude.planLine', { plan: planLabel }));- }- // 窗口明细: 5h → 总周限 → 全部分模型周限 (含非当前模型, 用户能看到谁先见底)。- // tooltip 保留精确 reset 时间点 (chip 上是倒计时, 两层信息互补)。- const windows: ClaudeWindowUsage[] = [];- const fiveHour = toClaudeWindowUsage('5h', snapshot.fiveHour);- if (fiveHour) windows.push(fiveHour);- const sevenDay = toClaudeWindowUsage(t('todaySpend.claude.weeklyLabel'), snapshot.sevenDay);- if (sevenDay) windows.push(sevenDay);- for (const scoped of snapshot.scoped ?? []) {- const usage = toClaudeWindowUsage(- t('todaySpend.claude.modelWeeklyLabel', { model: scoped.modelDisplayName }),- scoped,- );- if (usage) windows.push(usage);- }- for (const window of windows) {- const base = t('todaySpend.claude.windowLine', {- label: window.label,- remaining: window.remaining,- used: window.used,- });- lines.push(window.resetAt- ? `${base} · ${t('todaySpend.claude.resetAt', { at: window.resetAt })}`- : base,- );- }-- // tooltip 比 chip 宽一档: allowed_warning (服务端综合全部窗口的模糊信号) 也提示 ——- // 上面刚列完全量窗口, 用户能自己看出是哪个窗口吃紧; chip 颜色不吃这个信号 (见- // isClaudeSubscriptionAlerting)。- const status = snapshot.rateLimitStatus?.trim().toLowerCase();- if (status === 'rejected') {- lines.push(t('todaySpend.claude.limitRejected'));- } else if (status === 'allowed_warning' || hasAlertingClaudeSessionWindow(snapshot, modelId)) {- lines.push(t('todaySpend.claude.limitWarning'));- }-- if (snapshot.extraUsage?.isEnabled) {- // extra_usage 的 used_credits / monthly_limit 单位未文档化且本地暂无实样账号,- // 不能假设 cents 并渲染美元金额。这里只展示启用状态;数值原样保留在 snapshot,- // 等拿到 live response 后再补准确单位展示。- lines.push(t('todaySpend.claude.extraUsageEnabledLine'));- }-- if (lines.length === 0) {- lines.push(t('todaySpend.claude.waitingDetail'));- }- appendLatestTurnUsageLines(lines, latestTurnUsage, t);- pushDashboardLinkLine(lines, usageDashboardLabel);- return buildTooltipNode(lines);-}+// 的取舍) 已收进 shared/claudeSubscriptionUsage.ts 的+// isClaudeSubscriptionAlerting (纯数据判定, 有直接单测)。/** 最近一轮 tooltip 使用的 assistant 消息明细。 */interface LatestTurnUsageSummary {@@ -781,6 +692,111 @@ interface LatestTurnUsageSummary {details: TurnUsageDetails;}+function formatTurnUsagePercent(value: number | null): string | null {+ if (value === null || !Number.isFinite(value)) return null;+ const percent = Math.min(100, Math.max(0, value * 100));+ if (Math.abs(percent - Math.round(percent)) < 0.05) return `${Math.round(percent)}%`;+ return `${percent.toFixed(1).replace(/\.0$/, '')}%`;+}++function formatQuotaCacheLine(details: TurnUsageDetails, t: TFunction): string {+ const read = formatCompactTokens(Math.max(0, Math.floor(details.cacheReadTokens)));+ const create = formatCompactTokens(Math.max(0, Math.floor(details.cacheCreateTokens)));+ const rate = formatTurnUsagePercent(details.cacheHitRate);+ const localized = t(rate ? 'usageDetails.cacheLine' : 'usageDetails.cacheLineNoRate', {+ read,+ create,+ rate: rate ?? '',+ });++ // 卡片左列已有“缓存”标题,复用既有 i18n 后去掉重复前缀;中文再收成示意稿的短标签。+ return localized+ .replace(/^[^::]+[::]\s*/, '')+ .replace(/^读取\s/, '读 ')+ .replace(' · 写入 ', ' · 写 ')+ .replace(' · 命中率 ', ' · 命中 ');+}++function quotaTurnModel(details: TurnUsageDetails, t: TFunction): string | null {+ if (details.model) return details.model;+ if (details.models?.length === 1) return details.models[0];+ if (details.models && details.models.length > 1) {+ return t('usageDetails.multipleModels', { count: details.models.length });+ }+ return null;+}++function toQuotaHoverCardTurnUsage(+ summary: LatestTurnUsageSummary | null,+ t: TFunction,+): QuotaHoverCardTurnUsage | null {+ if (!summary) return null;+ const { details } = summary;+ const costText = summary.money+ ? formatTurnCostMoney(summary.money)+ : summary.costUsd != null+ ? formatTurnCostUsd(summary.costUsd)+ : null;+ const finalSegmentCostText = summary.segmentMoney+ ? formatTurnCostMoney(summary.segmentMoney)+ : summary.segmentCostUsd != null+ ? formatTurnCostUsd(summary.segmentCostUsd)+ : null;++ return {+ costText,+ costIsEstimate: summary.isEstimate,+ isUserTurnTotal: summary.isUserTurnTotal,+ // userTurnMoney 是用户轮累计,而 turnUsageDetails 始终只描述收尾 SDK 分段。+ // 两笔金额可能因前段无报价而恰好相等,不能用金额相等反推只有一个分段。+ ...(summary.isUserTurnTotal+ ? {+ finalSegment: {+ costText: finalSegmentCostText,+ costIsEstimate: summary.segmentIsEstimate,+ },+ }+ : {}),+ totalTokensText: formatCompactTokens(Math.max(0, Math.floor(details.totalTokens))),+ inputTokensText: formatCompactTokens(details.inputTokens),+ outputTokensText: formatCompactTokens(details.outputTokens),+ cacheLineText: formatQuotaCacheLine(details, t),+ model: quotaTurnModel(details, t),+ ...(details.perModelCost+ ? {+ perModelCost: details.perModelCost.map((entry) => ({+ model: formatModelShort(entry.model),+ costText: formatTurnCostMoney(entry.money),+ })),+ }+ : {}),+ suggestionText: getTurnUsageSuggestion(details, t),+ };+}++/** 把会话金额投影成卡片数据;混合合计保留实际费用与价值估算两条构成。 */+function toQuotaHoverCardSessionUsage(+ sessionUsage: SessionUsageMoney,+): QuotaHoverCardSessionUsage | null {+ const { actualMoney, estimatedValueMoney, totalMoney } = sessionUsage;+ if (!totalMoney?.amount) return null;++ return {+ costText: formatTurnCostMoney(totalMoney),+ // approximate 只说明金额精度,不能把第三方参考价的实际费用改成订阅价值语义。+ // 纯价值估算优先信任 kind;兼容旧投影时再以唯一存在的估值分量兜底。+ costIsEstimate:+ totalMoney.kind === 'value-estimate'+ || Boolean(!actualMoney?.amount && estimatedValueMoney?.amount),+ ...(actualMoney?.amount+ ? { actualCostText: formatTurnCostMoney(actualMoney) }+ : {}),+ ...(estimatedValueMoney?.amount+ ? { estimatedValueText: formatTurnCostMoney(estimatedValueMoney) }+ : {}),+ };+}+function findLatestTurnUsageSummary(messages: ChatMessage[]): LatestTurnUsageSummary | null {for (let i = messages.length - 1; i >= 0; i--) {const message = messages[i];@@ -792,6 +808,7 @@ function findLatestTurnUsageSummary(messages: ChatMessage[]): LatestTurnUsageSumconst userTurnCostUsd = typeof message.userTurnCostUsd === 'number' && message.userTurnCostUsd > 0? message.userTurnCostUsd: undefined;+ const displayedMoney = userTurnMoney ?? message.turnMoney;return {...(userTurnMoney? { money: userTurnMoney }@@ -804,11 +821,16 @@ function findLatestTurnUsageSummary(messages: ChatMessage[]): LatestTurnUsageSum: {}),...((userTurnMoney || userTurnCostUsd != null? message.userTurnCostIsEstimate- : message.turnCostIsEstimate) === true ? { isEstimate: true } : {}),+ : message.turnCostIsEstimate) === true+ || displayedMoney?.kind === 'value-estimate'+ ? { isEstimate: true }+ : {}),...((userTurnMoney || userTurnCostUsd != null) && message.turnMoney?.amount? {segmentMoney: message.turnMoney,- segmentIsEstimate: message.turnCostIsEstimate === true,+ segmentIsEstimate:+ message.turnCostIsEstimate === true+ || message.turnMoney.kind === 'value-estimate',}: userTurnCostUsd != null && typeof message.turnCostUsd === 'number' && message.turnCostUsd > 0? {@@ -1139,6 +1161,7 @@ export function TodaySpendChip({// 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);@@ -1221,6 +1244,118 @@ export function TodaySpendChip({isClaudeSubscription && !isSubscriptionBridge && !isDeviceLinkRemote,);const latestTurnUsage = useLatestTurnUsageSummary(sessionId);+ const quotaCardSessionUsage = toQuotaHoverCardSessionUsage(sessionUsage);+ const quotaCardTurnUsage = toQuotaHoverCardTurnUsage(latestTurnUsage, t);+ const [quotaPopoverOpen, setQuotaPopoverOpen] = React.useState(false);+ const quotaPopoverOpenTimerRef = React.useRef<number | null>(null);+ const quotaPopoverCloseTimerRef = React.useRef<number | null>(null);+ const quotaPopoverPointerInsideRef = React.useRef(false);+ const quotaPopoverFocusInsideRef = React.useRef(false);+ const quotaPopoverOpenSourceRef = React.useRef<'hover' | 'focus' | null>(null);+ const quotaPopoverFocusTakenRef = React.useRef(false);+ const quotaPopoverRestoringFocusRef = React.useRef(false);+ const quotaPopoverTriggerRef = React.useRef<HTMLElement>(null);+ const quotaPopoverDashboardButtonRef = React.useRef<HTMLButtonElement>(null);+ const setQuotaPopoverFocusTarget = React.useCallback((node: HTMLElement | null) => {+ quotaPopoverTriggerRef.current = node;+ }, []);++ const clearQuotaPopoverOpenTimer = React.useCallback(() => {+ if (quotaPopoverOpenTimerRef.current === null) return;+ window.clearTimeout(quotaPopoverOpenTimerRef.current);+ quotaPopoverOpenTimerRef.current = null;+ }, []);+ const clearQuotaPopoverCloseTimer = React.useCallback(() => {+ if (quotaPopoverCloseTimerRef.current === null) return;+ window.clearTimeout(quotaPopoverCloseTimerRef.current);+ quotaPopoverCloseTimerRef.current = null;+ }, []);+ const keepQuotaPopoverOpen = React.useCallback(() => {+ clearQuotaPopoverOpenTimer();+ clearQuotaPopoverCloseTimer();+ }, [clearQuotaPopoverCloseTimer, clearQuotaPopoverOpenTimer]);+ const restoreQuotaPopoverFocus = React.useCallback(() => {+ const shouldRestoreFocus = quotaPopoverFocusTakenRef.current;+ quotaPopoverFocusTakenRef.current = false;+ quotaPopoverOpenSourceRef.current = null;+ if (!shouldRestoreFocus) return;+ quotaPopoverRestoringFocusRef.current = true;+ quotaPopoverTriggerRef.current?.focus({ preventScroll: true });+ quotaPopoverRestoringFocusRef.current = false;+ }, []);+ const openQuotaPopoverImmediately = React.useCallback(() => {+ keepQuotaPopoverOpen();+ quotaPopoverOpenSourceRef.current = 'focus';+ setQuotaPopoverOpen(true);+ }, [keepQuotaPopoverOpen]);+ const closeQuotaPopoverImmediately = React.useCallback(() => {+ keepQuotaPopoverOpen();+ setQuotaPopoverOpen(false);+ // 受控关闭不保证 Radix 在内容卸载前触发 close-autofocus,先归还已接管的焦点。+ restoreQuotaPopoverFocus();+ }, [keepQuotaPopoverOpen, restoreQuotaPopoverFocus]);+ const scheduleQuotaPopoverOpen = React.useCallback(() => {+ clearQuotaPopoverCloseTimer();+ clearQuotaPopoverOpenTimer();+ quotaPopoverOpenTimerRef.current = window.setTimeout(() => {+ quotaPopoverOpenTimerRef.current = null;+ quotaPopoverOpenSourceRef.current = 'hover';+ setQuotaPopoverOpen(true);+ }, QUOTA_POPOVER_OPEN_DELAY_MS);+ }, [clearQuotaPopoverCloseTimer, clearQuotaPopoverOpenTimer]);+ const scheduleQuotaPopoverClose = React.useCallback(() => {+ clearQuotaPopoverOpenTimer();+ clearQuotaPopoverCloseTimer();+ quotaPopoverCloseTimerRef.current = window.setTimeout(() => {+ quotaPopoverCloseTimerRef.current = null;+ setQuotaPopoverOpen(false);+ restoreQuotaPopoverFocus();+ }, QUOTA_POPOVER_CLOSE_GRACE_MS);+ }, [clearQuotaPopoverCloseTimer, clearQuotaPopoverOpenTimer, restoreQuotaPopoverFocus]);+ const handleQuotaPopoverMouseEnter = React.useCallback(() => {+ quotaPopoverPointerInsideRef.current = true;+ keepQuotaPopoverOpen();+ }, [keepQuotaPopoverOpen]);+ const scheduleQuotaPopoverCloseIfOutside = React.useCallback(() => {+ if (quotaPopoverPointerInsideRef.current || quotaPopoverFocusInsideRef.current) return;+ scheduleQuotaPopoverClose();+ }, [scheduleQuotaPopoverClose]);+ const handleQuotaPopoverMouseLeave = React.useCallback(() => {+ quotaPopoverPointerInsideRef.current = false;+ // 鼠标离开不能抢走卡片内的键盘焦点;只有指针与焦点都在外部才走 hover 关闭。+ scheduleQuotaPopoverCloseIfOutside();+ }, [scheduleQuotaPopoverCloseIfOutside]);+ const handleQuotaPopoverTriggerMouseEnter = React.useCallback(() => {+ quotaPopoverPointerInsideRef.current = true;+ scheduleQuotaPopoverOpen();+ }, [scheduleQuotaPopoverOpen]);++ const quotaPopoverContextRef = React.useRef({+ enabled: usesClaudeSubscriptionPopover,+ sessionId,+ });+ React.useLayoutEffect(() => {+ const previousContext = quotaPopoverContextRef.current;+ const contextInvalidated = previousContext.enabled+ && (!usesClaudeSubscriptionPopover || previousContext.sessionId !== sessionId);+ quotaPopoverContextRef.current = {+ enabled: usesClaudeSubscriptionPopover,+ sessionId,+ };+ if (!contextInvalidated) return;++ // provider / model 或任务切换会原地复用组件;在新 chip 节点挂载后同步收口旧弹窗,+ // 清掉 hover / focus 残态与悬空 timer,并把卡片接管的键盘焦点交还给当前 chip。+ quotaPopoverPointerInsideRef.current = false;+ quotaPopoverFocusInsideRef.current = false;+ closeQuotaPopoverImmediately();+ }, [closeQuotaPopoverImmediately, sessionId, usesClaudeSubscriptionPopover]);++ React.useEffect(() => () => {+ clearQuotaPopoverOpenTimer();+ clearQuotaPopoverCloseTimer();+ }, [clearQuotaPopoverCloseTimer, clearQuotaPopoverOpenTimer]);+const sessionSegment = sessionMoney?.amount? t('todaySpend.sessionCostLabel', {cost: formatTurnCostMoney(sessionMoney),@@ -1336,7 +1471,6 @@ export function TodaySpendChip({const resetsAtSignature = chipWindows.map((window) => window.resetsAtMs ?? 'na').join(',');const chipResetsAtMsList = React.useMemo(() => chipWindows.map((window) => window.resetsAtMs),- // eslint-disable-next-line react-hooks/exhaustive-deps -- resetsAtSignature 是 chipWindows reset 时点的值签名[resetsAtSignature],);@@ -1422,20 +1556,12 @@ export function TodaySpendChip({);} else if (isClaudeSubscription) {// Claude 订阅形态 (方案 B): chip 显示「剩余时长 剩余%」倒计时段 + 本会话合计,- // 倒计时由 windowLabelNowMs 驱动 (常态 60s tick, 最后一分钟逐秒); tooltip 保留精确时间。+ // 倒计时由 windowLabelNowMs 驱动 (常态 60s tick, 最后一分钟逐秒)。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 = buildClaudeSubscriptionTooltipNode(- claudeSubscriptionUsage,- modelId,- sessionUsage,- t,- usageDashboardLabel,- latestTurnUsage,- );} else {const slots = computeMetricSlots(claudeQuota, creditTotals, sessionMoney, t);const chipSegments = getGatewayChipSegments(slots);@@ -1537,22 +1663,131 @@ export function TodaySpendChip({onMouseEnter={refreshCodexRateLimits}onFocusCapture={refreshCodexRateLimits}>- <Tip text={tooltipNode}>- {isDashboardClickable ? (- <button- type="button"- onClick={handleClick}- className={buttonClass}- aria-label={usageDashboardLabel ?? undefined}+ {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) => {+ 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] border-0 bg-transparent p-0 shadow-none">- {labelNode}- </button>- ) : (- // 网关 / 托管账号暂无看板可跳(见 usageDashboardUrl):渲染为非交互文本,- // 点击无反应、不显示手型 / hover 态;用量指标与 tooltip 仍照常展示。- <span className={cn(buttonClass, 'cursor-default')}>{labelNode}</span>- )}- </Tip>+ <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>+ )}{confettiBurst && (<QuotaResetConfettikey={confettiBurst.nonce}diff --git a/apps/desktop/src/renderer/components/status/__tests__/QuotaBar.test.tsx b/apps/desktop/src/renderer/components/status/__tests__/QuotaBar.test.tsxnew file mode 100644index 0000000000..ee89088517--- /dev/null+++ b/apps/desktop/src/renderer/components/status/__tests__/QuotaBar.test.tsx@@ -0,0 +1,116 @@+// @vitest-environment jsdom++import { render } from '@testing-library/react';+import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++import { QuotaBar, quotaSeverity } from '../QuotaBar';++const colorsSource = readFileSync(+ resolve(__dirname, '..', '..', '..', 'themes', 'colors.ts'),+ 'utf8',+).replace(/\r\n/g, '\n');+const globalsSource = readFileSync(+ resolve(__dirname, '..', '..', '..', 'styles', 'globals.css'),+ 'utf8',+).replace(/\r\n/g, '\n');++describe('QuotaBar', () => {+ it.each([+ { usedPercent: -5, expected: '0' },+ { usedPercent: 250, expected: '100' },+ { usedPercent: Number.NaN, expected: '0' },+ ])('clamps $usedPercent to aria-valuenow=$expected', ({ usedPercent, expected }) => {+ const { getByRole } = render(<QuotaBar usedPercent={usedPercent} />);++ expect(getByRole('progressbar').getAttribute('aria-valuenow')).toBe(expected);+ });++ it.each([+ { usedPercent: 70, expected: 'normal' },+ { usedPercent: 71, expected: 'warn' },+ { usedPercent: 89.9, expected: 'warn' },+ { usedPercent: 90, expected: 'crit' },+ { usedPercent: 100, expected: 'crit' },+ ])('renders $usedPercent as $expected severity', ({ usedPercent, expected }) => {+ const { getByRole } = render(<QuotaBar usedPercent={usedPercent} />);++ expect(getByRole('progressbar').getAttribute('data-severity')).toBe(expected);+ });++ it.each([+ { usedPercent: 70, expected: 'normal' },+ { usedPercent: 71, expected: 'warn' },+ { usedPercent: 89.9, expected: 'warn' },+ { usedPercent: 90, expected: 'crit' },+ { usedPercent: 100, expected: 'crit' },+ ] as const)('derives $usedPercent as $expected severity', ({ usedPercent, expected }) => {+ expect(quotaSeverity(usedPercent)).toBe(expected);+ });++ it('renders distinct regular and mini size classes', () => {+ const { getByRole, rerender } = render(<QuotaBar usedPercent={1} />);+ const regular = getByRole('progressbar');++ expect(regular.classList.contains('h-[7px]')).toBe(true);+ expect(regular.classList.contains('w-full')).toBe(true);+ expect(regular.firstElementChild?.classList.contains('min-w-[7px]')).toBe(true);++ rerender(<QuotaBar usedPercent={1} size="mini" />);+ const mini = getByRole('progressbar');++ expect(mini.classList.contains('h-[5px]')).toBe(true);+ expect(mini.classList.contains('w-[32px]')).toBe(true);+ expect(mini.classList.contains('inline-flex')).toBe(true);+ expect(mini.firstElementChild?.classList.contains('min-w-[4px]')).toBe(true);+ });++ it('hides the fill at zero while keeping the minimum dot for a positive fraction', () => {+ const { getByRole, rerender } = render(<QuotaBar usedPercent={0} />);+ const zeroFill = getByRole('progressbar').firstElementChild as HTMLElement;++ expect(zeroFill.style.width).toBe('0%');+ expect(zeroFill.classList.contains('min-w-[7px]')).toBe(false);++ rerender(<QuotaBar usedPercent={0.5} />);+ const fractionalFill = getByRole('progressbar').firstElementChild as HTMLElement;++ expect(fractionalFill.style.width).toBe('0.5%');+ expect(fractionalFill.classList.contains('min-w-[7px]')).toBe(true);+ });++ it('exposes the progressbar role and rounded aria values', () => {+ const { getByRole } = render(+ <QuotaBar usedPercent={42.6} ariaLabel="5 小时" />,+ );+ const progressbar = getByRole('progressbar', { name: '5 小时' });++ expect(progressbar.getAttribute('aria-valuemin')).toBe('0');+ expect(progressbar.getAttribute('aria-valuemax')).toBe('100');+ expect(progressbar.getAttribute('aria-valuenow')).toBe('43');+ });++ it('Light / Dark 都将额度条收敛到已批准语义色', () => {+ const aliases = {+ 'quota-bar-fill': 'text-secondary',+ 'quota-bar-warn': 'warning-fg',+ 'quota-bar-crit': 'error-flat',+ 'quota-bar-track': 'surface-chip',+ } as const;++ for (const [quotaToken, semanticToken] of Object.entries(aliases)) {+ expect(colorsSource).toContain(+ `registerColor('${quotaToken}', {\n`+ + ` light: 'var(--${semanticToken})',\n`+ + ` dark: 'var(--${semanticToken})',\n`+ + '}',+ );+ expect(+ globalsSource.match(+ new RegExp(`--${quotaToken}: var\\(--${semanticToken}\\);`, 'g'),+ ),+ ).toHaveLength(2);+ }+ });+});diff --git a/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx b/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsxnew file mode 100644index 0000000000..e861d3b506--- /dev/null+++ b/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx@@ -0,0 +1,650 @@+// @vitest-environment jsdom++import { fireEvent, render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import type { ClaudeSubscriptionUsageSnapshot } from '../../../../shared/claudeSubscriptionUsage';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ i18n: { language: 'zh-CN', resolvedLanguage: 'zh-CN' },+ t: (key: string, options: Record<string, string | number> = {}) => {+ if (key === 'quotaCard.fiveHourLabel') return '5 小时';+ if (key === 'quotaCard.weeklyLabel') return '周限';+ if (key === 'quotaCard.modelWeeklyLabel') return `${options.model} 周限`;+ if (key === 'quotaCard.windowsRegionLabel') return '配额窗口列表';+ if (key === 'quotaCard.usedPercent') return `已用 ${options.percent}%`;+ if (key === 'quotaCard.limitRejected') return '已触发套餐限额,请求可能被拒绝';+ if (key === 'quotaCard.limitWarning') return '接近套餐限额';+ if (key === 'quotaCard.resetAt') return `${options.at} 重置`;+ if (key === 'quotaCard.tokenBreakdown') {+ return `(输入 ${options.input} · 输出 ${options.output})`;+ }+ if (key === 'todaySpend.sessionCostLabel') return `本任务 ${options.cost}`;+ if (key === 'todaySpend.tooltip.sessionUsed') return `本任务已用 ${options.cost}`;+ if (key === 'todaySpend.codex.sessionValueLabel') return `本任务价值 ${options.cost}`;+ if (key === 'quotaCard.costLine') return `本轮消耗:${options.cost}`;+ if (key === 'quotaCard.valueLine') return `本轮 token 价值:${options.cost}`;+ if (key === 'quotaCard.noBilledCost') return '本轮费用暂不可用,仅显示用量';+ 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 === 'chat.messageActionBar.userTurnCostDetailsTitle') return '最后一个 SDK 分段';+ if (key === 'quotaCard.staleData') return `quotaCard.staleData:${options.minutes}`;+ return key;+ },+ }),+}));++import { QuotaHoverCard } from '../QuotaHoverCard';++const NOW_MS = new Date(2026, 7, 1, 10, 0, 0).getTime();++function epochSeconds(year: number, month: number, day: number, hour: number, minute: number) {+ return new Date(year, month, day, hour, minute, 0).getTime() / 1000;+}++function makeSnapshot(+ overrides: Partial<ClaudeSubscriptionUsageSnapshot> = {},+): ClaudeSubscriptionUsageSnapshot {+ return {+ source: 'oauth-endpoint',+ ...overrides,+ };+}++describe('QuotaHoverCard', () => {+ it('renders only the waiting branch when snapshot is null', () => {+ render(<QuotaHoverCard snapshot={null} nowMs={NOW_MS} />);++ const card = screen.getByTestId('quota-hover-card');+ expect(card.classList.contains('rounded-xl')).toBe(true);+ expect(card.classList.contains('rounded-2xl')).toBe(false);+ expect(card.classList.contains('border-[var(--border-default)]')).toBe(true);+ expect(card.classList.contains('bg-[var(--surface-elevated)]')).toBe(true);+ 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.queryAllByRole('progressbar')).toHaveLength(0);+ });++ it('renders five-hour, weekly, and every scoped window with percentages and reset labels', () => {+ render(+ <QuotaHoverCard+ nowMs={NOW_MS}+ snapshot={makeSnapshot({+ fiveHour: {+ utilization: 1.2,+ resetsAt: epochSeconds(2026, 7, 1, 17, 5),+ },+ sevenDay: {+ utilization: 4.4,+ resetsAt: epochSeconds(2026, 7, 7, 0, 0),+ },+ scoped: [+ {+ modelDisplayName: 'Fable',+ utilization: 0,+ resetsAt: epochSeconds(2026, 7, 6, 23, 59),+ },+ {+ modelDisplayName: 'Opus',+ utilization: 75.6,+ resetsAt: epochSeconds(2026, 7, 1, 18, 30),+ },+ ],+ })}+ />,+ );++ expect(screen.getAllByRole('progressbar')).toHaveLength(4);+ 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.getByText('5 小时')).toBeTruthy();+ expect(screen.getByText('周限')).toBeTruthy();+ expect(screen.getByText('Fable 周限')).toBeTruthy();+ expect(screen.getByText('Opus 周限')).toBeTruthy();+ expect(screen.getByText('已用 1%')).toBeTruthy();+ expect(screen.getByText('已用 4%')).toBeTruthy();+ expect(screen.getByText('已用 0%')).toBeTruthy();+ expect(screen.getByText('已用 76%')).toBeTruthy();+ expect(screen.getByText('17:05 重置')).toBeTruthy();+ expect(screen.getByText('8月7日 00:00 重置')).toBeTruthy();+ expect(screen.getByText('8月6日 23:59 重置')).toBeTruthy();+ expect(screen.getByText('18:30 重置')).toBeTruthy();+ });++ it('accepts the unified-headers shape without scoped windows or severity', () => {+ render(+ <QuotaHoverCard+ nowMs={NOW_MS}+ snapshot={makeSnapshot({+ source: 'unified-headers',+ fiveHour: { utilization: 12 },+ sevenDay: { utilization: 34 },+ })}+ />,+ );++ expect(screen.getAllByRole('progressbar')).toHaveLength(2);+ expect(screen.getByText('5 小时')).toBeTruthy();+ expect(screen.getByText('周限')).toBeTruthy();+ });++ it('skips a null five-hour window while keeping the weekly window', () => {+ render(+ <QuotaHoverCard+ nowMs={NOW_MS}+ snapshot={makeSnapshot({+ fiveHour: null,+ sevenDay: { utilization: 20 },+ })}+ />,+ );++ expect(screen.queryByText('5 小时')).toBeNull();+ expect(screen.getByText('周限')).toBeTruthy();+ expect(screen.getAllByRole('progressbar')).toHaveLength(1);+ });++ it('drops windows with string, null, or non-finite utilization while keeping valid siblings', () => {+ render(+ <QuotaHoverCard+ nowMs={NOW_MS}+ snapshot={makeSnapshot({+ fiveHour: { utilization: '67' as unknown as number },+ sevenDay: { utilization: 24 },+ scoped: [+ {+ modelDisplayName: 'Null model',+ utilization: null as unknown as number,+ },+ {+ modelDisplayName: 'Infinite model',+ utilization: Number.POSITIVE_INFINITY,+ },+ {+ modelDisplayName: 'Valid model',+ utilization: 45,+ },+ ],+ })}+ />,+ );++ expect(screen.queryByText('5 小时')).toBeNull();+ expect(screen.queryByText('Null model 周限')).toBeNull();+ expect(screen.queryByText('Infinite model 周限')).toBeNull();+ expect(screen.getByRole('progressbar', { name: '周限' })).toBeTruthy();+ expect(screen.getByRole('progressbar', { name: 'Valid model 周限' })).toBeTruthy();+ expect(screen.getAllByRole('progressbar')).toHaveLength(2);+ });++ it('renders the no-windows line when every window is absent', () => {+ render(<QuotaHoverCard snapshot={makeSnapshot()} nowMs={NOW_MS} />);++ expect(screen.getByText('quotaCard.noWindows')).toBeTruthy();+ expect(screen.queryAllByRole('progressbar')).toHaveLength(0);+ });++ it('omits a reset label when resetsAt is null', () => {+ render(+ <QuotaHoverCard+ nowMs={NOW_MS}+ snapshot={makeSnapshot({ sevenDay: { utilization: 30, resetsAt: null } })}+ />,+ );++ expect(screen.getByText('已用 30%')).toBeTruthy();+ expect(screen.queryByText(/重置$/)).toBeNull();+ });++ it('clamps dirty utilization for both the bar and used-percent text', () => {+ render(+ <QuotaHoverCard nowMs={NOW_MS} snapshot={makeSnapshot({ fiveHour: { utilization: 250 } })} />,+ );++ const bar = screen.getByRole('progressbar');+ expect(bar.getAttribute('aria-valuenow')).toBe('100');+ expect((bar.firstElementChild as HTMLElement | null)?.style.width).toBe('100%');+ expect(screen.getByText('已用 100%')).toBeTruthy();+ });++ it('omits a null subscription badge and maps max to Max', () => {+ const { rerender } = render(+ <QuotaHoverCard snapshot={makeSnapshot({ subscriptionType: null })} nowMs={NOW_MS} />,+ );++ expect(screen.queryByTestId('quota-plan-badge')).toBeNull();++ rerender(+ <QuotaHoverCard snapshot={makeSnapshot({ subscriptionType: 'max' })} nowMs={NOW_MS} />,+ );+ expect(screen.getByTestId('quota-plan-badge').textContent).toBe('Max');+ });++ it('renders rejected and warning statuses while omitting allowed', () => {+ const { rerender } = render(+ <QuotaHoverCard snapshot={makeSnapshot({ rateLimitStatus: 'rejected' })} nowMs={NOW_MS} />,+ );++ expect(screen.getByText('已触发套餐限额,请求可能被拒绝')).toBeTruthy();++ rerender(+ <QuotaHoverCard+ snapshot={makeSnapshot({ rateLimitStatus: 'allowed_warning' })}+ nowMs={NOW_MS}+ />,+ );+ expect(screen.getByText('接近套餐限额')).toBeTruthy();+ expect(screen.queryByText('已触发套餐限额,请求可能被拒绝')).toBeNull();++ rerender(+ <QuotaHoverCard snapshot={makeSnapshot({ rateLimitStatus: 'allowed' })} nowMs={NOW_MS} />,+ );+ expect(screen.queryByTestId('quota-status')).toBeNull();+ });++ it('shows only the enabled extra-usage line and never renders undocumented numbers', () => {+ render(+ <QuotaHoverCard+ nowMs={NOW_MS}+ snapshot={makeSnapshot({+ extraUsage: {+ isEnabled: true,+ usedCredits: 1234,+ monthlyLimit: 0,+ },+ })}+ />,+ );++ expect(screen.getByText('quotaCard.extraUsageEnabled')).toBeTruthy();+ expect(screen.queryByText('1234', { exact: false })).toBeNull();+ });++ it('hides present-but-disabled extra usage and its undocumented numbers', () => {+ render(+ <QuotaHoverCard+ nowMs={NOW_MS}+ snapshot={makeSnapshot({+ extraUsage: {+ isEnabled: false,+ usedCredits: 1234,+ },+ })}+ />,+ );++ expect(screen.queryByText('quotaCard.extraUsageEnabled')).toBeNull();+ expect(screen.queryByText('1234', { exact: false })).toBeNull();+ });++ it('renders full turn usage, omits a null section, and hides a null suggestion', () => {+ const { rerender } = render(+ <QuotaHoverCard+ snapshot={null}+ nowMs={NOW_MS}+ turnUsage={{+ costText: '$0.46',+ totalTokensText: '74.1K',+ inputTokensText: '2',+ outputTokensText: '16',+ cacheLineText: '读 0 · 写 74.0K · 命中 0%',+ model: 'claude-opus-5 [1m]',+ suggestionText: '缓存命中率偏低,本轮较多上下文重新计费',+ }}+ />,+ );++ expect(screen.getByText('本轮消耗:$0.46')).toBeTruthy();+ expect(screen.getByText('74.1K', { exact: false })).toBeTruthy();+ expect(screen.getByText('(输入 2 · 输出 16)')).toBeTruthy();+ expect(screen.getByText('读 0 · 写 74.0K · 命中 0%')).toBeTruthy();+ expect(screen.getByText('claude-opus-5 [1m]')).toBeTruthy();+ expect(screen.getByTestId('quota-suggestion')).toBeTruthy();++ rerender(<QuotaHoverCard snapshot={null} nowMs={NOW_MS} turnUsage={null} />);+ expect(screen.queryByTestId('quota-turn-usage')).toBeNull();++ rerender(+ <QuotaHoverCard+ snapshot={null}+ nowMs={NOW_MS}+ turnUsage={{ costText: '$0.46', suggestionText: null }}+ />,+ );+ expect(screen.getByTestId('quota-turn-usage')).toBeTruthy();+ expect(screen.queryByTestId('quota-suggestion')).toBeNull();+ });++ it('保留混合会话金额的合计、实际费用与价值估算拆分', () => {+ render(+ <QuotaHoverCard+ snapshot={null}+ nowMs={NOW_MS}+ sessionUsage={{+ costText: '$0.75',+ costIsEstimate: true,+ actualCostText: '$0.25',+ estimatedValueText: '$0.50',+ }}+ />,+ );++ expect(screen.getByText('本任务 $0.75')).toBeTruthy();+ expect(screen.getByText('本任务已用 $0.25')).toBeTruthy();+ expect(screen.getByText('本任务价值 $0.50')).toBeTruthy();+ });++ it('marks estimated value and separates cumulative totals from final-segment details', () => {+ const { rerender } = render(+ <QuotaHoverCard+ snapshot={null}+ nowMs={NOW_MS}+ turnUsage={{+ costText: '$0.46',+ costIsEstimate: true,+ totalTokensText: '74.1K',+ }}+ />,+ );++ expect(screen.getByText('本轮 token 价值:$0.46')).toBeTruthy();+ expect(screen.queryByText('最后一个 SDK 分段')).toBeNull();++ rerender(+ <QuotaHoverCard+ snapshot={null}+ nowMs={NOW_MS}+ turnUsage={{+ costText: '$0.70',+ isUserTurnTotal: true,+ finalSegment: { costText: '$0.20' },+ totalTokensText: '74.1K',+ }}+ />,+ );++ expect(screen.getByText('最近一轮用户请求累计')).toBeTruthy();+ expect(screen.getByText('本轮消耗:$0.70')).toBeTruthy();+ expect(screen.getByText('最后一个 SDK 分段')).toBeTruthy();+ expect(screen.getByText('本轮消耗:$0.20')).toBeTruthy();+ });++ it('多模型分段逐模型展示费用,不再重复笼统模型行', () => {+ render(+ <QuotaHoverCard+ snapshot={null}+ nowMs={NOW_MS}+ turnUsage={{+ costText: '$0.46',+ model: '2 个模型',+ perModelCost: [+ { model: 'Opus 4.8', costText: '$0.35' },+ { model: 'Haiku 4.5', costText: '$0.11' },+ ],+ }}+ />,+ );++ expect(screen.getByText('按模型拆分:')).toBeTruthy();+ expect(screen.getByText('· Opus 4.8 $0.35')).toBeTruthy();+ expect(screen.getByText('· Haiku 4.5 $0.11')).toBeTruthy();+ expect(screen.queryByText('2 个模型')).toBeNull();+ });++ it('states that cost is unavailable while retaining token, cache, and model rows', () => {+ render(+ <QuotaHoverCard+ snapshot={null}+ nowMs={NOW_MS}+ turnUsage={{+ costText: null,+ totalTokensText: '74.1K',+ inputTokensText: '2',+ outputTokensText: '16',+ cacheLineText: '读 0 · 写 74.0K · 命中 0%',+ model: 'claude-unknown',+ }}+ />,+ );++ expect(screen.getByText('本轮费用暂无法估算')).toBeTruthy();+ expect(screen.getByText('74.1K', { exact: false })).toBeTruthy();+ expect(screen.getByText('读 0 · 写 74.0K · 命中 0%')).toBeTruthy();+ expect(screen.getByText('claude-unknown')).toBeTruthy();+ });++ it('fires the dashboard callback from a real button and hides it for a null label', () => {+ const onOpenDashboard = vi.fn();+ const { rerender } = render(+ <QuotaHoverCard+ snapshot={null}+ nowMs={NOW_MS}+ dashboardLabel="打开 Claude 用量页面"+ onOpenDashboard={onOpenDashboard}+ />,+ );++ const button = screen.getByRole('button', { name: '打开 Claude 用量页面' });+ expect(button.getAttribute('type')).toBe('button');+ expect(button.classList.contains('hover:bg-[var(--surface-hover)]')).toBe(true);+ expect(button.classList.contains('focus-visible:ring-[var(--focus-ring)]')).toBe(true);+ expect(button.classList.contains('focus-visible:ring-offset-[var(--surface-elevated)]')).toBe(+ true,+ );+ fireEvent.click(button);+ expect(onOpenDashboard).toHaveBeenCalledTimes(1);++ rerender(+ <QuotaHoverCard+ snapshot={null}+ nowMs={NOW_MS}+ dashboardLabel={null}+ onOpenDashboard={onOpenDashboard}+ />,+ );+ expect(screen.queryByRole('button')).toBeNull();+ });++ it('多窗口时限制卡片高度并只滚动内容区,动作行保持在滚动区外', () => {+ render(+ <QuotaHoverCard+ snapshot={makeSnapshot({+ fiveHour: { utilization: 10 },+ sevenDay: { utilization: 20 },+ scoped: Array.from({ length: 6 }, (_, index) => ({+ modelDisplayName: `模型 ${index + 1}`,+ utilization: 30 + index,+ })),+ })}+ nowMs={NOW_MS}+ dashboardLabel="打开 Claude 用量页面"+ />,+ );++ 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(scrollContent.classList.contains('min-h-0')).toBe(true);+ expect(scrollContent.classList.contains('overflow-y-auto')).toBe(true);+ expect(scrollContent.contains(dashboardButton)).toBe(false);+ });++ it('让滚动内容区进入 Tab 顺序并提供可访问名称', () => {+ render(<QuotaHoverCard snapshot={makeSnapshot()} nowMs={NOW_MS} />);++ const scrollContent = screen.getByRole('region', { name: '配额窗口列表' });+ expect(scrollContent.tabIndex).toBe(0);+ });++ it('shows a ten-minute stale footnote but omits a one-minute age', () => {+ const { rerender } = render(+ <QuotaHoverCard+ snapshot={makeSnapshot({ updatedAt: NOW_MS - 10 * 60_000 })}+ nowMs={NOW_MS}+ />,+ );++ expect(screen.getByText('quotaCard.staleData:10')).toBeTruthy();++ rerender(+ <QuotaHoverCard snapshot={makeSnapshot({ updatedAt: NOW_MS - 60_000 })} nowMs={NOW_MS} />,+ );+ expect(screen.queryByText('quotaCard.staleData:10')).toBeNull();+ });++ it('shows the stale footnote only after the strict five-minute boundary', () => {+ const { rerender } = render(+ <QuotaHoverCard snapshot={makeSnapshot({ updatedAt: NOW_MS - 5 * 60_000 })} nowMs={NOW_MS} />,+ );++ expect(screen.queryByText('quotaCard.staleData:5')).toBeNull();++ rerender(+ <QuotaHoverCard+ snapshot={makeSnapshot({ updatedAt: NOW_MS - 5 * 60_000 - 1 })}+ nowMs={NOW_MS}+ />,+ );+ expect(screen.getByText('quotaCard.staleData:5')).toBeTruthy();+ });++ // 共享告警谓词把任何非 normal severity 视为告警,卡片的防御性映射不得降级。+ it.each([+ { severity: 'warning', utilization: 50, expected: 'warn' },+ { severity: undefined, utilization: 50, expected: 'normal' },+ { severity: '', utilization: 50, expected: 'normal' },+ { severity: 'unknown-upstream-value', utilization: 50, expected: 'warn' },+ { severity: 'hard_limit', utilization: 50, expected: 'warn' },+ { severity: 'quota_exceeded', utilization: 50, expected: 'crit' },+ { severity: 'critical', utilization: 50, expected: 'crit' },+ { severity: 'normal', utilization: 93, expected: 'crit' },+ ] as const)(+ 'combines server severity $severity and $utilization% utilization as $expected',+ ({ severity, utilization, expected }) => {+ render(+ <QuotaHoverCard+ snapshot={makeSnapshot({ fiveHour: { utilization, severity } })}+ nowMs={NOW_MS}+ />,+ );++ expect(screen.getByText('5 小时').getAttribute('data-severity')).toBe(expected);+ expect(screen.getByRole('progressbar').getAttribute('data-severity')).toBe(expected);+ },+ );++ it('将脏快照中的非字符串 severity 当作缺失值,不让分模型窗口崩溃或升级', () => {+ render(+ <QuotaHoverCard+ snapshot={makeSnapshot({+ scoped: [+ {+ modelDisplayName: 'Opus',+ utilization: 50,+ severity: 123 as unknown as string,+ },+ ],+ })}+ nowMs={NOW_MS}+ />,+ );++ expect(screen.getByText('Opus 周限').getAttribute('data-severity')).toBe('normal');+ expect(+ screen.getByRole('progressbar', { name: 'Opus 周限' }).getAttribute('data-severity'),+ ).toBe('normal');+ });++ it('将脏快照中的非数组 scoped 与非字符串套餐/限额字段当作缺失值,卡片不崩溃', () => {+ render(+ <QuotaHoverCard+ snapshot={makeSnapshot({+ fiveHour: { utilization: 50 },+ scoped: { corrupted: true } as unknown as ClaudeSubscriptionUsageSnapshot['scoped'],+ subscriptionType: 123 as unknown as string,+ rateLimitStatus: 456 as unknown as string,+ })}+ nowMs={NOW_MS}+ />,+ );++ // 有效窗口照常渲染;脏容器与脏字符串字段不产生分模型窗口、套餐徽章或限额行。+ expect(screen.getByText('5 小时')).toBeTruthy();+ expect(screen.getAllByRole('progressbar')).toHaveLength(1);+ expect(screen.queryByTestId('quota-plan-badge')).toBeNull();+ expect(screen.queryByTestId('quota-status')).toBeNull();+ });++ it('按告警级别播报对应措辞,并让进度条使用同一可访问名称', () => {+ const { rerender } = render(+ <QuotaHoverCard+ snapshot={makeSnapshot({ fiveHour: { utilization: 50, severity: 'critical' } })}+ nowMs={NOW_MS}+ />,+ );++ const criticalHint = screen.getByText(/已触发套餐限额,请求可能被拒绝/);+ expect(criticalHint.classList.contains('sr-only')).toBe(true);+ expect(+ screen.getByRole('progressbar', {+ name: /5 小时.*已触发套餐限额,请求可能被拒绝/,+ }),+ ).toBeTruthy();++ rerender(+ <QuotaHoverCard+ snapshot={makeSnapshot({ fiveHour: { utilization: 50, severity: 'warning' } })}+ nowMs={NOW_MS}+ />,+ );++ const warningHint = screen.getByText(/接近套餐限额/);+ expect(warningHint.classList.contains('sr-only')).toBe(true);+ expect(screen.getByRole('progressbar', { name: /5 小时.*接近套餐限额/ })).toBeTruthy();+ });++ it('marks a critical window title with the critical styling hook', () => {+ render(+ <QuotaHoverCard snapshot={makeSnapshot({ sevenDay: { utilization: 93 } })} nowMs={NOW_MS} />,+ );++ const title = screen.getByText('周限');+ expect(title.getAttribute('data-severity')).toBe('crit');+ expect(title.classList.contains('text-[var(--quota-bar-crit)]')).toBe(true);+ expect(screen.getByRole('progressbar').getAttribute('data-severity')).toBe('crit');+ });++ it('keeps an over-limit off-current-model scoped weekly window visible and critical', () => {+ // 非当前模型的分模型周限爆量时,卡片必须可见地告警(不依赖 rateLimitStatus)——补 issue 1300 review advisory。+ render(+ <QuotaHoverCard+ snapshot={makeSnapshot({+ fiveHour: { utilization: 10 },+ sevenDay: { utilization: 20 },+ scoped: [+ {+ modelDisplayName: 'Opus',+ utilization: 93,+ resetsAt: epochSeconds(2026, 7, 8, 10, 0),+ },+ ],+ })}+ nowMs={NOW_MS}+ />,+ );++ const opusTitle = screen.getByText('Opus 周限');+ expect(opusTitle.getAttribute('data-severity')).toBe('crit');+ expect(opusTitle.classList.contains('text-[var(--quota-bar-crit)]')).toBe(true);+ expect(screen.getByText('5 小时').getAttribute('data-severity')).toBe('normal');+ expect(screen.getByText('周限').getAttribute('data-severity')).toBe('normal');+ });+});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.tsxnew file mode 100644index 0000000000..82a6e94a9c--- /dev/null+++ b/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx@@ -0,0 +1,555 @@+// @vitest-environment jsdom++import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { ClaudeSubscriptionUsageSnapshot } from '../../../../shared/claudeSubscriptionUsage';+import type { RegionalMoney } from '../../../../shared/regionalMoney';+import type { SessionUsageMoney } from '@/hooks/useSessionUsageMoney';++const mocks = vi.hoisted(() => ({+ claudeSnapshot: null as ClaudeSubscriptionUsageSnapshot | null,+ displaySnapshot: {+ messages: [] as Array<Record<string, unknown>>,+ },+ sessionUsage: {+ actualMoney: null,+ estimatedValueMoney: null,+ totalMoney: null,+ } as SessionUsageMoney,+ openExternal: vi.fn(() => Promise.resolve()),+ refreshCodexRateLimits: vi.fn(),+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ i18n: { language: 'zh-CN', resolvedLanguage: 'zh-CN' },+ t: (key: string, options: Record<string, string | number> = {}) => {+ const templates: Record<string, string> = {+ 'todaySpend.openClaudeUsage': '打开 Claude 用量页面',+ 'todaySpend.claude.weeklyLabel': '周限',+ 'todaySpend.claude.windowSegment': '{{label}} 剩余 {{remaining}}',+ 'todaySpend.sessionCostLabel': '本任务 {{cost}}',+ 'todaySpend.tooltip.sessionUsed': '本任务已用 {{cost}}',+ 'todaySpend.codex.sessionValueLabel': '本任务价值 {{cost}}',+ 'todaySpend.unit.day': '天',+ 'todaySpend.unit.hour': '小时',+ 'todaySpend.unit.minute': '分钟',+ 'todaySpend.unit.second': '秒',+ 'quotaCard.fiveHourLabel': '5 小时',+ 'quotaCard.weeklyLabel': '周限',+ 'quotaCard.modelWeeklyLabel': '{{model}} 周限',+ 'quotaCard.usedPercent': '已用 {{percent}}%',+ 'quotaCard.resetAt': '{{at}} 重置',+ 'quotaCard.turnCostUnavailable': '本轮费用暂无法估算',+ 'quotaCard.tokenLabel': 'Token',+ 'quotaCard.tokenBreakdown': '(输入 {{input}} · 输出 {{output}})',+ 'quotaCard.cacheLabel': '缓存',+ 'quotaCard.modelLabel': '模型',+ 'quotaCard.waiting': '等待额度数据',+ 'quotaCard.latestMessageTitle': '最近一轮用户请求累计',+ 'chat.messageActionBar.userTurnCostDetailsTitle': '最后一个 SDK 分段',+ 'quotaCard.costLine': '本轮消耗:{{cost}}',+ 'quotaCard.valueLine': '本轮 token 价值:{{cost}}',+ 'quotaCard.noBilledCost': '本轮费用暂不可用,仅显示用量',+ 'usageDetails.costBreakdownHeader': '按模型拆分:',+ 'usageDetails.modelCostLine': '· {{model}} {{cost}}',+ 'usageDetails.cacheLine': '缓存拆分:读取 {{read}} · 写入 {{create}} · 命中率 {{rate}}',+ 'usageDetails.cacheLineNoRate': '缓存拆分:读取 {{read}} · 写入 {{create}}',+ 'usageDetails.multipleModels': '{{count}} 个模型',+ 'usageDetails.suggestion.lowCache': '缓存命中率偏低,本轮较多上下文重新计费',+ };+ return (templates[key] ?? key).replace(/{{(\w+)}}/g, (_, name: string) =>+ String(options[name] ?? ''),+ );+ },+ }),+}));++vi.mock('@/hooks/useApiKey', () => ({+ useApiKey: () => ({ hasSavedKey: false, isReconciling: false }),+}));+vi.mock('@/hooks/useClaudeOAuthConnected', () => ({+ useClaudeOAuthConnected: () => true,+}));+vi.mock('@/hooks/useClaudeSessionRoute', () => ({+ useClaudeSessionRoute: () => null,+}));+vi.mock('@/hooks/useSessionUsageMoney', () => ({+ useSessionUsageMoney: () => mocks.sessionUsage,+}));+vi.mock('@/hooks/useSessionTokens', () => ({ useSessionTokens: () => null }));+vi.mock('@/hooks/useAccountUsage', () => ({+ requestCodexAccountRefresh: vi.fn(),+ useAccountUsage: () => null,+}));+vi.mock('@/hooks/useClaudeAccountUsage', () => ({ useClaudeAccountUsage: () => null }));+vi.mock('@/hooks/useModelAccessCreditUsage', () => ({ useModelAccessCreditUsage: () => null }));+vi.mock('@/hooks/useClaudeSubscriptionUsage', () => ({+ requestClaudeSubscriptionRefresh: vi.fn(),+ useClaudeSubscriptionUsage: () => mocks.claudeSnapshot,+}));+vi.mock('@/hooks/useCodexRuntimeRoute', () => ({+ useCodexRuntimeRoute: () => ({ authInjection: null }),+}));+vi.mock('@/hooks/useCodexRateLimits', () => ({+ useCodexRateLimits: () => ({+ snapshot: null,+ refresh: mocks.refreshCodexRateLimits,+ }),+}));+vi.mock('@/hooks/useXaiRateLimit', () => ({ useXaiRateLimit: () => null }));+vi.mock('@/components/chat/ChatDisplaySnapshotContext', () => ({+ useChatDisplaySnapshot: () => mocks.displaySnapshot,+}));+vi.mock('@/lib/makerChatStore', () => ({+ makerChatStore: {+ getSnapshot: () => mocks.displaySnapshot,+ subscribe: () => () => undefined,+ },+}));++import { TodaySpendChip } from '../TodaySpendChip';++const CLAUDE_USAGE_URL = 'https://claude.ai/settings/usage';+const TURN_USAGE_DETAILS = {+ inputTokens: 2,+ outputTokens: 16,+ cacheReadTokens: 0,+ cacheCreateTokens: 74_000,+ totalTokens: 74_018,+ cacheHitRate: 0,+ model: 'claude-opus-5[1m]',+};++function usdMoney(+ amount: number,+ kind: 'actual-cost' | 'value-estimate' = 'actual-cost',+): RegionalMoney {+ return {+ amount,+ currency: 'USD',+ approximate: kind === 'value-estimate',+ kind,+ };+}++function setLatestUsageMessage(overrides: Record<string, unknown> = {}) {+ mocks.displaySnapshot.messages = [+ {+ role: 'assistant',+ turnMoney: usdMoney(0.46),+ turnUsageDetails: TURN_USAGE_DETAILS,+ ...overrides,+ },+ ];+}++function renderClaudeSubscriptionChip() {+ return render(+ <TodaySpendChip+ vendorKey="cc"+ providerId="anthropic"+ modelId="claude-opus-5[1m]"+ sessionId="session-1"+ />,+ );+}++function openCardFromHover() {+ const trigger = screen.getByRole('button', { name: '打开 Claude 用量页面' });+ fireEvent.mouseEnter(trigger);+ act(() => vi.advanceTimersByTime(300));+ return { trigger, card: screen.getByTestId('quota-hover-card') };+}++beforeEach(() => {+ vi.useFakeTimers();+ setLatestUsageMessage();+ mocks.sessionUsage = {+ actualMoney: null,+ estimatedValueMoney: null,+ totalMoney: null,+ };+ mocks.claudeSnapshot = {+ source: 'oauth-endpoint',+ subscriptionType: 'max',+ sevenDay: { utilization: 34, resetsAt: Date.now() / 1000 + 86_400 },+ };+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: { openExternal: mocks.openExternal },+ });+});++afterEach(() => {+ cleanup();+ vi.clearAllTimers();+ vi.useRealTimers();+ vi.clearAllMocks();+});++describe('TodaySpendChip Claude subscription popover', () => {+ it('悬停约 300ms 后显示额度卡片', () => {+ renderClaudeSubscriptionChip();+ const trigger = screen.getByRole('button', { name: '打开 Claude 用量页面' });++ fireEvent.mouseEnter(trigger);+ act(() => vi.advanceTimersByTime(299));+ expect(screen.queryByTestId('quota-hover-card')).toBeNull();++ act(() => vi.advanceTimersByTime(1));+ expect(screen.getByTestId('quota-hover-card')).toBeTruthy();+ expect(screen.getByRole('progressbar')).toBeTruthy();+ expect(screen.getByText('本轮消耗:$0.46')).toBeTruthy();+ expect(screen.getByText(/^74\.0k/)).toBeTruthy();+ expect(screen.getByText('(输入 2 · 输出 16)')).toBeTruthy();+ expect(screen.getByText('读 0 · 写 74.0k · 命中 0%')).toBeTruthy();+ expect(screen.getByText('claude-opus-5[1m]')).toBeTruthy();+ expect(screen.getByText('缓存命中率偏低,本轮较多上下文重新计费')).toBeTruthy();+ expect(document.activeElement).toBe(document.body);+ });++ it('把输入与输出 Token 分别压缩后再传入卡片', () => {+ setLatestUsageMessage({+ turnUsageDetails: {+ ...TURN_USAGE_DETAILS,+ inputTokens: 74_000,+ outputTokens: 16,+ cacheCreateTokens: 0,+ totalTokens: 74_016,+ },+ });+ renderClaudeSubscriptionChip();+ openCardFromHover();++ expect(screen.getByText(/^74\.0k/)).toBeTruthy();+ expect(screen.getByText('(输入 74.0k · 输出 16)')).toBeTruthy();+ expect(screen.queryByText('(输入 74000 · 输出 16)')).toBeNull();+ });++ it('键盘聚焦打开时把焦点移入卡片,关闭后归还 trigger', () => {+ renderClaudeSubscriptionChip();+ const trigger = screen.getByRole('button', { name: '打开 Claude 用量页面' });++ act(() => trigger.focus());+ const card = screen.getByTestId('quota-hover-card');+ const dashboardButton = within(card).getByRole('button', { name: '打开 Claude 用量页面' });+ expect(document.activeElement).toBe(dashboardButton);++ fireEvent.keyDown(document, { key: 'Escape' });+ expect(screen.queryByTestId('quota-hover-card')).toBeNull();+ expect(document.activeElement).toBe(trigger);+ });++ it('悬停打开后鼠标点击卡片按钮,Escape 关闭时归还 trigger', () => {+ renderClaudeSubscriptionChip();+ const { trigger, card } = openCardFromHover();+ const dashboardButton = within(card).getByRole('button', { name: '打开 Claude 用量页面' });++ fireEvent.mouseDown(dashboardButton);+ // JSDOM 不执行鼠标按下后的浏览器默认聚焦动作,这里显式补齐真实点击序列。+ act(() => dashboardButton.focus());+ fireEvent.mouseUp(dashboardButton);+ fireEvent.click(dashboardButton);+ expect(document.activeElement).toBe(dashboardButton);++ fireEvent.keyDown(document, { key: 'Escape' });+ expect(screen.queryByTestId('quota-hover-card')).toBeNull();+ expect(document.activeElement).toBe(trigger);+ });++ it('卡片内保持键盘焦点时,鼠标移入再移出不会关闭', () => {+ renderClaudeSubscriptionChip();+ const trigger = screen.getByRole('button', { name: '打开 Claude 用量页面' });++ act(() => trigger.focus());+ const card = screen.getByTestId('quota-hover-card');+ const dashboardButton = within(card).getByRole('button', { name: '打开 Claude 用量页面' });+ expect(document.activeElement).toBe(dashboardButton);++ fireEvent.mouseEnter(card);+ fireEvent.mouseLeave(card);+ act(() => vi.advanceTimersByTime(200));++ expect(screen.getByTestId('quota-hover-card')).toBeTruthy();+ expect(document.activeElement).toBe(dashboardButton);+ });++ it('切出 Claude 订阅形态时关闭卡片、清理定时器并归还焦点', () => {+ const { rerender } = renderClaudeSubscriptionChip();+ const trigger = screen.getByRole('button', { name: '打开 Claude 用量页面' });++ act(() => trigger.focus());+ const dashboardButton = within(screen.getByTestId('quota-hover-card')).getByRole('button', {+ name: '打开 Claude 用量页面',+ });+ expect(document.activeElement).toBe(dashboardButton);++ // 卡片已开时再挂一个待执行的 hover-open timer,形态切换必须一并清掉。+ fireEvent.mouseEnter(trigger);+ rerender(+ <TodaySpendChip+ vendorKey="cc"+ providerId="xd"+ modelId="claude-opus-5[1m]"+ sessionId="session-1"+ />,+ );++ expect(screen.queryByTestId('quota-hover-card')).toBeNull();+ const gatewayChip = document.querySelector<HTMLElement>('[tabindex="-1"]');+ expect(gatewayChip).toBeTruthy();+ expect(document.activeElement).toBe(gatewayChip);++ act(() => vi.advanceTimersByTime(300));+ rerender(+ <TodaySpendChip+ vendorKey="cc"+ providerId="anthropic"+ modelId="claude-opus-5[1m]"+ sessionId="session-1"+ />,+ );+ expect(screen.queryByTestId('quota-hover-card')).toBeNull();+ });++ it('Tab 离开卡片后自然保留下一控件的焦点', () => {+ render(+ <>+ <TodaySpendChip+ vendorKey="cc"+ providerId="anthropic"+ modelId="claude-opus-5[1m]"+ sessionId="session-1"+ />+ <button type="button">下一控件</button>+ </>,+ );+ const trigger = screen.getByRole('button', { name: '打开 Claude 用量页面' });++ act(() => trigger.focus());+ const dashboardButton = within(screen.getByTestId('quota-hover-card')).getByRole('button', {+ name: '打开 Claude 用量页面',+ });+ const nextButton = screen.getByRole('button', { name: '下一控件' });+ expect(document.activeElement).toBe(dashboardButton);++ act(() => nextButton.focus());+ act(() => vi.advanceTimersByTime(200));++ expect(screen.queryByTestId('quota-hover-card')).toBeNull();+ expect(document.activeElement).toBe(nextButton);+ });++ it('指针可在宽限期内移入卡片并点击看板动作', () => {+ renderClaudeSubscriptionChip();+ const { trigger, card } = openCardFromHover();++ fireEvent.mouseLeave(trigger);+ act(() => vi.advanceTimersByTime(100));+ fireEvent.mouseEnter(card);+ act(() => vi.advanceTimersByTime(150));++ expect(screen.getByTestId('quota-hover-card')).toBeTruthy();+ fireEvent.click(within(card).getByRole('button', { name: '打开 Claude 用量页面' }));+ expect(mocks.openExternal).toHaveBeenCalledTimes(1);+ expect(mocks.openExternal).toHaveBeenCalledWith(CLAUDE_USAGE_URL);+ });++ it('离开 trigger 和卡片后在宽限期结束时卸载内容', () => {+ renderClaudeSubscriptionChip();+ const { trigger, card } = openCardFromHover();++ fireEvent.mouseLeave(trigger);+ fireEvent.mouseEnter(card);+ fireEvent.mouseLeave(card);+ act(() => vi.advanceTimersByTime(199));+ expect(screen.getByTestId('quota-hover-card')).toBeTruthy();++ act(() => vi.advanceTimersByTime(1));+ expect(screen.queryByTestId('quota-hover-card')).toBeNull();+ });++ it('打开延迟触发前卸载会清理定时器且不更新已卸载组件', () => {+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);++ try {+ const { unmount } = renderClaudeSubscriptionChip();+ const trigger = screen.getByRole('button', { name: '打开 Claude 用量页面' });++ fireEvent.mouseEnter(trigger);+ unmount();+ expect(vi.getTimerCount()).toBe(0);+ act(() => vi.advanceTimersByTime(300));++ expect(errorSpy).not.toHaveBeenCalled();+ } finally {+ errorSpy.mockRestore();+ }+ });++ it('点击 chip 仍只打开一次 Claude 看板', () => {+ renderClaudeSubscriptionChip();++ fireEvent.click(screen.getByRole('button', { name: '打开 Claude 用量页面' }));+ expect(mocks.openExternal).toHaveBeenCalledTimes(1);+ expect(mocks.openExternal).toHaveBeenCalledWith(CLAUDE_USAGE_URL);+ });++ it('把精确费用与估算 token 价值映射成不同文案', () => {+ setLatestUsageMessage({+ turnMoney: usdMoney(0.46),+ turnCostIsEstimate: false,+ });+ const exact = renderClaudeSubscriptionChip();+ openCardFromHover();+ expect(screen.getByText('本轮消耗:$0.46')).toBeTruthy();+ expect(screen.queryByText('本轮 token 价值:$0.46')).toBeNull();++ exact.unmount();+ vi.clearAllTimers();+ setLatestUsageMessage({+ turnMoney: usdMoney(0.46, 'value-estimate'),+ turnCostIsEstimate: true,+ });+ renderClaudeSubscriptionChip();+ openCardFromHover();+ expect(screen.getByText('本轮 token 价值:$0.46')).toBeTruthy();+ expect(screen.queryByText('本轮消耗:$0.46')).toBeNull();+ });++ it('把混合会话合计及实际费用和价值估算拆分传入卡片', () => {+ mocks.sessionUsage = {+ actualMoney: usdMoney(0.25),+ estimatedValueMoney: usdMoney(0.50, 'value-estimate'),+ totalMoney: {+ ...usdMoney(0.75),+ approximate: true,+ estimateReasons: ['subscription-value'],+ },+ };++ renderClaudeSubscriptionChip();+ const { card } = openCardFromHover();+ const sessionSection = within(card).getByTestId('quota-session-usage');++ expect(within(sessionSection).getByText('本任务 $0.75')).toBeTruthy();+ expect(within(sessionSection).getByText('本任务已用 $0.25')).toBeTruthy();+ expect(within(sessionSection).getByText('本任务价值 $0.50')).toBeTruthy();+ expect(screen.getByText('本轮消耗:$0.46')).toBeTruthy();+ });++ it('第三方参考价的近似实际费用仍标为本任务已用', () => {+ const approximateActualMoney: RegionalMoney = {+ ...usdMoney(0.25),+ approximate: true,+ estimateReasons: ['reference-price'],+ };+ mocks.sessionUsage = {+ actualMoney: approximateActualMoney,+ estimatedValueMoney: null,+ totalMoney: approximateActualMoney,+ };++ renderClaudeSubscriptionChip();+ const { card } = openCardFromHover();+ const sessionSection = within(card).getByTestId('quota-session-usage');++ expect(within(sessionSection).getByText('本任务已用 $0.25')).toBeTruthy();+ expect(within(sessionSection).queryByText('本任务价值 $0.25')).toBeNull();+ });++ it('纯订阅价值估算仍标为本任务价值', () => {+ const estimatedValueMoney = usdMoney(0.50, 'value-estimate');+ mocks.sessionUsage = {+ actualMoney: null,+ estimatedValueMoney,+ totalMoney: estimatedValueMoney,+ };++ renderClaudeSubscriptionChip();+ const { card } = openCardFromHover();+ const sessionSection = within(card).getByTestId('quota-session-usage');++ expect(within(sessionSection).getByText('本任务价值 $0.50')).toBeTruthy();+ expect(within(sessionSection).queryByText('本任务已用 $0.50')).toBeNull();+ });++ it('等额累计投影仍分开用户轮累计与最后分段明细', () => {+ setLatestUsageMessage({+ turnMoney: usdMoney(0.46, 'value-estimate'),+ userTurnMoney: usdMoney(0.46, 'value-estimate'),+ turnCostIsEstimate: true,+ userTurnCostIsEstimate: true,+ });+ const equalAmount = renderClaudeSubscriptionChip();+ openCardFromHover();+ expect(screen.getByText('最近一轮用户请求累计')).toBeTruthy();+ expect(screen.getByText('最后一个 SDK 分段')).toBeTruthy();+ expect(screen.getAllByText('本轮 token 价值:$0.46')).toHaveLength(2);++ equalAmount.unmount();+ vi.clearAllTimers();+ setLatestUsageMessage({+ turnMoney: usdMoney(0.20),+ userTurnMoney: usdMoney(0.70),+ turnCostIsEstimate: false,+ userTurnCostIsEstimate: false,+ });+ renderClaudeSubscriptionChip();+ openCardFromHover();+ expect(screen.getByText('最近一轮用户请求累计')).toBeTruthy();+ expect(screen.getByText('本轮消耗:$0.70')).toBeTruthy();+ expect(screen.getByText('最后一个 SDK 分段')).toBeTruthy();+ expect(screen.getByText('本轮消耗:$0.20')).toBeTruthy();+ expect(screen.getByText(/^74\.0k/)).toBeTruthy();+ });++ it('无报价时说明费用不可用并保留 Token、缓存和模型明细', () => {+ setLatestUsageMessage({ turnMoney: undefined });+ renderClaudeSubscriptionChip();+ openCardFromHover();++ expect(screen.getByText('本轮费用暂无法估算')).toBeTruthy();+ expect(screen.getByText(/^74\.0k/)).toBeTruthy();+ expect(screen.getByText('读 0 · 写 74.0k · 命中 0%')).toBeTruthy();+ expect(screen.getByText('claude-opus-5[1m]')).toBeTruthy();+ });++ it('保留最后 SDK 分段的逐模型费用拆分', () => {+ setLatestUsageMessage({+ turnUsageDetails: {+ ...TURN_USAGE_DETAILS,+ models: ['claude-opus-4-8[1m]', 'claude-haiku-4-5-20251001'],+ perModelCost: [+ { model: 'claude-opus-4-8[1m]', money: usdMoney(0.35) },+ { model: 'claude-haiku-4-5-20251001', money: usdMoney(0.11) },+ ],+ },+ });+ renderClaudeSubscriptionChip();+ openCardFromHover();++ expect(screen.getByText('按模型拆分:')).toBeTruthy();+ expect(screen.getByText('· Opus 4.8 $0.35')).toBeTruthy();+ expect(screen.getByText('· Haiku 4.5 $0.11')).toBeTruthy();+ expect(screen.queryByText('claude-opus-5[1m]')).toBeNull();+ });++ it('非 Claude 订阅形态继续使用旧 Tip,不挂载额度卡片', () => {+ render(+ <TodaySpendChip+ vendorKey="cc"+ providerId="xd"+ sessionId="session-1"+ />,+ );++ 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));+ expect(screen.queryByTestId('quota-hover-card')).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 7368ad1dd8..0f2bbfa83b 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -4181,6 +4181,29 @@"latestUserTurnTitle": "Latest user-turn total"}},+ "quotaCard": {+ "fiveHourLabel": "5 hours",+ "weeklyLabel": "Weekly",+ "modelWeeklyLabel": "{{model}} weekly",+ "windowsRegionLabel": "Quota Windows",+ "usedPercent": "Used {{percent}}%",+ "resetAt": "Resets {{at}}",+ "noWindows": "No quota window data available",+ "limitRejected": "Plan limit reached; requests may be rejected",+ "limitWarning": "Approaching plan limit",+ "extraUsageEnabled": "Extra usage enabled",+ "costLine": "Cost this message: {{cost}}",+ "valueLine": "Token value this message: {{cost}}",+ "noBilledCost": "Cost unavailable for this message; showing usage only",+ "latestMessageTitle": "Latest message total",+ "turnCostUnavailable": "Cost unavailable for this message",+ "tokenLabel": "Tokens",+ "tokenBreakdown": "(input {{input}} · output {{output}})",+ "cacheLabel": "Cache",+ "modelLabel": "Model",+ "staleData": "Data updated {{minutes}} minutes ago",+ "waiting": "Claude subscription usage will update after the next request completes."+ },"usageDetails": {"costLine": "Cost this turn: {{cost}}","valueLine": "Token value this turn: {{cost}}",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex e729fe026c..105d10e967 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -4179,6 +4179,29 @@"latestUserTurnTitle": "直近のユーザーターン合計"}},+ "quotaCard": {+ "fiveHourLabel": "5 時間",+ "weeklyLabel": "週間",+ "modelWeeklyLabel": "{{model}} 週間",+ "windowsRegionLabel": "クォータ期間の一覧",+ "usedPercent": "使用済み {{percent}}%",+ "resetAt": "{{at}} にリセット",+ "noWindows": "クォータ期間のデータはありません",+ "limitRejected": "プランの上限に到達しました。リクエストが拒否される可能性があります",+ "limitWarning": "プランの上限に近づいています",+ "extraUsageEnabled": "追加使用量が有効です",+ "costLine": "このメッセージの消費: {{cost}}",+ "valueLine": "このメッセージの token 価値: {{cost}}",+ "noBilledCost": "このメッセージの料金は現在取得できないため、使用量のみ表示しています",+ "latestMessageTitle": "直近のメッセージ合計",+ "turnCostUnavailable": "このメッセージの料金は現在見積もれません",+ "tokenLabel": "Token",+ "tokenBreakdown": "(入力 {{input}} · 出力 {{output}})",+ "cacheLabel": "キャッシュ",+ "modelLabel": "モデル",+ "staleData": "データは {{minutes}} 分前に更新されました",+ "waiting": "Claude サブスクリプションの使用量は次のリクエスト完了後に更新されます。"+ },"usageDetails": {"costLine": "このターンの消費: {{cost}}","valueLine": "このターンの token 価値: {{cost}}",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 2d10501ba3..d861585335 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -4179,6 +4179,29 @@"latestUserTurnTitle": "최근 사용자 턴 합계"}},+ "quotaCard": {+ "fiveHourLabel": "5시간",+ "weeklyLabel": "주간",+ "modelWeeklyLabel": "{{model}} 주간",+ "windowsRegionLabel": "할당량 구간 목록",+ "usedPercent": "사용 {{percent}}%",+ "resetAt": "{{at}} 재설정",+ "noWindows": "할당량 구간 데이터가 없습니다",+ "limitRejected": "플랜 한도에 도달하여 요청이 거부될 수 있습니다",+ "limitWarning": "플랜 한도에 근접했습니다",+ "extraUsageEnabled": "추가 사용량 활성화됨",+ "costLine": "이번 메시지 비용: {{cost}}",+ "valueLine": "이번 메시지 토큰 가치: {{cost}}",+ "noBilledCost": "이번 메시지의 비용을 현재 확인할 수 없어 사용량만 표시합니다",+ "latestMessageTitle": "최근 메시지 합계",+ "turnCostUnavailable": "이 메시지의 비용을 현재 추정할 수 없습니다",+ "tokenLabel": "Token",+ "tokenBreakdown": "(입력 {{input}} · 출력 {{output}})",+ "cacheLabel": "캐시",+ "modelLabel": "모델",+ "staleData": "데이터가 {{minutes}}분 전에 업데이트되었습니다",+ "waiting": "Claude 구독 사용량은 다음 요청이 완료된 후 업데이트됩니다."+ },"usageDetails": {"costLine": "이번 턴 비용: {{cost}}","valueLine": "이번 턴 토큰 가치: {{cost}}",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 16fac33a07..746505b728 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -4179,6 +4179,29 @@"latestUserTurnTitle": "最近一轮用户请求累计"}},+ "quotaCard": {+ "fiveHourLabel": "5 小时",+ "weeklyLabel": "周限",+ "modelWeeklyLabel": "{{model}} 周限",+ "windowsRegionLabel": "配额窗口列表",+ "usedPercent": "已用 {{percent}}%",+ "resetAt": "{{at}} 重置",+ "noWindows": "暂无配额窗口数据",+ "limitRejected": "已触发套餐限额,请求可能被拒绝",+ "limitWarning": "接近套餐限额",+ "extraUsageEnabled": "额外用量已启用",+ "costLine": "本轮消耗:{{cost}}",+ "valueLine": "本轮 token 价值:{{cost}}",+ "noBilledCost": "本轮费用暂不可用,仅显示用量",+ "latestMessageTitle": "最近一轮用户请求累计",+ "turnCostUnavailable": "本轮费用暂无法估算",+ "tokenLabel": "Token",+ "tokenBreakdown": "(输入 {{input}} · 输出 {{output}})",+ "cacheLabel": "缓存",+ "modelLabel": "模型",+ "staleData": "数据更新于 {{minutes}} 分钟前",+ "waiting": "Claude 订阅余量会在下一轮完成后更新。"+ },"usageDetails": {"costLine": "本轮消耗:{{cost}}","valueLine": "本轮 token 价值:{{cost}}",diff --git a/apps/desktop/src/renderer/lib/turnUsageTooltip.ts b/apps/desktop/src/renderer/lib/turnUsageTooltip.tsindex 16d3c77add..4a752413fb 100644--- a/apps/desktop/src/renderer/lib/turnUsageTooltip.ts+++ b/apps/desktop/src/renderer/lib/turnUsageTooltip.ts@@ -47,7 +47,7 @@ function modelLabel(details: TurnUsageDetails, t: TFunction): string | null {const LOW_CACHE_MIN_INPUT_TOKENS = 50_000;const LOW_CACHE_MAX_HIT_RATE = 0.2;-function suggestion(details: TurnUsageDetails, t: TFunction): string | null {+export function getTurnUsageSuggestion(details: TurnUsageDetails, t: TFunction): string | null {const inputTotal = details.inputTokens + details.cacheReadTokens + details.cacheCreateTokens;if (inputTotal >= LOW_CACHE_MIN_INPUT_TOKENS &&@@ -108,7 +108,7 @@ export function buildTurnUsageTooltipLines({const model = modelLabel(details, t);if (model) lines.push(t('usageDetails.modelLine', { model }));}- const suggestionText = suggestion(details, t);+ const suggestionText = getTurnUsageSuggestion(details, t);if (suggestionText) {lines.push(t('usageDetails.suggestionLine', { suggestion: suggestionText }));}diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.cssindex 2f656107d3..793601fa3d 100644--- a/apps/desktop/src/renderer/styles/globals.css+++ b/apps/desktop/src/renderer/styles/globals.css@@ -58,6 +58,19 @@--motion-ease-out: cubic-bezier(0.16, 1, 0.3, 1); /* 入场/展开 */--motion-ease-in: cubic-bezier(0.4, 0, 1, 1); /* 退场 */--motion-ease-move: cubic-bezier(0.4, 0, 0.2, 1); /* 位置/尺寸插值 */++ /* Claude 额度条的首帧 alias 与 ColorRegistry 一致:只复用已批准语义槽。 */+ --quota-bar-fill: var(--text-secondary);+ --quota-bar-warn: var(--warning-fg);+ --quota-bar-crit: var(--error-flat);+ --quota-bar-track: var(--surface-chip);+ }++ .dark {+ --quota-bar-fill: var(--text-secondary);+ --quota-bar-warn: var(--warning-fg);+ --quota-bar-crit: var(--error-flat);+ --quota-bar-track: var(--surface-chip);}body {diff --git a/apps/desktop/src/renderer/themes/colors.ts b/apps/desktop/src/renderer/themes/colors.tsindex 801c138947..9049bdb384 100644--- a/apps/desktop/src/renderer/themes/colors.ts+++ b/apps/desktop/src/renderer/themes/colors.ts@@ -1288,6 +1288,25 @@ registerColor('annotation-accent', {dark: '#FF3B30',}, 'Annotation Red — 与烧录笔迹同色,语义豁免');+// Claude 额度条只保留组件 alias;色值收敛到已批准的中性 / 告警语义槽,+// 让内置与导入主题都跟随同一语义,不再冻结一组独立暖色。+registerColor('quota-bar-fill', {+ light: 'var(--text-secondary)',+ dark: 'var(--text-secondary)',+}, 'Claude 额度条正常填充(alias 到中性次要文字色)');+registerColor('quota-bar-warn', {+ light: 'var(--warning-fg)',+ dark: 'var(--warning-fg)',+}, 'Claude 额度条警告填充(alias 到已批准 warning 前景)');+registerColor('quota-bar-crit', {+ light: 'var(--error-flat)',+ dark: 'var(--error-flat)',+}, 'Claude 额度条临界填充(alias 到已批准 error 前景)');+registerColor('quota-bar-track', {+ light: 'var(--surface-chip)',+ dark: 'var(--surface-chip)',+}, 'Claude 额度条轨道(alias 到中性 chip 表面)');+// Running Status Bar (F-SDK-3)registerColor('status-bar-accent', {light: 'var(--warning-accent)',