Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usage.ts

174 lines5.8 KB

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