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