Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

66.9 KB
Raw Blame
import * as React from 'react';
import {
  ArrowDown,
  ArrowDownToLine,
  ChevronDown,
  CircleHelp,
  Cpu,
  Filter,
  LoaderCircle,
  Network,
  Pin,
  PinOff,
  Search,
  X,
  Zap,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';

import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { SegmentedRadio } from '@/components/ui/segmented';
import { cn } from '@/lib/utils';
import { atLeast, formatCost, formatPercent, formatUsd } from './format';
import { foldRegionRead, regionFailed, type RegionRead } from './regionRead';
import type { UsageCounters, UsageReport, UsageWindowKey } from './types';
import {
  aggregateCounters,
  aggregateServiceRows,
  costIsFloor,
  costIsUnpriced,
  filterBucketRows,
  filteredRows,
  foldUsageSelection,
  formatBucketAxisLabel,
  formatBucketLabel,
  formatBucketHeading,
  formatBucketRange,
  emptyCounters,
  isModelRow,
  isServiceRow,
  metricRows,
  reportHasPartialHistory,
  reportIsPriced,
  reportHasUnknownTokens,
  resolveUsageFilter,
  seriesFor,
  serviceUsageRows,
  unpricedServices,
  usageCachedInputShare,
  usageIdentities,
  usageIsEmpty,
  usageIsPriced,
  usageHasNoPrice,
  usageMetricValue,
  usageNonCachedInput,
  usageReportShortfall,
  usageTokensAreKnown,
  type ServiceTotals,
  type UsageFilter,
  type UsageGroup,
  type UsageMetric,
  type UsageSeries,
  type UsageText,
} from './usageProjection';
import { USAGE_WINDOW_OPTIONS } from './usageProjection';
import { buildUsageCsv } from './usageCsv';
import './modelHubSurface.css';

const SERIES_COLORS = [
  'var(--mint)',
  'var(--violet)',
  'var(--cyan)',
  'var(--gold)',
  'var(--destructive)',
  'var(--primary)',
] as const;

/** The removed-Sources aggregate reads as history, not as one more supplier. */
const seriesColor = (item: UsageSeries): string => (item.removed
  ? 'var(--muted)'
  : SERIES_COLORS[item.colorIndex % SERIES_COLORS.length]);

type FilterOption = { key: string; label: string; detail?: string };
type UsageTranslate = (key: string, options?: Record<string, unknown>) => string;

const metricKeys: UsageMetric[] = ['tokens', 'input', 'output', 'cache', 'requests'];
/** 折合 API 价格 is offered only when the server priced the report. */
const metricKeysFor = (report: UsageReport): UsageMetric[] => (reportIsPriced(report) ? [...metricKeys, 'cost'] : metricKeys);
/** Metrics with one series only, where 按类型 has nothing to split. */
const unsplitMetric = (metric: UsageMetric) => metric === 'requests' || metric === 'cost';
const groupKeys: UsageGroup[] = ['total', 'type', 'model', 'source'];

const useUsageTranslation = () => {
  const translation = useTranslation();
  return {
    ...translation,
    t: translation.t as unknown as UsageTranslate,
  };
};

const usageText = (t: UsageTranslate): UsageText => ({
  unknownModel: t('settings.models.usage.unknownModel'),
  removedSources: t('settings.models.usage.removedSources'),
  searchServices: t('settings.models.usage.services.title'),
  webFetch: t('settings.models.tools.tool.web_fetch.name'),
});

const useCount = () => {
  const { i18n } = useTranslation();
  return React.useCallback((value: number) => new Intl.NumberFormat(i18n.language).format(value), [i18n.language]);
};

/** The formatter for one metric's figures: dollars for 折合 API 价格, a count for the rest. */
const useMetricFormat = (metric: UsageMetric) => {
  const { i18n } = useTranslation();
  const count = useCount();
  return React.useCallback(
    (value: number) => (metric === 'cost' ? formatUsd(value, i18n.language) : count(value)),
    [count, i18n.language, metric],
  );
};

const tokenText = (
  counters: UsageCounters,
  metric: UsageMetric,
  count: (value: number) => string,
  blank: string,
): string => {
  const value = usageMetricValue(counters, metric);
  return value === null ? blank : count(value);
};

/** What a cost with nothing priced in it reads as: prices on their way while a first fetch runs, else none. */
const noPriceText = (report: UsageReport, t: UsageTranslate): string => (report.pricing?.pending
  ? t('settings.models.usage.cost.fetching')
  : t('settings.models.usage.cost.noPrice'));

const metricLabel = (metric: UsageMetric, t: UsageTranslate): string =>
  t(`settings.models.usage.metric.${metric}`);

function MultiFilter({
  label,
  icon,
  options,
  selected,
  onChange,
}: {
  label: string;
  icon: React.ReactNode;
  options: FilterOption[];
  selected: readonly string[];
  onChange: (next: string[]) => void;
}) {
  const { t } = useUsageTranslation();
  const [open, setOpen] = React.useState(false);
  const [query, setQuery] = React.useState('');
  const rootRef = React.useRef<HTMLDivElement>(null);
  const triggerRef = React.useRef<HTMLButtonElement>(null);

  React.useEffect(() => {
    if (!open) return undefined;
    const onPointerDown = (event: PointerEvent) => {
      if (!rootRef.current?.contains(event.target as Node)) {
        setOpen(false);
        triggerRef.current?.focus();
      }
    };
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        setOpen(false);
        triggerRef.current?.focus();
      }
    };
    document.addEventListener('pointerdown', onPointerDown);
    document.addEventListener('keydown', onKeyDown);
    return () => {
      document.removeEventListener('pointerdown', onPointerDown);
      document.removeEventListener('keydown', onKeyDown);
    };
  }, [open]);

  const visibleOptions = options.filter((option) => (
    option.label.toLocaleLowerCase().includes(query.toLocaleLowerCase())
      || option.detail?.toLocaleLowerCase().includes(query.toLocaleLowerCase())
  ));
  const buttonLabel = selected.length === 0
    ? t('settings.models.usage.filters.all', { label })
    : selected.length === 1
      ? options.find((option) => option.key === selected[0])?.label ?? label
      : t('settings.models.usage.filters.selected', { label, count: selected.length });

  const toggle = (key: string) => {
    onChange(selected.includes(key) ? selected.filter((item) => item !== key) : [...selected, key]);
  };

  return (
    <div className="model-hub-usage-filter" ref={rootRef}>
      <Button
        ref={triggerRef}
        type="button"
        variant="outline"
        size="sm"
        aria-expanded={open}
        aria-haspopup="listbox"
        className={cn('model-hub-usage-filter-trigger', selected.length > 0 && 'is-filtered')}
        onClick={() => { setOpen((value) => !value); setQuery(''); }}
      >
        {icon}
        <span className="truncate">{buttonLabel}</span>
        <ChevronDown aria-hidden className="size-3 shrink-0" />
      </Button>
      {open && (
        <div className="model-hub-usage-filter-menu" role="listbox" aria-label={label} aria-multiselectable="true">
          <div className="model-hub-usage-filter-search">
            <Search aria-hidden className="size-3.5 shrink-0" />
            <input
              autoFocus
              value={query}
              aria-label={t('settings.models.usage.filters.search', { label }) as string}
              placeholder={t('settings.models.usage.filters.search', { label }) as string}
              onChange={(event) => setQuery(event.target.value)}
            />
          </div>
          <button
            type="button"
            role="option"
            aria-selected={selected.length === 0}
            className="model-hub-usage-filter-option"
            onClick={() => onChange([])}
          >
            <Checkbox checked={selected.length === 0} presentational />
            {t('settings.models.usage.filters.all', { label })}
          </button>
          <div className="model-hub-usage-filter-divider" />
          {visibleOptions.map((option) => (
            <button
              type="button"
              role="option"
              aria-selected={selected.includes(option.key)}
              className="model-hub-usage-filter-option"
              key={option.key}
              onClick={() => toggle(option.key)}
            >
              <Checkbox checked={selected.includes(option.key)} presentational />
              <span className="min-w-0 truncate">
                <span className="block truncate">{option.label}</span>
                {option.detail && <span className="block truncate text-[10px] text-muted">{option.detail}</span>}
              </span>
            </button>
          ))}
          {visibleOptions.length === 0 && <p className="model-hub-usage-filter-empty">{t('settings.models.usage.filters.noMatch')}</p>}
          <p className="model-hub-usage-filter-foot">{t('settings.models.usage.filters.hint')}</p>
        </div>
      )}
    </div>
  );
}

