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 // Identity-based render sync needs a derivation retained by inputs across renders.
169 const [derived, setDerived] = useState(() =>
170 deriveSelection(environments, selectedEnvironmentIds, hiddenProviders),
171 );
172 let current = derived;
173 if (
174 derived.environments !== environments ||
175 derived.selectedEnvironmentIds !== selectedEnvironmentIds ||
176 derived.hiddenProviders !== hiddenProviders
177 ) {
178 current = deriveSelection(environments, selectedEnvironmentIds, hiddenProviders);
179 setDerived(current);
180 }
181 const { selectedEnvironments, merged } = current;
182
183 const refresh = (nextInput?: UsageSummaryInput) =>
184 refreshUsage({
185 registry: appAtomRegistry,
186 server: serverEnvironment,
187 presentations: environmentPresentations,
188 environmentIds: selectedEnvironments
189 .filter(
190 (environment) =>
191 environment.canReadDiagnostics &&
192 readEnvironmentScope(environment.environmentId, AuthDiagnosticsReadScope),
193 )
194 .map(({ environmentId }) => environmentId),
195 input: nextInput ?? (JSON.parse(windowKey) as UsageSummaryInput),
196 });
197
198 const answeredCount = selectedEnvironments.filter(
199 (environment) => environment.summary !== null,
200 ).length;
201 const stillReporting = selectedEnvironments.filter(
202 (environment) => environment.summary === null && environment.error === null,
203 ).length;
204 const isPending = answeredCount === 0 && stillReporting > 0;
205
206 const [lastAnswered, setLastAnswered] = useState<
207 | (NonNullable<UsageView["shown"]> & {
208 readonly selection: typeof selectedEnvironmentIds;
209 readonly hidden: typeof hiddenProviders;
210 })
211 | null
212 >(null);
213 if (
214 answeredCount > 0 &&
215 (lastAnswered?.merged !== merged ||
216 lastAnswered.window !== input ||
217 lastAnswered.selection !== selectedEnvironmentIds ||
218 lastAnswered.hidden !== hiddenProviders)
219 ) {
220 setLastAnswered({
221 window: input,
222 merged,
223 selection: selectedEnvironmentIds,
224 hidden: hiddenProviders,
225 });
226 }
227 const kept =
228 lastAnswered?.selection === selectedEnvironmentIds && lastAnswered.hidden === hiddenProviders
229 ? lastAnswered
230 : null;
231 const shown =
232 answeredCount > 0
233 ? { window: input, merged }
234 : (kept ?? (isPending ? null : { window: input, merged }));
235
236 return {
237 merged,
238 environments,
239 selectedEnvironments,
240 isPending,
241 shown,
242 isPartial: answeredCount > 0 && stillReporting > 0,
243 refresh,
244 };
245}