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