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

UsagePage.tsx

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