/** A legend item's border and padding before its swatch. */
const LEGEND_SWATCH_OFFSET = 7;

const ChartLegend: React.FC<{
  series: UsageSeries[];
  hidden: readonly string[];
  onToggle: (key: string) => void;
  labels: Map<string, string>;
  count: (value: number) => string;
  blank: string;
  noPrice: string;
  ariaLabel: string;
  /** The plot's left edge, which the first swatch lines up with. */
  inset: number;
}> = ({ series, hidden, onToggle, labels, count, blank, noPrice, ariaLabel, inset }) => (
  <div className="model-hub-usage-legend" aria-label={ariaLabel} style={{ marginLeft: Math.max(0, inset - LEGEND_SWATCH_OFFSET) }}>
    {series.map((item) => {
      const values = item.values.filter((value): value is number => value !== null);
      const total = values.reduce((sum, value) => sum + value, 0);
      const floor = item.floors.some(Boolean);
      // Costs are never negative, so a zero total with an unpriced bucket has nothing priced in it.
      const unpriced = total === 0 && item.unpriced.some(Boolean);
      const isHidden = hidden.includes(item.key);
      return (
        <button
          type="button"
          key={item.key}
          aria-pressed={!isHidden}
          className={cn('model-hub-usage-legend-item', isHidden && 'is-hidden')}
          onClick={() => onToggle(item.key)}
        >
          <span className="model-hub-usage-legend-swatch" style={{ background: seriesColor(item) }} />
          <span>{labels.get(item.key) ?? item.label}</span>
          <strong>{values.length === 0 ? blank : unpriced ? noPrice : atLeast(count(total), floor)}</strong>
        </button>
      );
    })}
  </div>
);

const TOOLTIP_WIDTH = 264;
const TOOLTIP_INSET = 8;
const TOOLTIP_GAP = 6;
/** Below this chart width the detail docks full-width across the top, for touch. */
const TOOLTIP_DOCK_BELOW = 560;
const HOUR_TICK_STEPS = [1, 2, 3, 4, 6, 12];
const DAY_TICK_STEPS = [1, 2, 3, 5, 7, 10, 14, 15, 30];

/**
 * The buckets that carry an x-axis label: the finest step whose labels stay a
 * readable distance apart. Hours align to the clock (every 3h lands on 00, 03,
 * 06 …); days count back from the newest, so today always has its label.
 */
function axisTickIndexes(report: UsageReport, bucketSpan: number, narrow: boolean): number[] {
  const count = report.buckets.length;
  if (count === 0) return [];
  const minGap = narrow ? 52 : 68;
  const hourly = report.granularity === 'hour';
  const steps = hourly ? HOUR_TICK_STEPS : DAY_TICK_STEPS;
  const step = steps.find((candidate) => candidate * bucketSpan >= minGap) ?? steps[steps.length - 1];
  const hourOf = (index: number) => Number(report.buckets[index].start_at.slice(11, 13));
  return report.buckets.map((_, index) => index).filter((index) => (hourly
    ? Number.isFinite(hourOf(index)) && hourOf(index) % step === 0
    : (count - 1 - index) % step === 0));
}

