The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { useAtomValue } from "@effect/atom-react"; |
| 2 | import { |
| 3 | AuthDiagnosticsReadScope, |
| 4 | USAGE_CONTRACT_VERSION, |
| 5 | type EnvironmentId, |
| 6 | type UsageBucket, |
| 7 | type UsageSummary, |
| 8 | type UsageProviderKind, |
| 9 | type UsageSummaryInput, |
| 10 | } from "@t3tools/contracts"; |
| 11 | import { refreshUsage, usageSummaryInput } from "@t3tools/client-runtime/state/usage"; |
| 12 | import { resolveUsageAccess } from "@t3tools/client-runtime/state/usage-access"; |
| 13 | import { AsyncResult, Atom } from "effect/reactivity"; |
| 14 | import { msg } from "gt-react"; |
| 15 | import { useState } from "react"; |
| 16 | |
| 17 | import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge"; |
| 18 | import { appAtomRegistry } from "../rpc/atomRegistry"; |
| 19 | import { environmentPresentations } from "./presentation"; |
| 20 | import { serverEnvironment } from "./server"; |
| 21 | import { environmentSession, readEnvironmentScope } from "./session"; |
| 22 | import { m } from "../i18n/messages"; |
| 23 | |
| 24 | export interface EnvironmentUsageStatus { |
| 25 | readonly environmentId: EnvironmentId; |
| 26 | readonly label: string; |
| 27 | readonly isPending: boolean; |
| 28 | readonly canReadDiagnostics: boolean; |
| 29 | readonly isConnected: boolean; |
| 30 | readonly error: string | null; |
| 31 | readonly summary: UsageSummary | null; |
| 32 | } |
| 33 | |
| 34 | const usageByWindowAtom = Atom.family((windowKey: string) => |
| 35 | Atom.make((get): readonly EnvironmentUsageStatus[] => { |
| 36 | const input = JSON.parse(windowKey) as UsageSummaryInput; |
| 37 | const presentations = get(environmentPresentations.presentationsAtom); |
| 38 | |
| 39 | const statuses: EnvironmentUsageStatus[] = []; |
| 40 | for (const [environmentId, presentation] of presentations) { |
| 41 | const isConnected = presentation.connection.phase === "connected"; |
| 42 | const sessionResult = get(environmentSession.sessionStateAtom(environmentId)); |
| 43 | const access = resolveUsageAccess({ |
| 44 | connectionPhase: presentation.connection.phase, |
| 45 | session: AsyncResult.getOrElse(sessionResult, () => null), |
| 46 | hasSessionError: sessionResult._tag === "Failure", |
| 47 | }); |
| 48 | if (!access.canReadDiagnostics) { |
| 49 | statuses.push({ |
| 50 | environmentId, |
| 51 | label: presentation.entry.target.label, |
| 52 | isConnected, |
| 53 | ...access, |
| 54 | summary: null, |
| 55 | }); |
| 56 | continue; |
| 57 | } |
| 58 | const result = get( |
| 59 | serverEnvironment.usageSummary({ |
| 60 | environmentId, |
| 61 | input: usageSummaryInput( |
| 62 | input, |
| 63 | get(serverEnvironment.usageModelFilterAtom(environmentId)), |
| 64 | ), |
| 65 | }), |
| 66 | ); |
| 67 | const summary = AsyncResult.getOrElse(result, () => null); |
| 68 | statuses.push({ |
| 69 | environmentId, |
| 70 | label: presentation.entry.target.label, |
| 71 | isPending: result.waiting, |
| 72 | canReadDiagnostics: true, |
| 73 | isConnected, |
| 74 | error: |
| 75 | result._tag === "Failure" ? m(msg("This environment could not report usage.")) : null, |
| 76 | summary, |
| 77 | }); |
| 78 | } |
| 79 | return statuses; |
| 80 | }).pipe(Atom.withLabel(`web-usage:window:${windowKey}`)), |
| 81 | ); |
| 82 | |
| 83 | export interface UsageView { |
| 84 | readonly merged: MergedUsage; |
| 85 | readonly environments: readonly EnvironmentUsageStatus[]; |
| 86 | readonly selectedEnvironments: readonly EnvironmentUsageStatus[]; |
| 87 | readonly isPending: boolean; |
| 88 | readonly shown: { readonly window: UsageSummaryInput; readonly merged: MergedUsage } | null; |
| 89 | readonly isPartial: boolean; |
| 90 | readonly refresh: (input?: UsageSummaryInput) => Promise<void>; |
| 91 | } |
| 92 | |
| 93 | export function mergeAnsweredUsage( |
| 94 | environments: readonly EnvironmentUsageStatus[], |
| 95 | keepBucket?: (bucket: UsageBucket) => boolean, |
| 96 | ): MergedUsage { |
| 97 | const answered: EnvironmentUsage[] = environments.flatMap(({ environmentId, label, summary }) => |
| 98 | summary === null |
| 99 | ? [] |
| 100 | : [ |
| 101 | { |
| 102 | environmentId, |
| 103 | label, |
| 104 | summary: |
| 105 | keepBucket === undefined |
| 106 | ? summary |
| 107 | : { ...summary, buckets: summary.buckets.filter(keepBucket) }, |
| 108 | }, |
| 109 | ], |
| 110 | ); |
| 111 | return mergeUsage(answered, USAGE_CONTRACT_VERSION); |
| 112 | } |
| 113 | |
| 114 | const NO_HIDDEN_PROVIDERS: ReadonlySet<UsageProviderKind> = new Set(); |
| 115 | |
| 116 | function withoutProviders( |
| 117 | environments: readonly EnvironmentUsageStatus[], |
| 118 | hiddenProviders: ReadonlySet<UsageProviderKind>, |
| 119 | ): readonly EnvironmentUsageStatus[] { |
| 120 | if (hiddenProviders.size === 0) return environments; |
| 121 | return environments.map((environment) => |
| 122 | environment.summary === null |
| 123 | ? environment |
| 124 | : { |
| 125 | ...environment, |
| 126 | summary: { |
| 127 | ...environment.summary, |
| 128 | buckets: environment.summary.buckets.filter( |
| 129 | (bucket) => !hiddenProviders.has(bucket.provider), |
| 130 | ), |
| 131 | sources: environment.summary.sources.filter( |
| 132 | (source) => !hiddenProviders.has(source.fingerprint.provider), |
| 133 | ), |
| 134 | }, |
| 135 | }, |
| 136 | ); |
| 137 | } |
| 138 | |
| 139 | function deriveSelection( |
| 140 | environments: readonly EnvironmentUsageStatus[], |
| 141 | selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null, |
| 142 | hiddenProviders: ReadonlySet<UsageProviderKind>, |
| 143 | ) { |
| 144 | const selectedEnvironments = |
| 145 | selectedEnvironmentIds === null |
| 146 | ? environments |
| 147 | : environments.filter((environment) => selectedEnvironmentIds.has(environment.environmentId)); |
| 148 | return { |
| 149 | environments, |
| 150 | selectedEnvironmentIds, |
| 151 | hiddenProviders, |
| 152 | selectedEnvironments, |
| 153 | merged: mergeAnsweredUsage(withoutProviders(selectedEnvironments, hiddenProviders)), |
| 154 | }; |
| 155 | } |
| 156 | |
| 157 | export function useUsage( |
| 158 | input: UsageSummaryInput, |
| 159 | selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null = null, |
| 160 | hiddenProviders: ReadonlySet<UsageProviderKind> = NO_HIDDEN_PROVIDERS, |
| 161 | ): UsageView { |
| 162 | const windowKey = JSON.stringify({ |
| 163 | sinceDay: input.sinceDay, |
| 164 | untilDay: input.untilDay, |
| 165 | timeZone: input.timeZone, |
| 166 | resolution: input.resolution, |
| 167 | sinceTime: input.sinceTime, |
| 168 | untilTime: input.untilTime, |
| 169 | }); |
| 170 | const atom = usageByWindowAtom(windowKey); |
| 171 | const environments = useAtomValue(atom); |
| 172 | // Identity-based render sync needs a derivation retained by inputs across renders. |
| 173 | const [derived, setDerived] = useState(() => |
| 174 | deriveSelection(environments, selectedEnvironmentIds, hiddenProviders), |
| 175 | ); |
| 176 | let current = derived; |
| 177 | if ( |
| 178 | derived.environments !== environments || |
| 179 | derived.selectedEnvironmentIds !== selectedEnvironmentIds || |
| 180 | derived.hiddenProviders !== hiddenProviders |
| 181 | ) { |
| 182 | current = deriveSelection(environments, selectedEnvironmentIds, hiddenProviders); |
| 183 | setDerived(current); |
| 184 | } |
| 185 | const { selectedEnvironments, merged } = current; |
| 186 | |
| 187 | const refresh = (nextInput?: UsageSummaryInput) => |
| 188 | refreshUsage({ |
| 189 | registry: appAtomRegistry, |
| 190 | server: serverEnvironment, |
| 191 | presentations: environmentPresentations, |
| 192 | environmentIds: selectedEnvironments |
| 193 | .filter( |
| 194 | (environment) => |
| 195 | environment.canReadDiagnostics && |
| 196 | readEnvironmentScope(environment.environmentId, AuthDiagnosticsReadScope), |
| 197 | ) |
| 198 | .map(({ environmentId }) => environmentId), |
| 199 | input: nextInput ?? (JSON.parse(windowKey) as UsageSummaryInput), |
| 200 | }); |
| 201 | |
| 202 | const answeredCount = selectedEnvironments.filter( |
| 203 | (environment) => environment.summary !== null, |
| 204 | ).length; |
| 205 | const stillReporting = selectedEnvironments.filter( |
| 206 | (environment) => environment.summary === null && environment.error === null, |
| 207 | ).length; |
| 208 | const isPending = answeredCount === 0 && stillReporting > 0; |
| 209 | |
| 210 | const [lastAnswered, setLastAnswered] = useState< |
| 211 | | (NonNullable<UsageView["shown"]> & { |
| 212 | readonly selection: typeof selectedEnvironmentIds; |
| 213 | readonly hidden: typeof hiddenProviders; |
| 214 | }) |
| 215 | | null |
| 216 | >(null); |
| 217 | if ( |
| 218 | answeredCount > 0 && |
| 219 | (lastAnswered?.merged !== merged || |
| 220 | lastAnswered.window !== input || |
| 221 | lastAnswered.selection !== selectedEnvironmentIds || |
| 222 | lastAnswered.hidden !== hiddenProviders) |
| 223 | ) { |
| 224 | setLastAnswered({ |
| 225 | window: input, |
| 226 | merged, |
| 227 | selection: selectedEnvironmentIds, |
| 228 | hidden: hiddenProviders, |
| 229 | }); |
| 230 | } |
| 231 | const kept = |
| 232 | lastAnswered?.selection === selectedEnvironmentIds && lastAnswered.hidden === hiddenProviders |
| 233 | ? lastAnswered |
| 234 | : null; |
| 235 | const shown = |
| 236 | answeredCount > 0 |
| 237 | ? { window: input, merged } |
| 238 | : (kept ?? (isPending ? null : { window: input, merged })); |
| 239 | |
| 240 | return { |
| 241 | merged, |
| 242 | environments, |
| 243 | selectedEnvironments, |
| 244 | isPending, |
| 245 | shown, |
| 246 | isPartial: answeredCount > 0 && stillReporting > 0, |
| 247 | refresh, |
| 248 | }; |
| 249 | } |