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