From a0debffc1d83f79d36dd92b51213ec3c533e62d4 Mon Sep 17 00:00:00 2001
From: "t3-code[bot]" <269035359+t3-code[bot]@users.noreply.github.com>
Date: Sun, 9 Aug 2026 12:17:16 +0000
Subject: [PATCH] fix(usage): handle unavailable environments
---
.../src/components/AndroidAnchoredMenu.tsx | 2 +
.../src/features/usage/UsageRouteScreen.tsx | 125 +++++++++++++--
apps/mobile/src/state/usage.test.ts | 50 ++++++
apps/mobile/src/state/usage.ts | 138 ++++++++++-------
.../mobile/src/state/usageEnvironmentScope.ts | 57 +++++++
apps/web/src/components/usage/UsagePage.tsx | 143 +++++++++++++++---
apps/web/src/state/usage.test.ts | 82 ++++++++++
apps/web/src/state/usage.ts | 133 +++++++++-------
apps/web/src/state/usageEnvironmentScope.ts | 57 +++++++
9 files changed, 640 insertions(+), 147 deletions(-)
create mode 100644 apps/mobile/src/state/usage.test.ts
create mode 100644 apps/mobile/src/state/usageEnvironmentScope.ts
create mode 100644 apps/web/src/state/usage.test.ts
create mode 100644 apps/web/src/state/usageEnvironmentScope.ts
diff --git a/apps/mobile/src/components/AndroidAnchoredMenu.tsx b/apps/mobile/src/components/AndroidAnchoredMenu.tsx
index c4a0045eef..ebc0388512 100644
--- a/apps/mobile/src/components/AndroidAnchoredMenu.tsx
+++ b/apps/mobile/src/components/AndroidAnchoredMenu.tsx
@@ -278,6 +278,8 @@ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
(30);
const [metric, setMetric] = useState("cost");
+ const [environmentFilter, setEnvironmentFilter] = useState(null);
// Recomputed only when the window length changes, so a re-render does not
// shift the range and refetch every environment.
const window = useMemo(() => makeWindow(windowDays), [windowDays]);
- const { merged, environments, isPending, isPartial, refresh } = useUsage(window);
+ const { merged, options, environments, selectedEnvironmentId, isPending, isPartial, refresh } =
+ useUsage(window, environmentFilter);
+
+ useEffect(() => {
+ if (environmentFilter !== null && selectedEnvironmentId === null) {
+ setEnvironmentFilter(null);
+ }
+ }, [environmentFilter, selectedEnvironmentId]);
+
+ const environmentActions = useMemo(
+ () => [
+ {
+ id: "all",
+ title: "All environments",
+ state: selectedEnvironmentId === null ? "on" : "off",
+ },
+ ...options.map((environment) => ({
+ id: `environment:${environment.environmentId}`,
+ title: environment.label,
+ state:
+ environment.environmentId === selectedEnvironmentId ? ("on" as const) : ("off" as const),
+ })),
+ ],
+ [options, selectedEnvironmentId],
+ );
+ const selectedEnvironmentLabel =
+ selectedEnvironmentId === null
+ ? "All environments"
+ : (options.find((environment) => environment.environmentId === selectedEnvironmentId)
+ ?.label ?? "All environments");
+ const selectedEnvironmentControlLabel =
+ selectedEnvironmentLabel.length > 20
+ ? `${selectedEnvironmentLabel.slice(0, 19)}…`
+ : selectedEnvironmentLabel;
+ const usableEnvironmentCount = environments.filter(
+ (environment) =>
+ environment.summary !== null && !merged.staleEnvironments.includes(environment.environmentId),
+ ).length;
const days = useMemo(
() => enumerateDays(window.sinceDay, window.untilDay),
[window.sinceDay, window.untilDay],
);
- // The pull spinner tracks re-scans of environments that have answered
- // before. The initial scan renders its own placeholder, and an unreachable
- // environment stays pending forever — neither may pin the spinner on.
+ // The pull spinner tracks re-scans of connected environments that have
+ // answered before. The initial scan renders its own placeholder.
const refreshing = environments.some((entry) => entry.isPending && entry.summary !== null);
return (
@@ -67,22 +107,52 @@ export function UsageRouteScreen() {
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
refreshControl={}
>
- ({ value: option.days, label: option.label }))}
- selected={windowDays}
- onSelect={setWindowDays}
- />
+
+ ({
+ value: option.days,
+ label: option.label,
+ }))}
+ selected={windowDays}
+ onSelect={setWindowDays}
+ />
+
+ {
+ setEnvironmentFilter(
+ nativeEvent.event === "all"
+ ? null
+ : (nativeEvent.event.slice("environment:".length) as EnvironmentId),
+ );
+ }}
+ >
+
+
+
+
- {isPending ? (
+ {isPending || (usableEnvironmentCount === 0 && isPartial) ? (
Scanning provider transcripts…
- ) : environments.length === 0 ? (
+ ) : options.length === 0 ? (
Connect an environment to see usage.
+ ) : usableEnvironmentCount === 0 ? (
+
+ {selectedEnvironmentId === null
+ ? "No connected environment could report usage."
+ : "This environment is unavailable for usage."}
+
) : (
<>
environment.phase === "connecting" || environment.phase === "reconnecting",
+ );
+ const unavailable = props.environments.filter(
+ (environment) =>
+ environment.phase === "available" ||
+ environment.phase === "offline" ||
+ environment.phase === "error",
+ );
const failed = props.environments.filter((environment) => environment.error !== null);
const stale = props.environments.filter((environment) =>
props.merged.staleEnvironments.includes(environment.environmentId),
);
const duplicateSources = props.merged.duplicateSources;
if (
+ settling.length === 0 &&
+ unavailable.length === 0 &&
failed.length === 0 &&
stale.length === 0 &&
duplicateSources.length === 0 &&
@@ -421,6 +500,22 @@ function UsageCoverageNotice(props: {
Some environments are still reporting. Totals are partial.
) : null}
+ {settling.map((environment) => (
+
+ {environment.label} is {environment.phase}.
+
+ ))}
+ {unavailable.map((environment) => (
+
+ {environment.label} is{" "}
+ {environment.phase === "available"
+ ? "not connected"
+ : environment.phase === "error"
+ ? "unavailable"
+ : environment.phase}
+ .
+
+ ))}
{failed.map((environment) => (
{environment.label} could not report usage.
diff --git a/apps/mobile/src/state/usage.test.ts b/apps/mobile/src/state/usage.test.ts
new file mode 100644
index 0000000000..d556819709
--- /dev/null
+++ b/apps/mobile/src/state/usage.test.ts
@@ -0,0 +1,50 @@
+import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
+import type { EnvironmentId } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ getEnvironmentUsageLoadingState,
+ isEnvironmentUsageSettling,
+ resolveEnvironmentUsageScope,
+ type EnvironmentUsageOption,
+} from "./usageEnvironmentScope";
+
+const environment = (
+ environmentId: string,
+ phase: EnvironmentConnectionPhase,
+): EnvironmentUsageOption => ({
+ environmentId: environmentId as EnvironmentId,
+ label: environmentId,
+ phase,
+});
+
+describe("mobile usage environment scope", () => {
+ it("distinguishes connection progress from terminal states", () => {
+ expect(isEnvironmentUsageSettling("available")).toBe(false);
+ expect(isEnvironmentUsageSettling("connecting")).toBe(true);
+ expect(isEnvironmentUsageSettling("reconnecting")).toBe(true);
+ expect(isEnvironmentUsageSettling("offline")).toBe(false);
+ expect(isEnvironmentUsageSettling("error")).toBe(false);
+ });
+
+ it("does not let an offline environment hold healthy totals open", () => {
+ expect(
+ getEnvironmentUsageLoadingState([
+ { phase: "connected", summary: {}, error: null },
+ { phase: "offline", summary: null, error: null },
+ ]),
+ ).toEqual({ isPending: false, isPartial: false });
+ });
+
+ it("isolates a selected environment and falls back when it disappears", () => {
+ const options = [environment("healthy", "connected"), environment("down", "offline")];
+
+ expect(resolveEnvironmentUsageScope(options, "down" as EnvironmentId).environments).toEqual([
+ options[1],
+ ]);
+ expect(
+ resolveEnvironmentUsageScope(options.slice(0, 1), "down" as EnvironmentId)
+ .selectedEnvironmentId,
+ ).toBeNull();
+ });
+});
diff --git a/apps/mobile/src/state/usage.ts b/apps/mobile/src/state/usage.ts
index 91cefda07f..4f4749101d 100644
--- a/apps/mobile/src/state/usage.ts
+++ b/apps/mobile/src/state/usage.ts
@@ -1,11 +1,11 @@
/**
* Multi-environment usage state.
*
- * Every connected environment answers the same typed query; the client merges
- * the results. Raw transcripts never leave the machine that produced them.
+ * Connected environments answer the typed usage query. Connection state
+ * determines whether a waiting query contributes to loading coverage, so one
+ * unreachable machine can never hold the dashboard open.
*
- * Mirror of `apps/web/src/state/usage.ts` over mobile's atom wiring; the merge
- * rules themselves live in `@t3tools/shared/usageMerge`.
+ * Mirror of web usage state over mobile's atom registry.
*
* @module state/usage
*/
@@ -16,91 +16,116 @@ import {
type UsageSummary,
type UsageSummaryInput,
} from "@t3tools/contracts";
-import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";
import * as Option from "effect/Option";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback, useMemo } from "react";
+import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";
import { appAtomRegistry } from "./atom-registry";
import { environmentPresentations } from "./presentation";
import { serverEnvironment } from "./server";
+import {
+ getEnvironmentUsageLoadingState,
+ isEnvironmentUsageSettling,
+ resolveEnvironmentUsageScope,
+ type EnvironmentUsageOption,
+} from "./usageEnvironmentScope";
-export interface EnvironmentUsageStatus {
- readonly environmentId: EnvironmentId;
- readonly label: string;
+export type { EnvironmentUsageOption } from "./usageEnvironmentScope";
+
+export interface EnvironmentUsageStatus extends EnvironmentUsageOption {
readonly isPending: boolean;
+ /** A connected usage query failed. Connection coverage uses `phase`. */
readonly error: string | null;
readonly summary: UsageSummary | null;
}
-/**
- * Reads every environment's summary for one window.
- *
- * Keyed by the serialised window so switching ranges does not thrash the atom
- * cache, and so each environment's query is shared with any other reader of the
- * same window.
- */
-const usageByWindowAtom = Atom.family((windowKey: string) =>
- Atom.make((get): readonly EnvironmentUsageStatus[] => {
- const input = JSON.parse(windowKey) as UsageSummaryInput;
- const presentations = get(environmentPresentations.presentationsAtom);
+interface UsageAtomValue {
+ readonly options: readonly EnvironmentUsageOption[];
+ readonly environments: readonly EnvironmentUsageStatus[];
+ readonly selectedEnvironmentId: EnvironmentId | null;
+}
- const statuses: EnvironmentUsageStatus[] = [];
- for (const [environmentId, presentation] of presentations) {
+interface UsageAtomKey {
+ readonly input: UsageSummaryInput;
+ readonly selectedEnvironmentId: EnvironmentId | null;
+}
+
+const usageByWindowAtom = Atom.family((key: string) =>
+ Atom.make((get): UsageAtomValue => {
+ const { input, selectedEnvironmentId } = JSON.parse(key) as UsageAtomKey;
+ const presentations = get(environmentPresentations.presentationsAtom);
+ const options = Array.from(presentations, ([environmentId, presentation]) => ({
+ environmentId,
+ label: presentation.entry.target.label,
+ phase: presentation.connection.phase,
+ }));
+ const scope = resolveEnvironmentUsageScope(options, selectedEnvironmentId);
+
+ const environments: EnvironmentUsageStatus[] = [];
+ for (const option of scope.environments) {
+ const { environmentId } = option;
+ // Keep reading the environment-scoped atom while disconnected so a prior
+ // successful value remains visible. Its waiting state only affects the UI
+ // while the connection is actively settling.
const result = get(serverEnvironment.usageSummary({ environmentId, input }));
- statuses.push({
- environmentId,
- label: presentation.entry.target.label,
- isPending: result.waiting,
- error: result._tag === "Failure" ? "This environment could not report usage." : null,
+ const failed = option.phase === "connected" && result._tag === "Failure";
+ environments.push({
+ ...option,
+ isPending: isEnvironmentUsageSettling(option.phase) && result.waiting,
+ error: failed ? "This environment could not report usage." : null,
summary: Option.getOrNull(AsyncResult.value(result)),
});
}
- return statuses;
- }).pipe(Atom.withLabel(`mobile-usage:window:${windowKey}`)),
+
+ return { options, environments, selectedEnvironmentId: scope.selectedEnvironmentId };
+ }).pipe(Atom.withLabel(`mobile-usage:${key}`)),
);
export interface UsageView {
readonly merged: MergedUsage;
+ /** All catalog entries, including entries outside the active filter. */
+ readonly options: readonly EnvironmentUsageOption[];
+ /** Coverage entries in the active filter. */
readonly environments: readonly EnvironmentUsageStatus[];
- /** True until at least one environment has answered. */
+ readonly selectedEnvironmentId: EnvironmentId | null;
+ /** True until at least one connected environment has answered. */
readonly isPending: boolean;
- /**
- * True while environments that have not failed are still answering. Failed
- * environments are reported through their own error rows: totals will not
- * improve by waiting on them, so they must not read as "still reporting".
- */
readonly isPartial: boolean;
readonly refresh: () => void;
}
-export function useUsage(input: UsageSummaryInput): UsageView {
- const windowKey = useMemo(
+export function useUsage(
+ input: UsageSummaryInput,
+ selectedEnvironmentId: EnvironmentId | null,
+): UsageView {
+ const key = useMemo(
() =>
JSON.stringify({
- sinceDay: input.sinceDay,
- untilDay: input.untilDay,
- timeZone: input.timeZone,
+ input: {
+ sinceDay: input.sinceDay,
+ untilDay: input.untilDay,
+ timeZone: input.timeZone,
+ },
+ selectedEnvironmentId,
}),
- [input.sinceDay, input.untilDay, input.timeZone],
+ [input.sinceDay, input.untilDay, input.timeZone, selectedEnvironmentId],
);
- const atom = usageByWindowAtom(windowKey);
- const environments = useAtomValue(atom);
+ const atom = usageByWindowAtom(key);
+ const value = useAtomValue(atom);
- // Refreshing only the derived atom would re-read the per-environment SWR
- // queries within their stale window and change nothing. Refresh each
- // environment's query so pull-to-refresh always rescans.
const refresh = useCallback(() => {
- const input = JSON.parse(windowKey) as UsageSummaryInput;
- for (const environment of environments) {
+ const { input } = JSON.parse(key) as UsageAtomKey;
+ for (const environment of value.environments) {
+ if (environment.phase !== "connected") continue;
appAtomRegistry.refresh(
serverEnvironment.usageSummary({ environmentId: environment.environmentId, input }),
);
}
- }, [environments, windowKey]);
+ }, [key, value.environments]);
const merged = useMemo(() => {
- const answered: EnvironmentUsage[] = environments.flatMap((environment) =>
+ const answered: EnvironmentUsage[] = value.environments.flatMap((environment) =>
environment.summary === null
? []
: [
@@ -112,18 +137,17 @@ export function useUsage(input: UsageSummaryInput): UsageView {
],
);
return mergeUsage(answered, USAGE_CONTRACT_VERSION);
- }, [environments]);
+ }, [value.environments]);
- const answeredCount = environments.filter((environment) => environment.summary !== null).length;
- const stillReporting = environments.filter(
- (environment) => environment.summary === null && environment.error === null,
- ).length;
+ const loadingState = getEnvironmentUsageLoadingState(value.environments);
return {
merged,
- environments,
- isPending: answeredCount === 0 && stillReporting > 0,
- isPartial: answeredCount > 0 && stillReporting > 0,
+ options: value.options,
+ environments: value.environments,
+ selectedEnvironmentId: value.selectedEnvironmentId,
+ isPending: loadingState.isPending,
+ isPartial: loadingState.isPartial,
refresh,
};
}
diff --git a/apps/mobile/src/state/usageEnvironmentScope.ts b/apps/mobile/src/state/usageEnvironmentScope.ts
new file mode 100644
index 0000000000..c5a48c42a9
--- /dev/null
+++ b/apps/mobile/src/state/usageEnvironmentScope.ts
@@ -0,0 +1,57 @@
+import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
+import type { EnvironmentId } from "@t3tools/contracts";
+
+export interface EnvironmentUsageOption {
+ readonly environmentId: EnvironmentId;
+ readonly label: string;
+ readonly phase: EnvironmentConnectionPhase;
+}
+
+/** Connection phases where a usage answer may still arrive without user action. */
+export function isEnvironmentUsageSettling(phase: EnvironmentConnectionPhase): boolean {
+ return phase === "connecting" || phase === "reconnecting" || phase === "connected";
+}
+
+export function resolveEnvironmentUsageScope(
+ options: readonly EnvironmentUsageOption[],
+ selectedEnvironmentId: EnvironmentId | null,
+): {
+ readonly selectedEnvironmentId: EnvironmentId | null;
+ readonly environments: readonly EnvironmentUsageOption[];
+} {
+ const effectiveSelection =
+ selectedEnvironmentId !== null &&
+ options.some((environment) => environment.environmentId === selectedEnvironmentId)
+ ? selectedEnvironmentId
+ : null;
+ return {
+ selectedEnvironmentId: effectiveSelection,
+ environments:
+ effectiveSelection === null
+ ? options
+ : options.filter((environment) => environment.environmentId === effectiveSelection),
+ };
+}
+
+interface EnvironmentUsageLoadingEntry {
+ readonly phase: EnvironmentConnectionPhase;
+ readonly summary: unknown | null;
+ readonly error: string | null;
+}
+
+export function getEnvironmentUsageLoadingState(
+ environments: readonly EnvironmentUsageLoadingEntry[],
+): { readonly isPending: boolean; readonly isPartial: boolean } {
+ const answeredCount = environments.filter((environment) => environment.summary !== null).length;
+ const stillReporting = environments.filter(
+ (environment) =>
+ isEnvironmentUsageSettling(environment.phase) &&
+ environment.summary === null &&
+ environment.error === null,
+ ).length;
+
+ return {
+ isPending: answeredCount === 0 && stillReporting > 0,
+ isPartial: answeredCount > 0 && stillReporting > 0,
+ };
+}
diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx
index b5b762aea7..e6ca7dc731 100644
--- a/apps/web/src/components/usage/UsagePage.tsx
+++ b/apps/web/src/components/usage/UsagePage.tsx
@@ -1,7 +1,7 @@
-import type { UsageProviderKind } from "@t3tools/contracts";
+import type { EnvironmentId, UsageProviderKind } from "@t3tools/contracts";
import { useCanGoBack, useNavigate, useRouter } from "@tanstack/react-router";
import { ArrowLeftIcon, CheckIcon, RefreshCwIcon, XIcon } from "lucide-react";
-import { useMemo, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { cn } from "../../lib/utils";
import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
@@ -15,6 +15,7 @@ import {
makeWindow,
} from "@t3tools/shared/usageFormat";
import { ScrollArea } from "../ui/scroll-area";
+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { UsageChartLegend, UsageProviderChart, type UsageChartMetric } from "./UsageProviderChart";
import { PROVIDER_COLOR, PROVIDER_LABEL, PROVIDER_MARK, PROVIDER_ORDER } from "./usageProviders";
@@ -28,6 +29,7 @@ export function UsagePage() {
const [windowDays, setWindowDays] = useState(30);
const [metric, setMetric] = useState("cost");
const [breakdown, setBreakdown] = useState<"model" | "day">("model");
+ const [environmentFilter, setEnvironmentFilter] = useState(null);
const canGoBack = useCanGoBack();
const navigate = useNavigate();
const router = useRouter();
@@ -35,12 +37,18 @@ export function UsagePage() {
// Recomputed only when the window length changes, so a re-render does not
// shift the range and refetch every environment.
const window = useMemo(() => makeWindow(windowDays), [windowDays]);
- const { merged, environments, isPending, isPartial, refresh } = useUsage(window);
+ const { merged, options, environments, selectedEnvironmentId, isPending, isPartial, refresh } =
+ useUsage(window, environmentFilter);
+ useEffect(() => {
+ if (environmentFilter !== null && selectedEnvironmentId === null) {
+ setEnvironmentFilter(null);
+ }
+ }, [environmentFilter, selectedEnvironmentId]);
- // Hold the content until every environment is terminal. Rendering merged
- // totals while devices are still answering makes every number on the page
- // jump as each one lands.
- const settling = isPending || isPartial;
+ const usableEnvironmentCount = environments.filter(
+ (environment) =>
+ environment.summary !== null && !merged.staleEnvironments.includes(environment.environmentId),
+ ).length;
const days = useMemo(
() => enumerateDays(window.sinceDay, window.untilDay),
@@ -88,7 +96,40 @@ export function UsagePage() {
-
+
+
{WINDOW_OPTIONS.map((option) => (