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