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 { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
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}
33
34/**
35 * Reads every environment's summary for one window.
36 *
37 * Keyed by the serialised window so switching ranges does not thrash the atom
38 * cache, and so each environment's query is shared with any other reader of the
39 * same window.
40 */
41const usageByWindowAtom = Atom.family((windowKey: string) =>
42 Atom.make((get): readonly EnvironmentUsageStatus[] => {
43 const input = JSON.parse(windowKey) as UsageSummaryInput;
44 const presentations = get(environmentPresentations.presentationsAtom);
45
46 const statuses: EnvironmentUsageStatus[] = [];
47 for (const [environmentId, presentation] of presentations) {
48 const result = get(serverEnvironment.usageSummary({ environmentId, input }));
49 statuses.push({
50 environmentId,
51 label: presentation.entry.target.label,
52 isPending: result.waiting,
53 error: result._tag === "Failure" ? "This environment could not report usage." : null,
54 summary: Option.getOrNull(AsyncResult.value(result)),
55 });
56 }
57 return statuses;
58 }).pipe(Atom.withLabel(`web-usage:window:${windowKey}`)),
59);
60
61export interface UsageView {
62 readonly merged: MergedUsage;
63 readonly environments: readonly EnvironmentUsageStatus[];
64 readonly selectedEnvironments: readonly EnvironmentUsageStatus[];
65 /** True until at least one selected environment has answered. */
66 readonly isPending: boolean;
67 /**
68 * True while environments that have not failed are still answering. Failed
69 * environments are reported through their own error rows: totals will not
70 * improve by waiting on them, so they must not read as "still reporting".
71 */
72 readonly isPartial: boolean;
73 readonly refresh: () => void;
74}
75
76export function useUsage(
77 input: UsageSummaryInput,
78 selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null = null,
79): UsageView {
80 const windowKey = useMemo(
81 () =>
82 JSON.stringify({
83 sinceDay: input.sinceDay,
84 untilDay: input.untilDay,
85 timeZone: input.timeZone,
86 resolution: input.resolution,
87 sinceTime: input.sinceTime,
88 untilTime: input.untilTime,
89 }),
90 [
91 input.sinceDay,
92 input.untilDay,
93 input.timeZone,
94 input.resolution,
95 input.sinceTime,
96 input.untilTime,
97 ],
98 );
99 const atom = usageByWindowAtom(windowKey);
100 const environments = useAtomValue(atom);
101 const selectedEnvironments = useMemo(
102 () =>
103 selectedEnvironmentIds === null
104 ? environments
105 : environments.filter((environment) =>
106 selectedEnvironmentIds.has(environment.environmentId),
107 ),
108 [environments, selectedEnvironmentIds],
109 );
110
111 // Refreshing only the derived atom would re-read the per-environment SWR
112 // queries within their stale window and change nothing. Refresh each
113 // environment's query so the button always rescans.
114 //
115 // Each environment refetches model pricing first, so a model released since
116 // its last daily fetch gets priced by the rescan. The rescan runs whether or
117 // not the refetch succeeds: an offline environment still recounts tokens.
118 const refresh = useCallback(() => {
119 const input = JSON.parse(windowKey) as UsageSummaryInput;
120 for (const environment of selectedEnvironments) {
121 const { environmentId } = environment;
122 const query = serverEnvironment.usageSummary({ environmentId, input });
123 void runAtomCommand(
124 appAtomRegistry,
125 serverEnvironment.refreshUsageRates,
126 { environmentId, input: {} },
127 { reportFailure: false },
128 ).finally(() => appAtomRegistry.refresh(query));
129 }
130 }, [selectedEnvironments, windowKey]);
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}