Skip to content

armgit / cindy

Public Imported from GitHub
0

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

87.2 KB
Raw Blame
import { useCodexRateLimitReset } from '@/hooks/useCodexRateLimitReset';
import { CodexResetCredits } from './CodexResetCredits';
import {
  FIVE_HOUR_WINDOW_MINUTES,
  formatCompactTimeUntilReset,
  WEEKLY_WINDOW_MINUTES,
} from '@/lib/compactQuotaCountdown';
import { isCodexGatewayWireModel, isOpenAiSubscriptionProvider, type AgentKind } from '@cindy/model-providers';
import { providerDisplayNameById } from '@/lib/providerDisplayName';
import { useDeviceProviders } from '@/hooks/useDeviceProviders';
import { useProviders } from '@/hooks/useProviders';
/**
 * TodaySpendChip — 右下角用量指示器与所有渠道共用的悬浮卡片入口。
 *
 * 主指标显示当前渠道的配额与任务累计金额,详情统一交给 QuotaHoverCard。
 * 供应商快照在 usageCardModel 中投影;实际费用、订阅价值估算与 Token 保持各自语义。
 * 订阅点击打开对应看板;无看板的渠道点击查看卡片。远程任务不借用本机账号配额。
 */

import React from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import { X } from 'lucide-react';
import { Tip } from '@/components/ui/tooltip';
import { Button } from '@/components/ui/button';
import { useTranslation } from 'react-i18next';
import type { TFunction } from 'i18next';
import { summarizeCodexRateLimitReset } from '@cindy/maker-shared/session-controls';

import { cn } from '@/lib/utils';
import { handOffTabFromCard } from '@/lib/focusTraversal';
import { TASK_USAGE_ACCOUNT, type UsageAccountLocation } from '@/lib/usageAccountLocation';
import {
  DAILY_SOFT_LIMIT_FACTOR,
  formatCompactMoney,
  formatCompactTokens,
  formatModelShort,
  formatTurnCostMoney,
  formatTurnCostUsd,
} from '@/lib/usageFormat';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
  registerStatusBarCard,
  STATUS_CARD_HOVER_OPEN_DELAY_MS,
  STATUS_CARD_HOVER_CLOSE_GRACE_MS,
  type StatusBarCardHandle,
} from '@/lib/statusBarCards';
import { useApiKey } from '@/hooks/useApiKey';
import { useClaudeOAuthConnected } from '@/hooks/useClaudeOAuthConnected';
import { useClaudeSessionRoute } from '@/hooks/useClaudeSessionRoute';
import { useSessionUsageMoney, type SessionUsageMoney } from '@/hooks/useSessionUsageMoney';
import { useSessionTokens } from '@/hooks/useSessionTokens';
import { useChatDisplaySnapshot } from '@/components/chat/ChatDisplaySnapshotContext';
import {
  requestCodexAccountRefresh,
  useAccountUsage,
  type RateLimitSnapshot,
} from '@/hooks/useAccountUsage';
import {
  useClaudeAccountUsage,
  type ClaudeAccountUsageSnapshot,
} from '@/hooks/useClaudeAccountUsage';
import { useModelAccessCreditUsage } from '@/hooks/useModelAccessCreditUsage';
import { resolveCreditTotals, type CreditTotals } from '@/lib/creditPoolTotals';
import {
  requestClaudeSubscriptionRefresh,
  useClaudeSubscriptionUsage,
  type ClaudeSubscriptionUsageSnapshot,
} from '@/hooks/useClaudeSubscriptionUsage';
import {
  requestRemoteClaudeSubscriptionRefresh,
  useRemoteClaudeSubscriptionUsage,
} from '@/hooks/useRemoteClaudeSubscriptionUsage';
import { useRemoteClaudeSessionRoute } from '@/hooks/useRemoteClaudeSessionRoute';
import {
  requestRemoteCodexAccountRefresh,
  requestRemoteXaiSubscriptionRefresh,
  selectRemoteCodexAccountUsage,
  useRemoteClaudeAccountUsage,
  useRemoteCodexAccountUsage,
  useRemoteXaiRateLimit,
  useRemoteXaiSubscriptionUsage,
} from '@/hooks/useRemoteDeviceUsage';
import {
  isClaudeSubscriptionAlerting,
  isClaudeUsageWindowAlerting,
  matchScopedWindowForModel,
  type ClaudeUsageWindow,
} from '../../../shared/claudeSubscriptionUsage';
import { useCodexRuntimeRoute } from '@/hooks/useCodexRuntimeRoute';
import { useCodexRateLimits } from '@/hooks/useCodexRateLimits';
import { useXaiRateLimit } from '@/hooks/useXaiRateLimit';
import {
  requestXaiSubscriptionRefresh,
  useXaiSubscriptionUsage,
  type XaiSubscriptionUsageSnapshot,
} from '@/hooks/useXaiSubscriptionUsage';
import {
  isXaiSubscriptionAlerting,
  isXaiWeeklyUsageCurrent,
} from '../../../shared/xaiSubscriptionUsage';
import { makerChatStore, type ChatMessage } from '@/lib/makerChatStore';
import {
  formatOutputTokenRate,
  formatTurnDuration,
  getTurnUsageSuggestion,
} from '@/lib/turnUsageTooltip';
import { aggregateAssistantTurnUsageDetails } from '@/lib/userTurnUsage';
import type { TurnUsageDetails } from '../../../shared/turnUsageDetails';
import {
  DEFAULT_USAGE_CURRENCY,
  gatewayMoney,
  type RegionalMoney,
} from '../../../shared/regionalMoney';
import { CHATGPT_MODEL_PREFIX, XAI_MODEL_PREFIX } from '../../../shared/subscriptionModels';
import {
  RESET_PENDING_MAX_MS,
  computeCountdownTickDelayMs,
  useQuotaResetRollup,
  type ChipWindowSlot,
} from './quotaResetRollup';
import {
  QuotaHoverCard,
  type QuotaHoverCardSessionUsage,
  type QuotaHoverCardTurnUsage,
} from './QuotaHoverCard';
import { QuotaResetConfetti } from './QuotaResetConfetti';
import { quotaFullCelebrations } from './quotaFullCelebrations';
import {
  buildClaudeUsageCard,
  buildCodexUsageCard,
  buildDeepSeekUsageCard,
  buildXaiUsageCard,
  buildZhipuUsageCard,
  type UsageCardAccount,
} from './usageCardModel';
import { useProviderAccountUsage } from '@/hooks/useProviderAccountUsage';
import {
  getProviderAccountUsageDashboardUrlView,
  hasDeepSeekOfficialRouteView,
  isZhipuCodingPlanProviderView,
} from '@/lib/providerAccountUsageView';
import { type ProviderAccountUsageSnapshot, type ZhipuCodingPlanQuotaSnapshot } from '../../../shared/providerAccountUsage';

// XD 网关 / 托管账号之前会跳到内部用量看板(内部域名)—— 开源前移除该硬编码。
// 登录随凭据只下发 { endpoint, apiKey }(见 main/model-access/credentialsSync.ts),不含
// 看板地址;推理 endpoint 与看板 console 不同源、无法从中推导。故网关账号暂无看板可跳
// (点击无反应)。
// TODO(后续): 若 model-access-server 在下发凭据时附带看板地址(按个人 / 企业租户区分的
// usageDashboardUrl / consoleUrl),据此恢复网关账号的跳转 + tooltip 链接行
// (i18n 文案 todaySpend.openProxyUsage 已保留待复用,勿当死 key 删)。
const CODEX_USAGE_DASHBOARD_URL = 'https://chatgpt.com/codex/settings/usage';
const XAI_USAGE_DASHBOARD_URL = 'https://grok.com';
const CLAUDE_USAGE_DASHBOARD_URL = 'https://claude.ai/settings/usage';

type MetricKey = 'daily' | 'monthly' | 'credit' | 'session';
// credit 排在 session 左边 —— 账号额度是"还能用多少"的前提, 本对话花费是它的增量。
// daily / monthly 与 credit 来自服务端两种不同的额度语义(周期配额 vs 额度池账本),
// 按账号所属租户二选一下发, 两组互斥, 同一形态下不会都占位。
const PRIMARY_GATEWAY_METRICS: readonly MetricKey[] = ['daily', 'credit', 'session'];
const DEFAULT_MONEY_SYMBOL = DEFAULT_USAGE_CURRENCY === 'CNY' ? '¥' : '$';
const DEFAULT_MONEY_PLACEHOLDER = `${DEFAULT_MONEY_SYMBOL}—`;

// 软日限额系数 + 紧凑金额格式化已抽到 lib/usageFormat.ts (与首页仪表盘共用同口径)。

/** chip / tooltip 共用: 一个 metric 的最终展示形态。 */
interface MetricSlot {
  /** "今日 $47/$300" / "本会话 $3.03" 这种成品字符串, 可用直接 render。 */
  label: string;
  /** tooltip 里使用的解释文案;不填则复用 label。 */
  tooltipLabel?: string;
  /** 是否有数据 — false 时不参与渲染 (无论 chip 还是 tooltip), 由调用方过滤。 */
  available: boolean;
}

/**
 * 把候选 metric 一次性算好 (label + 是否可用)。
 *   - daily / monthly: 需 claudeQuota 在线 (LiteLLM 语义租户); 否则 available=false
 *   - credit: 需三池账本汇总出非零总额 (个人租户); 否则 available=false
 *   - session: 需 sessionCostUsd > 0; 否则 available=false
 *
 * chip 段 / tooltip 段都从这里拿, 主显指标固定, 其它可用指标进 tooltip。
 */
function computeMetricSlots(
  claudeQuota: ClaudeAccountUsageSnapshot | null,
  creditTotals: CreditTotals | null,
  sessionLabel: string | null,
  t: TFunction,
): Record<MetricKey, MetricSlot> {
  const slots: Record<MetricKey, MetricSlot> = {
    daily: {
      label: t('todaySpend.dailyLimitLabel', {
        spend: DEFAULT_MONEY_PLACEHOLDER,
        limit: DEFAULT_MONEY_PLACEHOLDER,
      }),
      available: false,
    },
    monthly: {
      label: t('todaySpend.monthlyLimitLabel', {
        spend: DEFAULT_MONEY_PLACEHOLDER,
        limit: DEFAULT_MONEY_PLACEHOLDER,
      }),
      available: false,
    },
    credit: {
      label: t('todaySpend.creditLabel', {
        used: DEFAULT_MONEY_PLACEHOLDER,
        total: DEFAULT_MONEY_PLACEHOLDER,
      }),
      available: false,
    },
    session: {
      label: t('todaySpend.sessionCostLabel', { cost: DEFAULT_MONEY_PLACEHOLDER }),
      available: false,
    },
  };

  // 额度池账本没有周期概念(订阅发放 + 充值 + 赠送), 所以不派生日均软限额。
  // 账本历史缺失的池按余额兜底(见 resolveCreditTotals), 保证「总额 − 已用」恒等于
  // 设置页那个可用余额, chip 上永远是两个数、不退化成单值。
  //
  // 币种走 gatewayMoney 的默认值(DEFAULT_USAGE_CURRENCY = 按发行区域)。这三池是
  // Cindy 自己的计费账本, 与账单页 BILLING_CURRENCY 同一笔钱、必须同口径 —— 不能
  // 改用 Gateway 目录下发的币种, 否则同一笔余额在两个界面显示成不同货币。
  if (creditTotals) {
    const used = formatCompactMoney(gatewayMoney(creditTotals.used));
    const total = formatCompactMoney(gatewayMoney(creditTotals.total));
    slots.credit = {
      label: t('todaySpend.creditLabel', { used, total }),
      tooltipLabel: t('todaySpend.tooltip.creditUsed', { used, total }),
      available: true,
    };
  }

  if (claudeQuota && claudeQuota.maxBudget > 0) {
    // monthly 永远跟 cycle 一起拿到; daily 走单独 endpoint 可能拉不到 (todaySpend=null) → 隐藏
    slots.monthly = {
      label: t('todaySpend.monthlyLimitLabel', {
        spend: formatCompactMoney(gatewayMoney(claudeQuota.spend, claudeQuota.currency)),
        limit: formatCompactMoney(gatewayMoney(claudeQuota.maxBudget, claudeQuota.currency)),
      }),
      available: true,
    };
    if (claudeQuota.dailyLimitEnabled !== false && typeof claudeQuota.todaySpend === 'number') {
      const softLimit = (claudeQuota.maxBudget / 30) * DAILY_SOFT_LIMIT_FACTOR;
      slots.daily = {
        label: t('todaySpend.dailyLimitLabel', {
          spend: formatCompactMoney(gatewayMoney(claudeQuota.todaySpend, claudeQuota.currency)),
          limit: formatCompactMoney(gatewayMoney(softLimit, claudeQuota.currency)),
        }),
        available: true,
      };
    }
  }

  if (sessionLabel) {
    slots.session = {
      label: sessionLabel,
      tooltipLabel: sessionLabel,
      available: true,
    };
  }

  return slots;
}

