The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 05:30 UTC
refactor(web): the usage page keeps its caching without "use memo" (#20807)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 17, 2026 at 00:51 UTC
8c67f77af6b4ca8a34a48f0ea87c684f99e8fa83
1 file changed
+512
-496
apps/web/src/components/usage/UsagePage.tsx
+512
-496
@@ -7,6 +7,7 @@ import {
7
USAGE_CONTRACT_VERSION,
8
type EnvironmentId,
9
type UsageProviderKind,
10
+ type UsageSummaryInput,
11
} from "@t3tools/contracts";
12
import { CircleAlertIcon, ChevronDownIcon, InfoIcon, SlidersHorizontalIcon } from "lucide-react";
13
import { useEffect, useEffectEvent, useRef, useState } from "react";
@@ -114,12 +115,6 @@ function isUsageWindowDays(value: number): value is UsagePagePreferences["window
115
116
const providerLabel = (provider: UsageProviderKind) => PROVIDER_PRESENTATION[provider].label;
117
117
-// useUsage keys its queries on this set, so it must keep its identity.
118
-function useHiddenProviderSet(hiddenProviders: UsagePagePreferences["hiddenProviders"]) {
119
- "use memo";
120
- return new Set(hiddenProviders);
121
-}
122
-
118
function usageLoading(
119
showingKept: boolean,
120
selectedEnvironments: Parameters<typeof usageLoadingState>[0],
@@ -138,37 +133,6 @@ function usageLoading(
133
};
134
}
135
141
-// UsageProviderChart memoizes on the provider collections, so they must keep their identity.
142
-function useUsageProviders(
143
- showingKept: boolean,
144
- selectedEnvironments: Parameters<typeof usageLoadingState>[0],
145
- refreshingUsage: boolean,
146
- hiddenProviders: ReadonlySet<UsageProviderKind>,
147
- mergedProviders: MergedUsage["providers"],
148
-) {
149
- "use memo";
150
- const loading = usageLoading(showingKept, selectedEnvironments, refreshingUsage, hiddenProviders);
151
- const providersWithData = providersWithUsage(mergedProviders);
152
- const activeProviders = PROVIDER_ORDER.filter(
153
- (provider) => providersWithData.includes(provider) || loading.providers.has(provider),
154
- );
155
- const chartLoadingProviders = new Set(
156
- activeProviders.filter((provider) => loading.everyProvider || loading.providers.has(provider)),
157
- );
158
- return { loading, providersWithData, activeProviders, chartLoadingProviders };
159
-}
160
-
161
-// UsageProviderChart memoizes on these arrays, so they must keep their identity.
162
-function useUsagePeriods(usageWindow: ReturnType<typeof makeWindow>) {
163
- "use memo";
164
- const days = enumerateDays(usageWindow.sinceDay, usageWindow.untilDay);
165
- const hours =
166
- usageWindow.sinceTime === undefined || usageWindow.untilTime === undefined
167
- ? []
168
- : enumerateHourStarts(usageWindow.sinceTime, usageWindow.untilTime);
169
- return { days, hours };
170
-}
171
-
136
export function UsagePage() {
137
const [preferences, setPreferences] = useState(readUsagePagePreferences);
138
useEscapeToGoBack();
@@ -194,12 +158,11 @@ export function UsagePage() {
158
const [isRefreshing, setIsRefreshing] = useState(false);
159
const [limitsNow, setLimitsNow] = useState(() => Date.now());
160
const refreshingRef = useRef(false);
197
- const [breakdown, setBreakdown] = useState<"model" | "time">("model");
161
const [priceDialog, setPriceDialog] = useState<{ readonly model?: string } | null>(null);
162
const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);
163
const [selectedEnvironmentIds, setSelectedEnvironmentIds] =
164
useState<ReadonlySet<EnvironmentId> | null>(null);
202
- const hiddenProviders = useHiddenProviderSet(preferences.hiddenProviders);
165
+ const hiddenProviders = new Set(preferences.hiddenProviders);
166
const { days: windowDays, window } = windowSelection;
167
const isPast24Hours = windowDays === 1;
168
const {
@@ -215,36 +178,10 @@ export function UsagePage() {
178
const shownHourly = shownWindow.resolution === "hour";
179
const refreshingUsage = isRefreshing && !showingLimits;
180
const showingKept = shown !== null && shown.window !== window;
218
- const { loading, providersWithData, activeProviders, chartLoadingProviders } = useUsageProviders(
219
- showingKept,
220
- selectedEnvironments,
221
- refreshingUsage,
222
- hiddenProviders,
223
- merged.providers,
224
- );
225
- const isProviderLoading = (provider: UsageProviderKind) =>
226
- loading.everyProvider || loading.providers.has(provider);
181
const presentations = useAtomValue(environmentPresentations.presentationsAtom);
182
const cursorAccessEnvironments = hiddenProviders.has("cursor")
183
? []
184
: cursorKeychainAccessEnvironments(selectedEnvironments);
231
- const sourceMessages = [
232
- ...new Set(
233
- selectedEnvironments.flatMap(
234
- (environment) =>
235
- environment.summary?.sources.flatMap((source) =>
236
- source.message &&
237
- !source.action &&
238
- !hiddenProviders.has(source.fingerprint.provider) &&
239
- (source.status === "partial" ||
240
- source.status === "failed" ||
241
- source.fingerprint.provider === "cursor")
242
- ? [source.message]
243
- : [],
244
- ) ?? [],
245
- ),
246
- ),
247
- ];
185
const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
186
reportFailure: false,
187
});
@@ -253,35 +190,6 @@ export function UsagePage() {
190
(environment) => environment.canReadDiagnostics,
191
);
192
256
- const { days, hours } = useUsagePeriods(shownWindow);
257
- const breakdownPeriods: readonly (DailyTotals | HourlyTotals)[] = (
258
- shownHourly ? merged.hourly : merged.daily
259
- ).toReversed();
260
- const breakdownModels =
261
- breakdown === "model" && metric === "tokens"
262
- ? sortModelsByTokens(merged.models)
263
- : merged.models;
264
- const selectedModel =
265
- selectedModelKey === null
266
- ? undefined
267
- : merged.models.find((model) => `${model.provider}:${model.model}` === selectedModelKey);
268
- const breakdownPeak = breakdownModels.reduce(
269
- (peak, model) => Math.max(peak, metric === "tokens" ? model.totalTokens : model.costUsd),
270
- 0,
271
- );
272
- const summaryRows: Array<
273
- | { readonly kind: "usage"; readonly provider: UsageProviderKind }
274
- | { readonly kind: "enable"; readonly environment: EnvironmentUsageStatus }
275
- > = activeProviders.map((provider) => ({ kind: "usage", provider }));
276
- const cursorInsertAt =
277
- Math.max(activeProviders.indexOf("codex"), activeProviders.indexOf("claude")) + 1;
278
- summaryRows.splice(
279
- cursorInsertAt,
280
- 0,
281
- ...cursorAccessEnvironments.map((environment) => ({ kind: "enable" as const, environment })),
282
- );
283
- const timeValueColumnWidth = `${60 / (activeProviders.length + 2)}%`;
284
-
193
const updatePreferences = (patch: Partial<UsagePagePreferences>) => {
194
const nextPreferences = { ...preferences, ...patch };
195
setPreferences(nextPreferences);
@@ -390,6 +298,24 @@ export function UsagePage() {
298
if (showingLimits && connectedLimitsEnvironments) autoRefreshLimits();
299
}, [showingLimits, connectedLimitsEnvironments]);
300
301
+ const days = enumerateDays(shownWindow.sinceDay, shownWindow.untilDay);
302
+ const hours =
303
+ shownWindow.sinceTime === undefined || shownWindow.untilTime === undefined
304
+ ? []
305
+ : enumerateHourStarts(shownWindow.sinceTime, shownWindow.untilTime);
306
+ const selectedModel =
307
+ selectedModelKey === null
308
+ ? undefined
309
+ : merged.models.find((model) => `${model.provider}:${model.model}` === selectedModelKey);
310
+
311
+ const showChatGptSharing =
312
+ !hiddenProviders.has("codex") &&
313
+ [...presentations].some(
314
+ ([id, presentation]) =>
315
+ (selectedEnvironmentIds === null || selectedEnvironmentIds.has(id)) &&
316
+ presentation.serverConfig?.providers.some(usesChatGptSharing),
317
+ );
318
+
319
const windowLabel =
320
shownHourly && shownWindow.sinceTime !== undefined && shownWindow.untilTime !== undefined
321
? `${formatDateTimeShort(shownWindow.sinceTime, shownWindow.timeZone)} to ${formatDateTimeShort(shownWindow.untilTime, shownWindow.timeZone)}`
@@ -579,408 +505,24 @@ export function UsagePage() {
505
))}
506
</div>
507
) : (
582
- <div aria-busy={loading.partial} className="flex flex-col gap-6">
583
- {sourceMessages.map((message) => (
584
- <p key={message} className="mb-4 text-sm text-muted-foreground">
585
- {message}
586
- </p>
587
- ))}
588
- <section className="grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]">
589
- <div className="flex min-w-0 flex-col gap-5">
590
- <div className="flex flex-col gap-1">
591
- <span
592
- className={cn(
593
- "text-4xl font-semibold text-foreground tabular-nums",
594
- figureClass(loading.partial),
595
- )}
596
- >
597
- {metric === "cost"
598
- ? formatUsd(merged.costUsd)
599
- : formatTokens(merged.totalTokens)}
600
- </span>
601
- <span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
602
- <span>
603
- <span className={figureClass(loading.partial)}>
604
- {formatCount(merged.sessions)} sessions
605
- </span>
606
- {metric === "cost" && " · API estimate"}
607
- </span>
608
- {metric === "cost" && merged.costQuality.unpricedShare > 0 && (
609
- <Popover>
610
- <PopoverTrigger
611
- openOnHover
612
- render={<InlineButton tone="muted" />}
613
- aria-label="Unpriced usage details"
614
- >
615
- <InfoIcon className="size-3" aria-hidden />
616
- </PopoverTrigger>
617
- <PopoverPopup side="top" tooltipStyle>
618
- API estimate excludes{" "}
619
- {formatPercent(merged.costQuality.unpricedShare)} unpriced records.
620
- </PopoverPopup>
621
- </Popover>
622
- )}
623
- </span>
624
- </div>
625
-
626
- {!hiddenProviders.has("codex") &&
627
- [...presentations].some(
628
- ([id, presentation]) =>
629
- (selectedEnvironmentIds === null || selectedEnvironmentIds.has(id)) &&
630
- presentation.serverConfig?.providers.some(usesChatGptSharing),
631
- ) ? (
632
- <div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
633
- <span>ChatGPT shared usage</span>
634
- <ChatGptUsageButton size="xs" />
635
- </div>
636
- ) : null}
637
-
638
- {summaryRows.map((row) => {
639
- if (row.kind === "enable") {
640
- return (
641
- <CursorEnableRow
642
- key={`enable:${row.environment.environmentId}`}
643
- environmentId={row.environment.environmentId}
644
- label={row.environment.label}
645
- showEnvironment={selectedEnvironments.length > 1}
646
- onEnabled={() => {
647
- void refresh();
648
- void refreshLimits(false, true);
649
- }}
650
- />
651
- );
652
- }
653
- const provider = row.provider;
654
- const totals = merged.providers.find((entry) => entry.provider === provider);
655
- const share =
656
- metric === "cost" ? (totals?.costShare ?? 0) : (totals?.tokenShare ?? 0);
657
- const providerSessions = totals?.sessions ?? 0;
658
- const sessionLabel = `${formatCount(providerSessions)} ${
659
- providerSessions === 1 ? "session" : "sessions"
660
- }`;
661
- const providerLoading = isProviderLoading(provider);
662
- const awaitingData = providerLoading && !providersWithData.includes(provider);
663
- return (
664
- <div key={provider} className="flex flex-col gap-1">
665
- <div className="flex items-baseline justify-between gap-4">
666
- <span className="flex min-w-0 items-center gap-2 text-sm text-foreground">
667
- <span
668
- aria-hidden
669
- className="size-2 shrink-0 rounded-full"
670
- style={{
671
- backgroundColor: PROVIDER_PRESENTATION[provider].color,
672
- }}
673
- />
674
- <ProviderMark provider={provider} className="size-4" />
675
- <span className="flex min-w-0 items-baseline gap-1.5">
676
- <span className="truncate">
677
- {PROVIDER_PRESENTATION[provider].label}
678
- </span>
679
- <span
680
- className={cn(
681
- "shrink-0 whitespace-nowrap text-2xs text-muted-foreground tabular-nums",
682
- figureClass(providerLoading),
683
- awaitingData && "invisible",
684
- )}
685
- >
686
- {sessionLabel}
687
- </span>
688
- </span>
689
- </span>
690
- <span
691
- className={cn(
692
- "shrink-0 text-sm font-medium text-foreground tabular-nums",
693
- figureClass(providerLoading),
694
- )}
695
- >
696
- {awaitingData
697
- ? "—"
698
- : metric === "cost"
699
- ? formatUsd(totals?.costUsd ?? 0)
700
- : formatTokens(totals?.totalTokens ?? 0)}
701
- </span>
702
- </div>
703
- <span
704
- className={cn(
705
- "text-xs text-muted-foreground",
706
- figureClass(providerLoading),
707
- awaitingData && "invisible",
708
- )}
709
- >
710
- {metric === "cost"
711
- ? `${formatPercent(share)} of cost · ${formatTokens(totals?.totalTokens ?? 0)} tokens`
712
- : `${formatPercent(share)} of tokens · ${formatUsd(totals?.costUsd ?? 0)}`}
713
- </span>
714
- </div>
715
- );
716
- })}
717
- </div>
718
-
719
- <div className="flex min-w-0 flex-col gap-3">
720
- <h2 className="text-sm font-medium text-foreground">
721
- {shownHourly ? "Hourly" : "Daily"}{" "}
722
- {metric === "tokens" ? "processed tokens" : "cost"}
723
- </h2>
724
- <UsageProviderChart
725
- providers={activeProviders}
726
- loadingProviders={chartLoadingProviders}
727
- days={days}
728
- daily={merged.daily}
729
- hours={hours}
730
- hourly={merged.hourly}
731
- metric={metric}
732
- referenceTime={shownWindow.untilTime}
733
- resolution={shownHourly ? "hour" : "day"}
734
- timeZone={shownWindow.timeZone}
735
- />
736
- </div>
737
- </section>
738
-
739
- <section className="flex flex-col gap-2">
740
- <h2 className="text-sm font-medium text-foreground">Totals</h2>
741
- <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">
742
- <Metric
743
- loading={loading.partial}
744
- label="Processed tokens"
745
- value={formatTokens(merged.totalTokens)}
746
- />
747
- <Metric
748
- loading={loading.partial}
749
- label="Cached input"
750
- value={formatTokens(merged.cachedInputTokens)}
751
- />
752
- <Metric
753
- loading={loading.partial}
754
- label="Uncached input"
755
- value={formatTokens(merged.uncachedInputTokens)}
756
- />
757
- <Metric
758
- loading={loading.partial}
759
- label="Output"
760
- value={formatTokens(merged.outputTokens)}
761
- />
762
- <Metric
763
- loading={loading.partial}
764
- label="Cache savings"
765
- value={formatUsd(merged.costQuality.cacheSavingsUsd)}
766
- />
767
- </div>
768
- </section>
769
-
770
- {merged.totalTokens > 0 ? (
771
- <section
772
- className={cn(
773
- "grid gap-x-12 gap-y-8 lg:grid-cols-2",
774
- figureClass(loading.partial),
775
- )}
776
- >
777
- {metric === "tokens" ? (
778
- <UsageShareBar
779
- label="Tokens by type"
780
- segments={tokenTypeSegments(merged)}
781
- format={formatTokens}
782
- />
783
- ) : (
784
- <>
785
- <UsageShareBar
786
- label="Cost by type"
787
- segments={costTypeSegments(merged.categoryCost)}
788
- format={formatUsd}
789
- />
790
- {merged.speedCost.fast + merged.speedCost.ultrafast > 0 ? (
791
- <UsageShareBar
792
- label="Cost by speed"
793
- segments={speedCostSegments(merged.speedCost)}
794
- format={formatUsd}
795
- aside={<SpeedPremium premiumUsd={merged.speedCost.premium} />}
796
- />
797
- ) : null}
798
- </>
799
- )}
800
- </section>
801
- ) : null}
802
-
803
- <section className="flex flex-col gap-3">
804
- <div className="flex items-center justify-between gap-3">
805
- <h2 className="text-sm font-medium text-foreground">Breakdown</h2>
806
- <ToggleGroup
807
- aria-label="Usage breakdown"
808
- variant="segmented"
809
- value={[breakdown]}
810
- onValueChange={(next) => {
811
- const value = next[0];
812
- if (value === "model" || value === "time") setBreakdown(value);
813
- }}
814
- >
815
- {(
816
- [
817
- { value: "model", label: "Model" },
818
- { value: "time", label: shownHourly ? "Hour" : "Day" },
819
- ] as const
820
- ).map((option) => (
821
- <Toggle key={option.value} value={option.value}>
822
- {option.label}
823
- </Toggle>
824
- ))}
825
- </ToggleGroup>
826
- </div>
827
-
828
- {breakdown === "model" ? (
829
- <table className="w-full text-sm">
830
- <thead>
831
- <tr className="border-b border-border text-right text-xs text-muted-foreground">
832
- <th className="py-2 pr-3 text-left font-normal">#</th>
833
- <th className="w-full py-2 text-left font-normal">Model</th>
834
- <th className="py-2 pl-6 font-normal">Cost</th>
835
- <th className="hidden py-2 pl-6 font-normal sm:table-cell">Share</th>
836
- <th className="py-2 pl-6 font-normal">Tokens</th>
837
- </tr>
838
- </thead>
839
- <tbody>
840
- {breakdownModels.length === 0 ? (
841
- <tr>
842
- <td colSpan={5} className="py-6 text-center text-muted-foreground">
843
- No activity in this window.
844
- </td>
845
- </tr>
846
- ) : (
847
- breakdownModels.map((model, index) => {
848
- const key = `${model.provider}:${model.model}`;
849
- const value = metric === "tokens" ? model.totalTokens : model.costUsd;
850
- const share = modelShare(
851
- model,
852
- metric === "tokens" ? "tokens" : "cost",
853
- );
854
- const rowFigures = figureClass(isProviderLoading(model.provider));
855
- return (
856
- <tr
857
- key={key}
858
- className="relative border-b border-border/50 text-right whitespace-nowrap text-muted-foreground tabular-nums transition-colors hover:bg-muted/50 has-focus-visible:bg-muted/50"
859
- >
860
- <td className="py-2.5 pr-3 text-left text-xs">{index + 1}</td>
861
- <td className="py-2.5 text-left whitespace-normal">
862
- <button
863
- type="button"
864
- onClick={() => setSelectedModelKey(key)}
865
- className="flex items-center gap-2 text-left text-foreground outline-none after:absolute after:inset-0"
866
- >
867
- <ProviderMark provider={model.provider} className="size-3.5" />
868
- {model.model}
869
- </button>
870
- <div
871
- aria-hidden
872
- className={cn("mt-1.5 h-0.5 max-w-48", rowFigures)}
873
- >
874
- <div
875
- className="h-full rounded-full"
876
- style={{
877
- width:
878
- value > 0 && breakdownPeak > 0
879
- ? `max(0.5rem, ${(value / breakdownPeak) * 100}%)`
880
- : 0,
881
- backgroundColor:
882
- PROVIDER_PRESENTATION[model.provider].color,
883
- }}
884
- />
885
- </div>
886
- </td>
887
- <td className={cn("py-2.5 pl-6 text-foreground", rowFigures)}>
888
- {isModelCostUnknown(model) ? (
889
- <span className="text-muted-foreground">Unpriced</span>
890
- ) : (
891
- formatUsd(model.costUsd)
892
- )}
893
- </td>
894
- <td className={cn("hidden py-2.5 pl-6 sm:table-cell", rowFigures)}>
895
- {share === null ? "" : formatPercent(share)}
896
- </td>
897
- <td className={cn("py-2.5 pl-6", rowFigures)}>
898
- {formatTokens(model.totalTokens)}
899
- </td>
900
- </tr>
901
- );
902
- })
903
- )}
904
- </tbody>
905
- </table>
906
- ) : (
907
- <table className="w-full table-fixed text-sm">
908
- <colgroup>
909
- <col className="w-2/5" />
910
- {activeProviders.map((provider) => (
911
- <col key={provider} style={{ width: timeValueColumnWidth }} />
912
- ))}
913
- <col style={{ width: timeValueColumnWidth }} />
914
- <col style={{ width: timeValueColumnWidth }} />
915
- </colgroup>
916
- <thead>
917
- <tr className="border-b border-border text-left text-xs text-muted-foreground">
918
- <th className="py-2 font-normal">{shownHourly ? "Hour" : "Day"}</th>
919
- {activeProviders.map((provider) => (
920
- <th key={provider} className="py-2 text-right font-normal">
921
- {PROVIDER_PRESENTATION[provider].label}
922
- </th>
923
- ))}
924
- <th className="py-2 text-right font-normal">Total</th>
925
- <th className="py-2 text-right font-normal">Tokens</th>
926
- </tr>
927
- </thead>
928
- <tbody>
929
- {breakdownPeriods.length === 0 ? (
930
- <tr>
931
- <td
932
- colSpan={activeProviders.length + 3}
933
- className="py-6 text-center text-muted-foreground"
934
- >
935
- No activity in this window.
936
- </td>
937
- </tr>
938
- ) : (
939
- breakdownPeriods.map((period) => (
940
- <tr
941
- key={"hourStart" in period ? period.hourStart : period.day}
942
- className="border-b border-border/50 transition-colors hover:bg-muted/50"
943
- >
944
- <td className="py-2 text-foreground">
945
- {"hourStart" in period
946
- ? formatHourShort(period.hourStart, shownWindow.timeZone)
947
- : formatDayShort(period.day)}
948
- </td>
949
- {activeProviders.map((provider) => (
950
- <td
951
- key={provider}
952
- className={cn(
953
- "py-2 text-right text-muted-foreground tabular-nums",
954
- figureClass(isProviderLoading(provider)),
955
- )}
956
- >
957
- {formatUsd(period.byProvider.get(provider)?.costUsd ?? 0)}
958
- </td>
959
- ))}
960
- <td
961
- className={cn(
962
- "py-2 text-right text-foreground tabular-nums",
963
- figureClass(loading.partial),
964
- )}
965
- >
966
- {formatUsd(period.costUsd)}
967
- </td>
968
- <td
969
- className={cn(
970
- "py-2 text-right text-muted-foreground tabular-nums",
971
- figureClass(loading.partial),
972
- )}
973
- >
974
- {formatTokens(period.totalTokens)}
975
- </td>
976
- </tr>
977
- ))
978
- )}
979
- </tbody>
980
- </table>
981
- )}
982
- </section>
983
- </div>
508
+ <UsageOverview
509
+ merged={merged}
510
+ shownWindow={shownWindow}
511
+ days={days}
512
+ hours={hours}
513
+ showingKept={showingKept}
514
+ metric={metric === "tokens" ? "tokens" : "cost"}
515
+ selectedEnvironments={selectedEnvironments}
516
+ hiddenProviders={hiddenProviders}
517
+ refreshingUsage={refreshingUsage}
518
+ cursorAccessEnvironments={cursorAccessEnvironments}
519
+ showChatGptSharing={showChatGptSharing}
520
+ onCursorEnabled={() => {
521
+ void refresh();
522
+ void refreshLimits(false, true);
523
+ }}
524
+ onSelectModel={setSelectedModelKey}
525
+ />
526
)}
527
</WorkspacePageContainer>
528
</ScrollArea>
@@ -1018,6 +560,480 @@ export function UsagePage() {
560
);
561
}
562
563
+function UsageOverview({
564
+ merged,
565
+ shownWindow,
566
+ days,
567
+ hours,
568
+ showingKept,
569
+ metric,
570
+ selectedEnvironments,
571
+ hiddenProviders,
572
+ refreshingUsage,
573
+ cursorAccessEnvironments,
574
+ showChatGptSharing,
575
+ onCursorEnabled,
576
+ onSelectModel,
577
+}: {
578
+ readonly merged: MergedUsage;
579
+ readonly shownWindow: UsageSummaryInput;
580
+ readonly days: readonly string[];
581
+ readonly hours: readonly string[];
582
+ readonly showingKept: boolean;
583
+ readonly metric: "tokens" | "cost";
584
+ readonly selectedEnvironments: readonly EnvironmentUsageStatus[];
585
+ readonly hiddenProviders: ReadonlySet<UsageProviderKind>;
586
+ readonly refreshingUsage: boolean;
587
+ readonly cursorAccessEnvironments: readonly EnvironmentUsageStatus[];
588
+ readonly showChatGptSharing: boolean;
589
+ readonly onCursorEnabled: () => void;
590
+ readonly onSelectModel: (key: string) => void;
591
+}) {
592
+ const [breakdown, setBreakdown] = useState<"model" | "time">("model");
593
+ const shownHourly = shownWindow.resolution === "hour";
594
+ const loading = usageLoading(showingKept, selectedEnvironments, refreshingUsage, hiddenProviders);
595
+ // A primitive copy: reading `loading.partial` in the JSX would keep `loading` alive
596
+ // across every derivation below and fold them into one cache scope.
597
+ const loadingPartial = loading.partial === true;
598
+ const loadingProviders = new Set(
599
+ PROVIDER_ORDER.filter((provider) => loading.everyProvider || loading.providers.has(provider)),
600
+ );
601
+ const providersWithData = new Set(providersWithUsage(merged.providers));
602
+ // `everyProvider` marks shown providers as loading; only `loading.providers`, which excludes
603
+ // hidden ones, may add a provider that has no data yet.
604
+ // Filtering a fresh copy, not the shared module array, lets the compiler cache this on its own.
605
+ const activeProviders = [...PROVIDER_ORDER].filter(
606
+ (provider) => providersWithData.has(provider) || loading.providers.has(provider),
607
+ );
608
+ const chartLoadingProviders = new Set(
609
+ activeProviders.filter((provider) => loadingProviders.has(provider)),
610
+ );
611
+ const sourceMessages = [
612
+ ...new Set(
613
+ selectedEnvironments.flatMap(
614
+ (environment) =>
615
+ environment.summary?.sources.flatMap((source) =>
616
+ source.message &&
617
+ !source.action &&
618
+ !hiddenProviders.has(source.fingerprint.provider) &&
619
+ (source.status === "partial" ||
620
+ source.status === "failed" ||
621
+ source.fingerprint.provider === "cursor")
622
+ ? [source.message]
623
+ : [],
624
+ ) ?? [],
625
+ ),
626
+ ),
627
+ ];
628
+ const breakdownPeriods: readonly (DailyTotals | HourlyTotals)[] = (
629
+ shownHourly ? merged.hourly : merged.daily
630
+ ).toReversed();
631
+ const breakdownModels =
632
+ breakdown === "model" && metric === "tokens"
633
+ ? sortModelsByTokens(merged.models)
634
+ : merged.models;
635
+ const breakdownPeak = breakdownModels.reduce(
636
+ (peak, model) => Math.max(peak, metric === "tokens" ? model.totalTokens : model.costUsd),
637
+ 0,
638
+ );
639
+ const cursorInsertAt =
640
+ Math.max(activeProviders.indexOf("codex"), activeProviders.indexOf("claude")) + 1;
641
+ const summaryRows: ReadonlyArray<
642
+ | { readonly kind: "usage"; readonly provider: UsageProviderKind }
643
+ | { readonly kind: "enable"; readonly environment: EnvironmentUsageStatus }
644
+ > = [
645
+ ...activeProviders
646
+ .slice(0, cursorInsertAt)
647
+ .map((provider) => ({ kind: "usage" as const, provider })),
648
+ ...cursorAccessEnvironments.map((environment) => ({ kind: "enable" as const, environment })),
649
+ ...activeProviders
650
+ .slice(cursorInsertAt)
651
+ .map((provider) => ({ kind: "usage" as const, provider })),
652
+ ];
653
+ const timeValueColumnWidth = `${60 / (activeProviders.length + 2)}%`;
654
+
655
+ return (
656
+ <div aria-busy={loadingPartial} className="flex flex-col gap-6">
657
+ {sourceMessages.map((message) => (
658
+ <p key={message} className="mb-4 text-sm text-muted-foreground">
659
+ {message}
660
+ </p>
661
+ ))}
662
+ <section className="grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]">
663
+ <div className="flex min-w-0 flex-col gap-5">
664
+ <div className="flex flex-col gap-1">
665
+ <span
666
+ className={cn(
667
+ "text-4xl font-semibold text-foreground tabular-nums",
668
+ figureClass(loadingPartial),
669
+ )}
670
+ >
671
+ {metric === "cost" ? formatUsd(merged.costUsd) : formatTokens(merged.totalTokens)}
672
+ </span>
673
+ <span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
674
+ <span>
675
+ <span className={figureClass(loadingPartial)}>
676
+ {formatCount(merged.sessions)} sessions
677
+ </span>
678
+ {metric === "cost" && " · API estimate"}
679
+ </span>
680
+ {metric === "cost" && merged.costQuality.unpricedShare > 0 && (
681
+ <Popover>
682
+ <PopoverTrigger
683
+ openOnHover
684
+ render={<InlineButton tone="muted" />}
685
+ aria-label="Unpriced usage details"
686
+ >
687
+ <InfoIcon className="size-3" aria-hidden />
688
+ </PopoverTrigger>
689
+ <PopoverPopup side="top" tooltipStyle>
690
+ API estimate excludes {formatPercent(merged.costQuality.unpricedShare)} unpriced
691
+ records.
692
+ </PopoverPopup>
693
+ </Popover>
694
+ )}
695
+ </span>
696
+ </div>
697
+
698
+ {showChatGptSharing ? (
699
+ <div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
700
+ <span>ChatGPT shared usage</span>
701
+ <ChatGptUsageButton size="xs" />
702
+ </div>
703
+ ) : null}
704
+
705
+ {summaryRows.map((row) => {
706
+ if (row.kind === "enable") {
707
+ return (
708
+ <CursorEnableRow
709
+ key={`enable:${row.environment.environmentId}`}
710
+ environmentId={row.environment.environmentId}
711
+ label={row.environment.label}
712
+ showEnvironment={selectedEnvironments.length > 1}
713
+ onEnabled={onCursorEnabled}
714
+ />
715
+ );
716
+ }
717
+ const provider = row.provider;
718
+ const totals = merged.providers.find((entry) => entry.provider === provider);
719
+ const share = metric === "cost" ? (totals?.costShare ?? 0) : (totals?.tokenShare ?? 0);
720
+ const providerSessions = totals?.sessions ?? 0;
721
+ const sessionLabel = `${formatCount(providerSessions)} ${
722
+ providerSessions === 1 ? "session" : "sessions"
723
+ }`;
724
+ const providerLoading = loadingProviders.has(provider);
725
+ const awaitingData = providerLoading && !providersWithData.has(provider);
726
+ return (
727
+ <div key={provider} className="flex flex-col gap-1">
728
+ <div className="flex items-baseline justify-between gap-4">
729
+ <span className="flex min-w-0 items-center gap-2 text-sm text-foreground">
730
+ <span
731
+ aria-hidden
732
+ className="size-2 shrink-0 rounded-full"
733
+ style={{
734
+ backgroundColor: PROVIDER_PRESENTATION[provider].color,
735
+ }}
736
+ />
737
+ <ProviderMark provider={provider} className="size-4" />
738
+ <span className="flex min-w-0 items-baseline gap-1.5">
739
+ <span className="truncate">{PROVIDER_PRESENTATION[provider].label}</span>
740
+ <span
741
+ className={cn(
742
+ "shrink-0 whitespace-nowrap text-2xs text-muted-foreground tabular-nums",
743
+ figureClass(providerLoading),
744
+ awaitingData && "invisible",
745
+ )}
746
+ >
747
+ {sessionLabel}
748
+ </span>
749
+ </span>
750
+ </span>
751
+ <span
752
+ className={cn(
753
+ "shrink-0 text-sm font-medium text-foreground tabular-nums",
754
+ figureClass(providerLoading),
755
+ )}
756
+ >
757
+ {awaitingData
758
+ ? "—"
759
+ : metric === "cost"
760
+ ? formatUsd(totals?.costUsd ?? 0)
761
+ : formatTokens(totals?.totalTokens ?? 0)}
762
+ </span>
763
+ </div>
764
+ <span
765
+ className={cn(
766
+ "text-xs text-muted-foreground",
767
+ figureClass(providerLoading),
768
+ awaitingData && "invisible",
769
+ )}
770
+ >
771
+ {metric === "cost"
772
+ ? `${formatPercent(share)} of cost · ${formatTokens(totals?.totalTokens ?? 0)} tokens`
773
+ : `${formatPercent(share)} of tokens · ${formatUsd(totals?.costUsd ?? 0)}`}
774
+ </span>
775
+ </div>
776
+ );
777
+ })}
778
+ </div>
779
+
780
+ <div className="flex min-w-0 flex-col gap-3">
781
+ <h2 className="text-sm font-medium text-foreground">
782
+ {shownHourly ? "Hourly" : "Daily"} {metric === "tokens" ? "processed tokens" : "cost"}
783
+ </h2>
784
+ <UsageProviderChart
785
+ providers={activeProviders}
786
+ loadingProviders={chartLoadingProviders}
787
+ days={days}
788
+ daily={merged.daily}
789
+ hours={hours}
790
+ hourly={merged.hourly}
791
+ metric={metric}
792
+ referenceTime={shownWindow.untilTime}
793
+ resolution={shownHourly ? "hour" : "day"}
794
+ timeZone={shownWindow.timeZone}
795
+ />
796
+ </div>
797
+ </section>
798
+
799
+ <section className="flex flex-col gap-2">
800
+ <h2 className="text-sm font-medium text-foreground">Totals</h2>
801
+ <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">
802
+ <Metric
803
+ loading={loadingPartial}
804
+ label="Processed tokens"
805
+ value={formatTokens(merged.totalTokens)}
806
+ />
807
+ <Metric
808
+ loading={loadingPartial}
809
+ label="Cached input"
810
+ value={formatTokens(merged.cachedInputTokens)}
811
+ />
812
+ <Metric
813
+ loading={loadingPartial}
814
+ label="Uncached input"
815
+ value={formatTokens(merged.uncachedInputTokens)}
816
+ />
817
+ <Metric
818
+ loading={loadingPartial}
819
+ label="Output"
820
+ value={formatTokens(merged.outputTokens)}
821
+ />
822
+ <Metric
823
+ loading={loadingPartial}
824
+ label="Cache savings"
825
+ value={formatUsd(merged.costQuality.cacheSavingsUsd)}
826
+ />
827
+ </div>
828
+ </section>
829
+
830
+ {merged.totalTokens > 0 ? (
831
+ <section
832
+ className={cn("grid gap-x-12 gap-y-8 lg:grid-cols-2", figureClass(loadingPartial))}
833
+ >
834
+ {metric === "tokens" ? (
835
+ <UsageShareBar
836
+ label="Tokens by type"
837
+ segments={tokenTypeSegments(merged)}
838
+ format={formatTokens}
839
+ />
840
+ ) : (
841
+ <>
842
+ <UsageShareBar
843
+ label="Cost by type"
844
+ segments={costTypeSegments(merged.categoryCost)}
845
+ format={formatUsd}
846
+ />
847
+ {merged.speedCost.fast + merged.speedCost.ultrafast > 0 ? (
848
+ <UsageShareBar
849
+ label="Cost by speed"
850
+ segments={speedCostSegments(merged.speedCost)}
851
+ format={formatUsd}
852
+ aside={<SpeedPremium premiumUsd={merged.speedCost.premium} />}
853
+ />
854
+ ) : null}
855
+ </>
856
+ )}
857
+ </section>
858
+ ) : null}
859
+
860
+ <section className="flex flex-col gap-3">
861
+ <div className="flex items-center justify-between gap-3">
862
+ <h2 className="text-sm font-medium text-foreground">Breakdown</h2>
863
+ <ToggleGroup
864
+ aria-label="Usage breakdown"
865
+ variant="segmented"
866
+ value={[breakdown]}
867
+ onValueChange={(next) => {
868
+ const value = next[0];
869
+ if (value === "model" || value === "time") setBreakdown(value);
870
+ }}
871
+ >
872
+ {(
873
+ [
874
+ { value: "model", label: "Model" },
875
+ { value: "time", label: shownHourly ? "Hour" : "Day" },
876
+ ] as const
877
+ ).map((option) => (
878
+ <Toggle key={option.value} value={option.value}>
879
+ {option.label}
880
+ </Toggle>
881
+ ))}
882
+ </ToggleGroup>
883
+ </div>
884
+
885
+ {breakdown === "model" ? (
886
+ <table className="w-full text-sm">
887
+ <thead>
888
+ <tr className="border-b border-border text-right text-xs text-muted-foreground">
889
+ <th className="py-2 pr-3 text-left font-normal">#</th>
890
+ <th className="w-full py-2 text-left font-normal">Model</th>
891
+ <th className="py-2 pl-6 font-normal">Cost</th>
892
+ <th className="hidden py-2 pl-6 font-normal sm:table-cell">Share</th>
893
+ <th className="py-2 pl-6 font-normal">Tokens</th>
894
+ </tr>
895
+ </thead>
896
+ <tbody>
897
+ {breakdownModels.length === 0 ? (
898
+ <tr>
899
+ <td colSpan={5} className="py-6 text-center text-muted-foreground">
900
+ No activity in this window.
901
+ </td>
902
+ </tr>
903
+ ) : (
904
+ breakdownModels.map((model, index) => {
905
+ const key = `${model.provider}:${model.model}`;
906
+ const value = metric === "tokens" ? model.totalTokens : model.costUsd;
907
+ const share = modelShare(model, metric === "tokens" ? "tokens" : "cost");
908
+ const rowFigures = figureClass(loadingProviders.has(model.provider));
909
+ return (
910
+ <tr
911
+ key={key}
912
+ className="relative border-b border-border/50 text-right whitespace-nowrap text-muted-foreground tabular-nums transition-colors hover:bg-muted/50 has-focus-visible:bg-muted/50"
913
+ >
914
+ <td className="py-2.5 pr-3 text-left text-xs">{index + 1}</td>
915
+ <td className="py-2.5 text-left whitespace-normal">
916
+ <button
917
+ type="button"
918
+ onClick={() => onSelectModel(key)}
919
+ className="flex items-center gap-2 text-left text-foreground outline-none after:absolute after:inset-0"
920
+ >
921
+ <ProviderMark provider={model.provider} className="size-3.5" />
922
+ {model.model}
923
+ </button>
924
+ <div aria-hidden className={cn("mt-1.5 h-0.5 max-w-48", rowFigures)}>
925
+ <div
926
+ className="h-full rounded-full"
927
+ style={{
928
+ width:
929
+ value > 0 && breakdownPeak > 0
930
+ ? `max(0.5rem, ${(value / breakdownPeak) * 100}%)`
931
+ : 0,
932
+ backgroundColor: PROVIDER_PRESENTATION[model.provider].color,
933
+ }}
934
+ />
935
+ </div>
936
+ </td>
937
+ <td className={cn("py-2.5 pl-6 text-foreground", rowFigures)}>
938
+ {isModelCostUnknown(model) ? (
939
+ <span className="text-muted-foreground">Unpriced</span>
940
+ ) : (
941
+ formatUsd(model.costUsd)
942
+ )}
943
+ </td>
944
+ <td className={cn("hidden py-2.5 pl-6 sm:table-cell", rowFigures)}>
945
+ {share === null ? "" : formatPercent(share)}
946
+ </td>
947
+ <td className={cn("py-2.5 pl-6", rowFigures)}>
948
+ {formatTokens(model.totalTokens)}
949
+ </td>
950
+ </tr>
951
+ );
952
+ })
953
+ )}
954
+ </tbody>
955
+ </table>
956
+ ) : (
957
+ <table className="w-full table-fixed text-sm">
958
+ <colgroup>
959
+ <col className="w-2/5" />
960
+ {activeProviders.map((provider) => (
961
+ <col key={provider} style={{ width: timeValueColumnWidth }} />
962
+ ))}
963
+ <col style={{ width: timeValueColumnWidth }} />
964
+ <col style={{ width: timeValueColumnWidth }} />
965
+ </colgroup>
966
+ <thead>
967
+ <tr className="border-b border-border text-left text-xs text-muted-foreground">
968
+ <th className="py-2 font-normal">{shownHourly ? "Hour" : "Day"}</th>
969
+ {activeProviders.map((provider) => (
970
+ <th key={provider} className="py-2 text-right font-normal">
971
+ {PROVIDER_PRESENTATION[provider].label}
972
+ </th>
973
+ ))}
974
+ <th className="py-2 text-right font-normal">Total</th>
975
+ <th className="py-2 text-right font-normal">Tokens</th>
976
+ </tr>
977
+ </thead>
978
+ <tbody>
979
+ {breakdownPeriods.length === 0 ? (
980
+ <tr>
981
+ <td
982
+ colSpan={activeProviders.length + 3}
983
+ className="py-6 text-center text-muted-foreground"
984
+ >
985
+ No activity in this window.
986
+ </td>
987
+ </tr>
988
+ ) : (
989
+ breakdownPeriods.map((period) => (
990
+ <tr
991
+ key={"hourStart" in period ? period.hourStart : period.day}
992
+ className="border-b border-border/50 transition-colors hover:bg-muted/50"
993
+ >
994
+ <td className="py-2 text-foreground">
995
+ {"hourStart" in period
996
+ ? formatHourShort(period.hourStart, shownWindow.timeZone)
997
+ : formatDayShort(period.day)}
998
+ </td>
999
+ {activeProviders.map((provider) => (
1000
+ <td
1001
+ key={provider}
1002
+ className={cn(
1003
+ "py-2 text-right text-muted-foreground tabular-nums",
1004
+ figureClass(loadingProviders.has(provider)),
1005
+ )}
1006
+ >
1007
+ {formatUsd(period.byProvider.get(provider)?.costUsd ?? 0)}
1008
+ </td>
1009
+ ))}
1010
+ <td
1011
+ className={cn(
1012
+ "py-2 text-right text-foreground tabular-nums",
1013
+ figureClass(loadingPartial),
1014
+ )}
1015
+ >
1016
+ {formatUsd(period.costUsd)}
1017
+ </td>
1018
+ <td
1019
+ className={cn(
1020
+ "py-2 text-right text-muted-foreground tabular-nums",
1021
+ figureClass(loadingPartial),
1022
+ )}
1023
+ >
1024
+ {formatTokens(period.totalTokens)}
1025
+ </td>
1026
+ </tr>
1027
+ ))
1028
+ )}
1029
+ </tbody>
1030
+ </table>
1031
+ )}
1032
+ </section>
1033
+ </div>
1034
+ );
1035
+}
1036
+
1037
const CURSOR_KEYCHAIN_COPY = "Requires access to your Cursor login in macOS Keychain.";
1038
1039
function CursorEnableButton({