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