Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import {
3 AuthDiagnosticsReadScope,
4 USAGE_CONTRACT_VERSION,
5 type EnvironmentId,
6 type UsageBucket,
7 type UsageSummary,
8 type UsageProviderKind,
9 type UsageSummaryInput,
10} from "@t3tools/contracts";
11import { needsCursorKeychainAccess, refreshUsage } from "@t3tools/client-runtime/state/usage";
12import { resolveUsageAccess } from "@t3tools/client-runtime/state/usage-access";
13import * as Option from "effect/Option";
14import { AsyncResult, Atom } from "effect/reactivity";
15import { useState } from "react";
16
17import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";
18import { appAtomRegistry } from "../rpc/atomRegistry";
19import { environmentPresentations } from "./presentation";
20import { serverEnvironment } from "./server";
21import { environmentSession, readEnvironmentScope } from "./session";
22
23export interface EnvironmentUsageStatus {
24 readonly environmentId: EnvironmentId;
25 readonly label: string;
26 readonly isPending: boolean;
27 readonly canReadDiagnostics: boolean;
28 readonly isConnected: boolean;
29 readonly error: string | null;
30 readonly summary: UsageSummary | null;
31 readonly needsCursorKeychainAccess: boolean;
32}
33
34const usageByWindowAtom = Atom.family((windowKey: string) =>
35 Atom.make((get): readonly EnvironmentUsageStatus[] => {
36 const input = JSON.parse(windowKey) as UsageSummaryInput;
37 const presentations = get(environmentPresentations.presentationsAtom);
38
39 const statuses: EnvironmentUsageStatus[] = [];
40 for (const [environmentId, presentation] of presentations) {
41 const isConnected = presentation.connection.phase === "connected";
42 const sessionResult = get(environmentSession.sessionStateAtom(environmentId));
43 const access = resolveUsageAccess({
44 connectionPhase: presentation.connection.phase,
45 session: Option.getOrNull(AsyncResult.value(sessionResult)),
46 hasSessionError: sessionResult._tag === "Failure",
47 });
48 if (!access.canReadDiagnostics) {
49 statuses.push({
50 environmentId,
51 label: presentation.entry.target.label,
52 isConnected,
53 ...access,
54 summary: null,
55 needsCursorKeychainAccess: false,
56 });
57 continue;
58 }
59 const result = get(serverEnvironment.usageSummary({ environmentId, input }));
60 const summary = Option.getOrNull(AsyncResult.value(result));
61 statuses.push({
62 environmentId,
63 label: presentation.entry.target.label,
64 isPending: result.waiting,
65 canReadDiagnostics: true,
66 isConnected,
67 error: result._tag === "Failure" ? "This environment could not report usage." : null,
68 summary,
69 needsCursorKeychainAccess: needsCursorKeychainAccess(
70 summary,
71 get(serverEnvironment.providersValueAtom(environmentId)),
72 ),
73 });
74 }
75 return statuses;
76 }).pipe(Atom.withLabel(`web-usage:window:${windowKey}`)),
77);
78
79export interface UsageView {
80 readonly merged: MergedUsage;
81 readonly environments: readonly EnvironmentUsageStatus[];
82 readonly selectedEnvironments: readonly EnvironmentUsageStatus[];
83 readonly isPending: boolean;
84 readonly shown: { readonly window: UsageSummaryInput; readonly merged: MergedUsage } | null;
85 readonly isPartial: boolean;
86 readonly refresh: (input?: UsageSummaryInput) => Promise<void>;
87}
88
89export function mergeAnsweredUsage(
90 environments: readonly EnvironmentUsageStatus[],
91 keepBucket?: (bucket: UsageBucket) => boolean,
92): MergedUsage {
93 const answered: EnvironmentUsage[] = environments.flatMap(({ environmentId, label, summary }) =>
94 summary === null
95 ? []
96 : [
97 {
98 environmentId,
99 label,
100 summary:
101 keepBucket === undefined
102 ? summary
103 : { ...summary, buckets: summary.buckets.filter(keepBucket) },
104 },
105 ],
106 );
107 return mergeUsage(answered, USAGE_CONTRACT_VERSION);
108}
109
110const NO_HIDDEN_PROVIDERS: ReadonlySet<UsageProviderKind> = new Set();
111
112function withoutProviders(
113 environments: readonly EnvironmentUsageStatus[],
114 hiddenProviders: ReadonlySet<UsageProviderKind>,
115): readonly EnvironmentUsageStatus[] {
116 if (hiddenProviders.size === 0) return environments;
117 return environments.map((environment) =>
118 environment.summary === null
119 ? environment
120 : {
121 ...environment,
122 summary: {
123 ...environment.summary,
124 buckets: environment.summary.buckets.filter(
125 (bucket) => !hiddenProviders.has(bucket.provider),
126 ),
127 sources: environment.summary.sources.filter(
128 (source) => !hiddenProviders.has(source.fingerprint.provider),
129 ),
130 },
131 },
132 );
133}
134
135function deriveSelection(
136 environments: readonly EnvironmentUsageStatus[],
137 selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null,
138 hiddenProviders: ReadonlySet<UsageProviderKind>,
139) {
140 const selectedEnvironments =
141 selectedEnvironmentIds === null
142 ? environments
143 : environments.filter((environment) => selectedEnvironmentIds.has(environment.environmentId));
144 return {
145 environments,
146 selectedEnvironmentIds,
147 hiddenProviders,
148 selectedEnvironments,
149 merged: mergeAnsweredUsage(withoutProviders(selectedEnvironments, hiddenProviders)),
150 };
151}
152
153export function useUsage(
154 input: UsageSummaryInput,
155 selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null = null,
156 hiddenProviders: ReadonlySet<UsageProviderKind> = NO_HIDDEN_PROVIDERS,
157): UsageView {
158 const windowKey = JSON.stringify({
159 sinceDay: input.sinceDay,
160 untilDay: input.untilDay,
161 timeZone: input.timeZone,
162 resolution: input.resolution,
163 sinceTime: input.sinceTime,
164 untilTime: input.untilTime,
165 });
166 const atom = usageByWindowAtom(windowKey);
167 const environments = useAtomValue(atom);
168 // The render-time sync below compares merged by identity, so the derivation is
169 // held in state keyed on its inputs rather than rebuilt every render.
170 const [derived, setDerived] = useState(() =>
171 deriveSelection(environments, selectedEnvironmentIds, hiddenProviders),
172 );
173 let current = derived;
174 if (
175 derived.environments !== environments ||
176 derived.selectedEnvironmentIds !== selectedEnvironmentIds ||
177 derived.hiddenProviders !== hiddenProviders
178 ) {
179 current = deriveSelection(environments, selectedEnvironmentIds, hiddenProviders);
180 setDerived(current);
181 }
182 const { selectedEnvironments, merged } = current;
183
184 const refresh = (nextInput?: UsageSummaryInput) =>
185 refreshUsage({
186 registry: appAtomRegistry,
187 server: serverEnvironment,
188 presentations: environmentPresentations,
189 environmentIds: selectedEnvironments
190 .filter(
191 (environment) =>
192 environment.canReadDiagnostics &&
193 readEnvironmentScope(environment.environmentId, AuthDiagnosticsReadScope),
194 )
195 .map(({ environmentId }) => environmentId),
196 input: nextInput ?? (JSON.parse(windowKey) as UsageSummaryInput),
197 });
198
199 const answeredCount = selectedEnvironments.filter(
200 (environment) => environment.summary !== null,
201 ).length;
202 const stillReporting = selectedEnvironments.filter(
203 (environment) => environment.summary === null && environment.error === null,
204 ).length;
205 const isPending = answeredCount === 0 && stillReporting > 0;
206
207 const [lastAnswered, setLastAnswered] = useState<
208 | (NonNullable<UsageView["shown"]> & {
209 readonly selection: typeof selectedEnvironmentIds;
210 readonly hidden: typeof hiddenProviders;
211 })
212 | null
213 >(null);
214 if (
215 answeredCount > 0 &&
216 (lastAnswered?.merged !== merged ||
217 lastAnswered.window !== input ||
218 lastAnswered.selection !== selectedEnvironmentIds ||
219 lastAnswered.hidden !== hiddenProviders)
220 ) {
221 setLastAnswered({
222 window: input,
223 merged,
224 selection: selectedEnvironmentIds,
225 hidden: hiddenProviders,
226 });
227 }
228 const kept =
229 lastAnswered?.selection === selectedEnvironmentIds && lastAnswered.hidden === hiddenProviders
230 ? lastAnswered
231 : null;
232 const shown =
233 answeredCount > 0
234 ? { window: input, merged }
235 : (kept ?? (isPending ? null : { window: input, merged }));
236
237 return {
238 merged,
239 environments,
240 selectedEnvironments,
241 isPending,
242 shown,
243 isPartial: answeredCount > 0 && stillReporting > 0,
244 refresh,
245 };
246}