Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
845cd352de | ||
|
|
b29c9bbcde | ||
|
|
d0df7fd877 | ||
|
|
7f710c2bc8 | ||
|
|
a381ea94fb | ||
|
|
6b9bcebcc8 | ||
|
|
a0debffc1d |
No files matched your search
@@ -278,6 +278,13 @@ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
|
||||
<Pressable
|
||||
key={action.id ?? `${index}-${action.title}`}
|
||||
android_ripple={{ color: rippleColor }}
|
||||
accessibilityRole="menuitem"
|
||||
accessibilityState={{
|
||||
disabled,
|
||||
...(action.state === undefined
|
||||
? {}
|
||||
: { 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 { DailyTotals, MergedUsage } from "@t3tools/shared/usageMerge";
|
||||
import {
|
||||
enumerateDays,
|
||||
@@ -11,12 +13,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";
|
||||
@@ -41,9 +44,47 @@ export function UsageRouteScreen() {
|
||||
window: makeWindow(30),
|
||||
}));
|
||||
const [metric, setMetric] = useState<UsageChartMetric>("cost");
|
||||
const [environmentFilter, setEnvironmentFilter] = useState<EnvironmentId | null>(null);
|
||||
const { days: windowDays, window } = windowSelection;
|
||||
const isPast24Hours = windowDays === 1;
|
||||
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),
|
||||
@@ -69,10 +110,11 @@ export function UsageRouteScreen() {
|
||||
[isPast24Hours, merged.daily, merged.hourly],
|
||||
);
|
||||
|
||||
// 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.
|
||||
const refreshing = environments.some((entry) => entry.isPending && entry.summary !== null);
|
||||
// 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.phase === "connected" && entry.isPending && entry.summary !== null,
|
||||
);
|
||||
const selectWindow = (days: number) => {
|
||||
setWindowSelection({
|
||||
days,
|
||||
@@ -109,22 +151,52 @@ export function UsageRouteScreen() {
|
||||
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={refreshWindow} />}
|
||||
>
|
||||
<SegmentedControl
|
||||
options={WINDOW_OPTIONS.map((option) => ({ value: option.days, label: option.label }))}
|
||||
selected={windowDays}
|
||||
onSelect={selectWindow}
|
||||
/>
|
||||
<View className="gap-3">
|
||||
<SegmentedControl
|
||||
options={WINDOW_OPTIONS.map((option) => ({
|
||||
value: option.days,
|
||||
label: option.label,
|
||||
}))}
|
||||
selected={windowDays}
|
||||
onSelect={selectWindow}
|
||||
/>
|
||||
<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
|
||||
@@ -449,21 +521,31 @@ 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.isPending &&
|
||||
(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 &&
|
||||
@@ -479,6 +561,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.
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
getEnvironmentUsageLoadingState,
|
||||
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("does not wait indefinitely for a reconnecting environment", () => {
|
||||
expect(
|
||||
getEnvironmentUsageLoadingState([
|
||||
{ phase: "reconnecting", isPending: false, summary: null, error: null },
|
||||
]),
|
||||
).toEqual({ isPending: false, isPartial: false });
|
||||
});
|
||||
|
||||
it("does not let an offline environment hold healthy totals open", () => {
|
||||
expect(
|
||||
getEnvironmentUsageLoadingState([
|
||||
{ phase: "connected", isPending: false, summary: {}, error: null },
|
||||
{ phase: "offline", isPending: false, summary: null, error: null },
|
||||
]),
|
||||
).toEqual({ isPending: false, isPartial: false });
|
||||
});
|
||||
|
||||
it("waits for an initial available connection state", () => {
|
||||
expect(
|
||||
getEnvironmentUsageLoadingState([
|
||||
{ phase: "available", isPending: true, summary: null, error: null },
|
||||
]),
|
||||
).toEqual({ isPending: true, isPartial: false });
|
||||
});
|
||||
|
||||
it("waits for the first connection attempt", () => {
|
||||
expect(
|
||||
getEnvironmentUsageLoadingState([
|
||||
{ phase: "connecting", isPending: true, summary: null, error: null },
|
||||
]),
|
||||
).toEqual({ isPending: true, 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();
|
||||
});
|
||||
});
|
||||
@@ -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,74 +16,109 @@ 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 { environmentCatalog } from "../connection/catalog";
|
||||
import { environmentPresentations } from "./presentation";
|
||||
import { serverEnvironment } from "./server";
|
||||
import {
|
||||
getEnvironmentUsageLoadingState,
|
||||
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 isCatalogReady: boolean;
|
||||
readonly options: readonly EnvironmentUsageOption[];
|
||||
readonly environments: readonly EnvironmentUsageStatus[];
|
||||
}
|
||||
|
||||
const statuses: EnvironmentUsageStatus[] = [];
|
||||
for (const [environmentId, presentation] of presentations) {
|
||||
interface UsageAtomKey {
|
||||
readonly input: UsageSummaryInput;
|
||||
}
|
||||
|
||||
const usageByWindowAtom = Atom.family((key: string) =>
|
||||
Atom.make((get): UsageAtomValue => {
|
||||
const { input } = JSON.parse(key) as UsageAtomKey;
|
||||
const catalog = get(environmentCatalog.catalogValueAtom);
|
||||
const presentations = get(environmentPresentations.presentationsAtom);
|
||||
const options = Array.from(presentations, ([environmentId, presentation]) => ({
|
||||
environmentId,
|
||||
label: presentation.entry.target.label,
|
||||
phase: presentation.connection.phase,
|
||||
}));
|
||||
|
||||
// Keep every environment subscribed while this time window is mounted. Filtering
|
||||
// only the view avoids evicting sibling usage caches when switching scopes.
|
||||
const environments: EnvironmentUsageStatus[] = [];
|
||||
for (const option of options) {
|
||||
const { environmentId } = option;
|
||||
const connectionResult = get(environmentCatalog.stateAtom(environmentId));
|
||||
// Keep reading the environment-scoped atom while disconnected so a prior
|
||||
// successful value remains visible. Wait through the first connection attempt,
|
||||
// then treat retries as terminal coverage so a down machine cannot block the UI.
|
||||
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:
|
||||
(option.phase === "available" && connectionResult.waiting) ||
|
||||
option.phase === "connecting" ||
|
||||
(option.phase === "connected" && 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 {
|
||||
isCatalogReady: catalog.isReady,
|
||||
options,
|
||||
environments,
|
||||
};
|
||||
}).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,
|
||||
resolution: input.resolution,
|
||||
sinceTime: input.sinceTime,
|
||||
untilTime: input.untilTime,
|
||||
input: {
|
||||
sinceDay: input.sinceDay,
|
||||
untilDay: input.untilDay,
|
||||
timeZone: input.timeZone,
|
||||
resolution: input.resolution,
|
||||
sinceTime: input.sinceTime,
|
||||
untilTime: input.untilTime,
|
||||
},
|
||||
}),
|
||||
[
|
||||
input.sinceDay,
|
||||
@@ -94,20 +129,25 @@ export function useUsage(input: UsageSummaryInput): UsageView {
|
||||
input.untilTime,
|
||||
],
|
||||
);
|
||||
const atom = usageByWindowAtom(windowKey);
|
||||
const environments = useAtomValue(atom);
|
||||
const atom = usageByWindowAtom(key);
|
||||
const value = useAtomValue(atom);
|
||||
const scope = resolveEnvironmentUsageScope(value.options, selectedEnvironmentId);
|
||||
const environments = useMemo(() => {
|
||||
if (scope.selectedEnvironmentId === null) return value.environments;
|
||||
return value.environments.filter(
|
||||
(environment) => environment.environmentId === scope.selectedEnvironmentId,
|
||||
);
|
||||
}, [scope.selectedEnvironmentId, value.environments]);
|
||||
|
||||
// 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;
|
||||
const { input } = JSON.parse(key) as UsageAtomKey;
|
||||
for (const environment of environments) {
|
||||
if (environment.phase !== "connected") continue;
|
||||
appAtomRegistry.refresh(
|
||||
serverEnvironment.usageSummary({ environmentId: environment.environmentId, input }),
|
||||
);
|
||||
}
|
||||
}, [environments, windowKey]);
|
||||
}, [environments, key]);
|
||||
|
||||
const merged = useMemo(() => {
|
||||
const answered: EnvironmentUsage[] = environments.flatMap((environment) =>
|
||||
@@ -124,16 +164,15 @@ export function useUsage(input: UsageSummaryInput): UsageView {
|
||||
return mergeUsage(answered, USAGE_CONTRACT_VERSION);
|
||||
}, [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(environments);
|
||||
|
||||
return {
|
||||
merged,
|
||||
options: value.options,
|
||||
environments,
|
||||
isPending: answeredCount === 0 && stillReporting > 0,
|
||||
isPartial: answeredCount > 0 && stillReporting > 0,
|
||||
selectedEnvironmentId: scope.selectedEnvironmentId,
|
||||
isPending: !value.isCatalogReady || loadingState.isPending,
|
||||
isPartial: loadingState.isPartial,
|
||||
refresh,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
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;
|
||||
}
|
||||
|
||||
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 isPending: boolean;
|
||||
readonly summary: unknown | null;
|
||||
readonly error: string | null;
|
||||
}
|
||||
|
||||
export function isEnvironmentUsageStillReporting(
|
||||
environment: EnvironmentUsageLoadingEntry,
|
||||
): boolean {
|
||||
return environment.isPending && environment.summary === null && environment.error === 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(isEnvironmentUsageStillReporting).length;
|
||||
|
||||
return {
|
||||
isPending: answeredCount === 0 && stillReporting > 0,
|
||||
isPartial: answeredCount > 0 && stillReporting > 0,
|
||||
};
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
import type { UsageProviderKind } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, UsageProviderKind } from "@t3tools/contracts";
|
||||
import { CheckIcon, RefreshCwIcon, XIcon } from "lucide-react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import type { DailyTotals, HourlyTotals } from "@t3tools/shared/usageMerge";
|
||||
|
||||
import { isElectron } from "../../env";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
|
||||
import { isEnvironmentUsageStillReporting } from "../../state/usageEnvironmentScope";
|
||||
import {
|
||||
enumerateDays,
|
||||
enumerateHourStarts,
|
||||
@@ -23,6 +24,7 @@ import { ScrollArea } from "../ui/scroll-area";
|
||||
import { SidebarInset } from "../ui/sidebar";
|
||||
import { WorkspaceBreadcrumb, WorkspaceBreadcrumbItem } from "../WorkspaceBreadcrumb";
|
||||
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "../../workspaceTitlebar";
|
||||
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";
|
||||
|
||||
@@ -40,14 +42,21 @@ export function UsagePage() {
|
||||
}));
|
||||
const [metric, setMetric] = useState<UsageChartMetric>("cost");
|
||||
const [breakdown, setBreakdown] = useState<"model" | "time">("model");
|
||||
const [environmentFilter, setEnvironmentFilter] = useState<EnvironmentId | null>(null);
|
||||
const { days: windowDays, window } = windowSelection;
|
||||
const isPast24Hours = windowDays === 1;
|
||||
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),
|
||||
@@ -137,8 +146,43 @@ export function UsagePage() {
|
||||
? `${formatDateTimeShort(window.sinceTime, window.timeZone)} to ${formatDateTimeShort(window.untilTime, window.timeZone)}`
|
||||
: `${formatDayShort(window.sinceDay)} to ${formatDayShort(window.untilDay)}`}
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex rounded-md border border-border">
|
||||
<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
|
||||
key={option.days}
|
||||
@@ -167,17 +211,34 @@ export function UsagePage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{settling ? (
|
||||
{isPending || (usableEnvironmentCount === 0 && isPartial) ? (
|
||||
<>
|
||||
{environments.length > 1 ? <UsageDeviceStrip environments={environments} /> : null}
|
||||
<UsageSkeleton resolution={isPast24Hours ? "hour" : "day"} />
|
||||
</>
|
||||
) : 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. */}
|
||||
@@ -470,35 +531,68 @@ 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.isPending &&
|
||||
(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>
|
||||
))}
|
||||
@@ -512,19 +606,23 @@ 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,
|
||||
}: {
|
||||
readonly environments: readonly EnvironmentUsageStatus[];
|
||||
}) {
|
||||
const scanning = environments.filter(
|
||||
(environment) => environment.summary === null && environment.error === null,
|
||||
);
|
||||
const scanning = environments.filter(isEnvironmentUsageStillReporting);
|
||||
return (
|
||||
<div className="flex flex-wrap items-baseline gap-x-4 gap-y-1 border border-border px-3 py-2 text-xs">
|
||||
{environments.map((environment) => {
|
||||
@@ -539,10 +637,19 @@ function UsageDeviceStrip({
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (environment.error !== null) {
|
||||
if (environment.error !== null || !environment.isPending) {
|
||||
const status =
|
||||
environment.error !== null
|
||||
? "could not report usage"
|
||||
: environment.phase === "available"
|
||||
? "not connected"
|
||||
: environment.phase === "error"
|
||||
? "unavailable"
|
||||
: environment.phase;
|
||||
return (
|
||||
<span
|
||||
key={environment.environmentId}
|
||||
aria-label={`${environment.label}, ${status}`}
|
||||
className="flex items-center gap-1 text-destructive"
|
||||
>
|
||||
<XIcon className="size-3" aria-hidden />
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
getEnvironmentUsageLoadingState,
|
||||
isEnvironmentUsageStillReporting,
|
||||
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);
|
||||
});
|
||||
|
||||
it("finishes with healthy totals when another environment is offline", () => {
|
||||
expect(
|
||||
getEnvironmentUsageLoadingState([
|
||||
{ phase: "connected", isPending: false, summary: {}, error: null },
|
||||
{ phase: "offline", isPending: false, summary: null, error: null },
|
||||
]),
|
||||
).toEqual({ isPending: false, isPartial: false });
|
||||
});
|
||||
|
||||
it("returns immediately when the only environment is offline", () => {
|
||||
expect(
|
||||
getEnvironmentUsageLoadingState([
|
||||
{ phase: "offline", isPending: false, summary: null, error: null },
|
||||
]),
|
||||
).toEqual({ isPending: false, isPartial: false });
|
||||
});
|
||||
|
||||
it("keeps healthy totals visible while another environment reconnects", () => {
|
||||
expect(
|
||||
getEnvironmentUsageLoadingState([
|
||||
{ phase: "connected", isPending: false, summary: {}, error: null },
|
||||
{ phase: "reconnecting", isPending: false, summary: null, error: null },
|
||||
]),
|
||||
).toEqual({ isPending: false, isPartial: false });
|
||||
});
|
||||
|
||||
it("does not wait indefinitely for a reconnecting environment", () => {
|
||||
expect(
|
||||
getEnvironmentUsageLoadingState([
|
||||
{ phase: "reconnecting", isPending: false, summary: null, error: null },
|
||||
]),
|
||||
).toEqual({ isPending: false, isPartial: false });
|
||||
});
|
||||
|
||||
it("uses the same reporting state for loading and device progress", () => {
|
||||
expect(
|
||||
isEnvironmentUsageStillReporting({
|
||||
phase: "connected",
|
||||
isPending: true,
|
||||
summary: null,
|
||||
error: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isEnvironmentUsageStillReporting({
|
||||
phase: "connected",
|
||||
isPending: false,
|
||||
summary: null,
|
||||
error: "failed",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps an initial available connection pending until its state resolves", () => {
|
||||
expect(
|
||||
getEnvironmentUsageLoadingState([
|
||||
{ phase: "available", isPending: true, summary: null, error: null },
|
||||
]),
|
||||
).toEqual({ isPending: true, isPartial: false });
|
||||
});
|
||||
|
||||
it("keeps the first connection attempt pending", () => {
|
||||
expect(
|
||||
getEnvironmentUsageLoadingState([
|
||||
{ phase: "connecting", isPending: true, summary: null, error: null },
|
||||
]),
|
||||
).toEqual({ isPending: true, isPartial: 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")]);
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
+92
-52
@@ -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
|
||||
*/
|
||||
@@ -18,69 +19,104 @@ import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { useCallback, useMemo } from "react";
|
||||
|
||||
import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";
|
||||
import { environmentCatalog } from "../connection/catalog";
|
||||
import { appAtomRegistry } from "../rpc/atomRegistry";
|
||||
import { environmentPresentations } from "./presentation";
|
||||
import { serverEnvironment } from "./server";
|
||||
import {
|
||||
getEnvironmentUsageLoadingState,
|
||||
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 isCatalogReady: boolean;
|
||||
readonly options: readonly EnvironmentUsageOption[];
|
||||
readonly environments: readonly EnvironmentUsageStatus[];
|
||||
}
|
||||
|
||||
const statuses: EnvironmentUsageStatus[] = [];
|
||||
for (const [environmentId, presentation] of presentations) {
|
||||
interface UsageAtomKey {
|
||||
readonly input: UsageSummaryInput;
|
||||
}
|
||||
|
||||
const usageByWindowAtom = Atom.family((key: string) =>
|
||||
Atom.make((get): UsageAtomValue => {
|
||||
const { input } = JSON.parse(key) as UsageAtomKey;
|
||||
const catalog = get(environmentCatalog.catalogValueAtom);
|
||||
const presentations = get(environmentPresentations.presentationsAtom);
|
||||
const options = Array.from(presentations, ([environmentId, presentation]) => ({
|
||||
environmentId,
|
||||
label: presentation.entry.target.label,
|
||||
phase: presentation.connection.phase,
|
||||
}));
|
||||
|
||||
// Keep every environment subscribed while this time window is mounted. Filtering
|
||||
// only the view avoids evicting sibling usage caches when switching scopes.
|
||||
const environments: EnvironmentUsageStatus[] = [];
|
||||
for (const option of options) {
|
||||
const { environmentId } = option;
|
||||
const connectionResult = get(environmentCatalog.stateAtom(environmentId));
|
||||
// Keep reading the environment-scoped atom while disconnected so a prior
|
||||
// successful value remains visible. Wait through the first connection attempt,
|
||||
// then treat retries as terminal coverage so a down machine cannot block the UI.
|
||||
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:
|
||||
(option.phase === "available" && connectionResult.waiting) ||
|
||||
option.phase === "connecting" ||
|
||||
(option.phase === "connected" && 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 {
|
||||
isCatalogReady: catalog.isReady,
|
||||
options,
|
||||
environments,
|
||||
};
|
||||
}).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,
|
||||
resolution: input.resolution,
|
||||
sinceTime: input.sinceTime,
|
||||
untilTime: input.untilTime,
|
||||
input: {
|
||||
sinceDay: input.sinceDay,
|
||||
untilDay: input.untilDay,
|
||||
timeZone: input.timeZone,
|
||||
resolution: input.resolution,
|
||||
sinceTime: input.sinceTime,
|
||||
untilTime: input.untilTime,
|
||||
},
|
||||
}),
|
||||
[
|
||||
input.sinceDay,
|
||||
@@ -91,20 +127,25 @@ export function useUsage(input: UsageSummaryInput): UsageView {
|
||||
input.untilTime,
|
||||
],
|
||||
);
|
||||
const atom = usageByWindowAtom(windowKey);
|
||||
const environments = useAtomValue(atom);
|
||||
const atom = usageByWindowAtom(key);
|
||||
const value = useAtomValue(atom);
|
||||
const scope = resolveEnvironmentUsageScope(value.options, selectedEnvironmentId);
|
||||
const environments = useMemo(() => {
|
||||
if (scope.selectedEnvironmentId === null) return value.environments;
|
||||
return value.environments.filter(
|
||||
(environment) => environment.environmentId === scope.selectedEnvironmentId,
|
||||
);
|
||||
}, [scope.selectedEnvironmentId, value.environments]);
|
||||
|
||||
// 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;
|
||||
const { input } = JSON.parse(key) as UsageAtomKey;
|
||||
for (const environment of environments) {
|
||||
if (environment.phase !== "connected") continue;
|
||||
appAtomRegistry.refresh(
|
||||
serverEnvironment.usageSummary({ environmentId: environment.environmentId, input }),
|
||||
);
|
||||
}
|
||||
}, [environments, windowKey]);
|
||||
}, [environments, key]);
|
||||
|
||||
const merged = useMemo(() => {
|
||||
const answered: EnvironmentUsage[] = environments.flatMap((environment) =>
|
||||
@@ -121,16 +162,15 @@ export function useUsage(input: UsageSummaryInput): UsageView {
|
||||
return mergeUsage(answered, USAGE_CONTRACT_VERSION);
|
||||
}, [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(environments);
|
||||
|
||||
return {
|
||||
merged,
|
||||
options: value.options,
|
||||
environments,
|
||||
isPending: answeredCount === 0 && stillReporting > 0,
|
||||
isPartial: answeredCount > 0 && stillReporting > 0,
|
||||
selectedEnvironmentId: scope.selectedEnvironmentId,
|
||||
isPending: !value.isCatalogReady || loadingState.isPending,
|
||||
isPartial: loadingState.isPartial,
|
||||
refresh,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
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;
|
||||
}
|
||||
|
||||
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 isPending: boolean;
|
||||
readonly summary: unknown | null;
|
||||
readonly error: string | null;
|
||||
}
|
||||
|
||||
export function isEnvironmentUsageStillReporting(
|
||||
environment: EnvironmentUsageLoadingEntry,
|
||||
): boolean {
|
||||
return environment.isPending && environment.summary === null && environment.error === 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(isEnvironmentUsageStillReporting).length;
|
||||
|
||||
return {
|
||||
isPending: answeredCount === 0 && stillReporting > 0,
|
||||
isPartial: answeredCount > 0 && stillReporting > 0,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user