feat(mobile): pool usage limits across selected environments (#10334)

This commit is contained in:
Julius Marminge authored and GitHub committed 2026-09-06 00:57:43 -07:00
1 parent e5d086c262
commit b155c2199b
11 files changed
+719 -279

No files matched your search

+5
View File
@@ -56,6 +56,7 @@ import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteSc
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
import { SettingsProjectGroupingRouteScreen } from "./features/settings/SettingsProjectGroupingRouteScreen";
import { UsageLimitAccountScreen } from "./features/usage/UsageLimitsPooled";
import { UsageRouteScreen } from "./features/usage/UsageRouteScreen";
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";
@@ -192,6 +193,10 @@ const SettingsContentStack = createNativeStackNavigator({
title: "Client Storage",
},
}),
SettingsUsageAccount: createNativeStackScreen({
screen: UsageLimitAccountScreen,
options: { title: "Account" },
}),
SettingsUsage: createNativeStackScreen({
screen: UsageRouteScreen,
linking: "usage",
+3
View File
@@ -31,6 +31,7 @@ import IconChevronRight from "@tabler/icons-react-native/IconChevronRight";
import IconChevronUp from "@tabler/icons-react-native/IconChevronUp";
import IconCircleCheck from "@tabler/icons-react-native/IconCircleCheck";
import IconCircleXFilled from "@tabler/icons-react-native/IconCircleXFilled";
import IconTicket from "@tabler/icons-react-native/IconTicket";
import IconClock from "@tabler/icons-react-native/IconClock";
import IconCode from "@tabler/icons-react-native/IconCode";
import IconCopy from "@tabler/icons-react-native/IconCopy";
@@ -116,6 +117,7 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
checkmark: IconCheck,
"checkmark.circle": IconCircleCheck,
clock: IconClock,
ticket: IconTicket,
cloud: IconCloud,
cube: IconBox,
"chevron.down": IconChevronDown,
@@ -138,6 +140,7 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
"info.circle": IconInfoCircle,
laptopcomputer: IconDeviceLaptop,
link: IconLink,
"line.3.horizontal.decrease": IconFilter,
"line.3.horizontal.decrease.circle": IconFilter,
"line.3.horizontal.decrease.circle.fill": IconFilterFilled,
// Tabler has no Apple desktops; the closest silhouettes stand in on Android.
+13 -5
View File
@@ -9,7 +9,14 @@ import {
useMemo,
useRef,
} from "react";
import { Platform, Pressable, View, type ColorValue, type PressableProps } from "react-native";
import {
Platform,
Pressable,
View,
type ColorValue,
type PressableProps,
type AccessibilityProps,
} from "react-native";
import { withUniwind } from "uniwind";
import { useAppearancePreferences } from "../features/settings/appearance/AppearancePreferencesProvider";
@@ -144,10 +151,11 @@ export function ControlPill(props: {
// AppCompat popup can't be themed past its stock animation, metrics, and
// submenu chrome.
export function ControlPillMenu(
props: Omit<ComponentProps<typeof MenuView>, "children" | "themeVariant"> & {
readonly children: ReactNode;
readonly className?: string;
},
props: Omit<ComponentProps<typeof MenuView>, "children" | "themeVariant"> &
Pick<AccessibilityProps, "accessible" | "accessibilityLabel" | "accessibilityRole"> & {
readonly children: ReactNode;
readonly className?: string;
},
) {
const { themeAppearance } = useAppearancePreferences();
const isDarkMode = themeAppearance === "dark";
@@ -0,0 +1,374 @@
import { useAtomValue } from "@effect/atom-react";
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { EnvironmentId } from "@t3tools/contracts";
import {
collectLimitAccounts,
collectLimitNotices,
collectLimitPools,
formatDuration,
formatResetsIn,
remainingPercent,
type LimitAccount,
type LimitPoolWindow,
} from "@t3tools/shared/usageLimits";
import { useId, useState } from "react";
import { Platform, Pressable, ScrollView, View } from "react-native";
import { Defs, Path, Pattern, Rect, Svg } from "react-native-svg";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import { SymbolView } from "../../components/AppSymbol";
import { AppText as Text } from "../../components/AppText";
import { ProviderIcon } from "../../components/ProviderIcon";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { environmentPresentations } from "../../state/presentation";
import { ResetCredits } from "./UsageLimitsSection";
import { useProviderColors } from "./usageProviders";
const DRIVER_LABEL: Partial<Record<string, string>> = { codex: "Codex", claudeAgent: "Claude" };
const PACE_LABEL = { ahead: "Ahead of pace", on: "On pace", under: "Under pace" } as const;
function accountName(account: LimitAccount) {
if (account.displayName) return account.displayName;
if (!account.email) return DRIVER_LABEL[account.driver] ?? String(account.driver);
const [local = "", domain = ""] = account.email.split("@");
return `${local[0] ?? ""}${domain[0] ?? ""}`.toUpperCase() || "Account";
}
/** The spent share comes back at reset. SVG keeps the hatching static on both platforms. */
function AccountSegment({
remaining,
color,
pending,
}: {
readonly remaining: number;
readonly color: string;
readonly pending: boolean;
}) {
const patternId = useId().replace(/:/g, "");
return (
<Svg width="100%" height="100%" accessible={false}>
<Defs>
<Pattern id={patternId} width={6} height={6} patternUnits="userSpaceOnUse">
<Path d="M-1 1L1 -1M0 6L6 0M5 7L7 5" stroke={color} strokeWidth={1} opacity={0.22} />
</Pattern>
</Defs>
{pending ? (
<Rect
x={`${remaining}%`}
width={`${100 - remaining}%`}
height="100%"
fill={`url(#${patternId})`}
/>
) : null}
<Rect width={`${remaining}%`} height="100%" fill={color} opacity={0.35} />
</Svg>
);
}
function PoolWindowCard({
pool,
color,
now,
environmentIds,
}: {
readonly pool: LimitPoolWindow;
readonly color: string;
readonly now: number;
readonly environmentIds: readonly string[] | null;
}) {
const navigation = useNavigation();
const nextRefill = pool.resets.find((reset) => reset.restoresPercent > 0);
const openAccount = (account: LimitAccount) =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: {
screen: "SettingsUsageAccount",
params: {
accountKey: account.key,
windowId: pool.id,
windowKind: pool.kind,
environmentIds,
now,
},
},
});
return (
<View className="gap-3 rounded-[24px] border-continuous bg-card p-4">
<View className="flex-row items-start justify-between gap-3">
<View className="gap-1">
<Text className="text-sm font-t3-medium text-foreground">{pool.label}</Text>
<View className="flex-row items-baseline gap-1.5">
<Text className="text-3xl font-t3-bold tabular-nums text-foreground">
{pool.remainingPercent}%
</Text>
<Text className="text-sm text-foreground-muted">left</Text>
</View>
</View>
{pool.pace ? (
<Text className="text-xs text-foreground-tertiary">{PACE_LABEL[pool.pace]}</Text>
) : null}
</View>
{nextRefill ? (
<Text className="text-xs tabular-nums text-foreground-muted">
↻ +{nextRefill.restoresPercent}%{" "}
{nextRefill.at <= now ? "now" : `in ${formatDuration(nextRefill.at - now)}`}
</Text>
) : null}
<View className="flex-row gap-1">
{pool.members.map(({ account, window }, index) => (
<Pressable
key={account.key}
accessibilityRole="button"
accessibilityLabel={`Segment ${index + 1}, ${accountName(account)}, ${remainingPercent(window)}% left`}
accessibilityHint="Show account details"
onPress={() => openAccount(account)}
className="h-7 min-w-0 flex-1 overflow-hidden rounded-md bg-subtle"
>
<AccountSegment
remaining={remainingPercent(window)}
color={color}
pending={Boolean(window.resetsAt)}
/>
<View pointerEvents="none" className="absolute inset-0 items-center justify-center">
<Text className="text-xs font-t3-medium tabular-nums text-foreground">
{index + 1}
</Text>
</View>
</Pressable>
))}
</View>
<View>
{pool.members.map(({ account, window }, index) => {
const credits = account.redeem ? (account.limits.resetCredits?.availableCount ?? 0) : 0;
const resetsIn = formatResetsIn(window, now);
return (
<Pressable
key={account.key}
accessibilityRole="button"
accessibilityLabel={`Segment ${index + 1}, ${accountName(account)}, ${remainingPercent(window)}% left${resetsIn ? `, ${resetsIn}` : ""}${credits ? `, ${credits} reset credits banked` : ""}`}
accessibilityHint="Show account details"
onPress={() => openAccount(account)}
className="min-h-[44px] flex-row items-center gap-2 active:opacity-60"
>
<View className="size-5 items-center justify-center overflow-hidden rounded-md bg-subtle-strong">
<Text className="text-xs font-t3-medium tabular-nums text-foreground">
{index + 1}
</Text>
</View>
<Text
numberOfLines={1}
className="min-w-0 flex-1 text-sm font-t3-medium text-foreground"
>
{accountName(account)}
</Text>
<Text className="text-sm font-t3-medium tabular-nums text-foreground">
{remainingPercent(window)}%
</Text>
<View className="flex-row items-center gap-1">
{resetsIn ? (
<Text className="text-xs tabular-nums text-foreground-muted">
{resetsIn.replace("resets in ", "↻ ")}
</Text>
) : null}
{credits ? (
<>
{resetsIn ? <Text className="text-xs text-foreground-tertiary">·</Text> : null}
<SymbolView name="ticket" size={13} tintColorClassName="accent-icon" />
<Text className="text-xs font-t3-medium tabular-nums text-foreground">
{credits}
</Text>
</>
) : null}
</View>
</Pressable>
);
})}
</View>
</View>
);
}
export function UsageLimitsSection({
now,
failedLabels,
selectedEnvironmentIds,
}: {
readonly now: number;
readonly failedLabels: readonly string[];
readonly selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null;
}) {
const presentations = useAtomValue(environmentPresentations.presentationsAtom);
const selected =
selectedEnvironmentIds === null
? presentations
: new Map([...presentations].filter(([id]) => selectedEnvironmentIds.has(id)));
const pools = collectLimitPools(collectLimitAccounts(selected), now);
const notices = collectLimitNotices(selected);
const colors = useProviderColors();
return (
<View className="gap-6">
{failedLabels.length ? (
<Text className="text-sm text-foreground-muted">
{failedLabels.join(", ")} could not refresh limits. Showing the last known values.
</Text>
) : null}
{pools.length === 0 ? (
<Text className="py-12 text-center text-base text-foreground-muted">
{selected.size === 0
? "Select an environment to see limits."
: "No provider on the selected environments reports subscription limits."}
</Text>
) : null}
{pools.map((pool) => (
<View key={pool.driver} className="gap-3">
<View className="flex-row items-center gap-2 px-1">
<ProviderIcon provider={pool.driver} size={18} />
<Text className="text-base font-t3-medium text-foreground">
{DRIVER_LABEL[pool.driver] ?? pool.driver}
</Text>
</View>
{pool.windows.map((window) => (
<PoolWindowCard
key={`${window.kind}:${window.id}`}
pool={window}
color={pool.driver === "claudeAgent" ? colors.claude : colors.codex}
now={now}
environmentIds={selectedEnvironmentIds === null ? null : [...selectedEnvironmentIds]}
/>
))}
</View>
))}
{notices.map((notice) => (
<Text key={notice} className="text-sm text-foreground-muted">
{notice}
</Text>
))}
</View>
);
}
type AccountScreenProps = StaticScreenProps<{
accountKey: string;
windowId: string;
windowKind: LimitPoolWindow["kind"];
environmentIds: readonly string[] | null;
now: number;
}>;
/** Resolve the account again so live quota and credit updates reach the open detail screen. */
export function UsageLimitAccountScreen({ route }: AccountScreenProps) {
const navigation = useNavigation();
const insets = useSafeAreaInsets();
const presentations = useAtomValue(environmentPresentations.presentationsAtom);
const { accountKey, windowId, windowKind, environmentIds, now } = route.params;
const selectedIds =
environmentIds === null ? null : new Set(environmentIds.map((id) => EnvironmentId.make(id)));
const selected =
selectedIds === null
? presentations
: new Map([...presentations].filter(([id]) => selectedIds.has(id)));
const accounts = collectLimitAccounts(selected);
const account = accounts.find((candidate) => candidate.key === accountKey);
const pool = collectLimitPools(accounts, now)
.find((candidate) => candidate.driver === account?.driver)
?.windows.find((candidate) => candidate.id === windowId && candidate.kind === windowKind);
const window = pool?.members.find((member) => member.account.key === accountKey)?.window;
const reset = pool?.resets.find((candidate) => candidate.member.account.key === accountKey);
const [revealed, setRevealed] = useState(false);
return (
<View collapsable={false} className="flex-1 bg-sheet">
{Platform.OS === "android" ? (
<>
<NativeStackScreenOptions options={{ headerShown: false }} />
<AndroidScreenHeader title="Account" onBack={() => navigation.goBack()} />
</>
) : null}
<ScrollView
contentInsetAdjustmentBehavior="automatic"
contentContainerClassName="gap-5 p-5"
contentContainerStyle={{ paddingBottom: insets.bottom + 24 }}
>
{!account || !window ? (
<Text className="text-base text-foreground-muted">
This account is no longer reporting limits on the selected environments.
</Text>
) : (
<>
<View className="gap-2">
<View className="flex-row items-center gap-2">
<ProviderIcon provider={account.driver} size={24} />
<Text className="flex-1 text-xl font-t3-bold text-foreground">
{account.displayName ?? DRIVER_LABEL[account.driver] ?? account.driver}
</Text>
</View>
{account.email ? (
<Pressable
accessibilityRole="button"
accessibilityLabel={revealed ? "Hide account email" : "Reveal account email"}
onPress={() => setRevealed((value) => !value)}
className="min-h-[44px] justify-center"
>
<Text className="text-sm text-foreground-muted">
{revealed ? account.email : "••••••@••••••"}
</Text>
</Pressable>
) : null}
{account.plan ? (
<Text selectable className="text-sm text-foreground-muted">
{account.plan}
</Text>
) : null}
</View>
<View className="gap-3 rounded-[24px] border-continuous bg-card p-4">
<Text className="text-sm font-t3-medium text-foreground">{window.label}</Text>
<Text className="text-3xl font-t3-bold tabular-nums text-foreground">
{remainingPercent(window)}% left
</Text>
{window.resetsAt ? (
<Text selectable className="text-sm text-foreground-muted">
Resets{" "}
{new Date(window.resetsAt).toLocaleString(undefined, {
dateStyle: "medium",
timeStyle: "short",
})}
</Text>
) : null}
{reset && reset.restoresPercent > 0 ? (
<Text className="text-sm text-foreground-muted">
Restores {reset.restoresPercent}% of the pool
</Text>
) : null}
</View>
<View className="gap-2 rounded-[24px] border-continuous bg-card p-4">
<Text className="text-sm font-t3-medium text-foreground">
{account.environments.length ? "Signed in" : "Source"}
</Text>
{account.environments.length ? (
account.environments.map((environment) => (
<Text key={environment.environmentId} className="text-sm text-foreground-muted">
{environment.label}
</Text>
))
) : (
<Text className="text-sm text-foreground-muted">{account.sourceLabel}</Text>
)}
</View>
{account.redeem && account.limits.resetCredits ? (
<View className="gap-3 rounded-[24px] border-continuous bg-card p-4">
<Text className="text-sm font-t3-medium text-foreground">Reset credits</Text>
<ResetCredits
key={`${account.redeem.environmentId}:${account.redeem.instanceId}`}
environmentId={account.redeem.environmentId}
instanceId={account.redeem.instanceId}
credits={account.limits.resetCredits}
now={now}
/>
</View>
) : null}
</>
)}
</ScrollView>
</View>
);
}
@@ -6,18 +6,14 @@ import type {
ServerProvider,
ServerProviderResetCredits,
ServerProviderUsageWindow,
UsageLimitSourceAccount,
UsageProviderKind,
} from "@t3tools/contracts";
import {
collectLimitSources,
collectLimitsGroups,
elapsedShare,
formatDuration,
formatResetsIn,
limitsNotice,
paceOf,
providerLimitsLabel,
remainingPercent,
} from "@t3tools/shared/usageLimits";
import { type ReactNode, useState } from "react";
@@ -28,11 +24,9 @@ import { ProviderIcon } from "../../components/ProviderIcon";
import { environmentPresentations } from "../../state/presentation";
import { serverEnvironment } from "../../state/server";
import { useAtomCommand } from "../../state/use-atom-command";
import { SettingsSection } from "../settings/components/SettingsSection";
import { useProviderColors } from "./usageProviders";
const PACE_LABEL = { ahead: "ahead of pace", on: "on pace", under: "under pace" } as const;
const DRIVER_LABEL: Partial<Record<string, string>> = { codex: "Codex", claudeAgent: "Claude" };
type Driver = ServerProvider["driver"];
@@ -186,7 +180,7 @@ export function ResetCredits(props: {
});
const [busy, setBusy] = useState(false);
const [status, setStatus] = useState<string | null>(null);
if (credits.availableCount === 0 && status === null) return null;
if (dense && credits.availableCount === 0 && status === null) return null;
const expiresIn = credits.nextExpiresAt
? formatDuration(Date.parse(credits.nextExpiresAt) - now)
@@ -237,7 +231,7 @@ export function ResetCredits(props: {
className={
dense
? "rounded-full bg-subtle-strong px-2.5 py-1"
: "rounded-full bg-subtle-strong px-3 py-1.5"
: "min-h-[44px] justify-center rounded-full bg-subtle-strong px-3 py-1.5"
}
>
<Text
@@ -256,57 +250,6 @@ export function ResetCredits(props: {
);
}
function ProviderLimits(props: {
readonly provider: ServerProvider;
readonly environmentId: EnvironmentId;
readonly now: number;
readonly first: boolean;
}) {
const { provider, environmentId, now } = props;
const credits = provider.usageLimits?.resetCredits;
return (
<AccountLimits
driver={provider.driver}
label={DRIVER_LABEL[provider.driver] ?? String(provider.driver)}
instanceLabel={providerLimitsLabel(provider, (driver) => DRIVER_LABEL[driver])}
detail={provider.auth.label}
limits={provider.usageLimits}
now={now}
first={props.first}
footer={
credits ? (
<ResetCredits
environmentId={environmentId}
instanceId={provider.instanceId}
credits={credits}
now={now}
/>
) : undefined
}
/>
);
}
/** Emails stay off the phone screen; the plan and driver identify the row. */
function SourceAccountLimits(props: {
readonly account: UsageLimitSourceAccount;
readonly now: number;
readonly first: boolean;
}) {
const { account } = props;
return (
<AccountLimits
driver={account.driver}
label={DRIVER_LABEL[account.driver] ?? String(account.driver)}
instanceLabel="CLI Proxy"
detail={account.plan}
limits={account.usageLimits}
now={props.now}
first={props.first}
/>
);
}
/**
* Re-probes every provider (and usage-limit source) on each connected
* environment; the fresh snapshots then arrive over the config stream.
@@ -315,107 +258,47 @@ function SourceAccountLimits(props: {
* Environments whose probe failed are named, since their rows keep showing
* the previous quota with nothing else to say so.
*/
export function useRefreshLimits() {
export function useRefreshLimits(selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null = null) {
const presentations = useAtomValue(environmentPresentations.presentationsAtom);
const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
reportFailure: false,
});
const [now, setNow] = useState(() => Date.now());
const [refreshing, setRefreshing] = useState(false);
const [failedLabels, setFailedLabels] = useState<readonly string[]>([]);
const [failedEnvironments, setFailedEnvironments] = useState<
readonly { environmentId: EnvironmentId; label: string }[]
>([]);
// Always toggles `refreshing`, even with nothing to probe: Android's
// RefreshControl keeps its spinner up until it sees true then false.
const refresh = async () => {
const connected = [...presentations].filter(
([, presentation]) => presentation.connection.phase === "connected",
([environmentId, presentation]) =>
presentation.connection.phase === "connected" &&
(selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId)),
);
setRefreshing(true);
try {
const results = await Promise.all(
connected.map(([environmentId]) => refreshProviders({ environmentId, input: {} })),
);
setFailedLabels(
setFailedEnvironments(
connected
.filter((_, index) => results[index]?._tag === "Failure")
.map(([, presentation]) => presentation.entry.target.label),
.map(([environmentId, presentation]) => ({
environmentId,
label: presentation.entry.target.label,
})),
);
} finally {
setNow(Date.now());
setRefreshing(false);
}
};
const failedLabels = failedEnvironments
.filter(
({ environmentId }) =>
selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId),
)
.map(({ label }) => label);
return { now, refreshing, failedLabels, refresh };
}
/**
* Subscription quota windows from every connected environment's providers,
* read from the config each environment already streams.
*/
export function UsageLimitsSection(props: {
readonly now: number;
readonly failedLabels: readonly string[];
}) {
const { now } = props;
const presentations = useAtomValue(environmentPresentations.presentationsAtom);
const groups = collectLimitsGroups(presentations);
const sources = collectLimitSources(presentations);
if (groups.length === 0 && sources.length === 0) {
return (
<Text className="py-16 text-center text-base text-foreground-muted">
No provider on a connected environment reports subscription limits.
</Text>
);
}
return (
<>
{props.failedLabels.length > 0 ? (
<View className="rounded-[16px] border-continuous bg-card px-4 py-3">
<Text className="text-sm text-foreground-muted">
{props.failedLabels.join(", ")} could not refresh limits. Showing the last known values.
</Text>
</View>
) : null}
{groups.map((group) => (
<SettingsSection
key={group.environmentId}
title={group.environmentLabel ?? "Providers"}
card
>
{group.providers.map((provider, index) => (
<ProviderLimits
key={provider.instanceId}
provider={provider}
environmentId={group.environmentId}
now={now}
first={index === 0}
/>
))}
</SettingsSection>
))}
{sources.map((source) => (
<SettingsSection key={source.key} card>
{source.error ? (
<Text className="p-4 text-sm text-foreground-muted">{source.error}</Text>
) : source.accounts.length === 0 ? (
<Text className="p-4 text-sm text-foreground-muted">
{source.hiddenAccountCount > 0
? "All accounts are shown by connected providers."
: "No accounts reported."}
</Text>
) : (
source.accounts.map((account, index) => (
<SourceAccountLimits
key={account.id}
account={account}
now={now}
first={index === 0}
/>
))
)}
</SettingsSection>
))}
</>
);
}
@@ -1,5 +1,10 @@
import { EnvironmentId, USAGE_CONTRACT_VERSION } from "@t3tools/contracts";
import { useNavigation } from "@react-navigation/native";
import type { DailyTotals, MergedUsage } from "@t3tools/shared/usageMerge";
import {
isCompatibleUsageContractVersion,
type DailyTotals,
type MergedUsage,
} from "@t3tools/shared/usageMerge";
import {
enumerateDays,
enumerateHourStarts,
@@ -11,8 +16,9 @@ import {
formatUsd,
makeWindow,
} from "@t3tools/shared/usageFormat";
import { useMemo, useRef, useState } from "react";
import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
import { Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";
import Animated, { Easing, FadeIn, LinearTransition, ReduceMotion } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
@@ -22,7 +28,11 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
import { SettingsSection } from "../settings/components/SettingsSection";
import { UsageDailyChart } from "./UsageDailyChart";
import { UsageLimitsSection, useRefreshLimits } from "./UsageLimitsSection";
import { toggleUsageEnvironment } from "./usageEnvironmentSelection";
import { useRefreshLimits } from "./UsageLimitsSection";
import { UsageLimitsSection } from "./UsageLimitsPooled";
import { ControlPillMenu } from "../../components/ControlPill";
import { SymbolView } from "../../components/AppSymbol";
import type { UsageChartMetric } from "./usageChartData";
import { PROVIDER_LABEL, useProviderColors } from "./usageProviders";
@@ -64,8 +74,13 @@ export function UsageRouteScreen() {
const [metric, setMetric] = useState<UsageChartMetric>("cost");
const { days: windowDays, window } = windowSelection;
const isPast24Hours = windowDays === 1;
const { merged, environments, isPending, isPartial, refresh } = useUsage(window);
const limits = useRefreshLimits();
const [selectedEnvironmentIds, setSelectedEnvironmentIds] =
useState<ReadonlySet<EnvironmentId> | null>(null);
const { merged, environments, selectedEnvironments, isPending, refresh } = useUsage(
window,
selectedEnvironmentIds,
);
const limits = useRefreshLimits(selectedEnvironmentIds);
const days = useMemo(
() => enumerateDays(window.sinceDay, window.untilDay),
@@ -119,18 +134,104 @@ export function UsageRouteScreen() {
});
};
const showEnvironmentFilter = environments.length > 0 || selectedEnvironmentIds !== null;
const hasLoadingEnvironments = selectedEnvironments.some(isUsageLoading);
const filterAccessibilityLabel = hasLoadingEnvironments
? "Filter usage environments, some environments are loading"
: "Filter usage environments";
const filterIcon =
selectedEnvironmentIds === null
? "line.3.horizontal.decrease"
: "line.3.horizontal.decrease.circle.fill";
const environmentActions = useMemo(
() => [
{
id: "all",
title: "All environments",
subtitle: undefined,
state: selectedEnvironmentIds === null ? ("on" as const) : ("off" as const),
},
...environments.map((environment) => ({
id: environment.environmentId,
title: environment.label,
subtitle: usageEnvironmentStatus(environment),
state:
selectedEnvironmentIds === null || selectedEnvironmentIds.has(environment.environmentId)
? ("on" as const)
: ("off" as const),
})),
],
[environments, selectedEnvironmentIds],
);
const selectEnvironment = useCallback(
(value: string) => {
if (value === "all") {
setSelectedEnvironmentIds(null);
return;
}
const id = EnvironmentId.make(value);
setSelectedEnvironmentIds((selected) => toggleUsageEnvironment(selected, environments, id));
},
[environments],
);
const environmentFilter = useMemo(
() =>
showEnvironmentFilter ? (
<ControlPillMenu
accessible
accessibilityRole="button"
accessibilityLabel={filterAccessibilityLabel}
title="Environments"
actions={environmentActions}
onPressAction={({ nativeEvent }) => selectEnvironment(nativeEvent.event)}
>
<Pressable
accessibilityRole="button"
accessibilityLabel={filterAccessibilityLabel}
className={cn(
"items-center justify-center rounded-full",
Platform.OS === "ios" ? "size-[28px]" : "size-[44px]",
)}
>
<SymbolView name={filterIcon} size={22} tintColorClassName="accent-icon" />
{hasLoadingEnvironments ? (
<View
pointerEvents="none"
className="absolute -right-[2px] -top-[2px] size-[9px] rounded-full bg-amber-500"
/>
) : null}
</Pressable>
</ControlPillMenu>
) : null,
[
showEnvironmentFilter,
environmentActions,
selectEnvironment,
filterAccessibilityLabel,
filterIcon,
hasLoadingEnvironments,
],
);
useLayoutEffect(() => {
if (Platform.OS === "ios") {
navigation.setOptions({ headerRight: () => environmentFilter });
}
}, [navigation, environmentFilter]);
return (
<View collapsable={false} className="flex-1 bg-sheet">
{Platform.OS === "android" ? (
<>
<NativeStackScreenOptions options={{ headerShown: false }} />
<AndroidScreenHeader title="Usage" onBack={() => navigation.goBack()} />
<AndroidScreenHeader
title="Usage"
onBack={() => navigation.goBack()}
trailing={environmentFilter}
/>
</>
) : null}
<ScrollView
// Remount at each tab's native top. Scrolling to y: 0 ignores iOS's
// automatic header inset and hides the tab bar under the header.
key={tab}
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
className="flex-1"
@@ -145,60 +246,73 @@ export function UsageRouteScreen() {
>
<SegmentedControl options={TAB_OPTIONS} selected={tab} onSelect={setTab} role="tab" />
{showingLimits ? (
<UsageLimitsSection now={limits.now} failedLabels={limits.failedLabels} />
) : (
<>
{/* Period and metric together: neither applies to Limits, and
both change every number below, so they share one bar. */}
<View className="flex-row items-center gap-3">
<SegmentedControl
options={WINDOW_OPTIONS}
selected={windowDays}
onSelect={selectWindow}
size="compact"
className="flex-1"
/>
<SegmentedControl
options={METRIC_OPTIONS}
selected={metric}
onSelect={setMetric}
size="compact"
className="w-36"
/>
</View>
<UsageCoverageNotice
environments={environments}
merged={merged}
isPartial={isPartial}
<Animated.View
key={tab}
entering={FadeIn.duration(160).reduceMotion(ReduceMotion.System)}
className="gap-6"
>
{showingLimits ? (
<UsageLimitsSection
now={limits.now}
failedLabels={limits.failedLabels}
selectedEnvironmentIds={selectedEnvironmentIds}
/>
{isPending ? (
<Text className="py-16 text-center text-base text-foreground-muted">
Scanning provider transcripts…
</Text>
) : environments.length === 0 ? (
<Text className="py-16 text-center text-base text-foreground-muted">
Connect an environment to see usage.
</Text>
) : (
<>
<ChartCard
merged={merged}
days={chartDays}
daily={chartTotals}
metric={metric}
sinceDay={window.sinceDay}
untilDay={window.untilDay}
isPast24Hours={isPast24Hours}
timeZone={window.timeZone}
) : (
<>
{/* Period and metric together: neither applies to Limits, and
both change every number below, so they share one bar. */}
<View className="flex-row items-center gap-3">
<SegmentedControl
options={WINDOW_OPTIONS}
selected={windowDays}
onSelect={selectWindow}
size="compact"
className="flex-1"
/>
<ProviderSection merged={merged} metric={metric} />
<TotalsSection merged={merged} isPast24Hours={isPast24Hours} />
<ModelsSection merged={merged} />
</>
)}
</>
)}
<SegmentedControl
options={METRIC_OPTIONS}
selected={metric}
onSelect={setMetric}
size="compact"
className="w-36"
/>
</View>
{merged.duplicateSources.length > 0 ? (
<Text className="text-sm text-foreground-muted">
Counted once across environments sharing a transcript directory:{" "}
{merged.duplicateSources.join(", ")}
</Text>
) : null}
{isPending ? (
<Text className="py-16 text-center text-base text-foreground-muted">
Scanning provider transcripts…
</Text>
) : selectedEnvironments.length === 0 ? (
<Text className="py-16 text-center text-base text-foreground-muted">
{environments.length === 0
? "Connect an environment to see usage."
: "Select an environment to see usage."}
</Text>
) : (
<>
<ChartCard
merged={merged}
days={chartDays}
daily={chartTotals}
metric={metric}
sinceDay={window.sinceDay}
untilDay={window.untilDay}
isPast24Hours={isPast24Hours}
timeZone={window.timeZone}
/>
<ProviderSection merged={merged} metric={metric} />
<TotalsSection merged={merged} isPast24Hours={isPast24Hours} />
<ModelsSection merged={merged} />
</>
)}
</>
)}
</Animated.View>
</ScrollView>
</View>
);
@@ -221,25 +335,42 @@ function SegmentedControl<Value extends number | string>(props: {
const compact = props.size === "compact";
return (
<View
accessibilityRole={props.role === "tab" ? "tablist" : undefined}
accessible={false}
className={cn(
"flex-row overflow-hidden rounded-full border-continuous bg-card",
props.className,
)}
>
<Animated.View
pointerEvents="none"
layout={LinearTransition.duration(200)
.easing(Easing.out(Easing.cubic))
.reduceMotion(ReduceMotion.System)}
className="absolute bottom-0 top-0 rounded-full bg-subtle-strong"
style={{
width: `${100 / props.options.length}%`,
start: `${
(Math.max(
0,
props.options.findIndex((option) => option.value === props.selected),
) *
100) /
props.options.length
}%`,
}}
/>
{props.options.map((option) => {
const active = option.value === props.selected;
return (
<Pressable
key={String(option.value)}
accessibilityRole={props.role ?? "button"}
accessibilityLabel={option.accessibilityLabel}
accessibilityRole={Platform.OS === "ios" ? "button" : (props.role ?? "button")}
accessibilityLabel={option.accessibilityLabel ?? option.label}
accessibilityState={{ selected: active }}
onPress={() => props.onSelect(option.value)}
className={cn(
"flex-1 items-center justify-center rounded-full",
compact ? "h-9" : "h-11",
active && "bg-subtle-strong",
)}
>
<Text
@@ -491,48 +622,22 @@ function ModelsSection(props: { readonly merged: MergedUsage }) {
* one that failed, or one whose transcripts another environment already
* reported.
*/
function UsageCoverageNotice(props: {
readonly environments: readonly EnvironmentUsageStatus[];
readonly merged: MergedUsage;
readonly isPartial: boolean;
}) {
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 (
failed.length === 0 &&
stale.length === 0 &&
duplicateSources.length === 0 &&
!props.isPartial
) {
return null;
}
return (
<View className="gap-1 rounded-[16px] border-continuous bg-card px-4 py-3">
{props.isPartial ? (
<Text className="text-sm text-foreground-muted">
Some environments are still reporting. Totals are partial.
</Text>
) : null}
{failed.map((environment) => (
<Text key={environment.environmentId} className="text-sm text-foreground-muted">
{environment.label} could not report usage.
</Text>
))}
{stale.map((environment) => (
<Text key={environment.environmentId} className="text-sm text-foreground-muted">
{environment.label} runs an older server version and is excluded from totals.
</Text>
))}
{duplicateSources.length > 0 ? (
<Text className="text-sm text-foreground-muted">
Counted once across environments sharing a transcript directory:{" "}
{duplicateSources.join(", ")}
</Text>
) : null}
</View>
);
function isUsageLoading(environment: EnvironmentUsageStatus) {
return environment.isPending || (environment.summary === null && environment.error === null);
}
function usageEnvironmentStatus(environment: EnvironmentUsageStatus): string {
if (
environment.summary &&
!isCompatibleUsageContractVersion(environment.summary.contractVersion, USAGE_CONTRACT_VERSION)
) {
return "Older server · excluded from usage totals";
}
if (!environment.isConnected)
return environment.summary ? "Disconnected · showing saved usage" : "Waiting for connection…";
if (environment.error)
return environment.summary ? "Usage unavailable · showing saved totals" : "Usage unavailable";
if (isUsageLoading(environment))
return environment.summary ? "Updating usage…" : "Loading usage…";
return "Usage up to date";
}
@@ -0,0 +1,40 @@
import { EnvironmentId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { toggleUsageEnvironment } from "./usageEnvironmentSelection";
const a = EnvironmentId.make("a");
const b = EnvironmentId.make("b");
const c = EnvironmentId.make("c");
const removed = EnvironmentId.make("removed");
const environments = [a, b, c].map((environmentId) => ({ environmentId }));
describe("usage environment selection", () => {
it("can exclude an environment from all, then select all again", () => {
const selected = toggleUsageEnvironment(null, environments, b);
expect(selected).toEqual(new Set([a, c]));
expect(toggleUsageEnvironment(selected, environments, b)).toBeNull();
});
it("can deselect the last environment", () => {
expect(toggleUsageEnvironment(new Set([a]), environments, a)).toEqual(new Set());
});
it("does not count removed IDs toward selecting all current environments", () => {
expect(toggleUsageEnvironment(new Set([a, removed]), environments, b)).toEqual(new Set([a, b]));
});
it("returns to all mode despite stale IDs when every current environment is selected", () => {
expect(toggleUsageEnvironment(new Set([a, c, removed]), environments, b)).toBeNull();
});
it("ignores a menu action for an environment that was removed", () => {
expect(toggleUsageEnvironment(new Set([a]), environments, removed)).toEqual(new Set([a]));
});
it("includes newly connected environments only in all mode", () => {
const expanded = [...environments, { environmentId: removed }];
expect(toggleUsageEnvironment(null, expanded, a)).toEqual(new Set([b, c, removed]));
expect(toggleUsageEnvironment(new Set([a, b, c]), expanded, a)).toEqual(new Set([b, c]));
});
});
@@ -0,0 +1,16 @@
import type { EnvironmentId } from "@t3tools/contracts";
/** Null follows all environments, including ones connected after the menu opened. */
export function toggleUsageEnvironment(
selected: ReadonlySet<EnvironmentId> | null,
environments: readonly { readonly environmentId: EnvironmentId }[],
toggledId: EnvironmentId,
): ReadonlySet<EnvironmentId> | null {
const ids = environments.map(({ environmentId }) => environmentId);
const next = new Set(ids.filter((id) => selected === null || selected.has(id)));
if (ids.includes(toggledId)) {
if (next.has(toggledId)) next.delete(toggledId);
else next.add(toggledId);
}
return ids.every((id) => next.has(id)) ? null : next;
}
+24 -8
View File
@@ -30,6 +30,7 @@ export interface EnvironmentUsageStatus {
readonly environmentId: EnvironmentId;
readonly label: string;
readonly isPending: boolean;
readonly isConnected: boolean;
readonly error: string | null;
readonly summary: UsageSummary | null;
}
@@ -53,6 +54,7 @@ const usageByWindowAtom = Atom.family((windowKey: string) =>
environmentId,
label: presentation.entry.target.label,
isPending: result.waiting,
isConnected: presentation.connection.phase === "connected",
error: result._tag === "Failure" ? "This environment could not report usage." : null,
summary: Option.getOrNull(AsyncResult.value(result)),
});
@@ -64,18 +66,22 @@ const usageByWindowAtom = Atom.family((windowKey: string) =>
export interface UsageView {
readonly merged: MergedUsage;
readonly environments: readonly EnvironmentUsageStatus[];
readonly selectedEnvironments: readonly EnvironmentUsageStatus[];
/** True until at least one 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
* environments are reported in the environment menu: totals will not
* improve by waiting on them, so they must not read as "still reporting".
*/
readonly isPartial: boolean;
readonly refresh: (input?: UsageSummaryInput) => Promise<void>;
}
export function useUsage(input: UsageSummaryInput): UsageView {
export function useUsage(
input: UsageSummaryInput,
selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null = null,
): UsageView {
const windowKey = useMemo(
() =>
JSON.stringify({
@@ -97,6 +103,13 @@ export function useUsage(input: UsageSummaryInput): UsageView {
);
const atom = usageByWindowAtom(windowKey);
const environments = useAtomValue(atom);
const selectedEnvironments = useMemo(
() =>
selectedEnvironmentIds === null
? environments
: environments.filter(({ environmentId }) => selectedEnvironmentIds.has(environmentId)),
[environments, selectedEnvironmentIds],
);
const refresh = useCallback(
(nextInput?: UsageSummaryInput) =>
@@ -104,14 +117,14 @@ export function useUsage(input: UsageSummaryInput): UsageView {
registry: appAtomRegistry,
server: serverEnvironment,
presentations: environmentPresentations,
environmentIds: environments.map(({ environmentId }) => environmentId),
environmentIds: selectedEnvironments.map(({ environmentId }) => environmentId),
input: nextInput ?? (JSON.parse(windowKey) as UsageSummaryInput),
}),
[environments, windowKey],
[selectedEnvironments, windowKey],
);
const merged = useMemo(() => {
const answered: EnvironmentUsage[] = environments.flatMap((environment) =>
const answered: EnvironmentUsage[] = selectedEnvironments.flatMap((environment) =>
environment.summary === null
? []
: [
@@ -123,16 +136,19 @@ export function useUsage(input: UsageSummaryInput): UsageView {
],
);
return mergeUsage(answered, USAGE_CONTRACT_VERSION);
}, [environments]);
}, [selectedEnvironments]);
const answeredCount = environments.filter((environment) => environment.summary !== null).length;
const stillReporting = environments.filter(
const answeredCount = selectedEnvironments.filter(
(environment) => environment.summary !== null,
).length;
const stillReporting = selectedEnvironments.filter(
(environment) => environment.summary === null && environment.error === null,
).length;
return {
merged,
environments,
selectedEnvironments,
isPending: answeredCount === 0 && stillReporting > 0,
isPartial: answeredCount > 0 && stillReporting > 0,
refresh,
+4 -4
View File
@@ -39,14 +39,14 @@ the dialog.
## Track subscription limits
On web and desktop, **Usage → Limits** pools every subscription account it can see per provider, so with several Codex
**Usage → Limits** pools every subscription account it can see per provider, so with several Codex
or Claude accounts across your environments and hubs you read one number per window rather than a
list. Each window card shows how much of the pool is left and a bar with one segment per account,
ordered by which resets soonest; when the provider reports reset times, the card also says when
the next reset lands and how much it hands back. The hatched
part of a segment is what that reset restores. Tap or hover a segment for the account's plan, where it is
signed in, and its reset time; Codex accounts with banked reset credits show a ticket count on the
segment and the **Use reset** action in that popover. On narrow screens, numbered rows below
part of a segment is what that reset restores. Tap a segment or account row for the account's plan,
where it is signed in, and its reset time. On web, you can hover too. Codex accounts with banked
reset credits show a ticket count and the **Use reset** action in the account details. On narrow screens, numbered rows below
the bar show each account's quota, countdown, and credits. Tap a row to open its details.
The same account signed in on more than one environment, or reported by a hub as well, counts once.
+6 -16
View File
@@ -209,7 +209,7 @@ export function collectLimitAccounts(
// the freshest native snapshot supplies both, or neither.
const native = [previous, next]
.filter((candidate) => candidate.redeem !== null)
.toSorted((a, b) => Date.parse(b.limits.checkedAt) - Date.parse(a.limits.checkedAt))[0];
.sort((a, b) => Date.parse(b.limits.checkedAt) - Date.parse(a.limits.checkedAt))[0];
accounts.set(key, {
...previous,
displayName: previous.displayName ?? next.displayName,
@@ -374,7 +374,7 @@ export function collectLimitPools(
else byDriver.set(account.driver, [account]);
}
return [...byDriver].map(([driver, members]) => {
const sorted = members.toSorted(
const sorted = [...members].sort(
(left, right) =>
Number(left.redeem === null) - Number(right.redeem === null) ||
accountSortName(left).localeCompare(accountSortName(right)),
@@ -398,7 +398,7 @@ function poolWindows(accounts: readonly LimitAccount[], now: number): readonly L
}
}
const pools = [...byKey.values()].map((unordered): LimitPoolWindow => {
const members = unordered.toSorted(
const members = [...unordered].sort(
(left, right) =>
(resetMillis(left.window) ?? Number.POSITIVE_INFINITY) -
(resetMillis(right.window) ?? Number.POSITIVE_INFINITY),
@@ -428,7 +428,7 @@ function poolWindows(accounts: readonly LimitAccount[], now: number): readonly L
},
];
})
.toSorted((left, right) => left.at - right.at);
.sort((left, right) => left.at - right.at);
return {
id: first.id,
kind: first.kind,
@@ -440,17 +440,7 @@ function poolWindows(accounts: readonly LimitAccount[], now: number): readonly L
resets,
};
});
return pools.toSorted(
(left, right) => WINDOW_KIND_ORDER[left.kind] - WINDOW_KIND_ORDER[right.kind],
);
}
/** The instance's configured name, else the driver's, else its raw kind. */
export function providerLimitsLabel(
provider: Pick<ServerProvider, "driver" | "displayName">,
driverLabel: (driver: ServerProvider["driver"]) => string | undefined,
): string {
return provider.displayName?.trim() || driverLabel(provider.driver) || String(provider.driver);
return pools.sort((left, right) => WINDOW_KIND_ORDER[left.kind] - WINDOW_KIND_ORDER[right.kind]);
}
/** The one-line status under a provider heading when there are no bars to draw. */
@@ -627,7 +617,7 @@ export function collectProviderUsageLimits(
accounts.push({
id: provider.instanceId,
driver: provider.driver,
label: `${providerLimitsLabel(provider, () => undefined)} [${provider.instanceId}]`,
label: `${provider.displayName?.trim() || String(provider.driver)} [${provider.instanceId}]`,
...(provider.auth.label ? { plan: provider.auth.label } : {}),
instanceId: provider.instanceId,
...(provider.displayName ? { displayName: provider.displayName } : {}),