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

UsagePage.tsx

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