function UsageChart({
  report,
  filter,
  metric,
  group,
  pinnedKey,
  scopeKey,
  onPin,
}: {
  report: UsageReport;
  filter: UsageFilter;
  metric: UsageMetric;
  group: UsageGroup;
  pinnedKey: string | null;
  scopeKey: string;
  onPin: (key: string | null) => void;
}) {
  const { t, i18n } = useUsageTranslation();
  const count = useCount();
  const format = useMetricFormat(metric);
  const [hovered, setHovered] = React.useState<number | null>(null);
  const [inspected, setInspected] = React.useState<number | null>(null);
  const [dismissed, setDismissed] = React.useState(false);
  const [hidden, setHidden] = React.useState<string[]>([]);
  const [width, setWidth] = React.useState(920);
  const [keyboardActivation, setKeyboardActivation] = React.useState(0);
  const hostRef = React.useRef<HTMLDivElement>(null);
  const svgRef = React.useRef<SVGSVGElement>(null);
  const pinButtonRef = React.useRef<HTMLButtonElement>(null);
  const bucketButtonRefs = React.useRef(new Map<string, HTMLButtonElement>());
  const invokingBucketKeyRef = React.useRef<string | null>(null);
  const suppressNextBucketFocusRef = React.useRef(false);
  const focusPinAfterOpenRef = React.useRef(false);
  const previousUsageInputRef = React.useRef({ report, scopeKey, group, metric });
  const hoverClearTimer = React.useRef<number | null>(null);
  const [escapeDismissed, setEscapeDismissed] = React.useState(false);
  const pinnedIndex = pinnedKey === null ? -1 : report.buckets.findIndex((bucket) => bucket.key === pinnedKey);
  const requestedIndex = dismissed || escapeDismissed
    ? null
    : pinnedIndex >= 0 ? pinnedIndex : inspected ?? hovered;
  const activeIndex = requestedIndex !== null
    && requestedIndex >= 0
    && requestedIndex < report.buckets.length
    ? requestedIndex
    : null;
  const bars = report.window_key === '30d' || report.window_key === '60d';
  const { unknownModel, removedSources, searchServices, webFetch } = usageText(t);
  const series = React.useMemo(
    () => seriesFor(report, filter, group, metric, { unknownModel, removedSources, searchServices, webFetch }),
    [filter, group, metric, removedSources, report, searchServices, unknownModel, webFetch],
  );
  const unpriced = React.useMemo(() => unpricedServices(report), [report]);
  const labels = React.useMemo(() => new Map(series.map((item) => [
    item.key,
    item.key === 'total'
      ? metricLabel(metric, t)
      : item.key === 'input'
        ? t('settings.models.usage.series.input')
        : item.key === 'cache'
          ? t('settings.models.usage.series.cache')
          : item.key === 'output'
            ? t('settings.models.usage.series.output')
            : item.key === 'requests'
              ? t('settings.models.usage.series.requests')
              : item.key === 'cost'
                ? metricLabel('cost', t)
                : item.label,
  ])), [metric, series, t]);
  const visibleSeries = React.useMemo(() => series.filter((item) => !hidden.includes(item.key)), [hidden, series]);
  const narrow = width < 560;
  const height = narrow ? 236 : 292;
  const left = narrow ? 40 : 54;
  const right = 16;
  const top = 18;
  const bottom = 38;
  const plotWidth = Math.max(1, width - left - right);
  const plotHeight = Math.max(1, height - top - bottom);
  const bucketCount = report.buckets.length;
  // One bucket's share of the plot: a bar's column, or the span a line point
  // owns between its neighbours' midpoints.
  const bucketSpan = bars ? plotWidth / Math.max(1, bucketCount) : plotWidth / Math.max(1, bucketCount - 1);
  const values = report.buckets.map((_, index) => bars
    ? visibleSeries.reduce((sum, item) => sum + (item.values[index] ?? 0), 0)
    : Math.max(0, ...visibleSeries.map((item) => item.values[index] ?? 0)));
  const rawMax = Math.max(1, ...values);
  const scale = 10 ** Math.floor(Math.log10(rawMax));
  const max = Math.ceil(rawMax / scale / 0.5) * scale * 0.5;
  const x = (index: number) => left + (bars
    ? (index + 0.5) / bucketCount
    : index / Math.max(1, bucketCount - 1)) * plotWidth;
  const y = (value: number) => top + plotHeight * (1 - value / max);
  const bucket = activeIndex === null || activeIndex < 0 ? null : report.buckets[activeIndex];
  const bucketRows = bucket === null ? [] : metricRows(filterBucketRows(bucket, filter), metric);
  const bucketTotals = aggregateCounters(bucketRows, unpriced);
  const activeValue = bucket && !bucket.history_complete && bucketRows.length === 0
    ? null
    : usageMetricValue(bucketTotals, metric);
  const currentPartialHour = bucket !== null
    && report.window_key === '24h'
    && activeIndex === report.buckets.length - 1
    && Date.parse(bucket.end_at) - Date.parse(bucket.start_at) < 60 * 60 * 1000;
  const tickIndexes = axisTickIndexes(report, bucketSpan, narrow);
  const heading = bucket === null ? null : formatBucketHeading(bucket, i18n.language);
  const gradientId = React.useId().replace(/[^a-zA-Z0-9_-]/g, '');

  // Everything that does not depend on the hovered bucket. A hover change
  // re-renders only the highlight, crosshair, active dots, and tooltip.
  const seriesLayer = React.useMemo(() => {
    const xAt = (index: number) => left + (bars
      ? (index + 0.5) / bucketCount
      : index / Math.max(1, bucketCount - 1)) * plotWidth;
    const yAt = (value: number) => top + plotHeight * (1 - value / max);
    const colorOf = seriesColor;
    const columnWidth = plotWidth / Math.max(1, bucketCount);
    if (bars) {
      return report.buckets.map((currentBucket, index) => {
        let offset = 0;
        return (
          <g key={currentBucket.key}>
            {visibleSeries.map((item) => {
              const value = item.values[index];
              const start = offset;
              offset += value ?? 0;
              return (
                <rect
                  key={item.key}
                  x={xAt(index) - columnWidth * 0.32}
                  y={yAt(offset)}
                  width={columnWidth * 0.64}
                  height={value === null ? 4 : Math.max(0, yAt(start) - yAt(offset))}
                  fill={value === null ? 'url(#usage-unknown-pattern)' : colorOf(item)}
                  opacity={0.88}
                  rx="2"
                />
              );
            })}
          </g>
        );
      });
    }
    const baseline = yAt(0);
    return visibleSeries.map((item, seriesIndex) => {
      // Contiguous known runs; an unknown bucket breaks the line.
      const runs: number[][] = [];
      item.values.forEach((value, index) => {
        if (value === null) return;
        const previous = item.values[index - 1];
        if (previous === null || previous === undefined) runs.push([index]);
        else runs[runs.length - 1].push(index);
      });
      const line = runs.map((run) => run
        .map((index, position) => `${position === 0 ? 'M' : 'L'}${xAt(index)},${yAt(item.values[index] as number)}`)
        .join(' ')).join(' ');
      const area = runs.filter((run) => run.length > 1).map((run) => [
        ...run.map((index, position) => `${position === 0 ? 'M' : 'L'}${xAt(index)},${yAt(item.values[index] as number)}`),
        `L${xAt(run[run.length - 1])},${baseline}`,
        `L${xAt(run[0])},${baseline}`,
        'Z',
      ].join(' ')).join(' ');
      const color = colorOf(item);
      return (
        <g key={item.key}>
          <defs>
            <linearGradient id={`${gradientId}-area-${seriesIndex}`} x1="0" x2="0" y1="0" y2="1">
              <stop offset="0%" style={{ stopColor: color, stopOpacity: 0.16 }} />
              <stop offset="100%" style={{ stopColor: color, stopOpacity: 0 }} />
            </linearGradient>
          </defs>
          {area && <path d={area} fill={`url(#${gradientId}-area-${seriesIndex})`} stroke="none" className="model-hub-usage-area" />}
          <path d={line} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
          {/* A point with no known neighbour draws no segment, so it needs a dot to be seen at all. */}
          {runs.filter((run) => run.length === 1).map(([index]) => (
            <circle key={`solo-${index}`} cx={xAt(index)} cy={yAt(item.values[index] as number)} r="2.5" fill={color} stroke="var(--background)" strokeWidth="1.5" />
          ))}
          {item.values.map((value, index) => (value === null
            ? <circle key={`unknown-${index}`} cx={xAt(index)} cy={baseline} r="3" className="model-hub-usage-unknown-point" />
            : null))}
        </g>
      );
    });
  }, [bars, bucketCount, gradientId, left, max, plotHeight, plotWidth, report.buckets, visibleSeries]);

  const gridLayer = React.useMemo(() => [0, 1, 2, 3, 4].map((step) => {
    const value = max * step / 4;
    const lineY = top + plotHeight * (1 - step / 4);
    return (
      <g key={step}>
        <line x1={left} x2={width - right} y1={lineY} y2={lineY} className="model-hub-usage-grid" />
        <text x={left - 10} y={lineY + 4} textAnchor="end" className="model-hub-usage-tick model-hub-usage-tick--y">{format(value)}</text>
      </g>
    );
  }), [format, left, max, plotHeight, width]);

  // The hovered bucket's own stack, redrawn over the dimmed columns at full strength.
  const activeColumn = bars && activeIndex !== null
    ? (() => {
      let offset = 0;
      const columnWidth = plotWidth / Math.max(1, bucketCount);
      return (
        <g className="model-hub-usage-active-column">
          {visibleSeries.map((item) => {
            const value = item.values[activeIndex];
            const start = offset;
            offset += value ?? 0;
            return (
              <rect
                key={item.key}
                x={x(activeIndex) - columnWidth * 0.32}
                y={y(offset)}
                width={columnWidth * 0.64}
                height={value === null ? 4 : Math.max(0, y(start) - y(offset))}
                fill={value === null ? 'url(#usage-unknown-pattern)' : seriesColor(item)}
                opacity={0.88}
                rx="2"
              />
            );
          })}
        </g>
      );
    })()
    : null;

  // Beside the crosshair, right by default, flipped left where it would pass
  // the chart's right edge, and kept inside the chart either way. A narrow
  // chart docks it full-width across the top instead, for touch.
  const docked = width < TOOLTIP_DOCK_BELOW;
  const tooltipWidth = Math.min(TOOLTIP_WIDTH, width - 2 * TOOLTIP_INSET);
  // The detail starts past the active bucket's own edge: a pointer moving
  // across the plot enters the next bucket (and the detail moves on) before it
  // could land on the detail, while a deliberate jump onto it still holds it.
  const tooltipGap = bucketSpan / 2 + TOOLTIP_GAP;
  let tooltipLeft = 0;
  let tooltipSide: 'left' | 'right' = 'right';
  if (activeIndex !== null && !docked) {
    const anchor = x(activeIndex);
    const roomRight = width - TOOLTIP_INSET - (anchor + tooltipGap);
    const roomLeft = anchor - tooltipGap - TOOLTIP_INSET;
    // Flip only when the right side is short and the left side has more room;
    // the clamp below covers a chart too narrow for either.
    if (roomRight < tooltipWidth && roomLeft > roomRight) tooltipSide = 'left';
    tooltipLeft = tooltipSide === 'right' ? anchor + tooltipGap : anchor - tooltipGap - tooltipWidth;
    tooltipLeft = Math.max(TOOLTIP_INSET, Math.min(width - TOOLTIP_INSET - tooltipWidth, tooltipLeft));
  }

  const cancelHoverClear = () => {
    if (hoverClearTimer.current !== null) {
      window.clearTimeout(hoverClearTimer.current);
      hoverClearTimer.current = null;
    }
  };
  const handleEscape = React.useCallback(() => {
    if (hoverClearTimer.current !== null) {
      window.clearTimeout(hoverClearTimer.current);
      hoverClearTimer.current = null;
    }
    const invokingButton = invokingBucketKeyRef.current === null
      ? null
      : bucketButtonRefs.current.get(invokingBucketKeyRef.current) ?? null;
    if (pinnedKey !== null) {
      onPin(null);
    }
    setEscapeDismissed(true);
    setHovered(null);
    setInspected(null);
    setDismissed(true);
    focusPinAfterOpenRef.current = false;
    invokingBucketKeyRef.current = null;
    if (activeIndex !== null && invokingButton !== null
      && hostRef.current?.contains(document.activeElement)) {
      suppressNextBucketFocusRef.current = true;
      invokingButton.focus();
    }
  }, [activeIndex, onPin, pinnedKey]);

  React.useEffect(() => {
    const previousInput = previousUsageInputRef.current;
    const inputChanged = previousInput.report !== report
      || previousInput.scopeKey !== scopeKey
      || previousInput.group !== group
      || previousInput.metric !== metric;
    if (!inputChanged) return;
    const scopeChanged = previousInput.scopeKey !== scopeKey;
    previousUsageInputRef.current = { report, scopeKey, group, metric };
    const invokingKey = invokingBucketKeyRef.current;
    const invokingDetailSurvives = !scopeChanged
      && pinnedKey !== null
      && invokingKey !== null
      && report.buckets.some((currentBucket) => currentBucket.key === invokingKey);
    setHovered(null);
    setInspected(null);
    setDismissed(false);
    setEscapeDismissed(false);
    setHidden([]);
    if (!invokingDetailSurvives) invokingBucketKeyRef.current = null;
    suppressNextBucketFocusRef.current = false;
    focusPinAfterOpenRef.current = false;
  }, [group, metric, pinnedKey, report, scopeKey]);

  React.useEffect(() => {
    if (!focusPinAfterOpenRef.current || activeIndex === null) return;
    focusPinAfterOpenRef.current = false;
    pinButtonRef.current?.focus();
  }, [activeIndex, keyboardActivation]);

  React.useEffect(() => {
    if (!hostRef.current || typeof ResizeObserver === 'undefined') return undefined;
    const observer = new ResizeObserver((entries) => {
      setWidth(Math.max(280, entries[0]?.contentRect.width ?? 920));
    });
    observer.observe(hostRef.current);
    return () => observer.disconnect();
  }, []);

  React.useEffect(() => {
    const onPointerDown = (event: PointerEvent) => {
      if (pinnedKey !== null || hostRef.current?.contains(event.target as Node)) return;
      setHovered(null);
      setInspected(null);
      setDismissed(true);
      invokingBucketKeyRef.current = null;
      focusPinAfterOpenRef.current = false;
    };
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key !== 'Escape') return;
      handleEscape();
    };
    document.addEventListener('pointerdown', onPointerDown);
    document.addEventListener('keydown', onKeyDown);
    return () => {
      document.removeEventListener('pointerdown', onPointerDown);
      document.removeEventListener('keydown', onKeyDown);
    };
  }, [handleEscape, pinnedKey]);

  React.useEffect(() => () => {
    if (hoverClearTimer.current !== null) window.clearTimeout(hoverClearTimer.current);
  }, []);

  const scheduleHoverClear = () => {
    if (pinnedKey !== null || inspected !== null) return;
    cancelHoverClear();
    hoverClearTimer.current = window.setTimeout(() => {
      hoverClearTimer.current = null;
      setHovered(null);
    }, 100);
  };

  // Entering a bucket shows it at once; only leaving the plot waits (see
  // scheduleHoverClear), so the pointer can cross into the detail.
  const setHover = (index: number, reopenAfterEscape = false) => {
    if ((escapeDismissed && !reopenAfterEscape) || pinnedKey !== null || inspected !== null) return;
    cancelHoverClear();
    const next = Math.max(0, Math.min(report.buckets.length - 1, index));
    if (reopenAfterEscape) setEscapeDismissed(false);
    setDismissed(false);
    setHovered(next);
  };
  const openDetail = (index: number) => {
    if (pinnedKey !== null) return;
    invokingBucketKeyRef.current = null;
    focusPinAfterOpenRef.current = false;
    setEscapeDismissed(false);
    setDismissed(false);
    setInspected(index);
    setHovered(null);
  };
  const openKeyboardDetail = (index: number) => {
    if (pinnedKey !== null) return;
    invokingBucketKeyRef.current = report.buckets[index]?.key ?? null;
    focusPinAfterOpenRef.current = true;
    setKeyboardActivation((value) => value + 1);
    setEscapeDismissed(false);
    setDismissed(false);
    setInspected(index);
    setHovered(null);
  };
  const handleBucketFocus = (index: number) => {
    if (suppressNextBucketFocusRef.current) {
      suppressNextBucketFocusRef.current = false;
      return;
    }
    setHover(index, true);
  };
  const toggleHidden = (key: string) => {
    setHidden((current) => {
      if (current.includes(key)) return current.filter((item) => item !== key);
      if (current.length >= series.length - 1) return current;
      return [...current, key];
    });
  };
  // One pointer path for the whole chart, the detail included: a sweep that
  // crosses the detail keeps moving the bucket. Only the detail's header,
  // which holds the pin control, holds the bucket still so it can be reached.
  const trackPointer = (event: React.PointerEvent<HTMLDivElement>) => {
    const svg = svgRef.current;
    if (event.pointerType === 'touch' || !svg) return;
    if ((event.target as Element).closest('.model-hub-usage-tooltip-head')) {
      cancelHoverClear();
      return;
    }
    const bounds = svg.getBoundingClientRect();
    const position = ((event.clientX - bounds.left) / bounds.width) * width;
    const index = bars
      ? Math.floor((position - left) / plotWidth * report.buckets.length)
      : Math.round((position - left) / plotWidth * (report.buckets.length - 1));
    setHover(index, true);
  };
  const pinLabel = pinnedKey !== null
    ? t('settings.models.usage.chart.unpin')
    : t('settings.models.usage.chart.pin');

  return (
    <div className="model-hub-usage-chart-content">
      <ChartLegend
        series={series}
        hidden={hidden}
        onToggle={toggleHidden}
        labels={labels}
        count={format}
        blank={t('settings.models.usage.blank') as string}
        noPrice={noPriceText(report, t)}
        ariaLabel={t('settings.models.usage.chart.legend') as string}
        inset={left}
      />
      <div
        className="model-hub-usage-chart-wrap"
        ref={hostRef}
        onPointerMove={trackPointer}
        onPointerLeave={scheduleHoverClear}
      >
        <svg
          ref={svgRef}
          className="model-hub-usage-svg"
          viewBox={`0 0 ${width} ${height}`}
          aria-hidden="true"
        >
          <defs>
            <pattern id="usage-unknown-pattern" width="6" height="6" patternUnits="userSpaceOnUse">
              <path d="M-1,1 l2,-2 M0,6 L6,0 M5,7 l2,-2" stroke="var(--model-hub-usage-unknown)" strokeWidth="1" />
            </pattern>
          </defs>
          {gridLayer}
          {activeIndex !== null && (
            <rect
              x={x(activeIndex) - (bars ? bucketSpan / 2 : Math.min(18, bucketSpan / 2))}
              y={top}
              width={bars ? bucketSpan : Math.min(36, bucketSpan)}
              height={plotHeight}
              className="model-hub-usage-highlight"
              rx="3"
            />
          )}
          <g className={cn('model-hub-usage-series', bars && activeIndex !== null && 'is-dimmed')}>{seriesLayer}</g>
          {activeColumn}
          {activeIndex !== null && (
            <line x1={x(activeIndex)} x2={x(activeIndex)} y1={top} y2={top + plotHeight} className="model-hub-usage-crosshair" />
          )}
          {!bars && activeIndex !== null && visibleSeries.map((item) => {
            const value = item.values[activeIndex];
            if (value === null || value === undefined) return null;
            return (
              <circle
                key={`active-${item.key}`}
                cx={x(activeIndex)}
                cy={y(value)}
                r="4"
                fill={seriesColor(item)}
                stroke="var(--background)"
                strokeWidth="2"
              />
            );
          })}
          {report.buckets.map((currentBucket, index) => (
            <rect
              key={`hit-${currentBucket.key}`}
              className="model-hub-usage-hit-area"
              x={x(index) - bucketSpan / 2}
              y={top}
              width={bucketSpan}
              height={plotHeight}
              onClick={() => openDetail(index)}
            />
          ))}
          {tickIndexes.map((index) => (
            <text
              key={`tick-${report.buckets[index].key}`}
              x={x(index)}
              y={height - 12}
              textAnchor={x(index) - left < 20 ? 'start' : width - right - x(index) < 20 ? 'end' : 'middle'}
              className="model-hub-usage-tick"
            >
              {formatBucketAxisLabel(report.buckets[index], i18n.language)}
            </text>
          ))}
        </svg>
        <div
          className="sr-only"
          role="group"
          aria-label={t('settings.models.usage.chart.detail') as string}
        >
          {report.buckets.map((currentBucket, index) => (
            <button
              type="button"
              key={`accessible-${currentBucket.key}`}
              ref={(element) => {
                if (element) bucketButtonRefs.current.set(currentBucket.key, element);
                else bucketButtonRefs.current.delete(currentBucket.key);
              }}
              aria-label={t('settings.models.usage.chart.bucket', {
                bucket: formatBucketRange(currentBucket, i18n.language, true),
              }) as string}
              onPointerEnter={() => {
                setHover(index);
              }}
              onFocus={() => handleBucketFocus(index)}
              onClick={() => openKeyboardDetail(index)}
            >
              {formatBucketRange(currentBucket, i18n.language, true)}
            </button>
          ))}
        </div>
        {bucket && (
          <div
            className={cn('model-hub-usage-tooltip', pinnedKey !== null && 'is-pinned', docked && 'is-docked')}
            role="dialog"
            aria-label={t('settings.models.usage.chart.detail') as string}
            data-pinned={pinnedKey !== null ? 'true' : 'false'}
            data-side={docked ? 'docked' : tooltipSide}
            style={docked ? undefined : { width: tooltipWidth, transform: `translateX(${tooltipLeft}px)` }}
            onKeyDownCapture={(event) => {
              if (event.key !== 'Escape') return;
              event.stopPropagation();
              handleEscape();
            }}
          >
            <div className="model-hub-usage-tooltip-head">
              <span className="model-hub-usage-tooltip-range">
                <span aria-hidden="true">{heading?.range}</span>
                {heading?.zone && <small aria-hidden="true">{heading.zone}</small>}
                <span className="sr-only">{formatBucketRange(bucket, i18n.language, true)}</span>
              </span>
              <div className="model-hub-usage-tooltip-actions">
                {pinnedKey !== null && <span>{t('settings.models.usage.chart.pinned')}</span>}
                <button
                  type="button"
                  ref={pinButtonRef}
                  className="model-hub-usage-pin"
                  aria-label={pinLabel as string}
                  aria-pressed={pinnedKey !== null}
                  title={pinLabel as string}
                  onClick={() => onPin(pinnedKey !== null ? null : bucket.key)}
                >
                  {pinnedKey !== null ? <PinOff aria-hidden className="size-3.5" /> : <Pin aria-hidden className="size-3.5" />}
                </button>
              </div>
            </div>
            <div className="model-hub-usage-tooltip-total">
              <strong>{activeValue === null
                ? t('settings.models.usage.blank')
                : costIsUnpriced(bucketRows, metric, unpriced)
                  ? noPriceText(report, t)
                  : atLeast(format(activeValue), costIsFloor(bucketRows, metric))}</strong>
              <span>{metricLabel(metric, t)}</span>
            </div>
            <div className="model-hub-usage-tooltip-lines">
              {visibleSeries.map((item) => (
                <div key={item.key}>
                  <span><i style={{ background: seriesColor(item) }} />{labels.get(item.key) ?? item.label}</span>
                  <b>{item.values[activeIndex as number] === null
                    ? t('settings.models.usage.blank')
                    : item.unpriced[activeIndex as number]
                      ? noPriceText(report, t)
                      : atLeast(format(item.values[activeIndex as number] ?? 0), item.floors[activeIndex as number])}</b>
                </div>
              ))}
            </div>
            <div className="model-hub-usage-tooltip-foot">
              <span>
                {bucket.history_complete || bucketRows.some(isModelRow) ? count(bucketTotals.requests) : t('settings.models.usage.blank')}
                {' '}
                {t('settings.models.usage.requests.unit')}
              </span>
              {currentPartialHour && <span>{t('settings.models.usage.chart.currentPartial')}</span>}
              <span>{bucket.history_complete ? t('settings.models.usage.chart.complete') : t('settings.models.usage.chart.partial')}</span>
            </div>
          </div>
        )}
      </div>
      <div className="model-hub-usage-chart-foot">
        <span>{t('settings.models.usage.chart.points', { count: report.buckets.length, granularity: t(`settings.models.usage.granularity.${report.granularity}`) })}</span>
        {metric === 'cost' && <span className="model-hub-usage-cost-note">{t('settings.models.usage.cost.notBilled')}</span>}
        <span>{hidden.length > 0 ? t('settings.models.usage.chart.legendOnly') : t('settings.models.usage.chart.interaction')}</span>
      </div>
    </div>
  );
}