function clampPercent(value: number): number {
  if (!Number.isFinite(value)) return 0;
  return Math.min(100, Math.max(0, value));
}

function formatPercent(value: number): string {
  const clamped = clampPercent(value);
  if (Math.abs(clamped - Math.round(clamped)) < 0.05) return `${Math.round(clamped)}%`;
  return `${clamped.toFixed(1).replace(/\.0$/, '')}%`;
}

/** epoch 秒 → ms;无效值 → null(重置滚动动画与 tick 节奏都以 ms 为准)。 */
function toEpochMs(epochSeconds: number | null | undefined): number | null {
  if (typeof epochSeconds !== 'number' || !Number.isFinite(epochSeconds) || epochSeconds <= 0) {
    return null;
  }
  return epochSeconds * 1000;
}

/**
 * chip 上一个限额窗口段的素材: 倒计时 label + 数值化剩余百分比 + 窗口身份/reset
 * 时点(useQuotaResetRollup 检测重置并驱动 0% → 100% 滚动动画的输入)。
 * Codex 订阅与 Claude 订阅两种形态共用, 成品字符串在组件里统一格式化。
 */
interface ChipWindowSegment extends ChipWindowSlot {
  label: string;
  /**
   * 倒计时已过点、快照还停在上个周期 —— 悬念期: 段显示「重置中…」(呼吸省略号)
   * 而不是僵住的旧百分比, 新快照落地时由重置滚动动画揭晓。
   */
  resetPending: boolean;
  /** 本窗口自身达到告警条件:chip 只把这一段的剩余百分比染红, 其余段保持常色。 */
  alerting: boolean;
}

// 悬念期上限常量在 quotaResetRollup.ts(tick 节奏要踩着超时边界调度, 判定与
// 调度共用同一 RESET_PENDING_MAX_MS)。超时回落旧值 + 窗口名展示后, 新快照
// 到达时重置滚动动画照常触发。

/**
 * 悬念期判定: 有 reset 时点且已过(未超时), 快照仍是过点前的旧周期数据。
 * 超时侧用严格小于 —— tick 调度会把一跳精确排在超时边界上
 * (computeCountdownTickDelayMs), 边界 tick 必须判定为「已超时」当场退出悬念,
 * 含等号会让它再等一轮慢 tick(多挂最长一分钟)。
 */
function isResetPending(resetsAtMs: number | null, nowMs: number): boolean {
  return (
    typeof resetsAtMs === 'number' &&
    resetsAtMs <= nowMs &&
    nowMs - resetsAtMs < RESET_PENDING_MAX_MS
  );
}

function formatWindowLabel(
  window: RateLimitSnapshot['primary'],
  fallback: string,
  t: TFunction,
  nowMs: number,
  options?: { preferResetCountdown?: boolean },
): string {
  // chip 模式: label 直接用距 reset 的剩余时长(所有限额窗口都算给用户);
  // 无 reset 数据时回退下面的窗口名派生链。tooltip 模式不进这个分支(窗口名 + 精确时间)。
  if (options?.preferResetCountdown) {
    const countdown = formatCompactTimeUntilReset(
      window?.resetsAt,
      nowMs,
      t,
      window?.windowMinutes,
    );
    if (countdown !== null) return countdown;
  }

  const minutes = window?.windowMinutes;
  if (typeof minutes !== 'number' || !Number.isFinite(minutes) || minutes <= 0) {
    return fallback;
  }
  if (minutes % (24 * 60) === 0) {
    const days = minutes / (24 * 60);
    if (options?.preferResetCountdown || days < 7) {
      return t('todaySpend.codex.daysWindow', { days });
    }
  }
  if (minutes >= 7 * 24 * 60) return t('todaySpend.codex.weekWindow');
  if (minutes % 60 === 0) return `${minutes / 60}h`;
  return `${Math.round(minutes)}m`;
}

/** Codex 订阅 chip 的单个窗口段素材;窗口缺失 / 百分比不可解析 → null。 */
function toCodexChipWindow(
  slotKey: 'primary' | 'secondary',
  window: RateLimitSnapshot['primary'],
  t: TFunction,
  nowMs: number,
): ChipWindowSegment | null {
  if (!window || typeof window.usedPercent !== 'number' || !Number.isFinite(window.usedPercent)) {
    return null;
  }
  const resetsAtMs = toEpochMs(window.resetsAt);
  return {
    // 身份 key 带 windowMinutes: 上游调整窗口策略(如换掉 5h 窗)时视为新窗口,
    // 只重置动画基线, 不误触重置滚动。
    key: `codex-${slotKey}:${window.windowMinutes ?? 'na'}`,
    label: formatWindowLabel(window, t('todaySpend.codex.limitWindow'), t, nowMs, {
      preferResetCountdown: true,
    }),
    remainingPercent: 100 - clampPercent(window.usedPercent),
    resetsAtMs,
    resetPending: isResetPending(resetsAtMs, nowMs),
    alerting: false,
  };
}

/** chip 段素材 (Codex 订阅): label 是距 reset 的倒计时(最后一分钟逐秒走动)。 */
function getCodexChipWindows(
  snapshot: RateLimitSnapshot | null,
  t: TFunction,
  nowMs: number,
): ChipWindowSegment[] {
  if (!snapshot) return [];
  return [
    toCodexChipWindow('primary', snapshot.primary, t, nowMs),
    toCodexChipWindow('secondary', snapshot.secondary, t, nowMs),
  ]
    .filter((v): v is ChipWindowSegment => Boolean(v))
    .map((window) => ({
      ...window,
      // 相同长度的窗口也可能属于不同账号、数据源或模型桶,不能跨额度比较。
      key: JSON.stringify([
        window.key,
        snapshot.accountId ?? null,
        snapshot.source ?? null,
        snapshot.limitId ?? null,
      ]),
    }));
}

function getGatewayChipSegments(slots: Record<MetricKey, MetricSlot>): string[] {
  return PRIMARY_GATEWAY_METRICS.filter((key) => slots[key].available).map(
    (key) => slots[key].label,
  );
}

function hasPositiveSessionTokens(sessionTokens: number | null): boolean {
  return typeof sessionTokens === 'number' && Number.isFinite(sessionTokens) && sessionTokens > 0;
}

function getCodexApiEmptyState(
  latestTurnUsage: LatestTurnUsageSummary | null,
): 'no-usage' | 'unavailable' {
  // A completed assistant turn without a persisted USD/token value means the
  // session has usage data, but the billing data has not been recovered yet.
  return latestTurnUsage ? 'unavailable' : 'no-usage';
}

// ── Claude 订阅 (Anthropic OAuth) 形态 ───────────────────────────────────────
// 主 chip 方案 B: 5h 剩余% · 当前模型周限剩余% (weekly_scoped 按模型家族匹配, 匹配
// 不到回退总周限并标注口径) · 本会话价值 $。utilization 语义 = 已用百分比 (0-100)。

/**
 * 当前会话生效的周限窗口: 命中当前模型的 weekly_scoped 条目优先 (label 带模型名,
 * 如 "Fable 周限"), 否则回退总周限 —— 两种 label 口径可区分, 绝不臆造数字。
 * modelDisplayName 仅 scoped 命中时有, chip 倒计时 label 用它拼「Fable 7天」。
 */
function resolveClaudeWeeklyWindow(
  snapshot: ClaudeSubscriptionUsageSnapshot,
  modelId: string | null | undefined,
  t: TFunction,
): { label: string; window: ClaudeUsageWindow; modelDisplayName?: string } | null {
  const scoped = matchScopedWindowForModel(snapshot.scoped, modelId);
  if (scoped) {
    return {
      label: t('todaySpend.claude.modelWeeklyLabel', { model: scoped.modelDisplayName }),
      window: scoped,
      modelDisplayName: scoped.modelDisplayName,
    };
  }
  if (snapshot.sevenDay) {
    return { label: t('todaySpend.claude.weeklyLabel'), window: snapshot.sevenDay };
  }
  return null;
}

/**
 * chip 段素材 (方案 B + 倒计时 label): 窗口 label 直接用距 reset 的剩余时长 ——
 * 「3小时 剩余 45% · Fable 7天 剩余 78%」;scoped 命中时时长前带模型名标注口径。
 * 无 reset 数据回退窗口名 (5h / Fable 周限 / 周限), 绝不显示算不出的时间。
 * 剩余百分比留数值形态, 由组件经 useQuotaResetRollup(重置滚动动画)后再格式化。
 */
function getClaudeChipWindows(
  snapshot: ClaudeSubscriptionUsageSnapshot | null,
  modelId: string | null | undefined,
  t: TFunction,
  nowMs: number,
): ChipWindowSegment[] {
  if (!snapshot) return [];
  const windows: ChipWindowSegment[] = [];
  const fiveHour = snapshot.fiveHour;
  if (
    fiveHour &&
    typeof fiveHour.utilization === 'number' &&
    Number.isFinite(fiveHour.utilization)
  ) {
    const countdown = formatCompactTimeUntilReset(
      fiveHour.resetsAt,
      nowMs,
      t,
      FIVE_HOUR_WINDOW_MINUTES,
    );
    const resetsAtMs = toEpochMs(fiveHour.resetsAt);
    windows.push({
      key: 'claude-5h',
      label: countdown ?? '5h',
      remainingPercent: 100 - clampPercent(fiveHour.utilization),
      resetsAtMs,
      resetPending: isResetPending(resetsAtMs, nowMs),
      alerting: isClaudeUsageWindowAlerting(fiveHour),
    });
  }
  const weekly = resolveClaudeWeeklyWindow(snapshot, modelId, t);
  if (
    weekly &&
    typeof weekly.window.utilization === 'number' &&
    Number.isFinite(weekly.window.utilization)
  ) {
    const countdown = formatCompactTimeUntilReset(
      weekly.window.resetsAt,
      nowMs,
      t,
      WEEKLY_WINDOW_MINUTES,
    );
    const label = countdown
      ? weekly.modelDisplayName
        ? `${weekly.modelDisplayName} ${countdown}`
        : countdown
      : weekly.label;
    const resetsAtMs = toEpochMs(weekly.window.resetsAt);
    windows.push({
      // 身份 key 区分总周限与各 scoped 周限: 切模型导致窗口切换时只重置动画基线。
      key: weekly.modelDisplayName
        ? `claude-weekly:${weekly.modelDisplayName}`
        : 'claude-weekly:total',
      label,
      remainingPercent: 100 - clampPercent(weekly.window.utilization),
      resetsAtMs,
      resetPending: isResetPending(resetsAtMs, nowMs),
      alerting: isClaudeUsageWindowAlerting(weekly.window),
    });
  }
  return windows.map((window) => ({
    ...window,
    key: JSON.stringify([window.key, snapshot.accountFingerprint ?? null]),
  }));
}

