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 UsageSummary,
7 type UsageSummaryInput,
8} from "@t3tools/contracts";
9import { needsCursorKeychainAccess, refreshUsage } from "@t3tools/client-runtime/state/usage";
10import { resolveUsageAccess } from "@t3tools/client-runtime/state/usage-access";
11import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";
12import * as Option from "effect/Option";
13import { AsyncResult, Atom } from "effect/reactivity";
14import { useCallback, useMemo } from "react";
15
16import { appAtomRegistry } from "./atom-registry";
17import { environmentPresentations } from "./presentation";
18import { serverEnvironment } from "./server";
19import { environmentSession, readEnvironmentScope } from "./session";
20
21export interface EnvironmentUsageStatus {
22 readonly environmentId: EnvironmentId;
23 readonly label: string;
24 readonly isPending: boolean;
25 readonly isConnected: boolean;
26 readonly canReadDiagnostics: boolean;
27 readonly error: string | null;
28 readonly summary: UsageSummary | null;
29 readonly needsCursorKeychainAccess: boolean;
30}
31
32/**
33 * Keyed by the serialised window so switching ranges does not thrash the atom cache, and so
34 * each environment's query is shared with any other reader of the same window.
35 */
36const usageByWindowAtom = Atom.family((windowKey: string) =>
37 Atom.make((get): readonly EnvironmentUsageStatus[] => {
38 const input = JSON.parse(windowKey) as UsageSummaryInput;
39 const presentations = get(environmentPresentations.presentationsAtom);
40
41 const statuses: EnvironmentUsageStatus[] = [];
42 for (const [environmentId, presentation] of presentations) {
43 const sessionResult = get(environmentSession.sessionStateAtom(environmentId));
44 const access = resolveUsageAccess({
45 connectionPhase: presentation.connection.phase,
46 session: Option.getOrNull(AsyncResult.value(sessionResult)),
47 hasSessionError: sessionResult._tag === "Failure",
48 });
49 if (!access.canReadDiagnostics) {
50 statuses.push({
51 environmentId,
52 label: presentation.entry.target.label,
53 isConnected: presentation.connection.phase === "connected",
54 ...access,
55 summary: null,
56 needsCursorKeychainAccess: false,
57 });
58 continue;
59 }
60 const result = get(serverEnvironment.usageSummary({ environmentId, input }));
61 const summary = Option.getOrNull(AsyncResult.value(result));
62 statuses.push({
63 environmentId,
64 label: presentation.entry.target.label,
65 isPending: result.waiting,
66 isConnected: presentation.connection.phase === "connected",
67 canReadDiagnostics: true,
68 error: result._tag === "Failure" ? "This environment could not report usage." : null,
69 summary,
70 needsCursorKeychainAccess: needsCursorKeychainAccess(
71 summary,
72 get(serverEnvironment.providersValueAtom(environmentId)),
73 ),
74 });
75 }
76 return statuses;
77 }).pipe(Atom.withLabel(`mobile-usage:window:${windowKey}`)),
78);
79
80export interface UsageView {
81 readonly merged: MergedUsage;
82 readonly environments: readonly EnvironmentUsageStatus[];
83 readonly selectedEnvironments: readonly EnvironmentUsageStatus[];
84
85 readonly isPending: boolean;
86
87 readonly isPartial: boolean;
88 readonly refresh: (input?: UsageSummaryInput) => Promise<void>;
89}
90
91export function useUsage(
92 input: UsageSummaryInput,
93 selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null = null,
94): UsageView {
95 const windowKey = useMemo(
96 () =>
97 JSON.stringify({
98 sinceDay: input.sinceDay,
99 untilDay: input.untilDay,
100 timeZone: input.timeZone,
101 resolution: input.resolution,
102 sinceTime: input.sinceTime,
103 untilTime: input.untilTime,
104 }),
105 [
106 input.sinceDay,
107 input.untilDay,
108 input.timeZone,
109 input.resolution,
110 input.sinceTime,
111 input.untilTime,
112 ],
113 );
114 const atom = usageByWindowAtom(windowKey);
115 const environments = useAtomValue(atom);
116 const selectedEnvironments = useMemo(
117 () =>
118 selectedEnvironmentIds === null
119 ? environments
120 : environments.filter(({ environmentId }) => selectedEnvironmentIds.has(environmentId)),
121 [environments, selectedEnvironmentIds],
122 );
123
124 const refresh = useCallback(
125 (nextInput?: UsageSummaryInput) =>
126 refreshUsage({
127 registry: appAtomRegistry,
128 server: serverEnvironment,
129 presentations: environmentPresentations,
130
131 environmentIds: selectedEnvironments
132 .filter(
133 (environment) =>
134 environment.canReadDiagnostics &&
135 readEnvironmentScope(environment.environmentId, AuthDiagnosticsReadScope),
136 )
137 .map(({ environmentId }) => environmentId),
138 input: nextInput ?? (JSON.parse(windowKey) as UsageSummaryInput),
139 }),
140 [selectedEnvironments, windowKey],
141 );
142
143 const merged = useMemo(() => {
144 const answered: EnvironmentUsage[] = selectedEnvironments.flatMap((environment) =>
145 environment.summary === null
146 ? []
147 : [
148 {
149 environmentId: environment.environmentId,
150 label: environment.label,
151 summary: environment.summary,
152 },
153 ],
154 );
155 return mergeUsage(answered, USAGE_CONTRACT_VERSION);
156 }, [selectedEnvironments]);
157
158 const answeredCount = selectedEnvironments.filter(
159 (environment) => environment.summary !== null,
160 ).length;
161 const stillReporting = selectedEnvironments.filter(
162 (environment) => environment.summary === null && environment.error === null,
163 ).length;
164
165 return {
166 merged,
167 environments,
168 selectedEnvironments,
169 isPending: answeredCount === 0 && stillReporting > 0,
170 isPartial: answeredCount > 0 && stillReporting > 0,
171 refresh,
172 };
173}