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

UsagePage.tsx

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