type TableRow = {
  key: string;
  label: string;
  detail: string;
  removed: boolean;
  counters: UsageCounters;
};

function tableRows(
  report: UsageReport,
  filter: UsageFilter,
  group: 'model' | 'source',
  pinnedKey: string | null,
  t: UsageTranslate,
): TableRow[] {
  const buckets = pinnedKey === null ? report.buckets : report.buckets.filter((bucket) => bucket.key === pinnedKey);
  const rows = buckets.flatMap((bucket) => filterBucketRows(bucket, filter)).filter(isModelRow);
  const identities = usageIdentities(report, group, usageText(t));
  return identities.of(rows).map((identity) => ({
    key: identity.key,
    label: identity.label,
    detail: identity.removed
      ? t('settings.models.usage.removedSourcesHint')
      : identity.unlisted
        ? `${identity.sourceLabel} · ${t('settings.models.usage.removedModel')}`
        : identity.sourceLabel,
    removed: identity.removed,
    counters: aggregateCounters(rows.filter((row) => identities.keyOf(row) === identity.key)),
  }));
}

const StatCard: React.FC<{ label: string; value: React.ReactNode; note: React.ReactNode }> = ({ label, value, note }) => (
  <div className="model-hub-usage-stat-card">
    <span className="model-hub-usage-stat-label">{label}</span>
    <strong className="model-hub-usage-stat-value">{value}</strong>
    <span className="model-hub-usage-stat-note">{note}</span>
  </div>
);

