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 /** True until at least one environment has answered. */
65 readonly isPending: boolean;
66 /**
67 * True while environments that have not failed are still answering. Failed
68 * environments are reported through their own error rows: totals will not
69 * improve by waiting on them, so they must not read as "still reporting".
70 */
71 readonly isPartial: boolean;
72 readonly refresh: () => void;
73}
74
75export function useUsage(input: UsageSummaryInput): UsageView {
76 const windowKey = useMemo(
77 () =>
78 JSON.stringify({
79 sinceDay: input.sinceDay,
80 untilDay: input.untilDay,
81 timeZone: input.timeZone,
82 resolution: input.resolution,
83 sinceTime: input.sinceTime,
84 untilTime: input.untilTime,
85 }),
86 [
87 input.sinceDay,
88 input.untilDay,
89 input.timeZone,
90 input.resolution,
91 input.sinceTime,
92 input.untilTime,
93 ],
94 );
95 const atom = usageByWindowAtom(windowKey);
96 const environments = useAtomValue(atom);
97
98 // Refreshing only the derived atom would re-read the per-environment SWR
99 // queries within their stale window and change nothing. Refresh each
100 // environment's query so the button always rescans.
101 //
102 // Each environment refetches model pricing first, so a model released since
103 // its last daily fetch gets priced by the rescan. The rescan runs whether or
104 // not the refetch succeeds: an offline environment still recounts tokens.
105 const refresh = useCallback(() => {
106 const input = JSON.parse(windowKey) as UsageSummaryInput;
107 for (const environment of environments) {
108 const { environmentId } = environment;
109 const query = serverEnvironment.usageSummary({ environmentId, input });
110 void runAtomCommand(
111 appAtomRegistry,
112 serverEnvironment.refreshUsageRates,
113 { environmentId, input: {} },
114 { reportFailure: false },
115 ).finally(() => appAtomRegistry.refresh(query));
116 }
117 }, [environments, windowKey]);
118
119 const merged = useMemo(() => {
120 const answered: EnvironmentUsage[] = environments.flatMap((environment) =>
121 environment.summary === null
122 ? []
123 : [
124 {
125 environmentId: environment.environmentId,
126 label: environment.label,
127 summary: environment.summary,
128 },
129 ],
130 );
131 return mergeUsage(answered, USAGE_CONTRACT_VERSION);
132 }, [environments]);
133
134 const answeredCount = environments.filter((environment) => environment.summary !== null).length;
135 const stillReporting = environments.filter(
136 (environment) => environment.summary === null && environment.error === null,
137 ).length;
138
139 return {
140 merged,
141 environments,
142 isPending: answeredCount === 0 && stillReporting > 0,
143 isPartial: answeredCount > 0 && stillReporting > 0,
144 refresh,
145 };
146}