Open History to see the last commit
1/**
2 * Multi-environment usage state.
3 *
4 * Every connected environment answers the same typed query; the client merges
5 * the results. Raw transcripts never leave the machine that produced them.
6 *
7 * Mirror of `apps/web/src/state/usage.ts` over mobile's atom wiring; the merge
8 * rules themselves live in `@t3tools/shared/usageMerge`.
9 *
10 * @module state/usage
11 */
12import { useAtomValue } from "@effect/atom-react";
13import {
14 USAGE_CONTRACT_VERSION,
15 type EnvironmentId,
16 type UsageSummary,
17 type UsageSummaryInput,
18} from "@t3tools/contracts";
19import { needsCursorKeychainAccess, refreshUsage } from "@t3tools/client-runtime/state/usage";
20import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";
21import * as Option from "effect/Option";
22import { AsyncResult, Atom } from "effect/unstable/reactivity";
23import { useCallback, useMemo } from "react";
24
25import { appAtomRegistry } from "./atom-registry";
26import { environmentPresentations } from "./presentation";
27import { serverEnvironment } from "./server";
28
29export interface EnvironmentUsageStatus {
30 readonly environmentId: EnvironmentId;
31 readonly label: string;
32 readonly isPending: boolean;
33 readonly isConnected: boolean;
34 readonly error: string | null;
35 readonly summary: UsageSummary | null;
36 readonly needsCursorKeychainAccess: boolean;
37}
38
39/**
40 * Reads every environment's summary for one window.
41 *
42 * Keyed by the serialised window so switching ranges does not thrash the atom
43 * cache, and so each environment's query is shared with any other reader of the
44 * same window.
45 */
46const usageByWindowAtom = Atom.family((windowKey: string) =>
47 Atom.make((get): readonly EnvironmentUsageStatus[] => {
48 const input = JSON.parse(windowKey) as UsageSummaryInput;
49 const presentations = get(environmentPresentations.presentationsAtom);
50
51 const statuses: EnvironmentUsageStatus[] = [];
52 for (const [environmentId, presentation] of presentations) {
53 const result = get(serverEnvironment.usageSummary({ environmentId, input }));
54 const summary = Option.getOrNull(AsyncResult.value(result));
55 statuses.push({
56 environmentId,
57 label: presentation.entry.target.label,
58 isPending: result.waiting,
59 isConnected: presentation.connection.phase === "connected",
60 error: result._tag === "Failure" ? "This environment could not report usage." : null,
61 summary,
62 needsCursorKeychainAccess: needsCursorKeychainAccess(
63 summary,
64 get(serverEnvironment.providersValueAtom(environmentId)),
65 ),
66 });
67 }
68 return statuses;
69 }).pipe(Atom.withLabel(`mobile-usage:window:${windowKey}`)),
70);
71
72export interface UsageView {
73 readonly merged: MergedUsage;
74 readonly environments: readonly EnvironmentUsageStatus[];
75 readonly selectedEnvironments: readonly EnvironmentUsageStatus[];
76 /** True until at least one environment has answered. */
77 readonly isPending: boolean;
78 /**
79 * True while environments that have not failed are still answering. Failed
80 * environments are reported in the environment menu: totals will not
81 * improve by waiting on them, so they must not read as "still reporting".
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 environmentIds: selectedEnvironments.map(({ environmentId }) => environmentId),
127 input: nextInput ?? (JSON.parse(windowKey) as UsageSummaryInput),
128 }),
129 [selectedEnvironments, windowKey],
130 );
131
132 const merged = useMemo(() => {
133 const answered: EnvironmentUsage[] = selectedEnvironments.flatMap((environment) =>
134 environment.summary === null
135 ? []
136 : [
137 {
138 environmentId: environment.environmentId,
139 label: environment.label,
140 summary: environment.summary,
141 },
142 ],
143 );
144 return mergeUsage(answered, USAGE_CONTRACT_VERSION);
145 }, [selectedEnvironments]);
146
147 const answeredCount = selectedEnvironments.filter(
148 (environment) => environment.summary !== null,
149 ).length;
150 const stillReporting = selectedEnvironments.filter(
151 (environment) => environment.summary === null && environment.error === null,
152 ).length;
153
154 return {
155 merged,
156 environments,
157 selectedEnvironments,
158 isPending: answeredCount === 0 && stillReporting > 0,
159 isPartial: answeredCount > 0 && stillReporting > 0,
160 refresh,
161 };
162}