export const UsageTab: React.FC<{
  usage: RegionRead<UsageReport>;
  windowKey: UsageWindowKey;
  onWindowChange: (window: UsageWindowKey) => void;
  onRetry?: () => void | Promise<void>;
}> = ({ usage: usageRead, windowKey, onWindowChange, onRetry }) => {
  const { t, i18n } = useUsageTranslation();
  const count = useCount();
  const report = foldRegionRead<UsageReport, UsageReport | null>(usageRead, {
    loading: () => null,
    ready: (data) => data,
    unread: () => null,
    degraded: (staleData) => staleData,
  });
  const [sourceIds, setSourceIds] = React.useState<string[]>([]);
  const [modelKeys, setModelKeys] = React.useState<string[]>([]);
  const [metric, setMetric] = React.useState<UsageMetric>('tokens');
  const format = useMetricFormat(metric);
  const [group, setGroup] = React.useState<UsageGroup>('type');
  const [tableGroup, setTableGroup] = React.useState<'model' | 'source'>('model');
  const [sortAscending, setSortAscending] = React.useState(false);
  const [pinnedKey, setPinnedKey] = React.useState<string | null>(null);
  // What the filters show selected: this report's own options, never a key it no longer offers.
  const selection = React.useMemo(
    () => (report === null ? { sourceIds, modelKeys } : foldUsageSelection(report, { sourceIds, modelKeys })),
    [report, sourceIds, modelKeys],
  );
  const scopeKey = JSON.stringify([windowKey, selection.sourceIds, selection.modelKeys, metric, group]);

  React.useEffect(() => {
    setSourceIds([]);
    setModelKeys([]);
    setPinnedKey(null);
  }, [windowKey]);

  React.useEffect(() => {
    setPinnedKey(null);
  }, [scopeKey]);

  React.useEffect(() => {
    if (report !== null && metric === 'cost' && !reportIsPriced(report)) setMetric('tokens');
  }, [report, metric]);

  React.useEffect(() => {
    if (report !== null && pinnedKey !== null && !report.buckets.some((bucket) => bucket.key === pinnedKey)) {
      setPinnedKey(null);
    }
  }, [report, pinnedKey]);

  // The kept selection is the reconciled one, so a key this report dropped
  // cannot come back unseen once a later report offers it again.
  React.useEffect(() => {
    const same = (left: readonly string[], right: readonly string[]) =>
      left.length === right.length && left.every((key, index) => key === right[index]);
    if (!same(selection.sourceIds, sourceIds)) setSourceIds([...selection.sourceIds]);
    if (!same(selection.modelKeys, modelKeys)) setModelKeys([...selection.modelKeys]);
  }, [selection, sourceIds, modelKeys]);

  if (report === null) {
    return (
      <div className="model-hub-usage-analytics">
        <UsageHeading report={null} windowKey={windowKey} onWindowChange={onWindowChange} />
        {regionFailed(usageRead) ? (
          <FailureState onRetry={onRetry} />
        ) : (
          <div className="model-hub-usage-loading" role="status">
            <LoaderCircle className="size-4 animate-spin" />
            {t('common.loading')}
          </div>
        )}
      </div>
    );
  }

  const allRows = filteredRows(report, { sourceIds: [], modelKeys: [] });
  // A Source that metered nothing in this window still offers itself.
  const sourceOptions: FilterOption[] = usageIdentities(report, 'source', usageText(t))
    .of([...allRows, ...[...report.sources, ...report.services].map((source) => ({ ...emptyCounters(), source_id: source.source_id, model_id: '' }))])
    .map((identity) => ({ key: identity.key, label: identity.label }));
  const modelOptions: FilterOption[] = usageIdentities(report, 'model', usageText(t)).of(allRows.filter(isModelRow)).map((identity) => ({
    key: identity.key,
    label: identity.label,
    detail: identity.unlisted ? t('settings.models.usage.removedModel') : undefined,
  }));
  const filter = resolveUsageFilter(report, selection);
  const scopedRows = filteredRows(report, filter);
  const unpriced = unpricedServices(report);
  // Every figure counts model calls; only the cost also counts search requests.
  const totals = aggregateCounters(scopedRows, unpriced);
  const partialHistory = reportHasPartialHistory(report, filter);
  const reportEmpty = usageIsEmpty(report);
  const filteredEmpty = !reportEmpty && scopedRows.length === 0 && !partialHistory;
  const historyOnlyUnknown = partialHistory && !scopedRows.some(isModelRow);
  const costOnlyUnknown = partialHistory && scopedRows.length === 0;
  const pinnedBucket = pinnedKey === null
    ? null
    : report.buckets.find((bucket) => bucket.key === pinnedKey) ?? null;
  const activePinnedKey = pinnedBucket?.key ?? null;
  const rows = tableRows(report, filter, tableGroup, activePinnedKey, t);
  const sortValue = (row: TableRow): number => usageMetricValue(row.counters, metric) ?? -1;
  // The removed aggregate closes the list whichever way it is sorted.
  const sortedRows = [...rows].sort((left, right) => (Number(left.removed) - Number(right.removed))
    || (sortValue(right) - sortValue(left)) * (sortAscending ? -1 : 1));
  const tableScope = (activePinnedKey === null ? report.buckets : report.buckets.filter((bucket) => bucket.key === activePinnedKey))
    .flatMap((bucket) => filterBucketRows(bucket, filter));
  const tableTotal = aggregateCounters(tableScope.filter(isModelRow));
  const serviceRows = serviceUsageRows(report, filter, activePinnedKey, usageText(t));
  const serviceTotal = aggregateServiceRows(tableScope.filter(isServiceRow), unpriced);
  const reportHasServices = allRows.some(isServiceRow);
  const serviceCost = (totals: ServiceTotals) => (usageHasNoPrice(totals)
    ? noPriceText(report, t)
    : formatCost(totals.api_cost_usd ?? 0, totals.api_cost_lower_bound, i18n.language));
  const serviceReported = (totals: ServiceTotals) => (totals.reported_requests > 0
    ? formatUsd(totals.reported_usd ?? 0, i18n.language)
    : t('settings.models.usage.blank'));
  const serviceBillable = (totals: ServiceTotals) => (
    <>
      {count(totals.billable_requests)}
      {totals.uncertain_requests > 0 && (
        <span className="model-hub-usage-row-detail">
          {t('settings.models.usage.services.uncertain', { count: totals.uncertain_requests, requests: count(totals.uncertain_requests) })}
        </span>
      )}
    </>
  );
  const metricText = (counters: UsageCounters, selectedMetric = metric) => {
    const text = tokenText(counters, selectedMetric, selectedMetric === metric ? format : count, t('settings.models.usage.blank') as string);
    // A cost that is only a floor keeps its 「≥」 wherever it is itemized.
    return selectedMetric === 'cost' ? atLeast(text, counters.api_cost_lower_bound) : text;
  };
  const priced = reportIsPriced(report);
  const partialHistoryNote = String(t('settings.models.usage.partialHistory'));
  const unknownTokensNote = String(t('settings.models.usage.unknownTokens'));
  const allReportedNote = String(t('settings.models.usage.stats.allReported'));

  const exportCsv = () => {
    const csv = buildUsageCsv(report, filter, activePinnedKey, {
      bucketKey: t('settings.models.usage.csv.bucketKey') as string,
      startAt: t('settings.models.usage.csv.startAt') as string,
      endAt: t('settings.models.usage.csv.endAt') as string,
      historyComplete: t('settings.models.usage.csv.historyComplete') as string,
      sourceId: t('settings.models.usage.csv.sourceId') as string,
      modelId: t('settings.models.usage.csv.modelId') as string,
      ledgerKey: t('settings.models.usage.csv.ledgerKey') as string,
      sourceLabel: t('settings.models.usage.csv.sourceLabel') as string,
      modelLabel: t('settings.models.usage.csv.modelLabel') as string,
      requests: t('settings.models.usage.table.requests') as string,
      tokenReports: t('settings.models.usage.csv.tokenReports') as string,
      inputTokens: t('settings.models.usage.csv.inputTokens') as string,
      nonCachedInputTokens: t('settings.models.usage.csv.nonCachedInputTokens') as string,
      cachedInputTokens: t('settings.models.usage.csv.cachedInputTokens') as string,
      outputTokens: t('settings.models.usage.csv.outputTokens') as string,
      totalTokens: t('settings.models.usage.csv.totalTokens') as string,
    }, t('settings.models.usage.unknownModel') as string);
    const url = URL.createObjectURL(new Blob([`\ufeff${csv}`], { type: 'text/csv;charset=utf-8' }));
    const anchor = document.createElement('a');
    anchor.href = url;
    anchor.download = `model-usage-${report.window_key}.csv`;
    anchor.click();
    window.setTimeout(() => URL.revokeObjectURL(url), 0);
  };

  return (
    <div className="model-hub-usage-analytics">
      <UsageHeading report={report} windowKey={windowKey} onWindowChange={onWindowChange} />
      {regionFailed(usageRead) && <FailureState onRetry={onRetry} />}
      <div className="model-hub-usage-filter-bar">
        <Filter aria-hidden className="size-3.5 text-muted" />
        <MultiFilter
          label={t('settings.models.usage.filters.source') as string}
          icon={<Network aria-hidden className="size-3.5" />}
          options={sourceOptions}
          selected={selection.sourceIds}
          onChange={setSourceIds}
        />
        <MultiFilter
          label={t('settings.models.usage.filters.model') as string}
          icon={<Cpu aria-hidden className="size-3.5" />}
          options={modelOptions}
          selected={selection.modelKeys}
          onChange={setModelKeys}
        />
        <div className="model-hub-usage-select">
          <Zap aria-hidden className="size-3.5" />
          <select
            aria-label={t('settings.models.usage.metric.label') as string}
            value={metric}
            onChange={(event) => {
              const next = event.target.value as UsageMetric;
              setMetric(next);
              if (unsplitMetric(next) && group === 'type') setGroup('total');
            }}
          >
            {metricKeysFor(report).map((key) => <option value={key} key={key}>{metricLabel(key, t)}</option>)}
          </select>
          <ChevronDown aria-hidden className="size-3" />
        </div>
        {(selection.sourceIds.length > 0 || selection.modelKeys.length > 0 || metric !== 'tokens') && (
          <Button
            type="button"
            variant="ghost"
            size="sm"
            className="model-hub-usage-reset"
            onClick={() => { setSourceIds([]); setModelKeys([]); setMetric('tokens'); setGroup('type'); }}
          >
            <X aria-hidden className="size-3" />
            {t('settings.models.usage.filters.reset')}
          </Button>
        )}
        <span className="model-hub-usage-filter-context">
          {selection.sourceIds.length > 0 ? t('settings.models.usage.filters.sourceCount', { count: selection.sourceIds.length }) : t('settings.models.usage.filters.allSources')}
          <span>·</span>
          {selection.modelKeys.length > 0 ? t('settings.models.usage.filters.modelCount', { count: selection.modelKeys.length }) : t('settings.models.usage.filters.allModels')}
        </span>
      </div>

      {reportEmpty ? (
        <EmptyState kind="report" />
      ) : filteredEmpty ? (
        <EmptyState kind="filter" onReset={() => { setSourceIds([]); setModelKeys([]); }} />
      ) : (
        <>
          <div className={cn('model-hub-usage-stat-grid', priced && 'model-hub-usage-stat-grid--priced')}>
            <StatCard
              label={t('settings.models.usage.stats.tokens')}
              value={historyOnlyUnknown ? t('settings.models.usage.blank') : metricText(totals, 'tokens')}
              note={!historyOnlyUnknown && usageTokensAreKnown(totals)
                ? t('settings.models.usage.stats.tokenSplit', { input: count(totals.input_tokens), output: count(totals.output_tokens) })
                : historyOnlyUnknown ? partialHistoryNote : unknownTokensNote}
            />
            <StatCard
              label={t('settings.models.usage.stats.requests')}
              value={historyOnlyUnknown ? t('settings.models.usage.blank') : count(totals.requests)}
              note={!historyOnlyUnknown && usageReportShortfall(totals) > 0
                ? t('settings.models.usage.stats.shortfall', { count: usageReportShortfall(totals) })
                : historyOnlyUnknown ? partialHistoryNote : allReportedNote}
            />
            <StatCard
              label={t('settings.models.usage.stats.cached')}
              value={historyOnlyUnknown || usageCachedInputShare(totals) === null ? t('settings.models.usage.blank') : formatPercent(usageCachedInputShare(totals) ?? 0, i18n.language, 1)}
              note={historyOnlyUnknown || usageCachedInputShare(totals) === null
                ? t('settings.models.usage.stats.cacheUnknown')
                : t('settings.models.usage.stats.cacheSplit', { cached: count(totals.cached_input_tokens), input: count(totals.input_tokens) })}
            />
            {priced && (
              <StatCard
                label={t('settings.models.usage.stats.cost')}
                value={costOnlyUnknown || !usageIsPriced(totals)
                  ? t('settings.models.usage.blank')
                  : usageHasNoPrice(totals)
                    ? noPriceText(report, t)
                    : formatCost(totals.api_cost_usd ?? 0, totals.api_cost_lower_bound, i18n.language)}
                note={[
                  t('settings.models.usage.cost.notBilled'),
                  // The vendors' own figures sit beside the list valuation, never in it.
                  (totals.service_reported_usd ?? 0) > 0
                    ? t('settings.models.usage.cost.reported', { usd: formatUsd(totals.service_reported_usd ?? 0, i18n.language) })
                    : null,
                  (totals.excluded_tokens ?? 0) > 0 && !usageHasNoPrice(totals) && !report.pricing?.pending
                    ? t('settings.models.usage.cost.excluded', { count: totals.excluded_tokens ?? 0, tokens: count(totals.excluded_tokens ?? 0) })
                    : null,
                  (totals.excluded_service_requests ?? 0) > 0 && !usageHasNoPrice(totals)
                    ? t('settings.models.usage.cost.excludedServices', {
                      count: totals.excluded_service_requests ?? 0,
                      requests: count(totals.excluded_service_requests ?? 0),
                    })
                    : null,
                  report.pricing?.price_table_date
                    ? t('settings.models.usage.cost.tableDate', { date: report.pricing.price_table_date })
                    : report.pricing?.pending
                      ? t('settings.models.usage.cost.tableFetching')
                      : t('settings.models.usage.cost.tableDateUnknown'),
                ].filter(Boolean).join(' · ')}
              />
            )}
          </div>
          {(partialHistory || reportHasUnknownTokens(report, filter)) && (
            <div className="model-hub-usage-notice" role="status">
              <CircleHelp aria-hidden className="size-3.5 shrink-0" />
              <span>
                {partialHistory && t(report.granularity === 'hour'
                  ? 'settings.models.usage.historicalHourly'
                  : 'settings.models.usage.partialHistory')}
                {partialHistory && reportHasUnknownTokens(report, filter) && ' '}
                {reportHasUnknownTokens(report, filter) && t('settings.models.usage.unknownTokens')}
              </span>
            </div>
          )}
          <section className="model-hub-usage-card" aria-labelledby="model-hub-usage-chart-title">
            <div className="model-hub-usage-card-header">
              <div>
                <h3 id="model-hub-usage-chart-title">{t('settings.models.usage.chart.title')} <span>{t(`settings.models.usage.granularity.${report.granularity}`)}</span></h3>
                <p>{t('settings.models.usage.chart.subtitle')}</p>
              </div>
              <div className="model-hub-usage-group-control">
                <span>{t('settings.models.usage.group.label')}</span>
                <div role="group" aria-label={t('settings.models.usage.group.label') as string}>
                  {groupKeys.map((key) => (
                    <button
                      type="button"
                      key={key}
                      aria-pressed={group === key}
                      disabled={key === 'type' && unsplitMetric(metric)}
                      className={cn(group === key && 'is-selected')}
                      onClick={() => setGroup(key)}
                    >
                      {t(`settings.models.usage.group.${key}`)}
                    </button>
                  ))}
                </div>
              </div>
            </div>
            <UsageChart
              report={report}
              filter={filter}
              metric={metric}
              group={group}
              pinnedKey={activePinnedKey}
              scopeKey={scopeKey}
              onPin={setPinnedKey}
            />
          </section>
          <section className="model-hub-usage-card model-hub-usage-details" aria-labelledby="model-hub-usage-details-title">
            <div className="model-hub-usage-card-header model-hub-usage-details-header">
              <div>
                <h3 id="model-hub-usage-details-title">{t('settings.models.usage.table.title')} <span>{sortedRows.length}</span></h3>
                <p>{activePinnedKey === null
                  ? t('settings.models.usage.table.range')
                  : t('settings.models.usage.table.bucket', { bucket: formatBucketLabel(pinnedBucket!, i18n.language) })}</p>
              </div>
              <div className="model-hub-usage-details-actions">
                {activePinnedKey !== null && <Button type="button" variant="ghost" size="sm" onClick={() => setPinnedKey(null)}><X aria-hidden className="size-3" />{t('settings.models.usage.table.allBuckets')}</Button>}
                <div className="model-hub-usage-table-group" role="group" aria-label={t('settings.models.usage.table.group') as string}>
                  <button type="button" className={tableGroup === 'model' ? 'is-selected' : ''} aria-pressed={tableGroup === 'model'} onClick={() => setTableGroup('model')}>{t('settings.models.usage.table.byModel')}</button>
                  <button type="button" className={tableGroup === 'source' ? 'is-selected' : ''} aria-pressed={tableGroup === 'source'} onClick={() => setTableGroup('source')}>{t('settings.models.usage.table.bySource')}</button>
                </div>
                <Button type="button" variant="outline" size="sm" onClick={exportCsv}><ArrowDownToLine aria-hidden className="size-3.5" />{t('settings.models.usage.table.export')}</Button>
              </div>
            </div>
            <div className="model-hub-usage-table-scroll">
              <table>
                <thead>
                  <tr>
                    <th scope="col">{t('settings.models.usage.table.identity')}</th>
                    <th scope="col">{t('settings.models.usage.table.requests')}</th>
                    <th scope="col">{t('settings.models.usage.table.input')}</th>
                    <th scope="col">{t('settings.models.usage.table.nonCache')}</th>
                    <th scope="col">{t('settings.models.usage.table.cache')}</th>
                    <th scope="col">{t('settings.models.usage.table.output')}</th>
                    <th scope="col" aria-sort={sortAscending ? 'ascending' : 'descending'}>
                      <button
                        type="button"
                        aria-label={t(`settings.models.usage.table.${sortAscending ? 'sortAscending' : 'sortDescending'}`, { metric: metricLabel(metric, t) })}
                        onClick={() => setSortAscending((value) => !value)}
                      >
                        {metricLabel(metric, t)} <ArrowDown aria-hidden className={cn('size-3', sortAscending && 'rotate-180')} />
                      </button>
                    </th>
                    <th scope="col">{t('settings.models.usage.table.share')}</th>
                  </tr>
                </thead>
                <tbody>
                  {sortedRows.map((row) => {
                    const value = usageMetricValue(row.counters, metric);
                    const totalValue = usageMetricValue(tableTotal, metric);
                    // A share of a floor or of an unpriced part is not a known fraction.
                    const shareUnknown = metric === 'cost' && (row.counters.api_cost_lower_bound === true
                      || tableTotal.api_cost_lower_bound === true || usageHasNoPrice(row.counters));
                    const share = shareUnknown || value === null || totalValue === null || totalValue === 0 ? null : value / totalValue;
                    return (
                      <tr key={row.key} className={cn(row.removed && 'is-removed')}>
                        <th scope="row">
                          <span className="model-hub-usage-row-name">{row.label}</span>
                          {row.detail && <span className="model-hub-usage-row-detail">{row.detail}</span>}
                        </th>
                        <td>{count(row.counters.requests)}</td>
                        <td>{tokenText(row.counters, 'input', count, t('settings.models.usage.blank') as string)}</td>
                        <td>{usageTokensAreKnown(row.counters) ? count(usageNonCachedInput(row.counters)) : t('settings.models.usage.blank')}</td>
                        <td>{tokenText(row.counters, 'cache', count, t('settings.models.usage.blank') as string)}</td>
                        <td>{tokenText(row.counters, 'output', count, t('settings.models.usage.blank') as string)}</td>
                        <td className={cn('model-hub-usage-table-total', metric === 'cost' && usageHasNoPrice(row.counters) && 'is-unpriced')}>{metric === 'cost' && usageHasNoPrice(row.counters)
                          ? noPriceText(report, t)
                          : metricText(row.counters)}</td>
                        <td>{share === null ? t('settings.models.usage.blank') : formatPercent(share, i18n.language, 1)}</td>
                      </tr>
                    );
                  })}
                  {sortedRows.length === 0 && <tr><td colSpan={8} className="model-hub-usage-table-empty">{t('settings.models.usage.table.empty')}</td></tr>}
                </tbody>
                {sortedRows.length > 0 && (
                  <tfoot>
                    <tr>
                      <th scope="row">{t('settings.models.usage.table.total')}</th>
                      <td>{count(tableTotal.requests)}</td>
                      <td>{tokenText(tableTotal, 'input', count, t('settings.models.usage.blank') as string)}</td>
                      <td>{usageTokensAreKnown(tableTotal) ? count(usageNonCachedInput(tableTotal)) : t('settings.models.usage.blank')}</td>
                      <td>{tokenText(tableTotal, 'cache', count, t('settings.models.usage.blank') as string)}</td>
                      <td>{tokenText(tableTotal, 'output', count, t('settings.models.usage.blank') as string)}</td>
                      <td>{metric === 'cost' && usageHasNoPrice(tableTotal)
                        ? noPriceText(report, t)
                        : metricText(tableTotal)}</td>
                      <td>{(() => {
                        const totalValue = usageMetricValue(tableTotal, metric);
                        return totalValue === null || totalValue === 0
                          ? t('settings.models.usage.blank')
                          : formatPercent(1, i18n.language);
                      })()}</td>
                    </tr>
                  </tfoot>
                )}
              </table>
            </div>
            <div className="model-hub-usage-table-foot">
              <CircleHelp aria-hidden className="size-3.5 shrink-0" />
              {t('settings.models.usage.table.accounting')}
            </div>
          </section>
          {reportHasServices && (
            <section className="model-hub-usage-card model-hub-usage-details" aria-labelledby="model-hub-usage-services-title">
              <div className="model-hub-usage-card-header model-hub-usage-details-header">
                <div>
                  <h3 id="model-hub-usage-services-title">{t(serviceRows.some((row) => row.tool === 'web_fetch') ? 'settings.models.usage.services.hostedTitle' : 'settings.models.usage.services.title')} <span>{serviceRows.length}</span></h3>
                  <p>{activePinnedKey === null
                    ? t('settings.models.usage.table.range')
                    : t('settings.models.usage.table.bucket', { bucket: formatBucketLabel(pinnedBucket!, i18n.language) })}</p>
                </div>
              </div>
              <div className="model-hub-usage-table-scroll">
                <table>
                  <thead>
                    <tr>
                      <th scope="col">{t('settings.models.usage.services.identity')}</th>
                      <th scope="col">{t('settings.models.usage.table.requests')}</th>
                      <th scope="col">{t('settings.models.usage.services.billable')}</th>
                      {priced && <th scope="col">{t('settings.models.usage.metric.cost')}</th>}
                      {priced && <th scope="col">{t('settings.models.usage.services.reported')}</th>}
                    </tr>
                  </thead>
                  <tbody>
                    {serviceRows.map((row) => (
                      <tr key={row.key} className={cn(row.removed && 'is-removed')}>
                        <th scope="row">
                          <span className="model-hub-usage-row-name">{row.label}</span>
                          <span className="model-hub-usage-row-detail">{row.removed ? t('settings.models.usage.removedSourcesHint') : row.service}{row.tool === 'web_fetch' && ` · ${t('settings.models.tools.tool.web_fetch.name')}`}</span>
                        </th>
                        <td>{count(row.totals.requests)}</td>
                        <td>{serviceBillable(row.totals)}</td>
                        {priced && <td className={cn('model-hub-usage-table-total', usageHasNoPrice(row.totals) && 'is-unpriced')}>{serviceCost(row.totals)}</td>}
                        {priced && <td>{serviceReported(row.totals)}</td>}
                      </tr>
                    ))}
                    {serviceRows.length === 0 && <tr><td colSpan={priced ? 5 : 3} className="model-hub-usage-table-empty">{t('settings.models.usage.table.empty')}</td></tr>}
                  </tbody>
                  {serviceRows.length > 0 && (
                    <tfoot>
                      <tr>
                        <th scope="row">{t('settings.models.usage.table.total')}</th>
                        <td>{count(serviceTotal.requests)}</td>
                        <td>{serviceBillable(serviceTotal)}</td>
                        {priced && <td>{serviceCost(serviceTotal)}</td>}
                        {priced && <td>{serviceReported(serviceTotal)}</td>}
                      </tr>
                    </tfoot>
                  )}
                </table>
              </div>
              <div className="model-hub-usage-table-foot">
                <CircleHelp aria-hidden className="size-3.5 shrink-0" />
                {[
                  t('settings.models.usage.services.accounting'),
                  report.pricing?.service_price_date
                    ? t('settings.models.usage.services.priceDate', { date: report.pricing.service_price_date })
                    : null,
                ].filter(Boolean).join(' ')}
              </div>
            </section>
          )}
        </>
      )}
    </div>
  );
};

