fix(usage): handle unavailable environments

This commit is contained in:
t3-code[bot] committed 2026-08-09 12:17:16 +00:00
1 parent 1a003e383a
commit a0debffc1d
9 files changed
+640 -147

No files matched your search

@@ -278,6 +278,8 @@ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
<Pressable
key={action.id ?? `${index}-${action.title}`}
android_ripple={{ color: rippleColor }}
accessibilityRole="menuitem"
accessibilityState={{ disabled, selected: action.state === "on" }}
disabled={disabled}
className={cn(
"min-h-11 flex-row items-center gap-2.5 px-3.5 py-2.5",
@@ -1,4 +1,6 @@
import { useNavigation } from "@react-navigation/native";
import type { MenuAction } from "@react-native-menu/menu";
import type { EnvironmentId } from "@t3tools/contracts";
import type { MergedUsage } from "@t3tools/shared/usageMerge";
import {
enumerateDays,
@@ -9,12 +11,13 @@ import {
formatUsd,
makeWindow,
} from "@t3tools/shared/usageFormat";
import { useMemo, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import { Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import { AppText as Text } from "../../components/AppText";
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
import { SettingsSection } from "../settings/components/SettingsSection";
@@ -35,20 +38,57 @@ export function UsageRouteScreen() {
const insets = useSafeAreaInsets();
const [windowDays, setWindowDays] = useState<number>(30);
const [metric, setMetric] = useState<UsageChartMetric>("cost");
const [environmentFilter, setEnvironmentFilter] = useState<EnvironmentId | null>(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<readonly MenuAction[]>(
() => [
{
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={<RefreshControl refreshing={refreshing} onRefresh={refresh} />}
>
<SegmentedControl
options={WINDOW_OPTIONS.map((option) => ({ value: option.days, label: option.label }))}
selected={windowDays}
onSelect={setWindowDays}
/>
<View className="gap-3">
<SegmentedControl
options={WINDOW_OPTIONS.map((option) => ({
value: option.days,
label: option.label,
}))}
selected={windowDays}
onSelect={setWindowDays}
/>
<View className="max-w-full items-start">
<ControlPillMenu
title="Filter environments"
actions={[...environmentActions]}
onPressAction={({ nativeEvent }) => {
setEnvironmentFilter(
nativeEvent.event === "all"
? null
: (nativeEvent.event.slice("environment:".length) as EnvironmentId),
);
}}
>
<ControlPill
variant="pill"
label={selectedEnvironmentControlLabel}
accessibilityLabel={`Filter environments, ${selectedEnvironmentLabel}`}
/>
</ControlPillMenu>
</View>
</View>
<UsageCoverageNotice environments={environments} merged={merged} isPartial={isPartial} />
{isPending ? (
{isPending || (usableEnvironmentCount === 0 && isPartial) ? (
<Text className="py-16 text-center text-base text-foreground-muted">
Scanning provider transcripts…
</Text>
) : environments.length === 0 ? (
) : options.length === 0 ? (
<Text className="py-16 text-center text-base text-foreground-muted">
Connect an environment to see usage.
</Text>
) : usableEnvironmentCount === 0 ? (
<Text className="py-16 text-center text-base text-foreground-muted">
{selectedEnvironmentId === null
? "No connected environment could report usage."
: "This environment is unavailable for usage."}
</Text>
) : (
<>
<ChartCard
@@ -391,21 +461,30 @@ function ModelsSection(props: { readonly merged: MergedUsage }) {
}
/**
* Says plainly when the totals are incomplete: an environment still answering,
* one that failed, or one whose transcripts another environment already
* reported.
* Explains incomplete totals without hiding healthy environment data.
*/
function UsageCoverageNotice(props: {
readonly environments: readonly EnvironmentUsageStatus[];
readonly merged: MergedUsage;
readonly isPartial: boolean;
}) {
const settling = props.environments.filter(
(environment) => 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.
</Text>
) : null}
{settling.map((environment) => (
<Text key={environment.environmentId} className="text-sm text-foreground-muted">
{environment.label} is {environment.phase}.
</Text>
))}
{unavailable.map((environment) => (
<Text key={environment.environmentId} className="text-sm text-foreground-muted">
{environment.label} is{" "}
{environment.phase === "available"
? "not connected"
: environment.phase === "error"
? "unavailable"
: environment.phase}
.
</Text>
))}
{failed.map((environment) => (
<Text key={environment.environmentId} className="text-sm text-foreground-muted">
{environment.label} could not report usage.
+50
View File
@@ -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();
});
});
+81 -57
View File
@@ -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,
};
}
@@ -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,
};
}
+122 -21
View File
@@ -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<number>(30);
const [metric, setMetric] = useState<UsageChartMetric>("cost");
const [breakdown, setBreakdown] = useState<"model" | "day">("model");
const [environmentFilter, setEnvironmentFilter] = useState<EnvironmentId | null>(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() {
</p>
</div>
</div>
<div className="flex items-center gap-2">
<div className="flex flex-wrap items-center justify-end gap-2">
<Select
value={
selectedEnvironmentId === null ? "all" : `environment:${selectedEnvironmentId}`
}
onValueChange={(value) => {
if (value === null) return;
setEnvironmentFilter(
value === "all" ? null : (value.slice("environment:".length) as EnvironmentId),
);
}}
items={[
{ value: "all", label: "All environments" },
...options.map((environment) => ({
value: `environment:${environment.environmentId}`,
label: environment.label,
})),
]}
>
<SelectTrigger size="sm" className="w-44" aria-label="Filter environments">
<SelectValue />
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
<SelectItem value="all">All environments</SelectItem>
{options.map((environment) => (
<SelectItem
key={environment.environmentId}
value={`environment:${environment.environmentId}`}
>
{environment.label}
</SelectItem>
))}
</SelectPopup>
</Select>
<div className="flex overflow-hidden rounded-md border border-border">
{WINDOW_OPTIONS.map((option) => (
<button
@@ -117,17 +158,34 @@ export function UsagePage() {
</div>
</header>
{settling ? (
{isPending || (usableEnvironmentCount === 0 && isPartial) ? (
<>
{environments.length > 1 ? <UsageDeviceStrip environments={environments} /> : null}
<UsageSkeleton />
</>
) : options.length === 0 ? (
<UsageEmptyState>Connect an environment to see usage.</UsageEmptyState>
) : usableEnvironmentCount === 0 ? (
<>
<UsageCoverageNotice
environments={environments}
duplicateSources={merged.duplicateSources}
staleEnvironments={merged.staleEnvironments}
isPartial={isPartial}
/>
<UsageEmptyState>
{selectedEnvironmentId === null
? "No connected environment could report usage."
: "This environment is unavailable for usage."}
</UsageEmptyState>
</>
) : (
<>
<UsageCoverageNotice
environments={environments}
duplicateSources={merged.duplicateSources}
staleEnvironments={merged.staleEnvironments}
isPartial={isPartial}
/>
{/* Cost first: the financial answer, then the provider split. */}
@@ -396,35 +454,67 @@ function Metric({
}
/**
* Says plainly when the totals are incomplete: an environment that failed, or
* one whose transcripts another environment already reported. Environments
* that are still answering never reach this notice; the page shows the
* loading skeleton until every one is terminal.
* Explains incomplete totals without hiding healthy environment data.
*/
function UsageCoverageNotice({
environments,
duplicateSources,
staleEnvironments,
isPartial,
}: {
readonly environments: readonly EnvironmentUsageStatus[];
readonly duplicateSources: readonly string[];
readonly staleEnvironments: readonly string[];
readonly isPartial: boolean;
}) {
const settling = environments.filter(
(environment) => environment.phase === "connecting" || environment.phase === "reconnecting",
);
const unavailable = environments.filter(
(environment) =>
environment.phase === "available" ||
environment.phase === "offline" ||
environment.phase === "error",
);
const failed = environments.filter((environment) => environment.error !== null);
const stale = environments.filter((environment) =>
staleEnvironments.includes(environment.environmentId),
);
if (failed.length === 0 && stale.length === 0 && duplicateSources.length === 0) {
if (
settling.length === 0 &&
unavailable.length === 0 &&
failed.length === 0 &&
stale.length === 0 &&
duplicateSources.length === 0 &&
!isPartial
) {
return null;
}
return (
<div className="flex flex-col gap-1 border border-border px-3 py-2 text-xs text-muted-foreground">
{isPartial ? <span>Some environments are still reporting. Totals are partial.</span> : null}
{settling.map((environment) => (
<span key={environment.environmentId}>
{environment.label} is {environment.phase}.
</span>
))}
{unavailable.map((environment) => (
<span key={environment.environmentId}>
{environment.label} is{" "}
{environment.phase === "available"
? "not connected"
: environment.phase === "error"
? "unavailable"
: environment.phase}
.
</span>
))}
{failed.map((environment) => (
<span key={environment.label}>{environment.label} could not report usage.</span>
<span key={environment.environmentId}>{environment.label} could not report usage.</span>
))}
{stale.map((environment) => (
<span key={environment.label}>
<span key={environment.environmentId}>
{environment.label} runs an older server version and is excluded from totals.
</span>
))}
@@ -438,10 +528,16 @@ function UsageCoverageNotice({
);
}
function UsageEmptyState({ children }: { readonly children: string }) {
return (
<div className="border border-border px-6 py-16 text-center text-sm text-muted-foreground">
{children}
</div>
);
}
/**
* Per-device progress while the page waits for every environment to answer.
* Only rendered with two or more devices; a lone device has nothing to
* enumerate.
* Per-device progress while connected environments answer.
*/
function UsageDeviceStrip({
environments,
@@ -449,7 +545,7 @@ function UsageDeviceStrip({
readonly environments: readonly EnvironmentUsageStatus[];
}) {
const scanning = environments.filter(
(environment) => environment.summary === null && environment.error === null,
(environment) => environment.isPending && environment.summary === null,
);
return (
<div className="flex flex-wrap items-baseline gap-x-4 gap-y-1 border border-border px-3 py-2 text-xs">
@@ -465,7 +561,12 @@ function UsageDeviceStrip({
</span>
);
}
if (environment.error !== null) {
if (
environment.error !== null ||
environment.phase === "available" ||
environment.phase === "offline" ||
environment.phase === "error"
) {
return (
<span
key={environment.environmentId}
+82
View File
@@ -0,0 +1,82 @@
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("usage environment scope", () => {
it("keeps healthy and offline environments in all-environment coverage", () => {
const options = [environment("healthy", "connected"), environment("down", "offline")];
const scope = resolveEnvironmentUsageScope(options, null);
expect(scope.environments).toEqual(options);
expect(isEnvironmentUsageSettling(scope.environments[0]!.phase)).toBe(true);
expect(isEnvironmentUsageSettling(scope.environments[1]!.phase)).toBe(false);
});
it("finishes with healthy totals when another environment is offline", () => {
expect(
getEnvironmentUsageLoadingState([
{ phase: "connected", summary: {}, error: null },
{ phase: "offline", summary: null, error: null },
]),
).toEqual({ isPending: false, isPartial: false });
});
it("returns immediately when the only environment is offline", () => {
expect(
getEnvironmentUsageLoadingState([{ phase: "offline", summary: null, error: null }]),
).toEqual({ isPending: false, isPartial: false });
});
it("keeps healthy totals visible while another environment reconnects", () => {
expect(
getEnvironmentUsageLoadingState([
{ phase: "connected", summary: {}, error: null },
{ phase: "reconnecting", summary: null, error: null },
]),
).toEqual({ isPending: false, isPartial: true });
});
it("shows connection transitions as settling but leaves idle entries terminal", () => {
expect(isEnvironmentUsageSettling("available")).toBe(false);
expect(isEnvironmentUsageSettling("connecting")).toBe(true);
expect(isEnvironmentUsageSettling("reconnecting")).toBe(true);
expect(isEnvironmentUsageSettling("connected")).toBe(true);
expect(isEnvironmentUsageSettling("offline")).toBe(false);
expect(isEnvironmentUsageSettling("error")).toBe(false);
});
it("keeps a selected offline environment terminal and isolated", () => {
const scope = resolveEnvironmentUsageScope(
[environment("healthy", "connected"), environment("down", "offline")],
"down" as EnvironmentId,
);
expect(scope.selectedEnvironmentId).toBe("down");
expect(scope.environments).toEqual([environment("down", "offline")]);
expect(isEnvironmentUsageSettling(scope.environments[0]!.phase)).toBe(false);
});
it("falls back to all environments when the selection disappears", () => {
const options = [environment("healthy", "connected")];
const scope = resolveEnvironmentUsageScope(options, "removed" as EnvironmentId);
expect(scope.selectedEnvironmentId).toBeNull();
expect(scope.environments).toEqual(options);
});
});
+79 -54
View File
@@ -1,8 +1,9 @@
/**
* 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.
*
* @module state/usage
*/
@@ -21,83 +22,108 @@ import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/sh
import { appAtomRegistry } from "../rpc/atomRegistry";
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(`web-usage:window:${windowKey}`)),
return { options, environments, selectedEnvironmentId: scope.selectedEnvironmentId };
}).pipe(Atom.withLabel(`web-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 the button 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
? []
: [
@@ -109,18 +135,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,
};
}
@@ -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,
};
}