/** 智谱 GLM Coding Plan chip 窗口段(与 Claude 形态同构:5 小时 + 每周)。 */
function getZhipuChipWindows(
  snapshot: ZhipuCodingPlanQuotaSnapshot | null,
  t: TFunction,
  nowMs: number,
): ChipWindowSegment[] {
  if (!snapshot) return [];
  const windows: ChipWindowSegment[] = [];
  const push = (
    key: string,
    window: { usedPercent: number; resetsAt: number | null } | null,
    fallbackLabel: string,
    windowMinutes: number,
  ) => {
    if (!window || !Number.isFinite(window.usedPercent)) return;
    const resetsAtMs =
      typeof window.resetsAt === 'number' && window.resetsAt > 0 ? window.resetsAt : null;
    const countdown = formatCompactTimeUntilReset(
      resetsAtMs != null ? resetsAtMs / 1000 : null,
      nowMs,
      t,
      windowMinutes,
    );
    const remainingPercent = 100 - clampPercent(window.usedPercent);
    windows.push({
      key,
      label: countdown ?? fallbackLabel,
      remainingPercent,
      resetsAtMs,
      resetPending: isResetPending(resetsAtMs, nowMs),
      alerting: remainingPercent <= 20,
    });
  };
  push('zhipu-5h', snapshot.fiveHour, '5h', FIVE_HOUR_WINDOW_MINUTES);
  push('zhipu-weekly', snapshot.weekly, t('quotaCard.weeklyLabel'), WEEKLY_WINDOW_MINUTES);
  return windows;
}

// 告警判定 (chip 变红的口径 + allowed_warning 为何不染红、为何不用 representativeClaim
// 的取舍) 已收进 shared/claudeSubscriptionUsage.ts 的
// isClaudeSubscriptionAlerting (纯数据判定, 有直接单测)。

/** 最近一轮 tooltip 使用的 assistant 消息明细。 */
interface LatestTurnUsageSummary {
  money?: RegionalMoney;
  costUsd?: number;
  isEstimate?: boolean;
  isUserTurnTotal: boolean;
  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;

