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