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 * @module state/usage
8 */
9import { useAtomValue } from "@effect/atom-react";
10import {
11 AuthDiagnosticsReadScope,
12 USAGE_CONTRACT_VERSION,
13 type EnvironmentId,
14 type UsageBucket,
15 type UsageSummary,
16 type UsageSummaryInput,
17} from "@t3tools/contracts";
18import { needsCursorKeychainAccess, refreshUsage } from "@t3tools/client-runtime/state/usage";
19import { resolveUsageAccess } from "@t3tools/client-runtime/state/usage-access";
20import * as Option from "effect/Option";
21import { AsyncResult, Atom } from "effect/reactivity";
22import { useCallback, useMemo } from "react";
23
24import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";
25import { appAtomRegistry } from "../rpc/atomRegistry";
26import { environmentPresentations } from "./presentation";
27import { serverEnvironment } from "./server";
28import { environmentSession, readEnvironmentScope } from "./session";
29
30export interface EnvironmentUsageStatus {
31 readonly environmentId: EnvironmentId;
32 readonly label: string;
33 readonly isPending: boolean;
34 readonly canReadDiagnostics: boolean;
35 readonly error: string | null;
36 readonly summary: UsageSummary | null;
37 readonly needsCursorKeychainAccess: boolean;
38}
39
40/**
41 * Reads every environment's summary for one window.
42 *
43 * Keyed by the serialised window so switching ranges does not thrash the atom
44 * cache, and so each environment's query is shared with any other reader of the
45 * same window.
46 */
47const usageByWindowAtom = Atom.family((windowKey: string) =>
48 Atom.make((get): readonly EnvironmentUsageStatus[] => {
49 const input = JSON.parse(windowKey) as UsageSummaryInput;
50 const presentations = get(environmentPresentations.presentationsAtom);
51
52 const statuses: EnvironmentUsageStatus[] = [];
53 for (const [environmentId, presentation] of presentations) {
54 const sessionResult = get(environmentSession.sessionStateAtom(environmentId));
55 const access = resolveUsageAccess({
56 connectionPhase: presentation.connection.phase,
57 session: Option.getOrNull(AsyncResult.value(sessionResult)),
58 hasSessionError: sessionResult._tag === "Failure",
59 });
60 if (!access.canReadDiagnostics) {
61 statuses.push({
62 environmentId,
63 label: presentation.entry.target.label,
64 ...access,
65 summary: null,
66 needsCursorKeychainAccess: false,
67 });
68 continue;
69 }
70 const result = get(serverEnvironment.usageSummary({ environmentId, input }));
71 const summary = Option.getOrNull(AsyncResult.value(result));
72 statuses.push({
73 environmentId,
74 label: presentation.entry.target.label,
75 isPending: result.waiting,
76 canReadDiagnostics: true,
77 error: result._tag === "Failure" ? "This environment could not report usage." : null,
78 summary,
79 needsCursorKeychainAccess: needsCursorKeychainAccess(
80 summary,
81 get(serverEnvironment.providersValueAtom(environmentId)),
82 ),
83 });
84 }
85 return statuses;
86 }).pipe(Atom.withLabel(`web-usage:window:${windowKey}`)),
87);
88
89export interface UsageView {
90 readonly merged: MergedUsage;
91 readonly environments: readonly EnvironmentUsageStatus[];
92 readonly selectedEnvironments: readonly EnvironmentUsageStatus[];
93 /** True until at least one selected environment has answered. */
94 readonly isPending: boolean;
95 /**
96 * True while environments that have not failed are still answering. Failed
97 * environments are reported through their own error rows: totals will not
98 * improve by waiting on them, so they must not read as "still reporting".
99 */
100 readonly isPartial: boolean;
101 readonly refresh: (input?: UsageSummaryInput) => Promise<void>;
102}
103
104/**
105 * Merges every environment that has answered. `keepBucket` narrows the merge,
106 * for example to one model; source ownership still applies, so the result
107 * matches that slice of the full merge. Session counts are per directory and
108 * are not narrowed.
109 */
110export function mergeAnsweredUsage(
111 environments: readonly EnvironmentUsageStatus[],
112 keepBucket?: (bucket: UsageBucket) => boolean,
113): MergedUsage {
114 const answered: EnvironmentUsage[] = environments.flatMap(({ environmentId, label, summary }) =>
115 summary === null
116 ? []
117 : [
118 {
119 environmentId,
120 label,
121 summary:
122 keepBucket === undefined
123 ? summary
124 : { ...summary, buckets: summary.buckets.filter(keepBucket) },
125 },
126 ],
127 );
128 return mergeUsage(answered, USAGE_CONTRACT_VERSION);
129}
130
131export function useUsage(
132 input: UsageSummaryInput,
133 selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null = null,
134): UsageView {
135 const windowKey = useMemo(
136 () =>
137 JSON.stringify({
138 sinceDay: input.sinceDay,
139 untilDay: input.untilDay,
140 timeZone: input.timeZone,
141 resolution: input.resolution,
142 sinceTime: input.sinceTime,
143 untilTime: input.untilTime,
144 }),
145 [
146 input.sinceDay,
147 input.untilDay,
148 input.timeZone,
149 input.resolution,
150 input.sinceTime,
151 input.untilTime,
152 ],
153 );
154 const atom = usageByWindowAtom(windowKey);
155 const environments = useAtomValue(atom);
156 const selectedEnvironments = useMemo(
157 () =>
158 selectedEnvironmentIds === null
159 ? environments
160 : environments.filter((environment) =>
161 selectedEnvironmentIds.has(environment.environmentId),
162 ),
163 [environments, selectedEnvironmentIds],
164 );
165
166 const refresh = useCallback(
167 (nextInput?: UsageSummaryInput) =>
168 refreshUsage({
169 registry: appAtomRegistry,
170 server: serverEnvironment,
171 presentations: environmentPresentations,
172 // Only environments this connection may read; the others report a
173 // permission error instead of a stale or failed rescan.
174 environmentIds: selectedEnvironments
175 .filter(
176 (environment) =>
177 environment.canReadDiagnostics &&
178 readEnvironmentScope(environment.environmentId, AuthDiagnosticsReadScope),
179 )
180 .map(({ environmentId }) => environmentId),
181 input: nextInput ?? (JSON.parse(windowKey) as UsageSummaryInput),
182 }),
183 [selectedEnvironments, windowKey],
184 );
185
186 const merged = useMemo(() => mergeAnsweredUsage(selectedEnvironments), [selectedEnvironments]);
187
188 const answeredCount = selectedEnvironments.filter(
189 (environment) => environment.summary !== null,
190 ).length;
191 const stillReporting = selectedEnvironments.filter(
192 (environment) => environment.summary === null && environment.error === null,
193 ).length;
194
195 return {
196 merged,
197 environments,
198 selectedEnvironments,
199 isPending: answeredCount === 0 && stillReporting > 0,
200 isPartial: answeredCount > 0 && stillReporting > 0,
201 refresh,
202 };
203}