Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

UsagePage.tsx

562 lines22.6 KB

1import type { UsageProviderKind } from "@t3tools/contracts";
2import { useCanGoBack, useNavigate, useRouter } from "@tanstack/react-router";
3import { ArrowLeftIcon, CheckIcon, RefreshCwIcon, XIcon } from "lucide-react";
4import { useMemo, useState } from "react";
5​
6import { cn } from "../../lib/utils";
7import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
8import {
9 enumerateDays,
10 formatCount,
11 formatDayShort,
12 formatPercent,
13 formatTokens,
14 formatUsd,
15 makeWindow,
16} from "@t3tools/shared/usageFormat";
17import { ScrollArea } from "../ui/scroll-area";
18import { UsageChartLegend, UsageProviderChart, type UsageChartMetric } from "./UsageProviderChart";
19import { PROVIDER_COLOR, PROVIDER_LABEL, PROVIDER_MARK, PROVIDER_ORDER } from "./usageProviders";
20​
21const WINDOW_OPTIONS = [
22 { days: 7, label: "7 days" },
23 { days: 30, label: "30 days" },
24 { days: 90, label: "90 days" },
25] as const;
26​
27export function UsagePage() {
28 const [windowDays, setWindowDays] = useState<number>(30);
29 const [metric, setMetric] = useState<UsageChartMetric>("cost");
30 const [breakdown, setBreakdown] = useState<"model" | "day">("model");
31 const canGoBack = useCanGoBack();
32 const navigate = useNavigate();
33 const router = useRouter();
34​
35 // Recomputed only when the window length changes, so a re-render does not
36 // shift the range and refetch every environment.
37 const window = useMemo(() => makeWindow(windowDays), [windowDays]);
38 const { merged, environments, isPending, isPartial, refresh } = useUsage(window);
39​
40 // Hold the content until every environment is terminal. Rendering merged
41 // totals while devices are still answering makes every number on the page
42 // jump as each one lands.
43 const settling = isPending || isPartial;
44​
45 const days = useMemo(
46 () => enumerateDays(window.sinceDay, window.untilDay),
47 [window.sinceDay, window.untilDay],
48 );
49 const recentDays = useMemo(() => merged.daily.toReversed().slice(0, 8), [merged.daily]);
50​
51 // Ranked by whatever the toggle is showing, so the bars always descend.
52 const orderedProviders = useMemo(
53 () =>
54 merged.providers.toSorted((a, b) =>
55 metric === "cost" ? b.costUsd - a.costUsd : b.totalTokens - a.totalTokens,
56 ),
57 [merged.providers, metric],
58 );
59​
60 const activeDays = merged.daily.filter((day) => day.totalTokens > 0).length;
61 const dailyAverage = activeDays === 0 ? 0 : merged.totalTokens / activeDays;
62 const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens;
63 const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput;
64​
65 return (
66 <ScrollArea className="h-full">
67 <div className="mx-auto flex w-full max-w-6xl flex-col gap-8 px-6 py-6">
68 <header className="flex flex-wrap items-start justify-between gap-4">
69 <div className="flex items-start gap-3">
70 <button
71 type="button"
72 aria-label="Back"
73 onClick={() => {
74 if (canGoBack) {
75 router.history.back();
76 return;
77 }
78 void navigate({ to: "/" });
79 }}
80 className="mt-1 cursor-pointer rounded-md border border-border p-2 text-muted-foreground hover:text-foreground"
81 >
82 <ArrowLeftIcon className="size-3.5" />
83 </button>
84 <div className="flex flex-col gap-1">
85 <h1 className="text-2xl font-semibold text-foreground">Usage</h1>
86 <p className="text-sm text-muted-foreground">
87 {formatDayShort(window.sinceDay)} to {formatDayShort(window.untilDay)}
88 </p>
89 </div>
90 </div>
91 <div className="flex items-center gap-2">
92 <div className="flex overflow-hidden rounded-md border border-border">
93 {WINDOW_OPTIONS.map((option) => (
94 <button
95 key={option.days}
96 type="button"
97 onClick={() => setWindowDays(option.days)}
98 className={cn(
99 "cursor-pointer px-3 py-1.5 text-xs",
100 option.days === windowDays
101 ? "bg-muted text-foreground"
102 : "text-muted-foreground hover:text-foreground",
103 )}
104 >
105 {option.label}
106 </button>
107 ))}
108 </div>
109 <button
110 type="button"
111 onClick={refresh}
112 aria-label="Refresh usage"
113 className="cursor-pointer rounded-md border border-border p-2 text-muted-foreground hover:text-foreground"
114 >
115 <RefreshCwIcon className="size-3.5" />
116 </button>
117 </div>
118 </header>
119​
120 {settling ? (
121 <>
122 {environments.length > 1 ? <UsageDeviceStrip environments={environments} /> : null}
123 <UsageSkeleton />
124 </>
125 ) : (
126 <>
127 <UsageCoverageNotice
128 environments={environments}
129 duplicateSources={merged.duplicateSources}
130 staleEnvironments={merged.staleEnvironments}
131 />
132​
133 {/* Cost first: the financial answer, then the provider split. */}
134 <section className="grid gap-6 lg:grid-cols-[minmax(0,20rem)_minmax(0,1fr)]">
135 {/* The summary follows the chart toggle, so the headline and the
136 series are always reading the same units. */}
137 <div className="flex flex-col gap-5">
138 <div className="flex flex-col gap-1">
139 <span className="text-xs tracking-wide text-muted-foreground uppercase">
140 {metric === "cost" ? "Raw token cost" : "Processed tokens"}
141 </span>
142 <span className="text-4xl font-semibold text-foreground tabular-nums">
143 {metric === "cost"
144 ? `${formatUsd(merged.costUsd)}*`
145 : formatTokens(merged.totalTokens)}
146 </span>
147 <span className="text-xs text-muted-foreground">
148 {metric === "cost"
149 ? "* if billed at full API rate"
150 : `Input, cache reads and output across ${formatCount(merged.sessions)} sessions.`}
151 </span>
152 </div>
153​
154 {orderedProviders.map((provider) => {
155 const share = metric === "cost" ? provider.costShare : provider.tokenShare;
156 return (
157 <div key={provider.provider} className="flex flex-col gap-1.5">
158 <div className="flex items-baseline justify-between">
159 <span className="flex items-center gap-2 text-sm text-foreground">
160 <ProviderMark provider={provider.provider} className="size-4" />
161 {PROVIDER_LABEL[provider.provider]}
162 </span>
163 <span className="text-sm text-foreground tabular-nums">
164 {metric === "cost"
165 ? formatUsd(provider.costUsd)
166 : formatTokens(provider.totalTokens)}
167 </span>
168 </div>
169 <div className="h-1 w-full overflow-hidden rounded-full bg-muted">
170 <div
171 className="h-full"
172 style={{
173 width: `${(share * 100).toFixed(1)}%`,
174 backgroundColor: PROVIDER_COLOR[provider.provider],
175 }}
176 />
177 </div>
178 <span className="text-xs text-muted-foreground">
179 {metric === "cost"
180 ? `${formatPercent(share)} of cost · ${formatTokens(provider.totalTokens)} tokens`
181 : `${formatPercent(share)} of tokens · ${formatUsd(provider.costUsd)}`}
182 </span>
183 </div>
184 );
185 })}
186 </div>
187​
188 <div className="flex flex-col gap-3">
189 <div className="flex flex-wrap items-center justify-between gap-3">
190 <h2 className="text-sm font-medium text-foreground">
191 Daily {metric === "tokens" ? "processed tokens" : "cost"}
192 </h2>
193 <div className="flex items-center gap-4">
194 <div className="flex overflow-hidden rounded-md border border-border">
195 {(["cost", "tokens"] as const).map((option) => (
196 <button
197 key={option}
198 type="button"
199 onClick={() => setMetric(option)}
200 className={cn(
201 "cursor-pointer px-2.5 py-1 text-[10px] tracking-wide uppercase",
202 option === metric
203 ? "bg-muted text-foreground"
204 : "text-muted-foreground hover:text-foreground",
205 )}
206 >
207 {option}
208 </button>
209 ))}
210 </div>
211 <UsageChartLegend />
212 </div>
213 </div>
214 <UsageProviderChart days={days} daily={merged.daily} metric={metric} />
215 </div>
216 </section>
217​
218 <section className="grid grid-cols-2 gap-px border-y border-border bg-border md:grid-cols-5">
219 <Metric
220 label="Processed tokens"
221 value={formatTokens(merged.totalTokens)}
222 detail={`${formatTokens(dailyAverage)} per active day`}
223 />
224 <Metric
225 label="Cached input"
226 value={formatTokens(merged.cachedInputTokens)}
227 detail={`${formatPercent(cachedShare)} of observed input`}
228 />
229 <Metric
230 label="Uncached input"
231 value={formatTokens(merged.uncachedInputTokens)}
232 detail={`${formatTokens(merged.cacheCreationTokens)} cache writes`}
233 />
234 <Metric
235 label="Output"
236 value={formatTokens(merged.outputTokens)}
237 detail={`includes ${formatTokens(merged.reasoningTokens)} reasoning`}
238 />
239 <Metric
240 label="Cache savings"
241 value={formatUsd(merged.costQuality.cacheSavingsUsd)}
242 detail={
243 merged.costUsd > 0
244 ? `${(merged.costQuality.cacheSavingsUsd / merged.costUsd).toFixed(1)}x the raw token cost`
245 : "vs full input rates"
246 }
247 />
248 </section>
249​
250 <section className="flex flex-col gap-3">
251 <div className="flex items-center justify-between gap-3">
252 <h2 className="text-sm font-medium text-foreground">Breakdown</h2>
253 <div className="flex overflow-hidden rounded-md border border-border">
254 {(["model", "day"] as const).map((option) => (
255 <button
256 key={option}
257 type="button"
258 onClick={() => setBreakdown(option)}
259 className={cn(
260 "cursor-pointer px-2.5 py-1 text-[10px] tracking-wide uppercase",
261 option === breakdown
262 ? "bg-muted text-foreground"
263 : "text-muted-foreground hover:text-foreground",
264 )}
265 >
266 {option}
267 </button>
268 ))}
269 </div>
270 </div>
271​
272 {breakdown === "model" ? (
273 <table className="w-full text-sm">
274 <thead>
275 <tr className="border-b border-border text-left text-xs text-muted-foreground">
276 <th className="py-2 font-normal">Model</th>
277 <th className="py-2 text-right font-normal">Cost</th>
278 <th className="py-2 text-right font-normal">Share</th>
279 <th className="py-2 text-right font-normal">Tokens</th>
280 </tr>
281 </thead>
282 <tbody>
283 {merged.models.length === 0 ? (
284 <tr>
285 <td colSpan={4} className="py-6 text-center text-muted-foreground">
286 No activity in this window.
287 </td>
288 </tr>
289 ) : (
290 merged.models.map((model) => (
291 <tr
292 key={`${model.provider}:${model.model}`}
293 className="border-b border-border/50"
294 >
295 <td className="py-2 text-foreground">
296 <span className="flex items-center gap-2">
297 <ProviderMark provider={model.provider} className="size-3.5" />
298 {model.model}
299 </span>
300 </td>
301 <td className="py-2 text-right text-foreground tabular-nums">
302 {formatUsd(model.costUsd)}
303 </td>
304 <td className="py-2 text-right text-muted-foreground tabular-nums">
305 {formatPercent(model.costShare)}
306 </td>
307 <td className="py-2 text-right text-muted-foreground tabular-nums">
308 {formatTokens(model.totalTokens)}
309 </td>
310 </tr>
311 ))
312 )}
313 </tbody>
314 </table>
315 ) : (
316 <table className="w-full text-sm">
317 <thead>
318 <tr className="border-b border-border text-left text-xs text-muted-foreground">
319 <th className="py-2 font-normal">Day</th>
320 {PROVIDER_ORDER.map((provider) => (
321 <th key={provider} className="py-2 text-right font-normal">
322 {PROVIDER_LABEL[provider]}
323 </th>
324 ))}
325 <th className="py-2 text-right font-normal">Total</th>
326 <th className="py-2 text-right font-normal">Tokens</th>
327 </tr>
328 </thead>
329 <tbody>
330 {recentDays.length === 0 ? (
331 <tr>
332 <td colSpan={5} className="py-6 text-center text-muted-foreground">
333 No activity in this window.
334 </td>
335 </tr>
336 ) : (
337 recentDays.map((day) => (
338 <tr key={day.day} className="border-b border-border/50">
339 <td className="py-2 text-foreground">{formatDayShort(day.day)}</td>
340 {PROVIDER_ORDER.map((provider) => (
341 <td
342 key={provider}
343 className="py-2 text-right text-muted-foreground tabular-nums"
344 >
345 {formatUsd(day.byProvider.get(provider)?.costUsd ?? 0)}
346 </td>
347 ))}
348 <td className="py-2 text-right text-foreground tabular-nums">
349 {formatUsd(day.costUsd)}
350 </td>
351 <td className="py-2 text-right text-muted-foreground tabular-nums">
352 {formatTokens(day.totalTokens)}
353 </td>
354 </tr>
355 ))
356 )}
357 </tbody>
358 </table>
359 )}
360 </section>
361 </>
362 )}
363 </div>
364 </ScrollArea>
365 );
367​
368/** Brand mark for the harness a row belongs to. */
369function ProviderMark({
370 provider,
371 className,
372}: {
373 readonly provider: UsageProviderKind;
374 readonly className: string;
375}) {
376 const Mark = PROVIDER_MARK[provider];
377 return <Mark className={cn("shrink-0", className)} aria-hidden />;
379​
380function Metric({
381 label,
382 value,
383 detail,
384}: {
385 readonly label: string;
386 readonly value: string;
387 readonly detail: string;
388}) {
389 return (
390 <div className="flex flex-col gap-0.5 bg-background px-4 py-3">
391 <span className="text-xs text-muted-foreground">{label}</span>
392 <span className="text-lg text-foreground tabular-nums">{value}</span>
393 <span className="text-xs text-muted-foreground">{detail}</span>
394 </div>
395 );
397​
398/**
399 * Says plainly when the totals are incomplete: an environment that failed, or
400 * one whose transcripts another environment already reported. Environments
401 * that are still answering never reach this notice; the page shows the
402 * loading skeleton until every one is terminal.
403 */
404function UsageCoverageNotice({
405 environments,
406 duplicateSources,
407 staleEnvironments,
408}: {
409 readonly environments: readonly EnvironmentUsageStatus[];
410 readonly duplicateSources: readonly string[];
411 readonly staleEnvironments: readonly string[];
412}) {
413 const failed = environments.filter((environment) => environment.error !== null);
414 const stale = environments.filter((environment) =>
415 staleEnvironments.includes(environment.environmentId),
416 );
417 if (failed.length === 0 && stale.length === 0 && duplicateSources.length === 0) {
418 return null;
419 }
420​
421 return (
422 <div className="flex flex-col gap-1 border border-border px-3 py-2 text-xs text-muted-foreground">
423 {failed.map((environment) => (
424 <span key={environment.label}>{environment.label} could not report usage.</span>
425 ))}
426 {stale.map((environment) => (
427 <span key={environment.label}>
428 {environment.label} runs an older server version and is excluded from totals.
429 </span>
430 ))}
431 {duplicateSources.length > 0 ? (
432 <span>
433 Counted once across environments sharing a transcript directory:{" "}
434 {duplicateSources.join(", ")}
435 </span>
436 ) : null}
437 </div>
438 );
440​
441/**
442 * Per-device progress while the page waits for every environment to answer.
443 * Only rendered with two or more devices; a lone device has nothing to
444 * enumerate.
445 */
446function UsageDeviceStrip({
447 environments,
448}: {
449 readonly environments: readonly EnvironmentUsageStatus[];
450}) {
451 const scanning = environments.filter(
452 (environment) => environment.summary === null && environment.error === null,
453 );
454 return (
455 <div className="flex flex-wrap items-baseline gap-x-4 gap-y-1 border border-border px-3 py-2 text-xs">
456 {environments.map((environment) => {
457 if (environment.summary !== null) {
458 return (
459 <span
460 key={environment.environmentId}
461 className="flex items-center gap-1 text-foreground"
462 >
463 <CheckIcon className="size-3 text-emerald-600 dark:text-emerald-300/90" aria-hidden />
464 {environment.label}
465 </span>
466 );
467 }
468 if (environment.error !== null) {
469 return (
470 <span
471 key={environment.environmentId}
472 className="flex items-center gap-1 text-destructive"
473 >
474 <XIcon className="size-3" aria-hidden />
475 {environment.label}
476 </span>
477 );
478 }
479 return (
480 <span
481 key={environment.environmentId}
482 className="animate-status-pulse text-muted-foreground"
483 >
484 {environment.label}…
485 </span>
486 );
487 })}
488 <span className="ms-auto text-muted-foreground">
489 {scanning.length === 1
490 ? "1 device still scanning"
491 : `${scanning.length} devices still scanning`}
492 </span>
493 </div>
494 );
496​
497/** Deterministic bar heights (each unique: they double as keys). */
498const SKELETON_BAR_HEIGHTS = [34, 58, 41, 72, 22, 12, 49, 63, 80, 38, 55, 26, 44, 67];
499​
500/**
501 * Static stand-in with the loaded page's shape: headline, provider split,
502 * chart and metrics strip. No shimmer; blocks fill in exactly once when the
503 * last device answers.
504 */
505function UsageSkeleton() {
506 return (
507 <>
508 <section className="grid gap-6 lg:grid-cols-[minmax(0,20rem)_minmax(0,1fr)]">
509 <div className="flex flex-col gap-5">
510 <div className="flex flex-col gap-1">
511 <span className="text-xs tracking-wide text-muted-foreground uppercase">
512 Raw token cost
513 </span>
514 <div className="my-1.5 h-8 w-36 rounded-sm bg-muted" />
515 <div className="h-3 w-28 rounded-sm bg-muted" />
516 </div>
517​
518 {PROVIDER_ORDER.map((provider) => (
519 <div key={provider} className="flex flex-col gap-1.5">
520 <div className="flex items-center justify-between">
521 <span className="flex items-center gap-2 text-sm text-foreground">
522 <ProviderMark provider={provider} className="size-4" />
523 {PROVIDER_LABEL[provider]}
524 </span>
525 <div className="h-3.5 w-14 rounded-sm bg-muted" />
526 </div>
527 <div className="h-1 w-full rounded-full bg-muted" />
528 <div className="h-3 w-36 rounded-sm bg-muted" />
529 </div>
530 ))}
531 </div>
532​
533 <div className="flex flex-col gap-3">
534 <h2 className="py-1 text-sm font-medium text-foreground">Daily cost</h2>
535 {/* Mirrors the chart's h-56 body and w-14 axis gutter to avoid a
536 relayout when the real chart swaps in. */}
537 <div className="flex h-56 items-end gap-1 pl-16">
538 {SKELETON_BAR_HEIGHTS.map((height) => (
539 <div
540 key={height}
541 className="flex-1 rounded-sm bg-muted"
542 style={{ height: `${height}%` }}
543 />
544 ))}
545 </div>
546 </div>
547 </section>
548​
549 <section className="grid grid-cols-2 gap-px border-y border-border bg-border md:grid-cols-5">
550 {["Processed tokens", "Cached input", "Uncached input", "Output", "Cache savings"].map(
551 (label) => (
552 <div key={label} className="flex flex-col gap-0.5 bg-background px-4 py-3">
553 <span className="text-xs text-muted-foreground">{label}</span>
554 <div className="my-1 h-5 w-16 rounded-sm bg-muted" />
555 <div className="h-3 w-24 rounded-sm bg-muted" />
556 </div>
557 ),
558 )}
559 </section>
560 </>
561 );