Open History to see the last commit
1import { RefreshIcon } from "~/components/ui/refresh-icon";
2import { useAtomValue } from "@effect/atom-react";
3import {
4 USAGE_CONTRACT_VERSION,
5 type EnvironmentId,
6 type UsageAccountConsumption,
7 type UsageProviderKind,
8} from "@t3tools/contracts";
9import {
10 CheckIcon,
11 CircleAlertIcon,
12 ChevronDownIcon,
13 CircleDashedIcon,
14 DownloadIcon,
15 SlidersHorizontalIcon,
16} from "lucide-react";
17import { useMemo, useRef, useState } from "react";
18
19import {
20 isCompatibleUsageContractVersion,
21 type DailyTotals,
22 type HourlyTotals,
23} from "@t3tools/shared/usageMerge";
24
25import { isElectron } from "../../env";
26import { cn } from "../../lib/utils";
27import { environmentPresentations } from "../../state/presentation";
28import { serverEnvironment } from "../../state/server";
29import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
30import { useAtomCommand } from "../../state/use-atom-command";
31import {
32 enumerateDays,
33 enumerateHourStarts,
34 formatCount,
35 formatDateTimeShort,
36 formatDayShort,
37 formatHourShort,
38 formatPercent,
39 formatTokens,
40 formatUsd,
41 makeWindow,
42} from "@t3tools/shared/usageFormat";
43import { Button } from "../ui/button";
44import {
45 Menu,
46 MenuCheckboxItem,
47 MenuItem,
48 MenuPopup,
49 MenuSeparator,
50 MenuTrigger,
51} from "../ui/menu";
52import { ScrollArea } from "../ui/scroll-area";
53import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
54import { SidebarInset } from "../ui/sidebar";
55import { Skeleton } from "../ui/skeleton";
56import { Toggle, ToggleGroup } from "../ui/toggle-group";
57import {
58 WorkspaceBreadcrumb,
59 WorkspaceBreadcrumbItem,
60 WorkspaceBreadcrumbSeparator,
61} from "../WorkspaceBreadcrumb";
62import { WorkspacePageContainer } from "../WorkspacePageContainer";
63import { WorkspacePageHeader } from "../WorkspacePageHeader";
64import { UsageLimitsSection } from "./UsageLimits";
65import { UsagePriceOverrides } from "./UsagePriceOverrides";
66import { UsageProviderChart, type UsageChartMetric } from "./UsageProviderChart";
67import { PROVIDER_ORDER, PROVIDER_PRESENTATION, providersWithUsage } from "./usageProviders";
68import {
69 readUsagePagePreferences,
70 saveUsagePagePreferences,
71 type UsagePagePreferences,
72} from "./usagePagePreferences";
73import { usageToCsv, usageToJson } from "./usageExport";
74
75type UsageMetric = UsageChartMetric | "limits";
76const METRIC_OPTIONS = [
77 { value: "cost", label: "Cost" },
78 { value: "tokens", label: "Tokens" },
79 { value: "limits", label: "Limits" },
80] as const satisfies readonly { value: UsageMetric; label: string }[];
81
82function isUsageMetric(value: string | null | undefined): value is UsageMetric {
83 return METRIC_OPTIONS.some((option) => option.value === value);
84}
85
86const WINDOW_OPTIONS = [
87 { days: 1, label: "Past 24h" },
88 { days: 7, label: "7 days" },
89 { days: 30, label: "30 days" },
90 { days: 90, label: "90 days" },
91] as const;
92
93function isUsageWindowDays(value: number): value is UsagePagePreferences["windowDays"] {
94 return WINDOW_OPTIONS.some((option) => option.days === value);
95}
96
97function filterUsagePeriods<T extends DailyTotals | HourlyTotals>(
98 periods: readonly T[],
99 providerFilter: UsageProviderKind | "all",
100): readonly T[] {
101 if (providerFilter === "all") return periods;
102 return periods.map((period) => {
103 const selected = period.byProvider.get(providerFilter);
104 return {
105 ...period,
106 costUsd: selected?.costUsd ?? 0,
107 totalTokens: selected?.totalTokens ?? 0,
108 byProvider: selected
109 ? new Map([[providerFilter, selected]])
110 : new Map<UsageProviderKind, { costUsd: number; totalTokens: number }>(),
111 } as T;
112 });
113}
114
115export function UsagePage() {
116 const [preferences, setPreferences] = useState(readUsagePagePreferences);
117 const [windowSelection, setWindowSelection] = useState(() => ({
118 days: preferences.windowDays,
119 window: makeWindow(
120 preferences.windowDays,
121 undefined,
122 preferences.windowDays === 1 ? "hour" : "day",
123 ),
124 }));
125 const metric = preferences.metric;
126 const showingLimits = metric === "limits";
127 const [isRefreshing, setIsRefreshing] = useState(false);
128 const refreshingRef = useRef(false);
129 const [breakdown, setBreakdown] = useState<"model" | "time">("model");
130 const [selectedEnvironmentIds, setSelectedEnvironmentIds] =
131 useState<ReadonlySet<EnvironmentId> | null>(null);
132 const [providerFilter, setProviderFilter] = useState<UsageProviderKind | "all">("all");
133 const { days: windowDays, window } = windowSelection;
134 const isPast24Hours = windowDays === 1;
135 const { merged, environments, selectedEnvironments, isPending, isPartial, refresh } = useUsage(
136 window,
137 selectedEnvironmentIds,
138 );
139 const presentations = useAtomValue(environmentPresentations.presentationsAtom);
140 const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
141 reportFailure: false,
142 });
143
144 const days = useMemo(
145 () => enumerateDays(window.sinceDay, window.untilDay),
146 [window.sinceDay, window.untilDay],
147 );
148 const hours = useMemo(
149 () =>
150 window.sinceTime === undefined || window.untilTime === undefined
151 ? []
152 : enumerateHourStarts(window.sinceTime, window.untilTime),
153 [window.sinceTime, window.untilTime],
154 );
155 // Newest first: the window can run 90 periods, so the interesting end
156 // belongs at the top of the table.
157 const activeProviders = useMemo(() => providersWithUsage(merged.providers), [merged.providers]);
158 const visibleProviders = useMemo(
159 () =>
160 providerFilter === "all"
161 ? activeProviders
162 : activeProviders.filter((provider) => provider === providerFilter),
163 [activeProviders, providerFilter],
164 );
165 const visibleDaily = useMemo(
166 () => filterUsagePeriods(merged.daily, providerFilter),
167 [merged.daily, providerFilter],
168 );
169 const visibleHourly = useMemo(
170 () => filterUsagePeriods(merged.hourly, providerFilter),
171 [merged.hourly, providerFilter],
172 );
173 const breakdownPeriods = useMemo<readonly (DailyTotals | HourlyTotals)[]>(
174 () => (isPast24Hours ? visibleHourly : visibleDaily).toReversed(),
175 [isPast24Hours, visibleDaily, visibleHourly],
176 );
177 const breakdownModels = useMemo(
178 () =>
179 breakdown === "model" && metric === "tokens"
180 ? merged.models
181 .filter((model) => providerFilter === "all" || model.provider === providerFilter)
182 .toSorted(
183 (left, right) => right.totalTokens - left.totalTokens || right.costUsd - left.costUsd,
184 )
185 : merged.models.filter(
186 (model) => providerFilter === "all" || model.provider === providerFilter,
187 ),
188 [breakdown, merged.models, metric, providerFilter],
189 );
190 const timeValueColumnWidth = `${60 / (visibleProviders.length + 2)}%`;
191
192 const downloadExport = (format: "csv" | "json") => {
193 if (typeof document === "undefined") return;
194 const body = format === "csv" ? usageToCsv(merged, window) : usageToJson(merged, window);
195 const blob = new Blob([body], {
196 type: format === "csv" ? "text/csv;charset=utf-8" : "application/json;charset=utf-8",
197 });
198 const url = URL.createObjectURL(blob);
199 const anchor = document.createElement("a");
200 anchor.href = url;
201 anchor.download = `t3-usage-${window.sinceDay}-${window.untilDay}.${format}`;
202 anchor.click();
203 URL.revokeObjectURL(url);
204 };
205
206 const selectWindow = (days: number) => {
207 if (!isUsageWindowDays(days)) return;
208 const nextPreferences = { metric, windowDays: days };
209 setPreferences(nextPreferences);
210 saveUsagePagePreferences(nextPreferences);
211 setWindowSelection({
212 days,
213 window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),
214 });
215 };
216 const selectMetric = (nextMetric: UsageMetric) => {
217 const nextPreferences = { metric: nextMetric, windowDays };
218 setPreferences(nextPreferences);
219 saveUsagePagePreferences(nextPreferences);
220 };
221 const refreshWindow = () => {
222 if (refreshingRef.current) return;
223
224 if (showingLimits) {
225 refreshingRef.current = true;
226 setIsRefreshing(true);
227 void Promise.all(
228 Array.from(presentations, ([environmentId, presentation]) => {
229 if (selectedEnvironmentIds !== null && !selectedEnvironmentIds.has(environmentId)) return;
230 if (presentation.connection.phase === "connected" && presentation.serverConfig !== null) {
231 return refreshProviders({ environmentId, input: {} });
232 }
233 }),
234 ).finally(() => {
235 refreshingRef.current = false;
236 setIsRefreshing(false);
237 });
238 return;
239 }
240 const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");
241 if (
242 nextWindow.sinceDay !== window.sinceDay ||
243 nextWindow.untilDay !== window.untilDay ||
244 nextWindow.sinceTime !== window.sinceTime ||
245 nextWindow.untilTime !== window.untilTime
246 ) {
247 setWindowSelection({ days: windowDays, window: nextWindow });
248 }
249 refreshingRef.current = true;
250 setIsRefreshing(true);
251 void refresh(nextWindow).finally(() => {
252 refreshingRef.current = false;
253 setIsRefreshing(false);
254 });
255 };
256 const windowLabel =
257 isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined
258 ? `${formatDateTimeShort(window.sinceTime, window.timeZone)} to ${formatDateTimeShort(window.untilTime, window.timeZone)}`
259 : `${formatDayShort(window.sinceDay)} to ${formatDayShort(window.untilDay)}`;
260 const topbarContent = (
261 <div className="grid w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-2 py-2 xl:flex">
262 <WorkspaceBreadcrumb ariaLabel="Usage breadcrumb" className="col-span-2 min-w-0">
263 <WorkspaceBreadcrumbItem>
264 <h1>Usage</h1>
265 </WorkspaceBreadcrumbItem>
266 <WorkspaceBreadcrumbSeparator />
267 <WorkspaceBreadcrumbItem current className="min-w-10">
268 <UsageEnvironmentFilter
269 environments={environments}
270 selectedEnvironments={selectedEnvironments}
271 selectedEnvironmentIds={selectedEnvironmentIds}
272 onSelectionChange={setSelectedEnvironmentIds}
273 showUsageStatus={!showingLimits}
274 isPartial={isPartial}
275 duplicateSources={merged.duplicateSources}
276 staleEnvironments={merged.staleEnvironments}
277 accountUsage={merged.accountUsage}
278 />
279 </WorkspaceBreadcrumbItem>
280 </WorkspaceBreadcrumb>
281 {!showingLimits ? (
282 <span className="hidden min-w-0 truncate text-xs text-muted-foreground 2xl:block">
283 {windowLabel}
284 </span>
285 ) : null}
286 <div className="ms-auto hidden min-w-0 items-center justify-end gap-2 xl:flex">
287 <ToggleGroup
288 aria-label="Usage metric"
289 variant="segmented"
290 value={[metric]}
291 onValueChange={(next) => {
292 const value = next[0];
293 if (isUsageMetric(value)) selectMetric(value);
294 }}
295 >
296 {METRIC_OPTIONS.map((option) => (
297 <Toggle key={option.value} value={option.value}>
298 {option.label}
299 </Toggle>
300 ))}
301 </ToggleGroup>
302 {/* The period does not apply to Limits, so it stays in place but
303 disabled; unmounting it shifted the metric toggle ~300px. */}
304 <ToggleGroup
305 aria-label="Usage period"
306 variant="segmented"
307 value={[String(windowDays)]}
308 disabled={showingLimits}
309 onValueChange={(next) => {
310 const value = next[0];
311 if (value) selectWindow(Number(value));
312 }}
313 >
314 {WINDOW_OPTIONS.map((option) => (
315 <Toggle key={option.days} value={String(option.days)}>
316 {option.label}
317 </Toggle>
318 ))}
319 </ToggleGroup>
320 <Button
321 onClick={refreshWindow}
322 aria-label={showingLimits ? "Refresh limits" : "Refresh usage"}
323 aria-busy={isRefreshing}
324 disabled={isRefreshing}
325 size="icon-sm"
326 variant="ghost"
327 >
328 <RefreshIcon className="size-3.5" refreshing={isRefreshing} />
329 </Button>
330 <Button
331 onClick={() => downloadExport("csv")}
332 aria-label="Export usage as CSV"
333 size="icon-sm"
334 variant="ghost"
335 title="Export usage as CSV"
336 >
337 <DownloadIcon className="size-3.5" />
338 </Button>
339 </div>
340 <div className="col-span-2 ms-auto flex min-w-0 items-center justify-end gap-1 xl:hidden">
341 <Select
342 value={metric}
343 onValueChange={(value) => {
344 if (isUsageMetric(value)) selectMetric(value);
345 }}
346 >
347 <SelectTrigger
348 aria-label="Usage metric"
349 size="compact"
350 variant="ghost"
351 className="w-auto min-w-0"
352 >
353 <SelectValue>
354 {METRIC_OPTIONS.find((option) => option.value === metric)?.label}
355 </SelectValue>
356 </SelectTrigger>
357 <SelectPopup align="end" alignItemWithTrigger={false}>
358 {METRIC_OPTIONS.map((option) => (
359 <SelectItem key={option.value} value={option.value}>
360 {option.label}
361 </SelectItem>
362 ))}
363 </SelectPopup>
364 </Select>
365 <Select
366 value={String(windowDays)}
367 disabled={showingLimits}
368 onValueChange={(value) => selectWindow(Number(value))}
369 >
370 <SelectTrigger
371 aria-label="Usage period"
372 size="compact"
373 variant="ghost"
374 className="w-auto min-w-0"
375 >
376 <SelectValue>
377 {WINDOW_OPTIONS.find((option) => option.days === windowDays)?.label}
378 </SelectValue>
379 </SelectTrigger>
380 <SelectPopup align="end" alignItemWithTrigger={false}>
381 {WINDOW_OPTIONS.map((option) => (
382 <SelectItem key={option.days} value={String(option.days)}>
383 {option.label}
384 </SelectItem>
385 ))}
386 </SelectPopup>
387 </Select>
388 <Button
389 onClick={refreshWindow}
390 aria-label={showingLimits ? "Refresh limits" : "Refresh usage"}
391 aria-busy={isRefreshing}
392 disabled={isRefreshing}
393 size="icon-sm"
394 variant="ghost"
395 >
396 <RefreshIcon className="size-3.5" refreshing={isRefreshing} />
397 </Button>
398 <Button
399 onClick={() => downloadExport("csv")}
400 aria-label="Export usage as CSV"
401 size="icon-sm"
402 variant="ghost"
403 title="Export usage as CSV"
404 >
405 <DownloadIcon className="size-3.5" />
406 </Button>
407 </div>
408 </div>
409 );
410
411 return (
412 <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
413 <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
414 <WorkspacePageHeader electron={isElectron} className="h-auto">
415 {topbarContent}
416 </WorkspacePageHeader>
417
418 <ScrollArea className="min-h-0 flex-1">
419 <WorkspacePageContainer width="wide">
420 {selectedEnvironments.length === 0 ? (
421 <p className="text-sm text-muted-foreground">
422 {environments.length === 0
423 ? `Connect an environment to see ${showingLimits ? "limits" : "usage"}.`
424 : `Select an environment to see ${showingLimits ? "limits" : "usage"}.`}
425 </p>
426 ) : showingLimits ? (
427 <UsageLimitsSection selectedEnvironmentIds={selectedEnvironmentIds} />
428 ) : isPending ? (
429 <UsageSkeleton />
430 ) : (
431 <>
432 {merged.accountUsage !== null ? (
433 <DevinAccountUsageCard usage={merged.accountUsage} />
434 ) : null}
435 <section className="grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]">
436 <div className="flex min-w-0 flex-col gap-5">
437 <div className="flex flex-col gap-1">
438 <span className="text-4xl font-semibold text-foreground tabular-nums">
439 {metric === "cost"
440 ? formatUsd(merged.costUsd)
441 : formatTokens(merged.totalTokens)}
442 </span>
443 <span className="text-xs text-muted-foreground">
444 {metric === "cost"
445 ? `${formatCount(merged.sessions)} sessions · API estimate`
446 : `${formatCount(merged.sessions)} sessions`}
447 </span>
448 </div>
449
450 {activeProviders.map((provider) => {
451 const totals = merged.providers.find((entry) => entry.provider === provider);
452 const share =
453 metric === "cost" ? (totals?.costShare ?? 0) : (totals?.tokenShare ?? 0);
454 const providerSessions = totals?.sessions ?? 0;
455 const sessionLabel = `${formatCount(providerSessions)} ${
456 providerSessions === 1 ? "session" : "sessions"
457 }`;
458 return (
459 <div key={provider} className="flex flex-col gap-1">
460 <div className="flex items-baseline justify-between gap-4">
461 <span className="flex min-w-0 items-center gap-2 text-sm text-foreground">
462 <span
463 aria-hidden
464 className="size-2 shrink-0 rounded-full"
465 style={{
466 backgroundColor: PROVIDER_PRESENTATION[provider].color,
467 }}
468 />
469 <ProviderMark provider={provider} className="size-4" />
470 <span className="flex min-w-0 items-baseline gap-1.5">
471 <span className="truncate">
472 {PROVIDER_PRESENTATION[provider].label}
473 </span>
474 <span className="shrink-0 whitespace-nowrap text-[11px] text-muted-foreground tabular-nums">
475 {sessionLabel}
476 </span>
477 </span>
478 </span>
479 <span className="shrink-0 text-sm font-medium text-foreground tabular-nums">
480 {metric === "cost"
481 ? formatUsd(totals?.costUsd ?? 0)
482 : formatTokens(totals?.totalTokens ?? 0)}
483 </span>
484 </div>
485 <span className="text-xs text-muted-foreground">
486 {metric === "cost"
487 ? `${formatPercent(share)} of cost · ${formatTokens(totals?.totalTokens ?? 0)} tokens`
488 : `${formatPercent(share)} of tokens · ${formatUsd(totals?.costUsd ?? 0)}`}
489 </span>
490 </div>
491 );
492 })}
493 </div>
494
495 <div className="flex min-w-0 flex-col gap-3">
496 <h2 className="text-sm font-medium text-foreground">
497 {isPast24Hours ? "Hourly" : "Daily"}{" "}
498 {metric === "tokens" ? "processed tokens" : "cost"}
499 </h2>
500 <UsageProviderChart
501 providers={visibleProviders}
502 days={days}
503 daily={visibleDaily}
504 hours={hours}
505 hourly={visibleHourly}
506 metric={metric}
507 referenceTime={window.untilTime}
508 resolution={isPast24Hours ? "hour" : "day"}
509 timeZone={window.timeZone}
510 />
511 </div>
512 </section>
513
514 <section className="flex flex-col gap-2">
515 <h2 className="text-sm font-medium text-foreground">Totals</h2>
516 <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">
517 <Metric label="Processed tokens" value={formatTokens(merged.totalTokens)} />
518 <Metric label="Cached input" value={formatTokens(merged.cachedInputTokens)} />
519 <Metric
520 label="Uncached input"
521 value={formatTokens(merged.uncachedInputTokens)}
522 />
523 <Metric label="Output" value={formatTokens(merged.outputTokens)} />
524 <Metric
525 label="Cache savings"
526 value={formatUsd(merged.costQuality.cacheSavingsUsd)}
527 />
528 </div>
529 </section>
530
531 <section className="flex flex-col gap-3">
532 <div className="flex items-center justify-between gap-3">
533 <h2 className="text-sm font-medium text-foreground">
534 Breakdown
535 {providerFilter === "all"
536 ? ""
537 : ` · ${PROVIDER_PRESENTATION[providerFilter].label}`}
538 </h2>
539 <div className="flex items-center gap-2">
540 <Select
541 value={providerFilter}
542 onValueChange={(value) => {
543 if (
544 value === "all" ||
545 PROVIDER_ORDER.includes(value as UsageProviderKind)
546 ) {
547 setProviderFilter(value as UsageProviderKind | "all");
548 }
549 }}
550 >
551 <SelectTrigger
552 aria-label="Filter usage by provider"
553 size="compact"
554 variant="ghost"
555 >
556 <SelectValue>
557 {providerFilter === "all"
558 ? "All providers"
559 : PROVIDER_PRESENTATION[providerFilter].label}
560 </SelectValue>
561 </SelectTrigger>
562 <SelectPopup align="end" alignItemWithTrigger={false}>
563 <SelectItem value="all">All providers</SelectItem>
564 {PROVIDER_ORDER.filter(
565 (provider) => PROVIDER_PRESENTATION[provider] !== undefined,
566 ).map((provider) => (
567 <SelectItem key={provider} value={provider}>
568 {PROVIDER_PRESENTATION[provider].label}
569 </SelectItem>
570 ))}
571 </SelectPopup>
572 </Select>
573 <ToggleGroup
574 aria-label="Usage breakdown"
575 variant="segmented"
576 value={[breakdown]}
577 onValueChange={(next) => {
578 const value = next[0];
579 if (value === "model" || value === "time") setBreakdown(value);
580 }}
581 >
582 {(
583 [
584 { value: "model", label: "Model" },
585 { value: "time", label: isPast24Hours ? "Hour" : "Day" },
586 ] as const
587 ).map((option) => (
588 <Toggle key={option.value} value={option.value}>
589 {option.label}
590 </Toggle>
591 ))}
592 </ToggleGroup>
593 </div>
594 </div>
595
596 {breakdown === "model" ? (
597 <table className="w-full table-fixed text-sm">
598 <colgroup>
599 <col className="w-2/5" />
600 <col className="w-1/5" />
601 <col className="w-1/5" />
602 <col className="w-1/5" />
603 </colgroup>
604 <thead>
605 <tr className="border-b border-border text-left text-xs text-muted-foreground">
606 <th className="py-2 font-normal">Model</th>
607 <th className="py-2 text-right font-normal">Cost</th>
608 <th className="py-2 text-right font-normal">Share</th>
609 <th className="py-2 text-right font-normal">Tokens</th>
610 </tr>
611 </thead>
612 <tbody>
613 {breakdownModels.length === 0 ? (
614 <tr>
615 <td colSpan={4} className="py-6 text-center text-muted-foreground">
616 No activity in this window.
617 </td>
618 </tr>
619 ) : (
620 breakdownModels.map((model) => (
621 <tr
622 key={`${model.provider}:${model.model}`}
623 className="border-b border-border/50 transition-colors hover:bg-muted/50"
624 >
625 <td className="py-2 text-foreground">
626 <span className="flex items-center gap-2">
627 <ProviderMark provider={model.provider} className="size-3.5" />
628 {model.model}
629 </span>
630 </td>
631 <td className="py-2 text-right text-foreground tabular-nums">
632 {formatUsd(model.costUsd)}
633 </td>
634 <td className="py-2 text-right text-muted-foreground tabular-nums">
635 {formatPercent(model.costShare)}
636 </td>
637 <td className="py-2 text-right text-muted-foreground tabular-nums">
638 {formatTokens(model.totalTokens)}
639 </td>
640 </tr>
641 ))
642 )}
643 </tbody>
644 </table>
645 ) : (
646 <table className="w-full table-fixed text-sm">
647 <colgroup>
648 <col className="w-2/5" />
649 {visibleProviders.map((provider) => (
650 <col key={provider} style={{ width: timeValueColumnWidth }} />
651 ))}
652 <col style={{ width: timeValueColumnWidth }} />
653 <col style={{ width: timeValueColumnWidth }} />
654 </colgroup>
655 <thead>
656 <tr className="border-b border-border text-left text-xs text-muted-foreground">
657 <th className="py-2 font-normal">{isPast24Hours ? "Hour" : "Day"}</th>
658 {visibleProviders.map((provider) => (
659 <th key={provider} className="py-2 text-right font-normal">
660 {PROVIDER_PRESENTATION[provider].label}
661 </th>
662 ))}
663 <th className="py-2 text-right font-normal">Total</th>
664 <th className="py-2 text-right font-normal">Tokens</th>
665 </tr>
666 </thead>
667 <tbody>
668 {breakdownPeriods.length === 0 ? (
669 <tr>
670 <td
671 colSpan={visibleProviders.length + 3}
672 className="py-6 text-center text-muted-foreground"
673 >
674 No activity in this window.
675 </td>
676 </tr>
677 ) : (
678 breakdownPeriods.map((period) => (
679 <tr
680 key={"hourStart" in period ? period.hourStart : period.day}
681 className="border-b border-border/50 transition-colors hover:bg-muted/50"
682 >
683 <td className="py-2 text-foreground">
684 {"hourStart" in period
685 ? formatHourShort(period.hourStart, window.timeZone)
686 : formatDayShort(period.day)}
687 </td>
688 {visibleProviders.map((provider) => (
689 <td
690 key={provider}
691 className="py-2 text-right text-muted-foreground tabular-nums"
692 >
693 {formatUsd(period.byProvider.get(provider)?.costUsd ?? 0)}
694 </td>
695 ))}
696 <td className="py-2 text-right text-foreground tabular-nums">
697 {formatUsd(period.costUsd)}
698 </td>
699 <td className="py-2 text-right text-muted-foreground tabular-nums">
700 {formatTokens(period.totalTokens)}
701 </td>
702 </tr>
703 ))
704 )}
705 </tbody>
706 </table>
707 )}
708 </section>
709 </>
710 )}
711 </WorkspacePageContainer>
712 </ScrollArea>
713 </div>
714 </SidebarInset>
715 );
716}
717
718/** Brand mark for the harness a row belongs to. */
719function ProviderMark({
720 provider,
721 className,
722}: {
723 readonly provider: UsageProviderKind;
724 readonly className: string;
725}) {
726 const Mark = PROVIDER_PRESENTATION[provider].mark;
727 return <Mark className={cn("shrink-0", className)} aria-hidden />;
728}
729
730function Metric({ label, value }: { readonly label: string; readonly value: string }) {
731 return (
732 <div className="flex min-w-0 flex-col gap-0.5">
733 <span className="text-xs text-muted-foreground">{label}</span>
734 <span className="text-base font-medium text-foreground tabular-nums">{value}</span>
735 </div>
736 );
737}
738
739/**
740 * Explains failed or incompatible environments and deduplicated transcripts.
741 * Shown inside the environment filter so arriving results do not move the page.
742 */
743function UsageCoverageNotice({
744 environments,
745 duplicateSources,
746 staleEnvironments,
747 accountUsage,
748}: {
749 readonly environments: readonly EnvironmentUsageStatus[];
750 readonly duplicateSources: readonly string[];
751 readonly staleEnvironments: readonly string[];
752 readonly accountUsage: UsageAccountConsumption | null;
753}) {
754 const failed = environments.filter((environment) => environment.error !== null);
755 const stale = environments.filter((environment) =>
756 staleEnvironments.includes(environment.environmentId),
757 );
758 const hasDevinSource = environments.some((environment) =>
759 environment.summary?.sources.some(
760 (source) => source.fingerprint.provider === "devin" && source.status !== "missing",
761 ),
762 );
763 if (
764 failed.length === 0 &&
765 stale.length === 0 &&
766 duplicateSources.length === 0 &&
767 !hasDevinSource
768 ) {
769 return null;
770 }
771
772 return (
773 <div className="flex flex-col gap-1 border-t border-border px-2 py-2 text-xs text-muted-foreground">
774 {failed.map((environment) => (
775 <span key={environment.label}>{environment.label} could not report usage.</span>
776 ))}
777 {stale.map((environment) => (
778 <span key={environment.label}>
779 {environment.label} runs an older server version and is excluded from totals.
780 </span>
781 ))}
782 {duplicateSources.length > 0 ? (
783 <span>
784 Counted once across environments sharing a transcript directory:{" "}
785 {duplicateSources.join(", ")}
786 </span>
787 ) : null}
788 {hasDevinSource ? (
789 <span>
790 Devin ACP usage is read from this T3 server's local event logs. Devin account billing
791 is kept separate from the local token/cost estimate
792 {accountUsage?.status === "available" ? " and is shown below." : "."}
793 </span>
794 ) : null}
795 </div>
796 );
797}
798
799function formatAcus(value: number): string {
800 return new Intl.NumberFormat("en-US", {
801 maximumFractionDigits: 2,
802 }).format(value);
803}
804
805/** Official Devin account units, deliberately kept separate from token costs. */
806function DevinAccountUsageCard({ usage }: { readonly usage: UsageAccountConsumption }) {
807 const statusMessage =
808 usage.status === "notConfigured"
809 ? "Optional account usage is not configured. Add DEVIN_API_KEY and DEVIN_ORG_ID as sensitive Devin provider environment variables."
810 : usage.status === "forbidden"
811 ? "The configured Devin API key cannot read organization consumption. Use a cog_ service key with ViewOrgConsumption permission."
812 : usage.status === "failed"
813 ? (usage.message ?? "Devin account consumption could not be loaded.")
814 : null;
815
816 return (
817 <section className="flex flex-col gap-3 border border-border px-3 py-3">
818 <div className="flex flex-wrap items-baseline justify-between gap-3">
819 <div className="flex flex-col gap-0.5">
820 <h2 className="text-sm font-medium text-foreground">Devin account usage</h2>
821 <span className="text-xs text-muted-foreground">Official ACUs for this window</span>
822 </div>
823 {usage.status === "available" ? (
824 <span className="text-lg font-medium text-foreground tabular-nums">
825 {formatAcus(usage.totalAcus)} ACUs
826 </span>
827 ) : null}
828 </div>
829
830 {statusMessage !== null ? (
831 <p className="text-xs text-muted-foreground">{statusMessage}</p>
832 ) : (
833 <>
834 <div className="flex flex-wrap gap-x-5 gap-y-1 text-xs text-muted-foreground">
835 <span>{usage.days.length} billing days returned</span>
836 <span>Source: {usage.source}</span>
837 {usage.fetchedAt !== null ? (
838 <span>Updated {formatDateTimeShort(usage.fetchedAt)}</span>
839 ) : null}
840 </div>
841 {usage.days.length > 0 ? (
842 <div className="grid gap-1 text-xs">
843 {usage.days
844 .toReversed()
845 .slice(0, 5)
846 .map((day) => (
847 <div key={day.day} className="flex items-center justify-between gap-3">
848 <span className="text-muted-foreground">{formatDayShort(day.day)}</span>
849 <span className="text-foreground tabular-nums">
850 {formatAcus(day.acus)} ACUs
851 </span>
852 </div>
853 ))}
854 </div>
855 ) : null}
856 </>
857 )}
858 </section>
859 );
860}
861
862/** Environment selection and scan progress share a permanent header control. */
863function UsageEnvironmentFilter({
864 environments,
865 selectedEnvironments,
866 selectedEnvironmentIds,
867 onSelectionChange,
868 showUsageStatus,
869 isPartial,
870 duplicateSources,
871 staleEnvironments,
872 accountUsage,
873}: {
874 readonly environments: readonly EnvironmentUsageStatus[];
875 readonly selectedEnvironments: readonly EnvironmentUsageStatus[];
876 readonly selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null;
877 readonly onSelectionChange: (ids: ReadonlySet<EnvironmentId> | null) => void;
878 readonly showUsageStatus: boolean;
879 readonly isPartial: boolean;
880 readonly duplicateSources: readonly string[];
881 readonly staleEnvironments: readonly string[];
882 readonly accountUsage: UsageAccountConsumption | null;
883}) {
884 const [modelPricesOpen, setModelPricesOpen] = useState(false);
885 const allSelected = selectedEnvironmentIds === null;
886 const label = allSelected
887 ? "All environments"
888 : selectedEnvironments.length === 1
889 ? selectedEnvironments[0]!.label
890 : `${selectedEnvironments.length} environments`;
891 const pendingCount = selectedEnvironments.filter(
892 (environment) =>
893 environment.error === null && (environment.isPending || environment.summary === null),
894 ).length;
895 const hasIssue =
896 selectedEnvironments.some((environment) => environment.error !== null) ||
897 staleEnvironments.length > 0;
898
899 return (
900 <>
901 <Menu>
902 <MenuTrigger className="group/usage-environment inline-flex min-w-0 max-w-full cursor-pointer items-center gap-1 rounded-sm text-left focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring">
903 <span className="min-w-0 truncate">{label}</span>
904 <span className="flex size-3.5 shrink-0 items-center justify-center text-muted-foreground">
905 {showUsageStatus && pendingCount > 0 ? (
906 <>
907 <CircleDashedIcon className="size-3.5" aria-hidden />
908 <span className="sr-only">
909 {pendingCount} {pendingCount === 1 ? "environment" : "environments"} still
910 scanning
911 {isPartial ? "; totals are partial" : ""}
912 </span>
913 </>
914 ) : showUsageStatus && hasIssue ? (
915 <CircleAlertIcon
916 className="size-3.5 text-amber-600 dark:text-amber-400"
917 aria-label="Some environments could not report usage"
918 />
919 ) : (
920 <ChevronDownIcon
921 className="size-3.5 opacity-0 transition-opacity group-hover/usage-environment:opacity-100 group-focus-visible/usage-environment:opacity-100 group-data-popup-open/usage-environment:opacity-100"
922 aria-hidden
923 />
924 )}
925 </span>
926 </MenuTrigger>
927 <MenuPopup align="start" className="w-80 max-w-[calc(100vw-2rem)]">
928 <MenuCheckboxItem
929 checked={allSelected}
930 closeOnClick={false}
931 onCheckedChange={(checked) => onSelectionChange(checked ? null : new Set())}
932 >
933 All environments
934 </MenuCheckboxItem>
935 <MenuSeparator />
936 {environments.map((environment) => {
937 const checked =
938 selectedEnvironmentIds === null ||
939 selectedEnvironmentIds.has(environment.environmentId);
940 const status =
941 environment.error !== null
942 ? "Unavailable"
943 : environment.summary !== null &&
944 !isCompatibleUsageContractVersion(
945 environment.summary.contractVersion,
946 USAGE_CONTRACT_VERSION,
947 )
948 ? "Update required"
949 : environment.summary === null
950 ? "Scanning…"
951 : environment.isPending
952 ? "Refreshing…"
953 : "Ready";
954 return (
955 <MenuCheckboxItem
956 key={environment.environmentId}
957 checked={checked}
958 closeOnClick={false}
959 className="grid-cols-[1rem_minmax(0,1fr)]"
960 onCheckedChange={(nextChecked) => {
961 const next = new Set(selectedEnvironments.map((entry) => entry.environmentId));
962 if (nextChecked) next.add(environment.environmentId);
963 else next.delete(environment.environmentId);
964 onSelectionChange(next.size === environments.length ? null : next);
965 }}
966 >
967 <span className="flex min-w-0 items-center gap-3">
968 <span className="min-w-0 flex-1 truncate">{environment.label}</span>
969 {showUsageStatus ? (
970 <span
971 className={cn(
972 "shrink-0 text-xs text-muted-foreground",
973 environment.error !== null && "text-destructive",
974 )}
975 >
976 {status}
977 </span>
978 ) : null}
979 </span>
980 </MenuCheckboxItem>
981 );
982 })}
983 {environments.length === 0 ? (
984 <p className="px-2 py-2 text-xs text-muted-foreground">No environments connected.</p>
985 ) : null}
986 {showUsageStatus && isPartial ? (
987 <p className="px-2 py-2 text-xs text-muted-foreground">
988 Totals are partial while selected environments scan.
989 </p>
990 ) : null}
991 {showUsageStatus ? (
992 <UsageCoverageNotice
993 environments={selectedEnvironments}
994 duplicateSources={duplicateSources}
995 staleEnvironments={staleEnvironments}
996 accountUsage={accountUsage}
997 />
998 ) : null}
999 <MenuSeparator />
1000 <MenuItem onClick={() => setModelPricesOpen(true)}>
1001 <SlidersHorizontalIcon aria-hidden />
1002 Model prices
1003 </MenuItem>
1004 </MenuPopup>
1005 </Menu>
1006 {modelPricesOpen ? (
1007 <UsagePriceOverrides
1008 usage={environments}
1009 initialSelectedEnvironmentIds={selectedEnvironmentIds}
1010 onOpenChange={setModelPricesOpen}
1011 />
1012 ) : null}
1013 </>
1014 );
1015}
1016
1017/**
1018 * Stand-in with the loaded page's shape, using the shared `Skeleton` bars so it
1019 * breathes with the same `animate-skeleton` pulse as every other loading state.
1020 * Replaced by results as soon as the first environment answers.
1021 */
1022function UsageSkeleton() {
1023 return (
1024 <>
1025 <section className="grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]">
1026 <div className="flex flex-col gap-5">
1027 <div className="flex flex-col gap-1">
1028 <Skeleton className="h-10 w-36" />
1029 <Skeleton className="h-4 w-32" />
1030 </div>
1031 {PROVIDER_ORDER.map((provider) => (
1032 <div key={provider} className="flex flex-col gap-1">
1033 <div className="flex min-h-5 items-center justify-between gap-4">
1034 <span className="flex items-center gap-2">
1035 <Skeleton className="size-2 shrink-0 rounded-full" />
1036 <Skeleton className="size-4 shrink-0 rounded-full" />
1037 <Skeleton className="h-3.5 w-20" />
1038 </span>
1039 <Skeleton className="h-3.5 w-14" />
1040 </div>
1041 <Skeleton className="h-4 w-36" />
1042 </div>
1043 ))}
1044 </div>
1045
1046 <div className="flex flex-col gap-3">
1047 <Skeleton className="h-5 w-24" />
1048 <div className="flex flex-col gap-1">
1049 <Skeleton className="ml-16 h-56 bg-muted-foreground/10" />
1050 <Skeleton className="ml-16 h-4 bg-muted-foreground/10" />
1051 </div>
1052 </div>
1053 </section>
1054
1055 <section className="flex flex-col gap-2">
1056 <h2 className="text-sm font-medium text-foreground">Totals</h2>
1057 <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">
1058 {["Processed tokens", "Cached input", "Uncached input", "Output", "Cache savings"].map(
1059 (label) => (
1060 <div key={label} className="flex flex-col gap-0.5">
1061 <span className="text-xs text-muted-foreground">{label}</span>
1062 <Skeleton className="h-6 w-16" />
1063 </div>
1064 ),
1065 )}
1066 </div>
1067 </section>
1068
1069 <section className="flex flex-col gap-3">
1070 <div className="flex items-center justify-between gap-3">
1071 <h2 className="text-sm font-medium text-foreground">Breakdown</h2>
1072 <Skeleton className="h-7 w-28 rounded-lg" />
1073 </div>
1074 <Skeleton className="h-44 bg-muted-foreground/10" />
1075 </section>
1076 </>
1077 );
1078}