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

UsagePage.tsx

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