Spaces:
Running
Running
File size: 7,548 Bytes
b034029 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | import { useState, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Line } from 'react-chartjs-2';
import { Card } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import type { TokenCategory } from '@/utils/usage';
import { buildChartOptions, getHourChartMinWidth } from '@/utils/usage/chartConfig';
import type { UsageOverviewPayload } from './hooks/useUsageData';
import styles from '@/pages/UsagePage.module.scss';
const TOKEN_COLORS: Record<TokenCategory, { border: string; bg: string }> = {
input: { border: '#8b8680', bg: 'rgba(139, 134, 128, 0.25)' },
output: { border: '#22c55e', bg: 'rgba(34, 197, 94, 0.25)' },
cached: { border: '#f59e0b', bg: 'rgba(245, 158, 11, 0.25)' },
reasoning: { border: '#8b5cf6', bg: 'rgba(139, 92, 246, 0.25)' }
};
const CATEGORIES: TokenCategory[] = ['input', 'output', 'cached', 'reasoning'];
const HOUR_MS = 60 * 60 * 1000;
type TokenBreakdownChartPeriod = 'hour' | 'day';
type TokenSeriesSource = NonNullable<UsageOverviewPayload['series']>;
export type TokenBreakdownChartSeries = {
labels: string[];
dataByCategory: Record<TokenCategory, number[]>;
};
export type BuildTokenBreakdownChartSeriesOptions = {
usage: UsageOverviewPayload | null;
period: TokenBreakdownChartPeriod;
hourWindowHours?: number;
endMs?: number;
};
const normalizeHourWindow = (hourWindowHours?: number): number => {
if (!Number.isFinite(hourWindowHours) || !hourWindowHours || hourWindowHours <= 0) {
return 24;
}
return Math.min(Math.max(Math.floor(hourWindowHours), 1), 24);
};
const formatHourBucketKey = (timestampMs: number): string => `${new Date(timestampMs).toISOString().slice(0, 13)}:00:00Z`;
const formatChartLabel = (label: string, period: TokenBreakdownChartPeriod) => {
if (period !== 'hour') return label;
const date = new Date(label);
if (Number.isNaN(date.getTime())) return label;
return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};
const getTokenSource = (usage: UsageOverviewPayload | null, period: TokenBreakdownChartPeriod): TokenSeriesSource | undefined => (
period === 'hour' ? (usage?.hourly_series ?? usage?.series) : (usage?.daily_series ?? usage?.series)
);
const buildHourlyLabels = (source: TokenSeriesSource | undefined, hourWindowHours?: number, endMs?: number) => {
const labels = Object.keys(source?.input_tokens ?? {}).sort((a, b) => a.localeCompare(b));
if (labels.length === 0) return [];
const bucketCount = normalizeHourWindow(hourWindowHours);
const latestLabelMs = Date.parse(labels[labels.length - 1]);
const requestedEndMs = Number.isFinite(endMs) && endMs && endMs > 0 ? endMs : latestLabelMs;
const currentHour = new Date(requestedEndMs);
currentHour.setUTCMinutes(0, 0, 0);
const earliestTime = currentHour.getTime() - ((bucketCount - 1) * HOUR_MS);
return Array.from({ length: bucketCount }, (_, index) => formatHourBucketKey(earliestTime + index * HOUR_MS));
};
export const buildTokenBreakdownChartSeries = ({
usage,
period,
hourWindowHours,
endMs,
}: BuildTokenBreakdownChartSeriesOptions): TokenBreakdownChartSeries => {
const source = getTokenSource(usage, period);
const labels = period === 'hour'
? buildHourlyLabels(source, hourWindowHours, endMs)
: Object.keys(source?.input_tokens ?? {}).sort((a, b) => a.localeCompare(b));
return {
labels: labels.map((label) => formatChartLabel(label, period)),
dataByCategory: {
input: labels.map((label) => Number(source?.input_tokens?.[label] ?? 0)),
output: labels.map((label) => Number(source?.output_tokens?.[label] ?? 0)),
cached: labels.map((label) => Number(source?.cached_tokens?.[label] ?? 0)),
reasoning: labels.map((label) => Number(source?.reasoning_tokens?.[label] ?? 0)),
},
};
};
export interface TokenBreakdownChartProps {
usage: UsageOverviewPayload | null;
loading: boolean;
isDark: boolean;
isMobile: boolean;
hourWindowHours?: number;
endMs?: number;
}
export function TokenBreakdownChart({
usage,
loading,
isDark,
isMobile,
hourWindowHours,
endMs
}: TokenBreakdownChartProps) {
const { t } = useTranslation();
const [period, setPeriod] = useState<'hour' | 'day'>('hour');
const { chartData, chartOptions } = useMemo(() => {
const series = buildTokenBreakdownChartSeries({ usage, period, hourWindowHours, endMs });
const categoryLabels: Record<TokenCategory, string> = {
input: t('usage_stats.input_tokens'),
output: t('usage_stats.output_tokens'),
cached: t('usage_stats.cached_tokens'),
reasoning: t('usage_stats.reasoning_tokens')
};
const data = {
labels: series.labels,
datasets: CATEGORIES.map((cat) => ({
label: categoryLabels[cat],
data: series.dataByCategory[cat],
borderColor: TOKEN_COLORS[cat].border,
backgroundColor: TOKEN_COLORS[cat].bg,
pointBackgroundColor: TOKEN_COLORS[cat].border,
pointBorderColor: TOKEN_COLORS[cat].border,
fill: true,
tension: 0.35
}))
};
const baseOptions = buildChartOptions({ period, labels: series.labels, isDark, isMobile });
const options = {
...baseOptions,
scales: {
...baseOptions.scales,
y: {
...baseOptions.scales?.y,
stacked: true
},
x: {
...baseOptions.scales?.x,
stacked: true
}
}
};
return { chartData: data, chartOptions: options };
}, [usage, period, isDark, isMobile, hourWindowHours, endMs, t]);
return (
<Card
title={t('usage_stats.token_breakdown_title')}
extra={
<div className={styles.periodButtons}>
<Button
variant={period === 'hour' ? 'primary' : 'secondary'}
size="sm"
onClick={() => setPeriod('hour')}
>
{t('usage_stats.by_hour')}
</Button>
<Button
variant={period === 'day' ? 'primary' : 'secondary'}
size="sm"
onClick={() => setPeriod('day')}
>
{t('usage_stats.by_day')}
</Button>
</div>
}
>
{loading ? (
<div className={styles.hint}>{t('common.loading')}</div>
) : chartData.labels.length > 0 ? (
<div className={styles.chartWrapper}>
<div className={styles.chartLegend} aria-label="Chart legend">
{chartData.datasets.map((dataset, index) => (
<div
key={`${dataset.label}-${index}`}
className={styles.legendItem}
title={dataset.label}
>
<span className={styles.legendDot} style={{ backgroundColor: dataset.borderColor }} />
<span className={styles.legendLabel}>{dataset.label}</span>
</div>
))}
</div>
<div className={styles.chartArea}>
<div className={styles.chartScroller}>
<div
className={styles.chartCanvas}
style={
period === 'hour'
? { minWidth: getHourChartMinWidth(chartData.labels.length, isMobile) }
: undefined
}
>
<Line data={chartData} options={chartOptions} />
</div>
</div>
</div>
</div>
) : (
<div className={styles.hint}>{t('usage_stats.no_data')}</div>
)}
</Card>
);
}
|