  return {
    costText,
    costIsEstimate: summary.isEstimate,
    isUserTurnTotal: summary.isUserTurnTotal,
    totalTokensText: formatCompactTokens(Math.max(0, Math.floor(details.totalTokens))),
    inputTokensText: formatCompactTokens(details.inputTokens),
    outputTokensText: formatCompactTokens(details.outputTokens),
    outputRateText: formatOutputTokenRate(details),
    turnDurationText:
      typeof details.turnDurationMs === 'number'
        ? formatTurnDuration(details.turnDurationMs, t)
        : null,
    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,
  sessionTokens: number | null,
): QuotaHoverCardSessionUsage | null {
  const { actualMoney, estimatedValueMoney, totalMoney } = sessionUsage;
  if (
    !actualMoney?.amount &&
    !estimatedValueMoney?.amount &&
    !hasPositiveSessionTokens(sessionTokens)
  )
    return null;

  return {
    costText: totalMoney?.amount ? formatTurnCostMoney(totalMoney) : null,
    tokensText: hasPositiveSessionTokens(sessionTokens)
      ? formatCompactTokens(Math.floor(sessionTokens!))
      : null,
    // approximate 只说明金额精度,不能把第三方参考价的实际费用改成订阅价值语义。
    // 纯价值估算优先信任 kind;兼容旧投影时再以唯一存在的估值分量兜底。
    costIsEstimate:
      totalMoney?.kind === 'value-estimate' ||
      Boolean(!actualMoney?.amount && estimatedValueMoney?.amount),
    ...(actualMoney?.amount ? { actualCostText: formatTurnCostMoney(actualMoney) } : {}),
    ...(estimatedValueMoney?.amount
      ? { estimatedValueText: formatTurnCostMoney(estimatedValueMoney) }
      : {}),
  };
}

function findLatestTurnUsageSummary(messages: ChatMessage[]): LatestTurnUsageSummary | null {
  for (let i = messages.length - 1; i >= 0; i--) {
    const message = messages[i];
    if (message.role !== 'assistant' || !message.turnUsageDetails) continue;
    const userTurnMoney = message.userTurnMoney?.amount ? message.userTurnMoney : undefined;
    const userTurnCostUsd =
      typeof message.userTurnCostUsd === 'number' && message.userTurnCostUsd > 0
        ? message.userTurnCostUsd
        : undefined;
    const displayedMoney = userTurnMoney ?? message.turnMoney;
    return {
      ...(userTurnMoney
        ? { money: userTurnMoney }
        : userTurnCostUsd != null
          ? { costUsd: userTurnCostUsd }
          : message.turnMoney?.amount
            ? { money: message.turnMoney }
            : typeof message.turnCostUsd === 'number' && message.turnCostUsd > 0
              ? { costUsd: message.turnCostUsd }
              : {}),
      ...((userTurnMoney || userTurnCostUsd != null
        ? message.userTurnCostIsEstimate
        : message.turnCostIsEstimate) === true || displayedMoney?.kind === 'value-estimate'
        ? { isEstimate: true }
        : {}),
      isUserTurnTotal: Boolean(userTurnMoney || userTurnCostUsd != null),
      // Amount and token/model detail now describe the same visible user turn.
      // Raw segment costs remain persisted for billing and analytics, but are
      // an implementation detail rather than a second user-facing total.
      details:
        aggregateAssistantTurnUsageDetails(messages, message.clientId) ?? message.turnUsageDetails,
    };
  }
  return null;
}

function useLatestTurnUsageSummary(sessionId: string | undefined): LatestTurnUsageSummary | null {
  const displaySnapshot = useChatDisplaySnapshot(sessionId);
  const displaySummary = React.useMemo(
    () => (displaySnapshot ? findLatestTurnUsageSummary(displaySnapshot.messages) : null),
    [displaySnapshot],
  );
  const [summary, setSummary] = React.useState<LatestTurnUsageSummary | null>(() => {
    if (!sessionId) return null;
    return findLatestTurnUsageSummary(makerChatStore.getSnapshot(sessionId).messages);
  });

  React.useEffect(() => {
    if (displaySnapshot) return undefined;
    if (!sessionId) {
      setSummary(null);
      return undefined;
    }
    const update = () => {
      setSummary(findLatestTurnUsageSummary(makerChatStore.getSnapshot(sessionId).messages));
    };
    update();
    return makerChatStore.subscribe(sessionId, update);
  }, [displaySnapshot, sessionId]);

  return displaySnapshot ? displaySummary : summary;
}

function getXaiChipWindows(
  snapshot: XaiSubscriptionUsageSnapshot | null,
  t: TFunction,
  nowMs: number,
): ChipWindowSegment[] {
  if (!isXaiWeeklyUsageCurrent(snapshot, nowMs) || !snapshot) return [];
  const used = snapshot.creditUsagePercent ?? 0;
  // xAI 的 resetsAt 可能回退到非周窗口 / 月度账期结束时间, 不按周长封顶。
  const countdown = formatCompactTimeUntilReset(snapshot.resetsAt ?? undefined, nowMs, t);
  const resetsAtMs = toEpochMs(snapshot.resetsAt ?? undefined);
  return [
    {
      key: JSON.stringify(['xai-weekly', snapshot.accountFingerprint ?? null]),
      label: countdown ?? t('todaySpend.xai.weeklyLabel'),
      remainingPercent: 100 - clampPercent(used),
      resetsAtMs,
      resetPending: isResetPending(resetsAtMs, nowMs),
      alerting: isXaiSubscriptionAlerting(snapshot, nowMs),
    },
  ];
}

/** 文案里剩余百分比的占位符: 先整句翻译, 再把它换成独立节点, 语序跟随各语言。 */
const REMAINING_PLACEHOLDER = '\uE000';

function interpolateRemaining(text: string, remaining: React.ReactNode): React.ReactNode {
  const index = text.indexOf(REMAINING_PLACEHOLDER);
  if (index < 0) return text;
  return (
    <>
      {text.slice(0, index)}
      {remaining}
      {text.slice(index + REMAINING_PLACEHOLDER.length)}
    </>
  );
}

/** DeepSeek chip 主指标:首币种总余额(如「余额 ¥194.06」);无快照 → null。 */
function formatDeepSeekBalanceSegment(
  snapshot: ProviderAccountUsageSnapshot | null,
  t: TFunction,
  locale?: string,
): string | null {
  if (!snapshot || snapshot.kind !== 'deepseek-balance') return null;
  const line = snapshot.balances[0];
  if (!line) return null;
  let balance = `${line.totalBalance} ${line.currency}`;
  try {
    const formatter = new Intl.NumberFormat(locale, {
      style: 'currency',
      currency: line.currency,
      maximumFractionDigits: 2,
    });
    balance = (formatter.format as unknown as (input: string) => string)(line.totalBalance);
  } catch {
    // 非法货币码等:退回原始数字 + 货币码。
  }
  return t('providerAccountUsage.deepSeek.chipBalance', { balance });
}

function renderSegmentedLabel(segments: React.ReactNode[]): React.ReactNode {
  return segments.map((seg, i) => (
    <React.Fragment key={i}>
      {i > 0 && (
        <span aria-hidden="true" className="mx-2 inline-block h-3 w-px bg-current opacity-30" />
      )}
      <span className="tabular-nums">{seg}</span>
    </React.Fragment>
  ));
}

interface TodaySpendChipProps {
  vendorKey?: 'cc' | 'codex' | 'pi';
  /** 当前会话模型;codex/ 折扣 GPT 恒走 gateway API, 即使 oauth-bearer spawn 也按 API 形态显示。 */
  modelId?: string | null;
  /**
   * 本会话显式选定的供应商('anthropic' / 'openai' / 'xd' / null=默认路由)。
   * 决定计费形态:cc 选了 'anthropic' = 走订阅(抑制网关 quota);cc 默认路由的形态由
   * 本机有无网关 key 决定(无 key → proxy 直连 Anthropic, 同为订阅);codex 选了 'xd'
   * = 走网关(显示当前 region 币种)。与 register.ts 的
   * isClaudeSubscriptionSession / isSubscriptionValue 同口径。
   */
  providerId?: string | null;
  /** session 金额初值;展示层会与消息中的价值估算合并,不依赖当前 provider。 */
  sessionId?: string;
  /** 来自 session.totalCostUsd(sessionService.get 拿到)— mount 后由 IPC push 更新。 */
  sessionInitialMoney?: RegionalMoney | null;
  sessionInitialCostUsd?: number | null;
  /** 来自 session.totalTokenUsage(sessionService.get 拿到)— mount 后由 IPC push 更新。 */
  sessionInitialTokens?: number | null;
  /** 远端 Codex 由远端 daemon 路由,本机不能拿本地 app-server route / 账号快照来归类。 */
  remoteHostId?: string | null;
  /**
   * device-link 远程会话所属被控端 id(与 SSH remoteHostId 互斥)。非空 = turn 实际跑在
   * 被控端、消耗**被控端**账号的额度 —— 本机的 ChatGPT 账户快照 / xAI 限流快照与之无关,
   * 必须抑制本地账号读取(否则 chip 显示的是控制端账号的用量,张冠李戴)。
   */
  deviceLinkDeviceId?: string | null;
  /**
   * 本轮消耗哪台电脑的账号额度(远程 Agent 让 Agent 在另一台电脑运行,见 usageAccountLocation)。
   * 缺省 = 任务所在电脑:本机任务读本机,deviceLinkDeviceId 非空时读被控端。
   */
  usageAccount?: UsageAccountLocation;
}

export function TodaySpendChip({
  vendorKey = 'cc',
  modelId,
  providerId,
  sessionId,
  sessionInitialMoney,
  sessionInitialCostUsd,
  sessionInitialTokens,
  remoteHostId,
  deviceLinkDeviceId,
  usageAccount = TASK_USAGE_ACCOUNT,
}: TodaySpendChipProps) {
  const { t, i18n } = useTranslation();
  const formatterLocale = i18n.resolvedLanguage ?? i18n.language;
  // 账号余量从哪台电脑读:Agent 在任务所在电脑时就是那台(本机,或 deviceLinkDeviceId 的被控端);
  // 远程 Agent 在另一台电脑时是那台(经 device-link 读它的镜像,与模型选择器同一份)。
  // 读不到那份账号(别人分享的供应商等)时本机与远端都不读,只显示任务价值。
  const accountDeviceId =
    usageAccount.kind === 'device'
      ? usageAccount.deviceId
      : usageAccount.kind === 'task'
        ? (deviceLinkDeviceId ?? null)
        : null;
  const accountUnreadable = usageAccount.kind === 'unreadable';
  // 账号不在本机(device-link 远程会话 / 远程 Agent):turn 消耗另一台电脑的账号,计费形态
  // (订阅/网关)与账号余量的事实都在那台 —— 本机的 route 观察 / 账号快照与之无关,一律不读、
  // 不据此分类。
  const isDeviceLinkRemote = Boolean(accountDeviceId) || accountUnreadable;
  const { authInjection: codexAuthInjection } = useCodexRuntimeRoute({
    enabled: vendorKey === 'codex' && !isDeviceLinkRemote,
    refreshKey: sessionId,
  });
  // cc 订阅判定对齐 main 的 isClaudeSubscriptionSession(register.ts)+ proxy 实际路由:
  //   - 显式选 Anthropic 供应商 → 订阅直连(Claude 模型直连 api.anthropic.com,
  //     LiteLLM 看不到, gateway quota 不代表真实花费, 抑制 daily/monthly 展示);
  //   - 默认路由(providerId=null)→ **优先用 proxy 观察到的会话生效路由**
  //     (claude-session-route-registry, 每请求真值):cc 子进程凭证在 spawn 时冻结,
  //     用全局活性凭证状态重算会与实际路由发散(典型:gateway-spawn 会话跑着时
  //     连上 OAuth 并清掉网关 key, child 仍拿冻结的 x-api-key 走网关)。
  //   - 会话尚未发过请求(无观察值)→ 回落活性启发式「无网关 key 且连了 Claude
  //     OAuth = 订阅」:此时下一次 spawn 恰按当前凭证决定, 启发式即正确预测
  //     (main 计费侧不需要观察值: SDK 网关轮自报 costUsd>0, 天然不会误打订阅行)。
  // 网关 key 存在性经 useApiKey 读(与 main readClaudeApiKey 同一 safeStorage key,
  // 自带跨实例广播 + auth-change 刷新)。无观察值且 key reconcile / OAuth 首查未完成
  // 时默认路由形态未定 —— 不判订阅也不放行网关 quota 读, 避免 chip 先按一种形态
  // 渲染再闪切(规则 7)。
  // 远端 Claude 会话的额度事实在远端,本机订阅 / Gateway 快照都不能用于展示。
  const isRemoteClaudeSession = vendorKey === 'cc' && Boolean(remoteHostId);
  // device-link 远程会话不参与默认路由观察:本机 proxy 永远看不到被控端会话的请求,
  // 用本机 OAuth / 网关 key 状态推断只会张冠李戴(形态由下方 device-link 专属分支接管)。
  const isDefaultRouteClaudeSession =
    vendorKey === 'cc' && !isRemoteClaudeSession && !isDeviceLinkRemote && providerId == null;
  const { hasSavedKey: hasGatewayKey, isReconciling: gatewayKeyReconciling } = useApiKey();
  const claudeOAuthConnected = useClaudeOAuthConnected(isDefaultRouteClaudeSession);
  const observedClaudeRoute = useClaudeSessionRoute(sessionId, isDefaultRouteClaudeSession);
  const ccBillingFormPending =
    isDefaultRouteClaudeSession &&
    observedClaudeRoute == null &&
    (gatewayKeyReconciling || (!hasGatewayKey && claudeOAuthConnected == null));
  const { providers: localQuotaProviders } = useProviders();
  const { providers: deviceQuotaProviders } = useDeviceProviders(accountDeviceId ?? undefined);
  const quotaProviders = isDeviceLinkRemote ? deviceQuotaProviders : localQuotaProviders;
  const selectedQuotaProvider = quotaProviders.find((provider) => provider.id === providerId);
  const isClaudeAccount =
    providerId === 'anthropic' || selectedQuotaProvider?.auth?.native === 'claude';
  const isXaiAccount = providerId === 'xai' || selectedQuotaProvider?.auth?.native === 'xai';
  // Remote provider ids belong to the device running the Agent. Reuse its existing provider
  // catalog (also used by the model selector), never the controller's same-named account.
  const isDeviceLinkRemoteBridgeModel =
    typeof modelId === 'string' &&
    (modelId.startsWith(CHATGPT_MODEL_PREFIX) || modelId.startsWith(XAI_MODEL_PREFIX));
  // 默认路由只在被控端自己跑 Agent 时有观察值:远程 Agent 必带来源(没来源按读不到处理),
  // 走不到这里。
  const remoteClaudeRoute = useRemoteClaudeSessionRoute(
    isDeviceLinkRemote && vendorKey === 'cc' && providerId == null && !isDeviceLinkRemoteBridgeModel
      ? accountDeviceId
      : null,
    sessionId,
  );
  const isDeviceLinkRemoteClaudeSubscription =
    isDeviceLinkRemote &&
    (vendorKey === 'cc' || vendorKey === 'pi' || vendorKey === 'codex') &&
    (isClaudeAccount ||
      (vendorKey === 'cc' &&
        providerId == null &&
        !isDeviceLinkRemoteBridgeModel &&
        remoteClaudeRoute === 'subscription'));
  const isClaudeSubscription =
    isDeviceLinkRemoteClaudeSubscription ||
    (!isDeviceLinkRemote &&
      ((vendorKey === 'cc' &&
        !isRemoteClaudeSession &&
        (isClaudeAccount ||
          (providerId == null &&
            (observedClaudeRoute != null
              ? observedClaudeRoute === 'subscription'
              : !gatewayKeyReconciling && !hasGatewayKey && claudeOAuthConnected === true)))) ||
        // Pi 的 provider 在创建会话时已经显式固化,不需要再从 CC proxy route 猜。
        ((vendorKey === 'pi' || vendorKey === 'codex') && !remoteHostId && isClaudeAccount)));
  // cc 走「订阅直连 bridge」= model 带 chatgpt/ / xai/ 前缀(经本地 responses-bridge 打用户个人
  // 订阅额度,真实计费恒 0,gateway quota 与之无关):
  //   - chatgpt/ → 与 codex 同一 ChatGPT 账户,复用 codex 订阅 chip 形态(限额窗口 + 价值估算);
  //   - xai/    → SuperGrok 账号周用量(cli-chat-proxy billing) + 尽力显示限流头。
  // 优先级高于 Claude 订阅形态(model 前缀决定实际消耗的额度)。
  const isOpenAiAccount =
    providerId === 'openai' || isOpenAiSubscriptionProvider(selectedQuotaProvider);
  const isChatgptBridge =
    (vendorKey === 'cc' || vendorKey === 'pi') &&
    (providerId == null || isOpenAiAccount) &&
    typeof modelId === 'string' &&
    modelId.startsWith(CHATGPT_MODEL_PREFIX);
  // SuperGrok 周用量是账号级。Pi catalog 的模型 id 是 grok-4.6,没有 xai/ 前缀,
  // 只靠前缀会漏掉「显式选了 xAI」的 Pi/CC 会话(设置页看得到、chip 没有)。
  const isXaiPrefixedModel = typeof modelId === 'string' && modelId.startsWith(XAI_MODEL_PREFIX);
  const isXaiBridge =
    (vendorKey === 'cc' || vendorKey === 'pi') &&
    (isXaiAccount || (providerId == null && isXaiPrefixedModel));
  const isSubscriptionBridge = isChatgptBridge || isXaiBridge;
  const isRemoteCodexSession = vendorKey === 'codex' && Boolean(remoteHostId);
  const isCodexBudgetModel = typeof modelId === 'string' && isCodexGatewayWireModel(modelId);
  const isCodexGatewayBudgetModel =
    isCodexBudgetModel && (providerId == null || providerId === 'xd');
  const isCodexXaiProvider =
    vendorKey === 'codex' && (isXaiAccount || (providerId == null && isXaiPrefixedModel));
  // 显式 OpenAI 订阅连接在执行端固定走该账号的 OAuth(独立账号有自己的 host)。
  // 全局 authInjection 只用于未指定来源的旧任务,不能因本机 Codex 断开或其它
  // API host 的状态隐藏所选账号的额度。xAI 由 proxy 注入 SuperGrok OAuth。
  // 远端 Codex 的事实在远端 daemon 上,本机只记录 token 价值估算,不写本地 gateway cost。
  // device-link 远程 codex 与 SSH 远程同口径:非 xai / 非折扣模型 / 非显式 XD 即按订阅
  // 形态处理(本机 runtime route 观察对远程关闭,窗口数据走被控端镜像;被控端若是
  // API 模式,其账号快照为空,chip 与 SSH 远程一样只显示价值估算)。
  const isDeviceLinkRemoteCodexOauth =
    isDeviceLinkRemote &&
    vendorKey === 'codex' &&
    !isCodexXaiProvider &&
    !isCodexGatewayBudgetModel &&
    (providerId == null || isOpenAiAccount);
  const isCodexOauth =
    vendorKey === 'codex' &&
    !isCodexXaiProvider &&
    (isRemoteCodexSession ||
      isDeviceLinkRemoteCodexOauth ||
      (!isCodexGatewayBudgetModel &&
        (isOpenAiAccount || (providerId == null && codexAuthInjection === 'oauth-bearer'))));
  const isCodexSubscription = isCodexOauth || isCodexXaiProvider;
  const isCodexApi = vendorKey === 'codex' && !isCodexSubscription;
  const isPiGateway =
    vendorKey === 'pi' &&
    !remoteHostId &&
    !isDeviceLinkRemote &&
    (providerId == null || providerId === 'xd') &&
    !isClaudeSubscription &&
    !isChatgptBridge &&
    !isXaiBridge;
  // codex-oauth 与 cc+chatgpt/ bridge 共用同一 ChatGPT 账户 → 同一套限额窗口 chip 渲染。
  const usesCodexQuotaForm = isCodexOauth || isChatgptBridge;
  const usesXaiQuotaForm = isCodexXaiProvider || isXaiBridge;
  // 远程会话不读本机账户快照 —— 额度事实在远端:SSH 用 remoteHostId 判,device-link 与
  // 远程 Agent 用 isDeviceLinkRemote 判(任一成立即远程,turn 消耗的是远端账号的额度)。
  const isAnyRemoteSession = Boolean(remoteHostId) || isDeviceLinkRemote;
  // API Key 计费供应商(DeepSeek 余额 / 智谱 Coding Plan 额度):只认本机会话且显式选中
  // 该供应商的形态;额度事实在本机账户,远程会话不借用(口径同订阅形态)。
  const usesDeepSeekAccountForm =
    !isAnyRemoteSession && Boolean(hasDeepSeekOfficialRouteView(selectedQuotaProvider));
  const usesZhipuCodingPlanForm =
    !isAnyRemoteSession && Boolean(isZhipuCodingPlanProviderView(selectedQuotaProvider));
  const usesProviderAccountUsageForm = usesDeepSeekAccountForm || usesZhipuCodingPlanForm;
  // 会话所在引擎 → 查询用 runtime:同一供应商各引擎可用不同账户的独立密钥,
  // 余额/配额必须对准当前会话实际路由的账户(vendorKey 缺省 = 默认路由,不传)。
  const providerAccountAgent: AgentKind | undefined =
    vendorKey === 'cc'
      ? 'claude-code'
      : vendorKey === 'codex'
        ? 'codex'
        : vendorKey === 'pi'
          ? 'pi'
          : undefined;
  const providerAccountUsage = useProviderAccountUsage(
    usesProviderAccountUsageForm && providerAccountAgent ? selectedQuotaProvider : undefined,
    providerAccountAgent,
  );
  const providerAccountSnapshot =
    providerAccountUsage.result?.status === 'ready' ? providerAccountUsage.result.snapshot : null;
  // Model Access 配额只属于实际走 XD/Cindy AI Gateway 的本地会话。显式自定义供应商即使
  // 复用了 env-key / oauth-bearer host,也不能据 host 的启动凭证把 /v2/user/info 串进来。
  const isClaudeGateway =
    vendorKey === 'cc' &&
    !isAnyRemoteSession &&
    !isSubscriptionBridge &&
    !ccBillingFormPending &&
    (providerId === 'xd' ||
      (providerId == null &&
        (observedClaudeRoute != null
          ? observedClaudeRoute === 'gateway'
          : !gatewayKeyReconciling && hasGatewayKey)));
  const isCodexGateway =
    vendorKey === 'codex' &&
    !isAnyRemoteSession &&
    !isCodexSubscription &&
    (providerId === 'xd' ||
      (providerId == null &&
        (codexAuthInjection === 'env-key' ||
          isCodexGatewayBudgetModel ||
          (codexAuthInjection === 'provider-oauth' && hasGatewayKey))));
  const usesGatewayQuota = isClaudeGateway || isCodexGateway || isPiGateway;
  // device-link 远程网关形态:显式 XD / codex 折扣模型 / pi 默认(provider 创建时固化,
  // 空即 XD)直接判;cc 默认路由用被控端路由观察镜像。数据走被控端 LiteLLM 配额镜像,
  // 本机 quota hook(usesGatewayQuota)对远程保持关闭;credit 三池 handler 绑定主窗口
  // sender 不镜像 —— 按本机「拿不到就隐藏」的既有降级语义,credit 行远程不显示。
  const isDeviceLinkRemoteGateway =
    isDeviceLinkRemote &&
    ((vendorKey === 'cc' &&
      !isSubscriptionBridge &&
      (providerId === 'xd' ||
        (providerId == null &&
          !isDeviceLinkRemoteBridgeModel &&
          remoteClaudeRoute === 'gateway'))) ||
      (vendorKey === 'codex' &&
        !isCodexSubscription &&
        (providerId === 'xd' || isCodexGatewayBudgetModel)) ||
      (vendorKey === 'pi' &&
        !isClaudeSubscription &&
        !isSubscriptionBridge &&
        (providerId == null || providerId === 'xd')));
  const shouldReadLocalCodexAccountUsage = usesCodexQuotaForm && !isAnyRemoteSession;
  // 会话金额只由已发生的 turn 决定,不由当前选中的 provider/模型决定。实际费用从
  // session ledger 读取,订阅价值从消息明细重建,再统一汇总成“本对话”投影。
  const sessionUsage = useSessionUsageMoney(sessionId, sessionInitialMoney, sessionInitialCostUsd);
  const sessionTokens = useSessionTokens(
    vendorKey === 'pi' ||
      isCodexApi ||
      isCodexSubscription ||
      isSubscriptionBridge ||
      isDeviceLinkRemote ||
      Boolean(deviceLinkDeviceId)
      ? sessionId
      : undefined,
    sessionInitialTokens,
  );
  // 按会话形态选配额槽: chatgpt/ bridge 消耗 WHAM(openai-web)报告的配额,
  // Codex CLI 会话消耗 app-server 报告的配额 —— 不跨槽回退, 绝不显示不是这个
  // 会话在消耗的配额(账号多限额桶会互相污染, 见 useAccountUsage 头注释)。
  const localAccountUsage = useAccountUsage(
    sessionId,
    shouldReadLocalCodexAccountUsage ? 'codex' : undefined,
    isChatgptBridge ? 'openai-web' : 'app-server',
    // app-server 形态下据当前模型匹配限额桶(账号可能同时有主配额桶与模型专属
    // 促销桶, 见 useAccountUsage.matchCodexBucketForModel)。
    modelId,
    providerId ?? 'openai',
  );
  // device-link 远程 codex / chatgpt-bridge:账号所在电脑的权威组合 payload 镜像,选槽 / 选桶
  // 与本机同口径在消费点执行(selectRemoteCodexAccountUsage)。
  const remoteCodexAccountPayload = useRemoteCodexAccountUsage(
    isDeviceLinkRemote && usesCodexQuotaForm ? accountDeviceId : null,
    providerId ?? 'openai',
  );
  const accountUsage = isDeviceLinkRemote
    ? selectRemoteCodexAccountUsage(
        remoteCodexAccountPayload,
        isChatgptBridge ? 'openai-web' : 'app-server',
        modelId,
      )
    : localAccountUsage;
  const { snapshot: codexRateLimits, refresh: refreshCodexRateLimits } = useCodexRateLimits(
    usesCodexQuotaForm && !isAnyRemoteSession,
    providerId ?? 'openai',
  );
  const manualReset = useCodexRateLimitReset(codexRateLimits, refreshCodexRateLimits, providerId ?? 'openai');
  // xAI 限流快照同为本机 main 抓的 —— SSH 远程仍抑制回落价值估算;device-link 远程
  // 走被控端镜像(订阅周用量 invoke + push,限流头 push-only,与本机同语义降级)。
  // 本机侧按所选供应商账号取(多账号供应商,#4197 / #4246:限流 hook 同样带 providerId)。
  const remoteXaiDeviceId = isDeviceLinkRemote && usesXaiQuotaForm ? accountDeviceId : null;
  const localXaiRateLimit = useXaiRateLimit(
    usesXaiQuotaForm && !isAnyRemoteSession,
    providerId ?? 'xai',
  );
  const remoteXaiRateLimit = useRemoteXaiRateLimit(remoteXaiDeviceId, providerId ?? 'xai');
  const xaiRateLimit = isDeviceLinkRemote ? remoteXaiRateLimit : localXaiRateLimit;
  const localXaiSubscriptionUsage = useXaiSubscriptionUsage(
    usesXaiQuotaForm && !isAnyRemoteSession,
    providerId ?? 'xai',
  );
  const remoteXaiSubscriptionUsage = useRemoteXaiSubscriptionUsage(
    remoteXaiDeviceId,
    providerId ?? 'xai',
  );
  const xaiSubscriptionUsage = isDeviceLinkRemote
    ? remoteXaiSubscriptionUsage
    : localXaiSubscriptionUsage;
  // 只有实际 Gateway 会话读取同一把 XD key 的 LiteLLM quota。订阅与自定义供应商
  // 均只展示各自的额度/本地会话统计,不读取 Model Access 账号配额。
  const localClaudeQuota = useClaudeAccountUsage(usesGatewayQuota);
  const remoteClaudeQuota = useRemoteClaudeAccountUsage(
    isDeviceLinkRemoteGateway ? accountDeviceId : null,
  );
  const claudeQuota = isDeviceLinkRemote ? remoteClaudeQuota : localClaudeQuota;
  // 个人租户的额度事实在 Gateway 三池账本里(推理入口不提供管理面接口), 与上面的
  // LiteLLM quota 是两种租户的两种语义, 各自拿不到就各自隐藏 —— 不互相兜底。
  const creditUsage = useModelAccessCreditUsage(usesGatewayQuota);
  const creditTotals = React.useMemo(() => resolveCreditTotals(creditUsage), [creditUsage]);
  // Claude 订阅账号余量 (5h/周/分模型窗口, 端点 + proxy 旁路 headers 双源)。bridge 模型形态
  // 优先(不消耗 Claude 订阅额度),此时不读。device-link 远程会话 / 远程 Agent 读账号所在
  // 电脑的镜像,本机快照与其无关(额度事实在那台),两个 hook 的 enabled 互斥。
  const localClaudeSubscriptionUsage = useClaudeSubscriptionUsage(
    isClaudeSubscription && !isSubscriptionBridge && !isDeviceLinkRemote,
    providerId ?? 'anthropic',
  );
  const remoteClaudeSubscriptionUsage = useRemoteClaudeSubscriptionUsage(
    isDeviceLinkRemoteClaudeSubscription && !isSubscriptionBridge ? accountDeviceId : null,
    providerId ?? 'anthropic',
  );
  const claudeSubscriptionUsage = isDeviceLinkRemote
    ? remoteClaudeSubscriptionUsage
    : localClaudeSubscriptionUsage;
  const latestTurnUsage = useLatestTurnUsageSummary(sessionId);
  const quotaCardSessionUsage = toQuotaHoverCardSessionUsage(sessionUsage, sessionTokens);
  const quotaCardTurnUsage = toQuotaHoverCardTurnUsage(latestTurnUsage, t);
  const [quotaPopoverOpen, setQuotaPopoverOpen] = React.useState(false);
  // 浮层宿主:紧跟触发器之后(见 popover.tsx 的 portalContainer 注释)。portal 到 body
  // 末尾时,键盘焦点一旦进卡就再也 Tab 不回底栏(用户实测)。
  const [quotaPopoverPortalHost, setQuotaPopoverPortalHost] = React.useState<HTMLDivElement | null>(
    null,
  );
  const [resetListOpen, setResetListOpen] = 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 quotaPopoverContentRef = React.useRef<HTMLDivElement>(null);
  const quotaPopoverDashboardButtonRef = React.useRef<HTMLButtonElement>(null);
  // 底栏卡片互斥协调器的本实例句柄(见 statusBarCards:认实例,不认种类)。
  const statusCardHandleRef = React.useRef<StatusBarCardHandle | null>(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;
    // Tab 已把焦点交给卡片外**仍然存在**的控件时不要抢回触发器:关闭路径
    // (focus-outside → onOpenChange(false))会比浏览器的 Tab 目标更早执行,抢回焦点
    // 就把 Tab 正要去的控件顶掉,实测表现为焦点在 trigger 与卡片之间反复弹、永远走不到
    // 右边下一枚 chip(用户实测)。焦点在卡片里(Escape)、或卡片正在卸载而焦点即将掉
    // 到 body(形态切换)时,照旧归还 —— 那两种情况下不归还就是用户丢焦点。
    const activeElement = document.activeElement;
    const focusStillOwned =
      quotaPopoverTriggerRef.current === activeElement ||
      quotaPopoverContentRef.current?.contains(activeElement) === true;
    const focusLostOrDetached =
      activeElement === null || activeElement === document.body || !activeElement.isConnected;
    if (!focusStillOwned && !focusLostOrDetached) return;
    quotaPopoverRestoringFocusRef.current = true;
    quotaPopoverTriggerRef.current?.focus({ preventScroll: true });
    quotaPopoverRestoringFocusRef.current = false;
  }, []);
  const openQuotaPopoverImmediately = React.useCallback(() => {
    keepQuotaPopoverOpen();
    quotaPopoverOpenSourceRef.current = 'focus';
    setWindowLabelNowMs(Date.now());
    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';
      setWindowLabelNowMs(Date.now());
      setQuotaPopoverOpen(true);
    }, STATUS_CARD_HOVER_OPEN_DELAY_MS);
  }, [clearQuotaPopoverCloseTimer, clearQuotaPopoverOpenTimer]);
  const scheduleQuotaPopoverClose = React.useCallback(() => {
    clearQuotaPopoverOpenTimer();
    clearQuotaPopoverCloseTimer();
    quotaPopoverCloseTimerRef.current = window.setTimeout(() => {
      quotaPopoverCloseTimerRef.current = null;
      setQuotaPopoverOpen(false);
      restoreQuotaPopoverFocus();
    }, STATUS_CARD_HOVER_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]);

  // 底栏状态卡片互斥(用户要求"该窗体为唯一窗体"):本卡展开时请求独占(另一张立刻收起),
  // 收起时让位;另一张卡展开时由协调器回调到这里立刻收起。
  // 句柄认**本实例**:分屏可能同时挂载多份底栏,按种类登记会互相顶掉关闭回调。
  React.useEffect(() => {
    const handle = registerStatusBarCard('quota', () => {
      keepQuotaPopoverOpen();
      setQuotaPopoverOpen(false);
      restoreQuotaPopoverFocus();
    });
    statusCardHandleRef.current = handle;
    return () => {
      statusCardHandleRef.current = null;
      handle.unregister();
    };
  }, [keepQuotaPopoverOpen, restoreQuotaPopoverFocus]);
  React.useEffect(() => {
    if (!quotaPopoverOpen) {
      statusCardHandleRef.current?.release();
      return;
    }
    // 注册 effect 更早声明,挂载时句柄已就位。
    statusCardHandleRef.current?.request();
  }, [quotaPopoverOpen]);

  const quotaPopoverContextRef = React.useRef({
    identity: JSON.stringify([
      sessionId,
      providerId,
      modelId,
      vendorKey,
      remoteHostId,
      accountDeviceId,
      accountUnreadable,
      usesCodexQuotaForm,
      usesXaiQuotaForm,
      isClaudeSubscription,
      usesGatewayQuota,
    ]),
  });
  React.useLayoutEffect(() => {
    const previousContext = quotaPopoverContextRef.current;
    const identity = JSON.stringify([
      sessionId,
      providerId,
      modelId,
      vendorKey,
      remoteHostId,
      accountDeviceId,
      accountUnreadable,
      usesCodexQuotaForm,
      usesXaiQuotaForm,
      isClaudeSubscription,
      usesGatewayQuota,
    ]);
    const contextInvalidated = previousContext.identity !== identity;
    quotaPopoverContextRef.current = {
      identity,
    };
    if (!contextInvalidated) return;
    setResetListOpen(false);

    // provider / model 或任务切换会原地复用组件;在新 chip 节点挂载后同步收口旧弹窗,
    // 清掉 hover / focus 残态与悬空 timer,并把卡片接管的键盘焦点交还给当前 chip。
    quotaPopoverPointerInsideRef.current = false;
    quotaPopoverFocusInsideRef.current = false;
    closeQuotaPopoverImmediately();
  }, [
    closeQuotaPopoverImmediately,
    sessionId,
    providerId,
    modelId,
    vendorKey,
    remoteHostId,
    accountDeviceId,
    accountUnreadable,
    usesCodexQuotaForm,
    usesXaiQuotaForm,
    isClaudeSubscription,
    usesGatewayQuota,
  ]);

  React.useEffect(
    () => () => {
      clearQuotaPopoverOpenTimer();
      clearQuotaPopoverCloseTimer();
    },
    [clearQuotaPopoverCloseTimer, clearQuotaPopoverOpenTimer],
  );

  const sessionSegment = sessionUsage.totalMoney?.amount
    ? t(
        sessionUsage.totalMoney.kind === 'value-estimate'
          ? 'todaySpend.codex.sessionValueLabel'
          : 'todaySpend.sessionCostLabel',
        { cost: formatTurnCostMoney(sessionUsage.totalMoney) },
      )
    : [
        sessionUsage.actualMoney?.amount
          ? t('todaySpend.tooltip.sessionUsed', {
              cost: formatTurnCostMoney(sessionUsage.actualMoney),
            })
          : null,
        sessionUsage.estimatedValueMoney?.amount
          ? t('todaySpend.codex.sessionValueLabel', {
              cost: formatTurnCostMoney(sessionUsage.estimatedValueMoney),
            })
          : null,
      ]
        .filter(Boolean)
        .join(' · ') || null;
  // codex-oauth / cc+chatgpt bridge → ChatGPT 用量看板; cc+xai bridge → grok.com 用量页;
  // cc Claude 订阅 → claude.ai 用量页; 其余(cc 网关 / codex-api)→ 暂无看板(null,见文件头 TODO)。
  // device-link 远程会话额度属于被控端账号,本机浏览器打开的看板是控制端自己的账号 → 不跳。
  const usageDashboardUrl: string | null = isDeviceLinkRemote
    ? null
    : usesXaiQuotaForm
      ? XAI_USAGE_DASHBOARD_URL
      : isCodexOauth || isChatgptBridge
        ? CODEX_USAGE_DASHBOARD_URL
        : isClaudeSubscription
          ? CLAUDE_USAGE_DASHBOARD_URL
          : usesProviderAccountUsageForm
            ? providerAccountUsage.result?.dashboardUrl
              ?? getProviderAccountUsageDashboardUrlView(selectedQuotaProvider, providerAccountAgent)
              ?? null
            : null;
  // 看板链接行文案:与 usageDashboardUrl 一一对应;网关账号无看板 → null
  // (tooltip 不显示"打开看板"行,chip 也不可点)。
  const usageDashboardLabel: string | null = isDeviceLinkRemote
    ? null
    : usesXaiQuotaForm
      ? t('todaySpend.openXaiUsage')
      : isCodexOauth || isChatgptBridge
        ? t('todaySpend.openCodexUsage')
        : isClaudeSubscription
          ? t('todaySpend.openClaudeUsage')
          : usesDeepSeekAccountForm
            ? t('providerAccountUsage.openDashboard')
            : usesZhipuCodingPlanForm
              ? t('providerAccountUsage.zhipuCodingPlan.usage')
              : null;
  const [windowLabelNowMs, setWindowLabelNowMs] = React.useState(() => Date.now());
  const codexResetSummary = React.useMemo(
    () => summarizeCodexRateLimitReset(codexRateLimits, windowLabelNowMs),
    [codexRateLimits, windowLabelNowMs],
  );

  // 当前形态下 chip 展示的限额窗口段 (Codex 订阅 / Claude 订阅 / 智谱 Coding Plan 共用结构);
  // 其它形态为空数组, 两个 rollup slot 空转。
  const chipWindows: ChipWindowSegment[] = usesCodexQuotaForm
    ? getCodexChipWindows(accountUsage, t, windowLabelNowMs)
    : usesXaiQuotaForm
      ? getXaiChipWindows(xaiSubscriptionUsage, t, windowLabelNowMs)
      : isClaudeSubscription
        ? getClaudeChipWindows(claudeSubscriptionUsage, modelId, t, windowLabelNowMs)
        : usesZhipuCodingPlanForm
          ? getZhipuChipWindows(
              providerAccountSnapshot?.kind === 'zhipu-coding-plan-quota'
                ? providerAccountSnapshot
                : null,
              t,
              windowLabelNowMs,
            )
          : [];
  // chip 最多两个窗口段, 固定两个 slot 无条件调 hook(Rules of Hooks)。
  // 重置滚动: 快照刷新中同窗口剩余百分比大幅回升(典型: 窗口到点重置 0% → 100%)
  // 时, 显示值从 0% 快速滚动到新值。
  const windowSlotA = chipWindows[0] ?? null;
  const windowSlotB = chipWindows[1] ?? null;
  const rollupA = useQuotaResetRollup(windowSlotA);
  const rollupB = useQuotaResetRollup(windowSlotB);
  // 窗口段元素登记表(key → span): 撒花锚点用, 段消失时由 ref 回调置 null。
  const segmentElsRef = React.useRef<Record<string, HTMLSpanElement | null>>({});
  const windowSegments: React.ReactNode[] = chipWindows.map((window, index) => {
    if (window.resetPending) {
      // 悬念期: 倒计时已归零、新快照未落地 —— 旧百分比已失真, 换成「重置中…」,
      // 呼吸省略号 (HTML span + opacity, 仅悬念期挂载; motion-safe = 尊重
      // prefers-reduced-motion, 降级为静态省略号)。新快照落地时由重置滚动
      // 动画从 0% 跳到新值揭晓。
      return (
        <React.Fragment key={window.key}>
          {t('todaySpend.resetPendingSegment', { label: window.label })}
          <span className="motion-safe:animate-pulse">…</span>
        </React.Fragment>
      );
    }
    const rollup = index === 0 ? rollupA : rollupB;
    const text = t(
      usesCodexQuotaForm
        ? 'todaySpend.codex.windowSegment'
        : usesXaiQuotaForm
          ? 'todaySpend.xai.windowSegment'
          : 'todaySpend.claude.windowSegment',
      { label: window.label, remaining: REMAINING_PLACEHOLDER },
    );
    const remaining = formatPercent(rollup?.percent ?? window.remainingPercent);
    // 段落包一层 span 并登记元素: 撒花以「正在揭晓的这一段」的矩形为迸发范围
    // (粒子沿整段文字宽度散布, 而非集中在 chip 中心一点)。
    return (
      <span
        key={window.key}
        ref={(el) => {
          segmentElsRef.current[window.key] = el;
        }}
      >
        {interpolateRemaining(
          text,
          window.alerting ? <span className="text-[var(--error-fg)]">{remaining}</span> : remaining,
        )}
      </span>
    );
  });

  // 礼花按供应商共享去重,不依赖任务组件的挂载或数字滚动状态。
  const chipRef = React.useRef<HTMLDivElement | null>(null);
  const celebrationProvider = JSON.stringify([
    isDeviceLinkRemote ? accountDeviceId : 'local',
    providerId ?? (usesCodexQuotaForm ? 'openai' : usesXaiQuotaForm ? 'xai' : 'anthropic'),
  ]);
  const quotaSnapshotUpdatedAt = usesCodexQuotaForm
    ? accountUsage?.updatedAt
    : usesXaiQuotaForm
      ? xaiSubscriptionUsage?.updatedAt
      : claudeSubscriptionUsage?.updatedAt;
  const [confettiBurst, setConfettiBurst] = React.useState<{
    nonce: number;
    anchor: HTMLElement;
  } | null>(null);
  React.useEffect(() => {
    if (!chipRef.current) return;
    const key = quotaFullCelebrations.observe(
      celebrationProvider,
      chipWindows,
      quotaSnapshotUpdatedAt,
    );
    if (
      key === null ||
      (typeof window.matchMedia === 'function' &&
        window.matchMedia('(prefers-reduced-motion: reduce)').matches)
    )
      return;
    const anchor = segmentElsRef.current[key] ?? chipRef.current;
    setConfettiBurst((prev) => ({ nonce: (prev?.nonce ?? 0) + 1, anchor }));
  });

  // 窗口 reset 时点列表以值签名 memo —— chipWindows 数组身份每次渲染都变
  // (含滚动动画的每一帧), 直接进 tick effect 依赖会让定时器反复重建。
  const resetsAtSignature = chipWindows.map((window) => window.resetsAtMs ?? 'na').join(',');
  const chipResetsAtMsList = React.useMemo(
    () =>
      resetsAtSignature === ''
        ? []
        : resetsAtSignature.split(',').map((value) => (value === 'na' ? null : Number(value))),
    [resetsAtSignature],
  );

  React.useEffect(() => {
    // 订阅形态 (codex-oauth / cc+chatgpt bridge / claude 订阅 / 智谱 Coding Plan) 的
    // reset 倒计时文案需要随时间走动: 常态分钟级 tick 足够; 任一窗口进入最后一分钟切秒级
    // tick, 让「59秒 → 1秒」逐秒跳动。setTimeout 链每次 tick 后按最新窗口重估下一次延迟。
    if (
      !usesCodexQuotaForm
      && !usesXaiQuotaForm
      && !isClaudeSubscription
      && !usesZhipuCodingPlanForm
      && !quotaPopoverOpen
    ) {
      return undefined;
    }
    const delay = computeCountdownTickDelayMs(chipResetsAtMsList, Date.now());
    const timer = window.setTimeout(() => {
      setWindowLabelNowMs(Date.now());
    }, delay);
    return () => window.clearTimeout(timer);
  }, [
    usesCodexQuotaForm,
    usesXaiQuotaForm,
    isClaudeSubscription,
    usesZhipuCodingPlanForm,
    quotaPopoverOpen,
    windowLabelNowMs,
    chipResetsAtMsList,
  ]);

  // 悬念期主动催一次余量刷新, 让「重置揭晓」尽快到来 —— main read 都是
  // cached-first + 节流(Claude 订阅端点 180s + 退避; Codex WHAM 10s + in-flight
  // 去重), 每个 tick 重试一次是安全的; 新快照落地即结束悬念期。
  // 催刷通道必须与 chip 实际显示的配额槽一致:
  //   - chatgpt/ bridge 形态显示 WHAM(openai-web)槽 → 催 WHAM;
  //   - Codex CLI 形态显示 app-server 槽 —— WHAM 刷新只落 web 槽、帮不上它,
  //     且无空闲期 app-server 催刷通道, 靠下一个 turn 事件或悬念超时回落兜底;
  //   - Claude 订阅形态催订阅端点。
  const hasPendingResetWindow = chipWindows.some((window) => window.resetPending);
  const xaiNeedsWeeklyRefresh =
    usesXaiQuotaForm && !isXaiWeeklyUsageCurrent(xaiSubscriptionUsage, windowLabelNowMs);
  React.useEffect(() => {
    if (!hasPendingResetWindow && !xaiNeedsWeeklyRefresh) return;
    // 悬念期催刷按账号所在分路:device-link 远程 / 远程 Agent 催账号所在电脑(经隧道,那台
    // 节流兜底),本机催本机(按所选供应商账号,#4197);不得拿本机通道替远程会话催刷(账号不同)。
    if (isChatgptBridge || (isDeviceLinkRemote && usesCodexQuotaForm)) {
      if (isDeviceLinkRemote) {
        if (accountDeviceId)
          requestRemoteCodexAccountRefresh(accountDeviceId, providerId ?? 'openai');
      } else {
        requestCodexAccountRefresh(providerId ?? undefined);
      }
    } else if (usesXaiQuotaForm) {
      if (isDeviceLinkRemote) {
        if (accountDeviceId)
          requestRemoteXaiSubscriptionRefresh(accountDeviceId, providerId ?? 'xai');
      } else {
        requestXaiSubscriptionRefresh(providerId ?? 'xai');
      }
    } else if (isClaudeSubscription && !usesCodexQuotaForm) {
      if (isDeviceLinkRemoteClaudeSubscription && accountDeviceId) {
        requestRemoteClaudeSubscriptionRefresh(accountDeviceId, providerId ?? 'anthropic');
      } else if (!isDeviceLinkRemote) {
        requestClaudeSubscriptionRefresh(providerId ?? 'anthropic');
      }
    }
  }, [
    hasPendingResetWindow,
    xaiNeedsWeeklyRefresh,
    isChatgptBridge,
    isClaudeSubscription,
    isDeviceLinkRemote,
    isDeviceLinkRemoteClaudeSubscription,
    accountDeviceId,
    usesCodexQuotaForm,
    usesXaiQuotaForm,
    providerId,
    windowLabelNowMs,
  ]);

  const isDashboardClickable = usageDashboardUrl !== null;
  const handleClick = () => {
    if (!usageDashboardUrl) return; // 网关账号暂无看板:点击无反应
    void window.electronAPI.openExternal(usageDashboardUrl);
  };

  // device-link 远程形态已解析 = 走与本机一致的对应分支(数据全部来自账号所在电脑的镜像);
  // 未解析(默认路由无观察值 / 老被控端)或那份账号读不到(分享来的供应商等)才落占位分支。
  const deviceLinkRemoteFormResolved =
    !accountUnreadable &&
    (isDeviceLinkRemoteClaudeSubscription ||
      (isDeviceLinkRemote &&
        (usesCodexQuotaForm || usesXaiQuotaForm || isDeviceLinkRemoteGateway)));
  let labelNode: React.ReactNode;
  let account: UsageCardAccount = { title: t('quotaCard.usageTitle'), windows: [] };
  if (isDeviceLinkRemote && !deviceLinkRemoteFormResolved) {
    // device-link 远程会话不读取本机账号形态;金额仍使用同一个会话合计投影。
    // (形态已解析的远程会话不走这里——落到下方对应形态分支,用被控端镜像渲染。)
    const chipSegments = sessionSegment ? [sessionSegment] : [];
    labelNode =
      chipSegments.length > 0 ? (
        renderSegmentedLabel(chipSegments)
      ) : (
        <span className="tabular-nums opacity-60">{DEFAULT_MONEY_SYMBOL}</span>
      );
  } else if (usesCodexQuotaForm || usesXaiQuotaForm || isClaudeSubscription || usesProviderAccountUsageForm) {
    // DeepSeek 余额形态无窗口段:chip 主指标直接显示余额(与 GPT credits 同层)。
    const deepSeekBalanceSegment = usesDeepSeekAccountForm
      ? formatDeepSeekBalanceSegment(providerAccountSnapshot, t, formatterLocale)
      : null;
    const chipSegments = [
      ...(usesDeepSeekAccountForm && deepSeekBalanceSegment ? [deepSeekBalanceSegment] : []),
      ...windowSegments,
    ];
    if (sessionSegment) chipSegments.push(sessionSegment);
    labelNode =
      chipSegments.length > 0 ? (
        renderSegmentedLabel(chipSegments)
      ) : (
        <span className="tabular-nums opacity-60">{DEFAULT_MONEY_SYMBOL}</span>
      );
    // SSH 远程(remoteHostId)没有账号快照镜像,只显示价值估算;device-link 远程的
    // accountUsage / xai / claude 快照均已在上方切到被控端镜像,与本机同一套卡片渲染。
    if (!remoteHostId) {
      account = usesCodexQuotaForm
        ? buildCodexUsageCard(
            accountUsage,
            !isAnyRemoteSession && codexRateLimits?.rateLimitResetCredits ? null : codexResetSummary,
            t,
            windowLabelNowMs,
            formatterLocale,
          )
        : usesXaiQuotaForm
          ? buildXaiUsageCard(xaiSubscriptionUsage, xaiRateLimit, t, windowLabelNowMs)
          : usesDeepSeekAccountForm
            ? buildDeepSeekUsageCard(
                providerAccountSnapshot?.kind === 'deepseek-balance' ? providerAccountSnapshot : null,
                t,
                formatterLocale,
              )
            : usesZhipuCodingPlanForm
              ? buildZhipuUsageCard(
                  providerAccountSnapshot?.kind === 'zhipu-coding-plan-quota'
                    ? providerAccountSnapshot
                    : null,
                  t,
                )
              : buildClaudeUsageCard(claudeSubscriptionUsage, t);
      if (usesProviderAccountUsageForm && providerAccountUsage.result?.status === 'unavailable') {
        account.emptyText = t(`providerAccountUsage.error.${providerAccountUsage.result.error}`);
      }
      if (
        !usesProviderAccountUsageForm &&
        (usesCodexQuotaForm || usesXaiQuotaForm || isClaudeSubscription)
      ) {
        // Identity and quota must come from the same provider on the same execution device.
        const identityProvider = quotaProviders.find(
          (provider) =>
            provider.id ===
            (providerId ?? (usesCodexQuotaForm ? 'openai' : usesXaiQuotaForm ? 'xai' : 'anthropic')),
        );
        account.identity = usesCodexQuotaForm
          ? identityProvider?.openAiAccount?.identity
          : identityProvider?.subscriptionAccount?.identity;
      }
    }
  } else {
    const slots = computeMetricSlots(claudeQuota, creditTotals, sessionSegment, t);
    const chipSegments = getGatewayChipSegments(slots);
    const codexApiHasTokenFallback =
      isCodexApi && !slots.session.available && hasPositiveSessionTokens(sessionTokens);
    const codexApiEmptyState =
      isCodexApi && !slots.session.available && !hasPositiveSessionTokens(sessionTokens)
        ? getCodexApiEmptyState(latestTurnUsage)
        : null;
    if (codexApiHasTokenFallback) {
      chipSegments.push(
        t('todaySpend.codex.sessionTokensLine', {
          tokens: formatCompactTokens(Math.floor(sessionTokens ?? 0)),
        }),
      );
    }
    // Account quota is separate from lifetime task cost. API and SSH-remote routes never borrow it;
    // device-link 网关形态用被控端 LiteLLM 配额镜像(claudeQuota 已切换),credit 三池不镜像。
    if (usesGatewayQuota || isDeviceLinkRemoteGateway) {
      account.title = providerDisplayNameById('xd', quotaProviders, t);
      if (creditTotals) {
        // Keep the retained balance's observation time; a render/refresh is not new data.
        const observedAt = Date.parse(creditUsage?.observedAt ?? '');
        if (Number.isFinite(observedAt)) account.updatedAt = observedAt;
        account.windows.push({
          key: 'balance',
          title: t('quotaCard.balanceLabel'),
          window: {
            utilization:
              creditTotals.total > 0 ? (creditTotals.used / creditTotals.total) * 100 : 0,
          },
          detail: slots.credit.tooltipLabel ?? slots.credit.label,
        });
      }
      if (claudeQuota && claudeQuota.maxBudget > 0) {
        if (claudeQuota.dailyLimitEnabled !== false && typeof claudeQuota.todaySpend === 'number') {
          const softLimit = (claudeQuota.maxBudget / 30) * DAILY_SOFT_LIMIT_FACTOR;
          account.windows.push({
            key: 'daily',
            title: t('quotaCard.dailyLabel'),
            window: { utilization: (claudeQuota.todaySpend / softLimit) * 100 },
            detail: slots.daily.label,
          });
        }
        account.windows.push({
          key: 'monthly',
          title: t('quotaCard.monthlyLabel'),
          window: {
            utilization: (claudeQuota.spend / claudeQuota.maxBudget) * 100,
            resetsAt: claudeQuota.budgetResetAt
              ? Date.parse(claudeQuota.budgetResetAt) / 1000
              : null,
          },
          detail: slots.monthly.label,
        });
        account.updatedAt = claudeQuota.fetchedAt;
      }
      if (!claudeQuota && !creditTotals) {
        account.emptyText = t('todaySpend.tooltip.monthlyUnavailable');
      } else if (claudeQuota?.dailyLimitEnabled !== false && claudeQuota?.todaySpend === null) {
        account.details = [t('todaySpend.tooltip.dailyUnavailable')];
      }
    }
    if (codexApiEmptyState) {
      account.emptyText = t(
        codexApiEmptyState === 'no-usage'
          ? 'todaySpend.codex.noUsageDetail'
          : 'todaySpend.codex.unavailableDetail',
      );
    }

    if (chipSegments.length === 0) {
      if (codexApiEmptyState) {
        labelNode = (
          <span className="tabular-nums opacity-60">
            {t(
              codexApiEmptyState === 'no-usage'
                ? 'todaySpend.codex.noUsageLabel'
                : 'todaySpend.codex.unavailableLabel',
            )}
          </span>
        );
      } else {
        labelNode = <span className="tabular-nums opacity-60">{DEFAULT_MONEY_SYMBOL}</span>;
      }
    } else {
      // 之前用纯字符串 ".join(' · ')" — middle dot · 落在 x-height, 周围混着 cap-height
      // 大写字母 + 数字 + $/k, 视觉上文字"高低不齐"。改成结构化渲染:
      //   - 段间用 CSS 横线 (border-l h-3) 当分隔符 — 高度与字号绑定, 视觉上像条直线
      //   - 文字段内统一加 tabular-nums + slashed-zero, 数字等宽对齐
      labelNode = renderSegmentedLabel(chipSegments);
    }
  }

  if (
    !account.emptyText &&
    !account.windows.length &&
    !quotaCardSessionUsage &&
    !quotaCardTurnUsage
  ) {
    account.emptyText = t('todaySpend.codex.noUsageDetail');
  }

  // 告警态: 达到条件的窗口只把它自己的剩余百分比染 error 色 (语义豁免色, 跨主题一致),
  // 其它窗口段、分隔线与任务价值保持常色。其它模型的周限吃紧不染红 —— chip 上没有
  // 那一段, 红了也无从解释 (见 isClaudeSubscriptionAlerting 对 allowed_warning 的取舍)。
  // 兜底: 当前会话确实受限 (headers 报 rejected, 或 scoped 周限占位时总周限告警) 但
  // chip 上没有任何一个窗口达到条件 → 仍整条变红, 不丢受限信号。悬念期的告警窗口也算
  // 「chip 上有」: 它的旧数据已失真, 段上显示「重置中…」不染红, 也不借兜底把整条染红。
  const hasAlertingChipWindow = chipWindows.some((window) => window.alerting);
  const chipAlertingFallback =
    !hasAlertingChipWindow &&
    ((isClaudeSubscription && isClaudeSubscriptionAlerting(claudeSubscriptionUsage, modelId)) ||
      (usesXaiQuotaForm && isXaiSubscriptionAlerting(xaiSubscriptionUsage)));

  // 与 ContextCapacityRing 视觉对齐 (h-5 = 20px) + reset button UA 默认 padding/border。
  // tabular-nums 让 "$306 / $1.2k" 这类数字段的字符宽度等宽, 段间数字落点对齐。
  const buttonClass = cn(
    'inline-flex h-5 shrink-0 items-center',
    'text-12 font-medium leading-none tabular-nums',
    chipAlertingFallback
      ? 'text-[var(--error-fg)] hover:text-[var(--error-fg-strong)]'
      : 'text-[var(--msg-tool-card-chevron)] hover:text-foreground',
    'border-0 bg-transparent p-0 m-0',
    'transition-colors',
    'focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] rounded-full',
  );

  return (
    <div
      ref={chipRef}
      className="inline-flex h-5 shrink-0 items-center gap-3"
      onMouseEnter={refreshCodexRateLimits}
      onFocusCapture={refreshCodexRateLimits}
    >
      <Popover
        open={quotaPopoverOpen && !resetListOpen}
        onOpenChange={(open) => {
          // 打开只由 hover / focus 驱动;Radix 的 outside / Escape 仍可请求关闭。
          if (!open) closeQuotaPopoverImmediately();
        }}
        modal={false}
      >
        <PopoverTrigger asChild>
          <button
            ref={setQuotaPopoverFocusTarget}
            type="button"
            onClick={(event) => {
              // 阻止 Radix 把 dashboard 点击解释成开关,chip 原动作保持不变。
              event.preventDefault();
              if (isDashboardClickable) handleClick();
              else openQuotaPopoverImmediately();
            }}
            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 ?? t('quotaCard.usageTitle')}
          >
            {labelNode}
          </button>
        </PopoverTrigger>
        {/* 浮层挂到触发器紧跟其后的宿主:DOM 顺序 = 视觉顺序,Tab 才能从卡片继续走到
            右边下一枚 chip(原实现 portal 到 body 末尾,焦点进卡后就出不来了)。 */}
        <div ref={setQuotaPopoverPortalHost} className="contents" />
        <PopoverContent
          ref={quotaPopoverContentRef}
          portalContainer={quotaPopoverPortalHost}
          // Radix 给 FocusScope 写死 `loop:true`(见 popover.tsx):Tab 在卡内永远环回。
          // 把两个 Tab 边缘接过来,让 Tab 能从卡片走到右边下一枚 chip(用户实测)。
          onKeyDownCapture={(event) => {
            if (event.key !== 'Tab') return;
            const cardRoot = event.currentTarget;
            if (!(cardRoot instanceof HTMLElement)) return;
            if (handOffTabFromCard(cardRoot, event)) {
              event.preventDefault();
              event.stopPropagation();
            }
          }}
          side="top"
          align="end"
          sideOffset={8}
          collisionPadding={8}
          onOpenAutoFocus={(event) => {
            event.preventDefault();
            if (quotaPopoverOpenSourceRef.current !== 'focus') return;
            const dashboardButton = quotaPopoverDashboardButtonRef.current;
            const focusTarget =
              dashboardButton ??
              quotaPopoverContentRef.current?.querySelector<HTMLElement>('[role=region]');
            focusTarget?.focus({ preventScroll: true });
            quotaPopoverFocusTakenRef.current = Boolean(
              focusTarget && document.activeElement === focusTarget,
            );
          }}
          onCloseAutoFocus={(event) => {
            event.preventDefault();
            restoreQuotaPopoverFocus();
          }}
          onEscapeKeyDown={closeQuotaPopoverImmediately}
          onMouseEnter={handleQuotaPopoverMouseEnter}
          onMouseLeave={handleQuotaPopoverMouseLeave}
          onFocusCapture={() => {
            quotaPopoverFocusInsideRef.current = true;
            // 内容无论因键盘还是鼠标获得焦点,都算卡片已接管焦点;关闭时统一归还 trigger。
            quotaPopoverFocusTakenRef.current = true;
            keepQuotaPopoverOpen();
          }}
          onBlurCapture={(event) => {
            const nextTarget = event.relatedTarget;
            if (nextTarget instanceof Node && event.currentTarget.contains(nextTarget)) return;
            if (quotaPopoverRestoringFocusRef.current) return;
            // Tab 已将焦点交给卡片外的控件;自然离开只关闭卡片,
            // 不让延时器或 close-autofocus 再把焦点抢回 trigger。
            quotaPopoverFocusInsideRef.current = false;
            quotaPopoverFocusTakenRef.current = false;
            quotaPopoverOpenSourceRef.current = null;
            scheduleQuotaPopoverClose();
          }}
          className="w-auto max-w-[calc(100vw-16px)] border-0 bg-transparent p-0 shadow-none"
        >
          <QuotaHoverCard
            account={account}
            nowMs={windowLabelNowMs}
            sessionUsage={quotaCardSessionUsage}
            turnUsage={quotaCardTurnUsage}
            dashboardLabel={usageDashboardLabel}
            onOpenDashboard={handleClick}
            dashboardButtonRef={quotaPopoverDashboardButtonRef}
            windowAction={usesCodexQuotaForm && !isAnyRemoteSession && (codexRateLimits?.rateLimitResetCredits || manualReset.canRetry) ? (
              <Button size="xs" compact tone="quiet" aria-label={t('codexResets.title')} title={t('codexResets.title')}
                onClick={() => {
                  quotaPopoverFocusTakenRef.current = false;
                  closeQuotaPopoverImmediately();
                  setResetListOpen(true);
                }}>
                {manualReset.canRetry ? t('codexResets.retryReset') : t('codexResets.available', { count: codexRateLimits?.rateLimitResetCredits?.availableCount ?? 0 })}
              </Button>
            ) : null}
          />
        </PopoverContent>
      </Popover>
      <Dialog.Root open={resetListOpen && usesCodexQuotaForm && !isAnyRemoteSession} onOpenChange={setResetListOpen}>
        <Dialog.Portal>
          <Dialog.Overlay className="modal-scrim fixed inset-0 z-[10000]" />
          <Dialog.Content
            aria-describedby={undefined}
            onPointerDownOutside={(event) => event.preventDefault()}
            className="modal-panel fixed left-1/2 top-1/2 z-[10000] w-[400px] max-w-[calc(100vw-32px)] -translate-x-1/2 -translate-y-1/2 p-4"
            onCloseAutoFocus={(event) => {
              event.preventDefault();
              // The confirmation owns focus when it opens after this dialog closes.
              if (!manualReset.busy) {
                quotaPopoverFocusTakenRef.current = true;
                restoreQuotaPopoverFocus();
              }
            }}
          >
            <Dialog.Title className="sr-only">{t('codexResets.title')}</Dialog.Title>
            <div className="max-h-[60vh] overflow-y-auto">
              <CodexResetCredits providerId={providerId ?? 'openai'} onChanged={refreshCodexRateLimits} variant="dialog" snapshot={codexRateLimits} busy={manualReset.busy}
                canReset={manualReset.canReset} canRetry={manualReset.canRetry} onReset={(credit) => {
                  setResetListOpen(false);
                  const context = quotaPopoverContextRef.current.identity;
                  void manualReset.reset(credit).finally(() => {
                    if (quotaPopoverContextRef.current.identity !== context) return;
                    quotaPopoverFocusTakenRef.current = true;
                    restoreQuotaPopoverFocus();
                  });
                }} />
            </div>
            <Dialog.Close asChild>
              <Tip text={t('common.dismiss')} contentClassName="z-[10001]">
                <button type="button" aria-label={t('common.dismiss')}
                  className="absolute right-3 top-3 flex h-8 w-8 items-center justify-center rounded-full text-[var(--confirm-desc)] transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--confirm-title)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]">
                  <X className="h-4 w-4" aria-hidden="true" />
                </button>
              </Tip>
            </Dialog.Close>
          </Dialog.Content>
        </Dialog.Portal>
      </Dialog.Root>
      {confettiBurst && (
        <QuotaResetConfetti
          key={confettiBurst.nonce}
          anchor={confettiBurst.anchor}
          onDone={() => setConfettiBurst(null)}
        />
      )}
    </div>
  );
}