Open History to see the last commit
1import {
2 AuthProvidersManageScope,
3 AuthDiagnosticsReadScope,
4 USAGE_CONTRACT_VERSION,
5 type EnvironmentId,
6 type UsageAccessRequest,
7 type UsageSummary,
8 type UsageSummaryInput,
9} from "@t3tools/contracts";
10import { refreshUsage, usageSummaryInput } from "@t3tools/client-runtime/state/usage";
11import {
12 resolveUsageAccess,
13 unansweredUsageAccessRequests,
14} from "@t3tools/client-runtime/state/usage-access";
15import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";
16import { AsyncResult, Atom } from "effect/reactivity";
17import { msg, useMessages } from "gt-react-native";
18import { use, useCallback, useMemo } from "react";
19
20import { useAtomValueWhileVisible } from "../features/home/home-route-visibility";
21import { keepMarked } from "../i18n/messages";
22import { NativeWorkspaceTabActivityContext } from "../native/v5-workspace-context";
23import { appAtomRegistry } from "./atom-registry";
24import { environmentPresentations } from "./presentation";
25import { serverEnvironment } from "./server";
26import { environmentSession, readEnvironmentScope, sessionHasScope } from "./session";
27
28export interface EnvironmentUsageStatus {
29 readonly environmentId: EnvironmentId;
30 readonly label: string;
31 readonly isPending: boolean;
32 readonly isConnected: 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 error: string | null;
37 readonly summary: UsageSummary | null;
38}
39
40const usageByWindowAtom = Atom.family((windowKey: string) =>
41 Atom.make((get): readonly EnvironmentUsageStatus[] => {
42 const input = JSON.parse(windowKey) as UsageSummaryInput;
43 const presentations = get(environmentPresentations.presentationsAtom);
44
45 const statuses: EnvironmentUsageStatus[] = [];
46 for (const [environmentId, presentation] of presentations) {
47 const sessionResult = get(environmentSession.sessionStateAtom(environmentId));
48 const access = resolveUsageAccess(
49 {
50 connectionPhase: presentation.connection.phase,
51 session: AsyncResult.getOrElse(sessionResult, () => null),
52 hasSessionError: sessionResult._tag === "Failure",
53 },
54 keepMarked,
55 );
56 if (!access.canReadDiagnostics) {
57 statuses.push({
58 environmentId,
59 label: presentation.entry.target.label,
60 isConnected: presentation.connection.phase === "connected",
61 ...access,
62 accessRequests: [],
63 summary: null,
64 });
65 continue;
66 }
67 const result = get(
68 serverEnvironment.usageSummary({
69 environmentId,
70 input: usageSummaryInput(
71 input,
72 get(serverEnvironment.usageModelFilterAtom(environmentId)),
73 ),
74 }),
75 );
76 const summary = AsyncResult.getOrElse(result, () => null);
77 statuses.push({
78 environmentId,
79 label: presentation.entry.target.label,
80 isPending: result.waiting,
81 isConnected: presentation.connection.phase === "connected",
82 canReadDiagnostics: true,
83 accessRequests: unansweredUsageAccessRequests({
84 canAnswer: sessionHasScope(sessionResult, AuthProvidersManageScope),
85 summary,
86 config: get(serverEnvironment.configValueAtom(environmentId)),
87 }),
88 error: result._tag === "Failure" ? msg("This environment could not report usage.") : null,
89 summary,
90 });
91 }
92 return statuses;
93 }).pipe(Atom.withLabel(`mobile-usage:window:${windowKey}`)),
94);
95
96/** Every environment usage can come from, without asking any of them for usage. */
97const usageEnvironmentsAtom = Atom.make((get): readonly EnvironmentUsageStatus[] =>
98 [...get(environmentPresentations.presentationsAtom)].map(([environmentId, presentation]) => ({
99 environmentId,
100 label: presentation.entry.target.label,
101 isPending: true,
102 isConnected: presentation.connection.phase === "connected",
103 canReadDiagnostics: false,
104 accessRequests: [],
105 error: null,
106 summary: null,
107 })),
108).pipe(Atom.withLabel("mobile-usage:environments"));
109
110export interface UsageView {
111 readonly merged: MergedUsage;
112 readonly environments: readonly EnvironmentUsageStatus[];
113 readonly selectedEnvironments: readonly EnvironmentUsageStatus[];
114
115 readonly isPending: boolean;
116
117 readonly isPartial: boolean;
118 readonly refresh: (input?: UsageSummaryInput) => Promise<void>;
119}
120
121export function useUsage(
122 input: UsageSummaryInput,
123 selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null = null,
124 /** Off, it lists the environments without loading their usage. */
125 load = true,
126): UsageView {
127 const windowKey = useMemo(
128 () =>
129 JSON.stringify({
130 sinceDay: input.sinceDay,
131 untilDay: input.untilDay,
132 timeZone: input.timeZone,
133 resolution: input.resolution,
134 sinceTime: input.sinceTime,
135 untilTime: input.untilTime,
136 }),
137 [
138 input.sinceDay,
139 input.untilDay,
140 input.timeZone,
141 input.resolution,
142 input.sinceTime,
143 input.untilTime,
144 ],
145 );
146 const messages = useMessages();
147 // Reads each environment's config, which every provider check rewrites; a retained, hidden
148 // Usage tab holds its last value until shown.
149 const markedEnvironments = useAtomValueWhileVisible(
150 load ? usageByWindowAtom(windowKey) : usageEnvironmentsAtom,
151 use(NativeWorkspaceTabActivityContext)?.active ?? true,
152 );
153 const environments = useMemo(
154 () =>
155 markedEnvironments.map((environment) =>
156 environment.error === null
157 ? environment
158 : { ...environment, error: messages(environment.error) },
159 ),
160 [markedEnvironments, messages],
161 );
162 const selectedEnvironments = useMemo(
163 () =>
164 selectedEnvironmentIds === null
165 ? environments
166 : environments.filter(({ environmentId }) => selectedEnvironmentIds.has(environmentId)),
167 [environments, selectedEnvironmentIds],
168 );
169
170 const refresh = useCallback(
171 (nextInput?: UsageSummaryInput) =>
172 refreshUsage({
173 registry: appAtomRegistry,
174 server: serverEnvironment,
175 presentations: environmentPresentations,
176
177 environmentIds: selectedEnvironments
178 .filter(
179 (environment) =>
180 environment.canReadDiagnostics &&
181 readEnvironmentScope(environment.environmentId, AuthDiagnosticsReadScope),
182 )
183 .map(({ environmentId }) => environmentId),
184 input: nextInput ?? (JSON.parse(windowKey) as UsageSummaryInput),
185 }),
186 [selectedEnvironments, windowKey],
187 );
188
189 const merged = useMemo(() => {
190 const answered: EnvironmentUsage[] = selectedEnvironments.flatMap((environment) =>
191 environment.summary === null
192 ? []
193 : [
194 {
195 environmentId: environment.environmentId,
196 label: environment.label,
197 summary: environment.summary,
198 },
199 ],
200 );
201 return mergeUsage(answered, USAGE_CONTRACT_VERSION);
202 }, [selectedEnvironments]);
203
204 const answeredCount = selectedEnvironments.filter(
205 (environment) => environment.summary !== null,
206 ).length;
207 const stillReporting = selectedEnvironments.filter(
208 (environment) => environment.summary === null && environment.error === null,
209 ).length;
210
211 return {
212 merged,
213 environments,
214 selectedEnvironments,
215 isPending: answeredCount === 0 && stillReporting > 0,
216 isPartial: answeredCount > 0 && stillReporting > 0,
217 refresh,
218 };
219}