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