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