The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 581 lines 19 KB
Raw
1 import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
2 import type { UsageProviderKind } from "@t3tools/contracts";
3 import { T, useGT, useLocale, useMessages } from "gt-react";
4 import { useLayoutEffect, useRef, useState } from "react";
5
6 import type { DailyTotals, HourlyTotals } from "@t3tools/shared/usageMerge";
7 import {
8 formatDayShort,
9 formatHourShort,
10 formatTokens,
11 formatUsd,
12 } from "@t3tools/shared/usageFormat";
13 import { formatRelativeHourShort } from "@t3tools/shared/usageFormatCopy";
14 import { cn } from "~/lib/utils";
15 import { PROVIDER_ORDER, PROVIDER_PRESENTATION } from "./usageProviders";
16 import { observeResize } from "~/lib/observeResize";
17
18 const VIEW_WIDTH = 960;
19 const VIEW_HEIGHT = 260;
20 const TICK_COUNT = 4;
21 const PLOT_TOP = 8;
22 const NONE_LOADING: ReadonlySet<UsageProviderKind> = new Set();
23
24 export type UsageChartMetric = "tokens" | "cost";
25
26 interface UsageProviderChartProps {
27 readonly providers: readonly UsageProviderKind[];
28 readonly loadingProviders?: ReadonlySet<UsageProviderKind>;
29 readonly days: readonly string[];
30 readonly daily: readonly DailyTotals[];
31 readonly hours: readonly string[];
32 readonly hourly: readonly HourlyTotals[];
33 readonly metric: UsageChartMetric;
34 readonly referenceTime: string | undefined;
35 readonly resolution: "day" | "hour";
36 readonly timeZone: string;
37 readonly hour12: boolean;
38 }
39
40 export interface DayColumn {
41 readonly bands: readonly {
42 readonly provider: UsageProviderKind;
43 readonly value: number;
44 }[];
45 readonly total: number;
46 }
47
48 interface Point {
49 readonly x: number;
50 readonly y: number;
51 }
52
53 function valueFor(
54 totals: DailyTotals | HourlyTotals | undefined,
55 provider: UsageProviderKind,
56 metric: UsageChartMetric,
57 ): number {
58 const entry = totals?.byProvider.get(provider);
59 if (entry === undefined) return 0;
60 return metric === "tokens" ? entry.totalTokens : entry.costUsd;
61 }
62
63 export function buildPeriodColumns(
64 periods: readonly string[],
65 byPeriod: ReadonlyMap<string, DailyTotals | HourlyTotals>,
66 metric: UsageChartMetric,
67 ): readonly DayColumn[] {
68 return periods.map((period) => {
69 const entry = byPeriod.get(period);
70 const bands = PROVIDER_ORDER.map((provider) => ({
71 provider,
72 value: valueFor(entry, provider, metric),
73 }));
74 return { bands, total: bands.reduce((sum, band) => sum + band.value, 0) };
75 });
76 }
77
78 function monotoneTangents(points: readonly Point[]): readonly number[] {
79 const count = points.length;
80 if (count < 2) return [0];
81
82 const slopes: number[] = [];
83 for (let index = 0; index < count - 1; index += 1) {
84 const dx = (points[index + 1]?.x ?? 0) - (points[index]?.x ?? 0);
85 const dy = (points[index + 1]?.y ?? 0) - (points[index]?.y ?? 0);
86 slopes.push(dx === 0 ? 0 : dy / dx);
87 }
88
89 const tangents: number[] = Array.from({ length: count }, () => 0);
90 tangents[0] = slopes[0] ?? 0;
91 tangents[count - 1] = slopes[count - 2] ?? 0;
92 for (let index = 1; index < count - 1; index += 1) {
93 const previous = slopes[index - 1] ?? 0;
94 const next = slopes[index] ?? 0;
95 tangents[index] = previous * next <= 0 ? 0 : (previous + next) / 2;
96 }
97
98 for (let index = 0; index < count - 1; index += 1) {
99 const slope = slopes[index] ?? 0;
100 if (slope === 0) {
101 tangents[index] = 0;
102 tangents[index + 1] = 0;
103 continue;
104 }
105 const a = (tangents[index] ?? 0) / slope;
106 const b = (tangents[index + 1] ?? 0) / slope;
107 const magnitude = a * a + b * b;
108 if (magnitude > 9) {
109 const scale = 3 / Math.sqrt(magnitude);
110 tangents[index] = scale * a * slope;
111 tangents[index + 1] = scale * b * slope;
112 }
113 }
114
115 return tangents;
116 }
117
118 interface CurveSegment {
119 readonly from: Point;
120 readonly c1: Point;
121 readonly c2: Point;
122 readonly to: Point;
123 }
124
125 function smoothCurve(points: readonly Point[]): readonly CurveSegment[] {
126 if (points.length < 2) return [];
127 const tangents = monotoneTangents(points);
128 const segments: CurveSegment[] = [];
129
130 for (let index = 0; index < points.length - 1; index += 1) {
131 const from = points[index];
132 const to = points[index + 1];
133 if (from === undefined || to === undefined) continue;
134 const dx = to.x - from.x;
135 segments.push({
136 from,
137 c1: { x: from.x + dx / 3, y: from.y + ((tangents[index] ?? 0) * dx) / 3 },
138 c2: { x: to.x - dx / 3, y: to.y - ((tangents[index + 1] ?? 0) * dx) / 3 },
139 to,
140 });
141 }
142 return segments;
143 }
144
145 function curvePath(segments: readonly CurveSegment[]): string {
146 const first = segments[0];
147 if (first === undefined) return "";
148 let path = `M${first.from.x.toFixed(2)},${first.from.y.toFixed(2)}`;
149 for (const segment of segments) {
150 path += ` C${segment.c1.x.toFixed(2)},${segment.c1.y.toFixed(2)} ${segment.c2.x.toFixed(2)},${segment.c2.y.toFixed(2)} ${segment.to.x.toFixed(2)},${segment.to.y.toFixed(2)}`;
151 }
152 return path;
153 }
154
155 function areaPath(line: string) {
156 return line === "" ? "" : `${line} L${VIEW_WIDTH},${VIEW_HEIGHT} L0,${VIEW_HEIGHT} Z`;
157 }
158
159 function niceScale(peak: number, count: number): { max: number; ticks: readonly number[] } {
160 if (peak <= 0) return { max: 0, ticks: [0] };
161
162 const rawStep = peak / count;
163 const magnitude = 10 ** Math.floor(Math.log10(rawStep));
164 const normalized = rawStep / magnitude;
165 const step = (normalized > 5 ? 10 : normalized > 2 ? 5 : normalized > 1 ? 2 : 1) * magnitude;
166
167 const max = Math.ceil(peak / step) * step;
168 const ticks: number[] = [];
169 for (let value = 0; value <= max + step * 1e-6; value += step) ticks.push(value);
170 return { max, ticks };
171 }
172
173 const PLACEHOLDER_TICKS = Array.from({ length: TICK_COUNT + 1 }, (_, index) => index);
174
175 function chartScale(
176 columns: readonly DayColumn[],
177 loadingProviders: ReadonlySet<UsageProviderKind>,
178 ) {
179 // Layered series each start at zero; summing peaks would waste plot height.
180 const peak = columns.reduce(
181 (max, column) => column.bands.reduce((inner, band) => Math.max(inner, band.value), max),
182 0,
183 );
184 return peak === 0 && loadingProviders.size > 0
185 ? { max: TICK_COUNT, ticks: PLACEHOLDER_TICKS, labeled: false }
186 : { ...niceScale(peak, TICK_COUNT), labeled: true };
187 }
188
189 function valueToY(value: number, max: number) {
190 return max === 0 ? VIEW_HEIGHT : VIEW_HEIGHT - (value / max) * (VIEW_HEIGHT - PLOT_TOP);
191 }
192
193 function buildChart(
194 periods: readonly string[],
195 byPeriod: ReadonlyMap<string, DailyTotals | HourlyTotals>,
196 metric: UsageChartMetric,
197 providers: readonly UsageProviderKind[],
198 loadingProviders: ReadonlySet<UsageProviderKind>,
199 ) {
200 const columns = buildPeriodColumns(periods, byPeriod, metric);
201 const scale = chartScale(columns, loadingProviders);
202 const stepX = periods.length < 2 ? 0 : VIEW_WIDTH / (periods.length - 1);
203 const paths = providers.map((provider) => {
204 const slot = PROVIDER_ORDER.indexOf(provider);
205 const line = curvePath(
206 smoothCurve(
207 columns.map((column, periodIndex) => ({
208 x: periodIndex * stepX,
209 y: valueToY(column.bands[slot]?.value ?? 0, scale.max),
210 })),
211 ),
212 );
213 return {
214 provider,
215 loading: loadingProviders.has(provider),
216 total: columns.reduce((sum, column) => sum + (column.bands[slot]?.value ?? 0), 0),
217 line,
218 area: areaPath(line),
219 };
220 });
221
222 return { columns, scale, stepX, paths: paths.toSorted((a, b) => b.total - a.total) };
223 }
224
225 function UsageChartTooltip({
226 tooltipRef,
227 label,
228 column,
229 providers,
230 loadingProviders,
231 format,
232 }: {
233 readonly tooltipRef: React.Ref<HTMLDivElement>;
234 readonly label: string;
235 readonly column: DayColumn | undefined;
236 readonly providers: readonly UsageProviderKind[];
237 readonly loadingProviders: ReadonlySet<UsageProviderKind>;
238 readonly format: (value: number) => string;
239 }) {
240 const partial = providers.some((provider) => loadingProviders.has(provider));
241 return (
242 <div
243 ref={tooltipRef}
244 className="surface-glass pointer-events-none absolute z-10 min-w-36 max-w-full rounded-xl border border-border/50 px-2.5 py-2 text-xs shadow-lg"
245 style={{
246 left: "var(--usage-tooltip-left, 0px)",
247 top: "var(--usage-tooltip-top, 0px)",
248 }}
249 >
250 <div className="mb-1 text-muted-foreground">{label}</div>
251 {providers.map((provider) => {
252 const { label: providerLabel, driverKind } = PROVIDER_PRESENTATION[provider];
253 return (
254 <div key={provider} className="flex items-center justify-between gap-3">
255 <span className="flex items-center gap-1.5 text-muted-foreground">
256 <ProviderInstanceIcon
257 driverKind={driverKind}
258 displayName={providerLabel}
259 iconClassName="size-3"
260 />
261 {providerLabel}
262 </span>
263 <span
264 className={cn(
265 "tabular-nums",
266 loadingProviders.has(provider) ? "text-muted-foreground" : "text-foreground",
267 )}
268 >
269 {format(column?.bands.find((band) => band.provider === provider)?.value ?? 0)}
270 </span>
271 </div>
272 );
273 })}
274 <div className="mt-1 flex items-center justify-between gap-3 border-t border-border pt-1">
275 <span className="text-muted-foreground">
276 <T>Total</T>
277 </span>
278 <span className={cn("tabular-nums", partial ? "text-muted-foreground" : "text-foreground")}>
279 {format(column?.total ?? 0)}
280 </span>
281 </div>
282 </div>
283 );
284 }
285
286 function UsageChartPlot({
287 periods,
288 columns,
289 stepX,
290 providers,
291 loadingProviders,
292 format,
293 formatTooltipPeriod,
294 children,
295 }: {
296 readonly periods: readonly string[];
297 readonly columns: readonly DayColumn[];
298 readonly stepX: number;
299 readonly providers: readonly UsageProviderKind[];
300 readonly loadingProviders: ReadonlySet<UsageProviderKind>;
301 readonly format: (value: number) => string;
302 readonly formatTooltipPeriod: (period: string) => string;
303 readonly children: React.ReactNode;
304 }) {
305 const [hoverIndex, setHoverIndex] = useState<number | null>(null);
306 const plotRef = useRef<HTMLDivElement | null>(null);
307 const tooltipRef = useRef<HTMLDivElement | null>(null);
308 const hoverPositionRef = useRef<{ x: number; y: number } | null>(null);
309
310 const positionTooltip = () => {
311 const plot = plotRef.current;
312 const tooltip = tooltipRef.current;
313 const hoverPosition = hoverPositionRef.current;
314 if (plot === null || tooltip === null || hoverPosition === null) return;
315
316 const gap = 12;
317 const tooltipWidth = tooltip.offsetWidth;
318 const tooltipHeight = tooltip.offsetHeight;
319 const plotWidth = plot.clientWidth;
320 const plotHeight = plot.clientHeight;
321 const preferredLeft =
322 hoverPosition.x + gap + tooltipWidth <= plotWidth
323 ? hoverPosition.x + gap
324 : hoverPosition.x - gap - tooltipWidth;
325 const preferredTop =
326 hoverPosition.y + gap + tooltipHeight <= plotHeight
327 ? hoverPosition.y + gap
328 : hoverPosition.y - gap - tooltipHeight;
329 const left = Math.min(Math.max(0, preferredLeft), Math.max(0, plotWidth - tooltipWidth));
330 const top = Math.min(Math.max(0, preferredTop), Math.max(0, plotHeight - tooltipHeight));
331 plot.style.setProperty("--usage-tooltip-left", `${left}px`);
332 plot.style.setProperty("--usage-tooltip-top", `${top}px`);
333 };
334
335 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- positions the hover tooltip through plot CSS variables before paint and on ResizeObserver
336 useLayoutEffect(() => {
337 if (hoverIndex === null) return;
338 positionTooltip();
339
340 const plot = plotRef.current;
341 const tooltip = tooltipRef.current;
342 if (plot === null || tooltip === null) return;
343
344 return observeResize([plot, tooltip], positionTooltip);
345 }, [hoverIndex, positionTooltip]);
346
347 const handleMove = (event: React.MouseEvent<HTMLDivElement>) => {
348 const plot = plotRef.current;
349 if (plot === null || periods.length === 0) return;
350 const bounds = plot.getBoundingClientRect();
351 if (bounds.width === 0) return;
352 const localX = Math.min(bounds.width, Math.max(0, event.clientX - bounds.left));
353 const localY = Math.min(bounds.height, Math.max(0, event.clientY - bounds.top));
354 const fraction = localX / bounds.width;
355 const index = Math.round(fraction * (periods.length - 1));
356 hoverPositionRef.current = { x: localX, y: localY };
357 positionTooltip();
358 setHoverIndex(Math.min(periods.length - 1, Math.max(0, index)));
359 };
360
361 const hoveredPeriod = hoverIndex === null ? undefined : periods[hoverIndex];
362
363 return (
364 <div
365 ref={plotRef}
366 className="relative h-56 flex-1"
367 onMouseMove={handleMove}
368 onMouseLeave={() => {
369 hoverPositionRef.current = null;
370 setHoverIndex(null);
371 }}
372 >
373 <svg
374 className="h-full w-full"
375 viewBox={`0 0 ${VIEW_WIDTH} ${VIEW_HEIGHT}`}
376 preserveAspectRatio="none"
377 aria-hidden
378 >
379 {children}
380 {hoverIndex === null ? null : (
381 <line
382 x1={hoverIndex * stepX}
383 x2={hoverIndex * stepX}
384 y1={PLOT_TOP}
385 y2={VIEW_HEIGHT}
386 stroke="currentColor"
387 strokeWidth={1}
388 className="text-muted-foreground"
389 vectorEffect="non-scaling-stroke"
390 />
391 )}
392 </svg>
393
394 {hoverIndex === null || hoveredPeriod === undefined ? null : (
395 <UsageChartTooltip
396 tooltipRef={tooltipRef}
397 label={formatTooltipPeriod(hoveredPeriod)}
398 column={columns[hoverIndex]}
399 providers={providers}
400 loadingProviders={loadingProviders}
401 format={format}
402 />
403 )}
404 </div>
405 );
406 }
407
408 export function UsageProviderChart({
409 providers,
410 loadingProviders = NONE_LOADING,
411 days,
412 daily,
413 hours,
414 hourly,
415 metric,
416 referenceTime,
417 resolution,
418 timeZone,
419 hour12,
420 }: UsageProviderChartProps) {
421 const gt = useGT();
422 const locale = useLocale();
423 const m = useMessages();
424 const periods = resolution === "hour" ? hours : days;
425 const totals: readonly (DailyTotals | HourlyTotals)[] = resolution === "hour" ? hourly : daily;
426 const byPeriod = new Map(
427 totals.map((entry) => ["hourStart" in entry ? entry.hourStart : entry.day, entry]),
428 );
429 const { columns, scale, paths, stepX } = buildChart(
430 periods,
431 byPeriod,
432 metric,
433 providers,
434 loadingProviders,
435 );
436
437 const toY = (value: number) => valueToY(value, scale.max);
438 const seriesClassName = (loading: boolean) =>
439 cn("transition-opacity", loading && "opacity-40 delay-150");
440 const format = metric === "tokens" ? formatTokens : (value: number) => formatUsd(value, locale);
441 const formatPeriod = (period: string) =>
442 resolution === "hour"
443 ? formatHourShort(period, timeZone, hour12, locale)
444 : formatDayShort(period, locale);
445 const formatTooltipPeriod = (period: string) =>
446 resolution === "hour" && referenceTime !== undefined
447 ? formatRelativeHourShort(period, referenceTime, timeZone, hour12, m, locale)
448 : formatPeriod(period);
449
450 return (
451 <div className="flex flex-col gap-1">
452 <div className="flex gap-2">
453 <div aria-hidden className="relative h-56 w-14 shrink-0">
454 {scale.labeled
455 ? scale.ticks.map((tick) => (
456 <span
457 key={tick}
458 className="absolute right-0 -translate-y-1/2 text-3xs text-muted-foreground tabular-nums"
459 style={{ top: `${(toY(tick) / VIEW_HEIGHT) * 100}%` }}
460 >
461 {tick === 0 ? "0" : format(tick)}
462 </span>
463 ))
464 : null}
465 </div>
466
467 <UsageChartPlot
468 periods={periods}
469 columns={columns}
470 stepX={stepX}
471 providers={providers}
472 loadingProviders={loadingProviders}
473 format={format}
474 formatTooltipPeriod={formatTooltipPeriod}
475 >
476 {scale.ticks.map((tick) => {
477 const y = toY(tick);
478 return (
479 <line
480 key={tick}
481 x1={0}
482 x2={VIEW_WIDTH}
483 y1={y}
484 y2={y}
485 stroke="currentColor"
486 strokeWidth={1}
487 className="text-border"
488 vectorEffect="non-scaling-stroke"
489 />
490 );
491 })}
492
493 {paths.map(({ provider, loading, area }) => (
494 <path
495 key={provider}
496 d={area}
497 className={seriesClassName(loading)}
498 fill={PROVIDER_PRESENTATION[provider].color}
499 fillOpacity={0.12}
500 />
501 ))}
502 {paths.map(({ provider, loading, line }) => (
503 <path
504 key={provider}
505 d={line}
506 className={seriesClassName(loading)}
507 fill="none"
508 stroke={PROVIDER_PRESENTATION[provider].color}
509 strokeWidth={2}
510 vectorEffect="non-scaling-stroke"
511 />
512 ))}
513 </UsageChartPlot>
514 </div>
515
516 <div
517 aria-hidden
518 className="flex justify-between pl-16 text-3xs text-muted-foreground uppercase"
519 >
520 <span>{periods[0] === undefined ? "" : formatPeriod(periods[0])}</span>
521 <span>
522 {periods[Math.floor(periods.length / 2)] === undefined
523 ? ""
524 : formatPeriod(periods[Math.floor(periods.length / 2)] ?? "")}
525 </span>
526 <span>
527 {periods[periods.length - 1] === undefined
528 ? ""
529 : formatPeriod(periods[periods.length - 1] ?? "")}
530 </span>
531 </div>
532
533 {/* The plot and its axes are hover-only; this carries the same figures for screen readers.
534 sr-only sits on a wrapper: Firefox does not clip a table's caption by the table's own box. */}
535 <div className="sr-only">
536 <table>
537 <caption>
538 {resolution === "hour"
539 ? metric === "tokens"
540 ? gt("Hourly processed tokens by provider")
541 : gt("Hourly cost by provider")
542 : metric === "tokens"
543 ? gt("Daily processed tokens by provider")
544 : gt("Daily cost by provider")}
545 </caption>
546 <thead>
547 <tr>
548 <th scope="col">{resolution === "hour" ? gt("Hour") : gt("Day")}</th>
549 {providers.map((provider) => (
550 <th key={provider} scope="col">
551 {PROVIDER_PRESENTATION[provider].label}
552 </th>
553 ))}
554 {providers.length > 1 ? (
555 <th scope="col">
556 <T>Total</T>
557 </th>
558 ) : null}
559 </tr>
560 </thead>
561 <tbody>
562 {periods.map((period, index) => {
563 const column = columns[index];
564 return (
565 <tr key={period}>
566 <th scope="row">{formatTooltipPeriod(period)}</th>
567 {providers.map((provider) => (
568 <td key={provider}>
569 {format(column?.bands.find((band) => band.provider === provider)?.value ?? 0)}
570 </td>
571 ))}
572 {providers.length > 1 ? <td>{format(column?.total ?? 0)}</td> : null}
573 </tr>
574 );
575 })}
576 </tbody>
577 </table>
578 </div>
579 </div>
580 );
581 }