Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

UsagePage.tsx

628 lines26.0 KB

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 { Button } from "../ui/button";
23import { ScrollArea } from "../ui/scroll-area";
24import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
25import { SidebarInset } from "../ui/sidebar";
26import { Toggle, ToggleGroup } from "../ui/toggle-group";
27import {
28 WorkspaceBreadcrumb,
29 WorkspaceBreadcrumbItem,
30 WorkspaceBreadcrumbSeparator,
31} from "../WorkspaceBreadcrumb";
32import { WorkspacePageContainer } from "../WorkspacePageContainer";
33import { WorkspacePageHeader } from "../WorkspacePageHeader";
34import { UsageProviderChart, type UsageChartMetric } from "./UsageProviderChart";
35import { PROVIDER_ORDER, PROVIDER_PRESENTATION } from "./usageProviders";
36​
37const WINDOW_OPTIONS = [
38 { days: 1, label: "Past 24h" },
39 { days: 7, label: "7 days" },
40 { days: 30, label: "30 days" },
41 { days: 90, label: "90 days" },
42] as const;
43​
44export function UsagePage() {
45 const [windowSelection, setWindowSelection] = useState(() => ({
46 days: 30,
47 window: makeWindow(30),
48 }));
49 const [metric, setMetric] = useState<UsageChartMetric>("cost");
50 const [breakdown, setBreakdown] = useState<"model" | "time">("model");
51 const { days: windowDays, window } = windowSelection;
52 const isPast24Hours = windowDays === 1;
53 const { merged, environments, isPending, isPartial, refresh } = useUsage(window);
54​
55 // Hold the content until every environment is terminal. Rendering merged
56 // totals while devices are still answering makes every number on the page
57 // jump as each one lands.
58 const settling = isPending || isPartial;
59​
60 const days = useMemo(
61 () => enumerateDays(window.sinceDay, window.untilDay),
62 [window.sinceDay, window.untilDay],
63 );
64 const hours = useMemo(
65 () =>
66 window.sinceTime === undefined || window.untilTime === undefined
67 ? []
68 : enumerateHourStarts(window.sinceTime, window.untilTime),
69 [window.sinceTime, window.untilTime],
70 );
71 // The hourly window is small enough to render every period: the table then
72 // reads chronologically like the chart, instead of jumping between the hours
73 // that happened to have activity. Daily windows can run 90 periods, so those
74 // stay newest-first with the interesting end on top.
75 const breakdownPeriods = useMemo<readonly (DailyTotals | HourlyTotals)[]>(() => {
76 if (!isPast24Hours) return merged.daily.toReversed();
77 const byHour = new Map(merged.hourly.map((entry) => [entry.hourStart, entry]));
78 return hours.map((hourStart) => byHour.get(hourStart) ?? zeroHour(hourStart));
79 }, [isPast24Hours, merged.daily, merged.hourly, hours]);
80​
81 const selectWindow = (days: number) => {
82 setWindowSelection({
83 days,
84 window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),
85 });
86 };
87 const refreshWindow = () => {
88 const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");
89 if (
90 nextWindow.sinceDay === window.sinceDay &&
91 nextWindow.untilDay === window.untilDay &&
92 nextWindow.sinceTime === window.sinceTime &&
93 nextWindow.untilTime === window.untilTime
94 ) {
95 refresh();
96 } else {
97 setWindowSelection({ days: windowDays, window: nextWindow });
98 }
99 };
100 const windowLabel =
101 isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined
102 ? `${formatDateTimeShort(window.sinceTime, window.timeZone)} to ${formatDateTimeShort(window.untilTime, window.timeZone)}`
103 : `${formatDayShort(window.sinceDay)} to ${formatDayShort(window.untilDay)}`;
104 const topbarContent = (
105 <div className="flex w-full min-w-0 items-center gap-3">
106 <WorkspaceBreadcrumb ariaLabel="Usage breadcrumb" className="min-w-0">
107 <WorkspaceBreadcrumbItem current>
108 <h1>Usage</h1>
109 </WorkspaceBreadcrumbItem>
110 <WorkspaceBreadcrumbSeparator className="hidden md:flex" />
111 <WorkspaceBreadcrumbItem className="hidden min-w-0 shrink md:flex">
112 <span className="truncate">{windowLabel}</span>
113 </WorkspaceBreadcrumbItem>
114 </WorkspaceBreadcrumb>
115 <div className="ms-auto hidden min-w-0 items-center justify-end gap-2 lg:flex">
116 <ToggleGroup
117 aria-label="Usage metric"
118 variant="segmented"
119 value={[metric]}
120 onValueChange={(next) => {
121 const value = next[0];
122 if (value === "cost" || value === "tokens") setMetric(value);
123 }}
124 >
125 {(["cost", "tokens"] as const).map((option) => (
126 <Toggle key={option} value={option}>
127 {option === "cost" ? "Cost" : "Tokens"}
128 </Toggle>
129 ))}
130 </ToggleGroup>
131 <ToggleGroup
132 aria-label="Usage period"
133 variant="segmented"
134 value={[String(windowDays)]}
135 onValueChange={(next) => {
136 const value = next[0];
137 if (value) selectWindow(Number(value));
138 }}
139 >
140 {WINDOW_OPTIONS.map((option) => (
141 <Toggle key={option.days} value={String(option.days)}>
142 {option.label}
143 </Toggle>
144 ))}
145 </ToggleGroup>
146 <Button onClick={refreshWindow} aria-label="Refresh usage" size="icon-sm" variant="ghost">
147 <RefreshCwIcon className="size-3.5" />
148 </Button>
149 </div>
150 <div className="ms-auto flex min-w-0 items-center justify-end gap-1 lg:hidden">
151 <Select
152 value={metric}
153 onValueChange={(value) => {
154 if (value === "cost" || value === "tokens") setMetric(value);
155 }}
156 >
157 <SelectTrigger
158 aria-label="Usage metric"
159 size="compact"
160 variant="ghost"
161 className="w-auto min-w-0"
162 >
163 <SelectValue>{metric === "cost" ? "Cost" : "Tokens"}</SelectValue>
164 </SelectTrigger>
165 <SelectPopup align="end" alignItemWithTrigger={false}>
166 <SelectItem value="cost">Cost</SelectItem>
167 <SelectItem value="tokens">Tokens</SelectItem>
168 </SelectPopup>
169 </Select>
170 <Select value={String(windowDays)} onValueChange={(value) => selectWindow(Number(value))}>
171 <SelectTrigger
172 aria-label="Usage period"
173 size="compact"
174 variant="ghost"
175 className="w-auto min-w-0"
176 >
177 <SelectValue>
178 {WINDOW_OPTIONS.find((option) => option.days === windowDays)?.label}
179 </SelectValue>
180 </SelectTrigger>
181 <SelectPopup align="end" alignItemWithTrigger={false}>
182 {WINDOW_OPTIONS.map((option) => (
183 <SelectItem key={option.days} value={String(option.days)}>
184 {option.label}
185 </SelectItem>
186 ))}
187 </SelectPopup>
188 </Select>
189 <Button onClick={refreshWindow} aria-label="Refresh usage" size="icon-sm" variant="ghost">
190 <RefreshCwIcon className="size-3.5" />
191 </Button>
192 </div>
193 </div>
194 );
195​
196 return (
197 <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
198 <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
199 <WorkspacePageHeader electron={isElectron}>{topbarContent}</WorkspacePageHeader>
200​
201 <ScrollArea className="min-h-0 flex-1">
202 <WorkspacePageContainer width="wide">
203 {settling ? (
204 <>
205 {environments.length > 1 ? <UsageDeviceStrip environments={environments} /> : null}
206 <UsageSkeleton />
207 </>
208 ) : (
209 <>
210 <UsageCoverageNotice
211 environments={environments}
212 duplicateSources={merged.duplicateSources}
213 staleEnvironments={merged.staleEnvironments}
214 />
215​
216 <section className="grid gap-6 lg:grid-cols-[minmax(0,16rem)_minmax(0,1fr)]">
217 <div className="flex min-w-0 flex-col gap-5">
218 <div className="flex flex-col gap-1">
219 <span className="text-4xl font-semibold text-foreground tabular-nums">
220 {metric === "cost"
221 ? formatUsd(merged.costUsd)
222 : formatTokens(merged.totalTokens)}
223 </span>
224 <span className="text-xs text-muted-foreground">
225 {metric === "cost"
226 ? `${formatCount(merged.sessions)} sessions · API estimate`
227 : `${formatCount(merged.sessions)} sessions`}
228 </span>
229 </div>
230​
231 {PROVIDER_ORDER.map((provider) => {
232 const totals = merged.providers.find((entry) => entry.provider === provider);
233 const share =
234 metric === "cost" ? (totals?.costShare ?? 0) : (totals?.tokenShare ?? 0);
235 const providerSessions = totals?.sessions ?? 0;
236 const sessionLabel = `${formatCount(providerSessions)} ${
237 providerSessions === 1 ? "session" : "sessions"
238 }`;
239 return (
240 <div key={provider} className="flex flex-col gap-1">
241 <div className="flex items-baseline justify-between gap-4">
242 <span className="flex min-w-0 items-center gap-2 text-sm text-foreground">
243 <span
244 aria-hidden
245 className="size-2 shrink-0 rounded-full"
246 style={{
247 backgroundColor: PROVIDER_PRESENTATION[provider].color,
248 }}
249 />
250 <ProviderMark provider={provider} className="size-4" />
251 <span className="flex min-w-0 items-baseline gap-1.5">
252 <span className="truncate">
253 {PROVIDER_PRESENTATION[provider].label}
254 </span>
255 <span className="shrink-0 whitespace-nowrap text-[11px] text-muted-foreground tabular-nums">
256 {sessionLabel}
257 </span>
258 </span>
259 </span>
260 <span className="shrink-0 text-sm font-medium text-foreground tabular-nums">
261 {metric === "cost"
262 ? formatUsd(totals?.costUsd ?? 0)
263 : formatTokens(totals?.totalTokens ?? 0)}
264 </span>
265 </div>
266 <span className="text-xs text-muted-foreground">
267 {metric === "cost"
268 ? `${formatPercent(share)} of cost · ${formatTokens(totals?.totalTokens ?? 0)} tokens`
269 : `${formatPercent(share)} of tokens · ${formatUsd(totals?.costUsd ?? 0)}`}
270 </span>
271 </div>
272 );
273 })}
274 </div>
275​
276 <div className="flex min-w-0 flex-col gap-3">
277 <h2 className="text-sm font-medium text-foreground">
278 {isPast24Hours ? "Hourly" : "Daily"}{" "}
279 {metric === "tokens" ? "processed tokens" : "cost"}
280 </h2>
281 <UsageProviderChart
282 days={days}
283 daily={merged.daily}
284 hours={hours}
285 hourly={merged.hourly}
286 metric={metric}
287 referenceTime={window.untilTime}
288 resolution={isPast24Hours ? "hour" : "day"}
289 timeZone={window.timeZone}
290 />
291 </div>
292 </section>
293​
294 <section className="flex flex-col gap-2">
295 <h2 className="text-sm font-medium text-foreground">Totals</h2>
296 <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">
297 <Metric label="Processed tokens" value={formatTokens(merged.totalTokens)} />
298 <Metric label="Cached input" value={formatTokens(merged.cachedInputTokens)} />
299 <Metric
300 label="Uncached input"
301 value={formatTokens(merged.uncachedInputTokens)}
302 />
303 <Metric label="Output" value={formatTokens(merged.outputTokens)} />
304 <Metric
305 label="Cache savings"
306 value={formatUsd(merged.costQuality.cacheSavingsUsd)}
307 />
308 </div>
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 <ToggleGroup
315 aria-label="Usage breakdown"
316 variant="segmented"
317 value={[breakdown]}
318 onValueChange={(next) => {
319 const value = next[0];
320 if (value === "model" || value === "time") setBreakdown(value);
321 }}
322 >
323 {(
324 [
325 { value: "model", label: "Model" },
326 { value: "time", label: isPast24Hours ? "Hour" : "Day" },
327 ] as const
328 ).map((option) => (
329 <Toggle key={option.value} value={option.value}>
330 {option.label}
331 </Toggle>
332 ))}
333 </ToggleGroup>
334 </div>
335​
336 {breakdown === "model" ? (
337 <table className="w-full text-sm">
338 <thead>
339 <tr className="border-b border-border text-left text-xs text-muted-foreground">
340 <th className="py-2 font-normal">Model</th>
341 <th className="py-2 text-right font-normal">Cost</th>
342 <th className="py-2 text-right font-normal">Share</th>
343 <th className="py-2 text-right font-normal">Tokens</th>
344 </tr>
345 </thead>
346 <tbody>
347 {merged.models.length === 0 ? (
348 <tr>
349 <td colSpan={4} className="py-6 text-center text-muted-foreground">
350 No activity in this window.
351 </td>
352 </tr>
353 ) : (
354 merged.models.map((model) => (
355 <tr
356 key={`${model.provider}:${model.model}`}
357 className="border-b border-border/50 transition-colors hover:bg-muted/50"
358 >
359 <td className="py-2 text-foreground">
360 <span className="flex items-center gap-2">
361 <ProviderMark provider={model.provider} className="size-3.5" />
362 {model.model}
363 </span>
364 </td>
365 <td className="py-2 text-right text-foreground tabular-nums">
366 {formatUsd(model.costUsd)}
367 </td>
368 <td className="py-2 text-right text-muted-foreground tabular-nums">
369 {formatPercent(model.costShare)}
370 </td>
371 <td className="py-2 text-right text-muted-foreground tabular-nums">
372 {formatTokens(model.totalTokens)}
373 </td>
374 </tr>
375 ))
376 )}
377 </tbody>
378 </table>
379 ) : (
380 <table className="w-full text-sm">
381 <thead>
382 <tr className="border-b border-border text-left text-xs text-muted-foreground">
383 <th className="py-2 font-normal">{isPast24Hours ? "Hour" : "Day"}</th>
384 {PROVIDER_ORDER.map((provider) => (
385 <th key={provider} className="py-2 text-right font-normal">
386 {PROVIDER_PRESENTATION[provider].label}
387 </th>
388 ))}
389 <th className="py-2 text-right font-normal">Total</th>
390 <th className="py-2 text-right font-normal">Tokens</th>
391 </tr>
392 </thead>
393 <tbody>
394 {breakdownPeriods.length === 0 ? (
395 <tr>
396 <td colSpan={5} className="py-6 text-center text-muted-foreground">
397 No activity in this window.
398 </td>
399 </tr>
400 ) : (
401 breakdownPeriods.map((period) => (
402 <tr
403 key={"hourStart" in period ? period.hourStart : period.day}
404 className="border-b border-border/50 transition-colors hover:bg-muted/50"
405 >
406 <td className="py-2 text-foreground">
407 {"hourStart" in period
408 ? formatHourShort(period.hourStart, window.timeZone)
409 : formatDayShort(period.day)}
410 </td>
411 {PROVIDER_ORDER.map((provider) => (
412 <td
413 key={provider}
414 className="py-2 text-right text-muted-foreground tabular-nums"
415 >
416 {formatUsd(period.byProvider.get(provider)?.costUsd ?? 0)}
417 </td>
418 ))}
419 <td className="py-2 text-right text-foreground tabular-nums">
420 {formatUsd(period.costUsd)}
421 </td>
422 <td className="py-2 text-right text-muted-foreground tabular-nums">
423 {formatTokens(period.totalTokens)}
424 </td>
425 </tr>
426 ))
427 )}
428 </tbody>
429 </table>
430 )}
431 </section>
432 </>
433 )}
434 </WorkspacePageContainer>
435 </ScrollArea>
436 </div>
437 </SidebarInset>
438 );
440​
441/** A zero-filled hourly period so the breakdown lists every hour in the window. */
442function zeroHour(hourStart: string): HourlyTotals {
443 return {
444 day: "",
445 hourStart,
446 costUsd: 0,
447 totalTokens: 0,
448 byProvider: new Map<UsageProviderKind, { costUsd: number; totalTokens: number }>(),
449 };
451​
452/** Brand mark for the harness a row belongs to. */
453function ProviderMark({
454 provider,
455 className,
456}: {
457 readonly provider: UsageProviderKind;
458 readonly className: string;
459}) {
460 const Mark = PROVIDER_PRESENTATION[provider].mark;
461 return <Mark className={cn("shrink-0", className)} aria-hidden />;
463​
464function Metric({ label, value }: { readonly label: string; readonly value: string }) {
465 return (
466 <div className="flex min-w-0 flex-col gap-0.5">
467 <span className="text-xs text-muted-foreground">{label}</span>
468 <span className="text-base font-medium text-foreground tabular-nums">{value}</span>
469 </div>
470 );
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 );
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 );
571​
572/**
573 * Static stand-in with the loaded page's shape. No shimmer; blocks fill in
574 * exactly once when the last device answers.
575 */
576function UsageSkeleton() {
577 return (
578 <>
579 <section className="grid gap-6 lg:grid-cols-[minmax(0,16rem)_minmax(0,1fr)]">
580 <div className="flex flex-col gap-5">
581 <div className="flex flex-col gap-1">
582 <div className="h-10 w-36 rounded-sm bg-muted" />
583 <div className="h-4 w-32 rounded-sm bg-muted" />
584 </div>
585 {PROVIDER_ORDER.map((provider) => (
586 <div key={provider} className="flex flex-col gap-1">
587 <div className="flex min-h-5 items-center justify-between gap-4">
588 <span className="flex items-center gap-2">
589 <span
590 aria-hidden
591 className="size-2 shrink-0 rounded-full"
592 style={{ backgroundColor: PROVIDER_PRESENTATION[provider].color }}
593 />
594 <ProviderMark provider={provider} className="size-4" />
595 <div className="h-3.5 w-20 rounded-sm bg-muted" />
596 </span>
597 <div className="h-3.5 w-14 rounded-sm bg-muted" />
598 </div>
599 <div className="h-4 w-36 rounded-sm bg-muted" />
600 </div>
601 ))}
602 </div>
603​
604 <div className="flex flex-col gap-3">
605 <div className="h-5 w-24 rounded-sm bg-muted" />
606 <div className="flex flex-col gap-1">
607 <div className="ml-16 h-56 rounded-sm bg-muted/35" />
608 <div className="ml-16 h-3 rounded-sm bg-muted/35" />
609 </div>
610 </div>
611 </section>
612​
613 <section className="flex flex-col gap-2">
614 <h2 className="text-sm font-medium text-foreground">Totals</h2>
615 <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">
616 {["Processed tokens", "Cached input", "Uncached input", "Output", "Cache savings"].map(
617 (label) => (
618 <div key={label} className="flex flex-col gap-0.5">
619 <span className="text-xs text-muted-foreground">{label}</span>
620 <div className="my-0.5 h-4 w-16 rounded-sm bg-muted" />
621 </div>
622 ),
623 )}
624 </div>
625 </section>
626 </>
627 );