function UsageHeading({
  report,
  windowKey,
  onWindowChange,
}: {
  report: UsageReport | null;
  windowKey: UsageWindowKey;
  onWindowChange: (window: UsageWindowKey) => void;
}) {
  const { t, i18n } = useUsageTranslation();
  return (
    <div className="model-hub-usage-heading">
      <div>
        <h2>{t('settings.models.usage.title')}</h2>
        <p>
          {report
            ? formatBucketRange({ start_at: report.from_at, end_at: report.to_at, key: report.from_at, history_complete: true, rows: [] }, i18n.language, true)
            : t('settings.models.usage.detail')}
        </p>
      </div>
      <SegmentedRadio
        value={windowKey}
        onChange={onWindowChange}
        options={USAGE_WINDOW_OPTIONS.map((key) => ({ id: key, label: t(`settings.models.usage.window.${key}`) as string }))}
        ariaLabel={t('settings.models.usage.window.label') as string}
        className="model-hub-usage-window"
      />
    </div>
  );
}

function FailureState({ onRetry }: { onRetry?: () => void | Promise<void> }) {
  const { t } = useUsageTranslation();
  return (
    <div className="model-hub-usage-failure" role="alert">
      <span>{t('settings.models.usage.failure')}</span>
      <button type="button" onClick={() => void onRetry?.()}>{t('settings.models.usage.retry')}</button>
    </div>
  );
}

function EmptyState({ kind, onReset }: { kind: 'report' | 'filter'; onReset?: () => void }) {
  const { t } = useUsageTranslation();
  return (
    <div className="model-hub-usage-empty-state">
      <Search aria-hidden className="size-7" />
      <h3>{t(`settings.models.usage.empty.${kind}.title`)}</h3>
      <p>{t(`settings.models.usage.empty.${kind}.body`)}</p>
      {onReset && <Button type="button" variant="outline" onClick={onReset}>{t('settings.models.usage.filters.reset')}</Button>}
    </div>
  );
}