TypeScript
feat(mobile): split the usage page into Usage and Limits tabs (#9775)
Julius Marminge24aef0e6c1bd
diff --git a/apps/mobile/src/features/usage/UsageLimitsSection.tsx b/apps/mobile/src/features/usage/UsageLimitsSection.tsxindex 08e939e9b4b..0668efa3005 100644--- a/apps/mobile/src/features/usage/UsageLimitsSection.tsx+++ b/apps/mobile/src/features/usage/UsageLimitsSection.tsx@@ -7,6 +7,7 @@ import type {ServerProviderResetCredits,ServerProviderUsageWindow,UsageLimitSourceAccount,+ UsageProviderKind,} from "@t3tools/contracts";import {collectLimitSources,@@ -22,30 +23,46 @@ import { type ReactNode, useState } from "react";import { Alert, Pressable, View } from "react-native";import { AppText as Text } from "../../components/AppText";+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"];++/** The series colour the usage chart uses for this driver, so the two views read as one. */+function useBarColor(driver: Driver): string | null {+ const colors = useProviderColors();+ const kind: UsageProviderKind | null =+ driver === "codex" ? "codex" : driver === "claudeAgent" ? "claude" : null;+ return kind ? colors[kind] : null;+}+/*** One window as a bar spanning its whole duration: the fill is quota spent,- * the hairline is how far into the window the clock is.+ * the hairline is how far into the window the clock is. Pace sits under the+ * left edge, the countdown under the right, so a row reads in one glance.*/-function WindowBar(props: { readonly window: ServerProviderUsageWindow; readonly now: number }) {+function WindowRow(props: {+ readonly window: ServerProviderUsageWindow;+ readonly color: string | null;+ readonly now: number;+}) {const { window, now } = props;const used = Math.round(Math.max(0, Math.min(100, window.usedPercent)));const elapsed = elapsedShare(window, now);const pace = paceOf(window, now);const resetsIn = formatResetsIn(window, now);- const detail = [pace ? PACE_LABEL[pace] : null, resetsIn].filter(Boolean).join(" · ");return (- <View className="gap-1.5">+ <View className="gap-1"><View className="flex-row items-baseline justify-between gap-3">- <Text className="text-base text-foreground">{window.label}</Text>- <Text className="text-base tabular-nums text-foreground">{used}% used</Text>+ <Text className="text-sm text-foreground">{window.label}</Text>+ <Text className="text-sm font-t3-medium tabular-nums text-foreground">{used}%</Text></View><View className="h-3 justify-center"><View className="h-1.5 flex-row overflow-hidden rounded-full bg-subtle">@@ -57,7 +74,10 @@ function WindowBar(props: { readonly window: ServerProviderUsageWindow; readonly? "h-full rounded-full bg-warning": "h-full rounded-full bg-foreground"}- style={{ flex: used }}+ style={[+ { flex: used },+ used < 70 && props.color ? { backgroundColor: props.color } : null,+ ]}/><View style={{ flex: 100 - used }} /></View>@@ -68,12 +88,19 @@ function WindowBar(props: { readonly window: ServerProviderUsageWindow; readonly/>) : null}</View>- {detail ? <Text className="text-xs text-foreground-tertiary">{detail}</Text> : null}+ {pace || resetsIn ? (+ <View className="flex-row justify-between gap-3">+ <Text className="text-xs text-foreground-tertiary">{pace ? PACE_LABEL[pace] : ""}</Text>+ <Text className="text-xs tabular-nums text-foreground-tertiary">{resetsIn ?? ""}</Text>+ </View>+ ) : null}</View>);}+/** One account: icon, name and plan on a single line, then its windows. */function AccountLimits(props: {+ readonly driver: Driver;readonly label: string;readonly instanceLabel: string;readonly detail: string | undefined;@@ -83,23 +110,35 @@ function AccountLimits(props: {readonly footer?: ReactNode;}) {const { limits, now } = props;+ const color = useBarColor(props.driver);if (!limits) return null;const notice = limitsNotice(limits);return (<View className={props.first ? "gap-3 p-4" : "gap-3 border-t border-border-subtle p-4"}>- <View className="flex-row flex-wrap items-baseline gap-x-2 gap-y-1">- <Text className="text-lg text-foreground">{props.label}</Text>- {props.instanceLabel !== props.label ? (- <Text className="shrink text-xs text-foreground-tertiary">· {props.instanceLabel}</Text>- ) : null}- {props.detail ? (- <Text className="shrink text-sm text-foreground-muted">· {props.detail}</Text>- ) : null}+ <View className="flex-row items-center gap-2">+ <ProviderIcon provider={props.driver} size={16} />+ <View className="min-w-0 flex-1 flex-row items-baseline gap-2">+ <Text className="text-base font-t3-medium text-foreground">{props.label}</Text>+ {props.instanceLabel !== props.label ? (+ <Text className="shrink text-xs text-foreground-tertiary" numberOfLines={1}>+ · {props.instanceLabel}+ </Text>+ ) : null}+ {props.detail ? (+ <Text className="shrink text-sm text-foreground-muted" numberOfLines={1}>+ · {props.detail}+ </Text>+ ) : null}+ </View></View>{notice ? (<Text className="text-sm text-foreground-muted">{notice}</Text>) : (- limits.windows.map((window) => <WindowBar key={window.id} window={window} now={now} />)+ <View className="gap-3">+ {limits.windows.map((window) => (+ <WindowRow key={window.id} window={window} color={color} now={now} />+ ))}+ </View>)}{props.footer}</View>@@ -170,7 +209,7 @@ function ResetCredits(props: {};return (- <View className="gap-2">+ <View className="flex-row flex-wrap items-center gap-x-3 gap-y-1"><Text className="text-xs tabular-nums text-foreground-tertiary">{summary}</Text>{credits.availableCount > 0 ? (<Pressable@@ -178,7 +217,7 @@ function ResetCredits(props: {accessibilityState={{ disabled: busy }}disabled={busy}onPress={confirm}- className="self-start rounded-full bg-subtle-strong px-3 py-1.5"+ className="rounded-full bg-subtle-strong px-3 py-1.5"><Text className="text-sm font-t3-medium text-foreground">{busy ? "Using credit…" : "Use a reset credit"}@@ -200,6 +239,7 @@ function ProviderLimits(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}@@ -229,6 +269,7 @@ function SourceAccountLimits(props: {const { account } = props;return (<AccountLimits+ driver={account.driver}label={DRIVER_LABEL[account.driver] ?? String(account.driver)}instanceLabel="CLI Proxy"detail={account.plan}@@ -239,21 +280,93 @@ function SourceAccountLimits(props: {);}+/**+ * Re-probes every provider (and usage-limit source) on each connected+ * environment; the fresh snapshots then arrive over the config stream.+ * Countdowns and pace anchor to `now` rather than ticking, so a refresh also+ * re-anchors the clock: quota and elapsed time move together, or not at all.+ * Environments whose probe failed are named, since their rows keep showing+ * the previous quota with nothing else to say so.+ */+export function useRefreshLimits() {+ 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[]>([]);+ // 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",+ );+ setRefreshing(true);+ try {+ const results = await Promise.all(+ connected.map(([environmentId]) => refreshProviders({ environmentId, input: {} })),+ );+ setFailedLabels(+ connected+ .filter((_, index) => results[index]?._tag === "Failure")+ .map(([, presentation]) => presentation.entry.target.label),+ );+ } finally {+ setNow(Date.now());+ setRefreshing(false);+ }+ };+ return { now, refreshing, failedLabels, refresh };+}+/*** Subscription quota windows from every connected environment's providers,- * read from the config each environment already streams. Countdowns anchor to- * render time rather than ticking.+ * read from the config each environment already streams.*/-export function UsageLimitsSection() {+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);- // Anchored once per mount on purpose: countdowns must not tick.- const [now] = useState(() => Date.now());- if (groups.length === 0 && sources.length === 0) return null;++ 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 ? (@@ -276,23 +389,6 @@ export function UsageLimitsSection() {)}</SettingsSection>))}- {groups.map((group) => (- <SettingsSection- key={group.environmentId}- title={group.environmentLabel ? `Limits · ${group.environmentLabel}` : "Limits"}- card- >- {group.providers.map((provider, index) => (- <ProviderLimits- key={provider.instanceId}- provider={provider}- environmentId={group.environmentId}- now={now}- first={index === 0}- />- ))}- </SettingsSection>- ))}</>);}diff --git a/apps/mobile/src/features/usage/UsageRouteScreen.tsx b/apps/mobile/src/features/usage/UsageRouteScreen.tsxindex 6e913b4999d..be7c36173f1 100644--- a/apps/mobile/src/features/usage/UsageRouteScreen.tsx+++ b/apps/mobile/src/features/usage/UsageRouteScreen.tsx@@ -11,32 +11,52 @@ import {formatUsd,makeWindow,} from "@t3tools/shared/usageFormat";-import { useMemo, useState } from "react";+import { useMemo, useRef, 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 { cn } from "../../lib/cn";import { NativeStackScreenOptions } from "../../native/StackHeader";import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";import { SettingsSection } from "../settings/components/SettingsSection";import { UsageDailyChart } from "./UsageDailyChart";-import { UsageLimitsSection } from "./UsageLimitsSection";+import { UsageLimitsSection, useRefreshLimits } from "./UsageLimitsSection";import type { UsageChartMetric } from "./usageChartData";import { PROVIDER_LABEL, useProviderColors } from "./usageProviders";+type UsageTab = "usage" | "limits";+const TAB_OPTIONS = [+ { value: "usage", label: "Usage" },+ { value: "limits", label: "Limits" },+] as const satisfies readonly { value: UsageTab; label: string }[];++// Labels are abbreviated to share a row with the metric toggle; screen+// readers get the full phrase.const WINDOW_OPTIONS = [- { days: 1, label: "Past 24h" },- { days: 7, label: "7 days" },- { days: 30, label: "30 days" },- { days: 90, label: "90 days" },+ { value: 1, label: "24h", accessibilityLabel: "Past 24 hours" },+ { value: 7, label: "7d", accessibilityLabel: "Past 7 days" },+ { value: 30, label: "30d", accessibilityLabel: "Past 30 days" },+ { value: 90, label: "90d", accessibilityLabel: "Past 90 days" },] as const;+const METRIC_OPTIONS = [+ { value: "cost", label: "Cost" },+ { value: "tokens", label: "Tokens" },+] as const satisfies readonly { value: UsageChartMetric; label: string }[];+const CHART_HEIGHT = 180;+/**+ * Two tabs over one screen. Usage is the transcript-derived spend for a+ * period; Limits is the live subscription quota, which has no period. Both+ * pull to refresh, each refreshing its own data.+ */export function UsageRouteScreen() {const navigation = useNavigation();const insets = useSafeAreaInsets();+ const [tab, setTab] = useState<UsageTab>("usage");const [windowSelection, setWindowSelection] = useState(() => ({days: 30,window: makeWindow(30),@@ -45,6 +65,7 @@ export function UsageRouteScreen() {const { days: windowDays, window } = windowSelection;const isPast24Hours = windowDays === 1;const { merged, environments, isPending, isPartial, refresh } = useUsage(window);+ const limits = useRefreshLimits();const days = useMemo(() => enumerateDays(window.sinceDay, window.untilDay),@@ -73,7 +94,16 @@ export function UsageRouteScreen() {// 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);+ const refreshingUsage = environments.some((entry) => entry.isPending && entry.summary !== null);+ const showingLimits = tab === "limits";+ // One ScrollView serves both tabs, so the offset would otherwise carry over+ // and a short Limits list could open scrolled past its own content.+ const scrollRef = useRef<ScrollView>(null);+ const selectTab = (next: UsageTab) => {+ if (next === tab) return;+ setTab(next);+ scrollRef.current?.scrollTo({ y: 0, animated: false });+ };const selectWindow = (days: number) => {setWindowSelection({days,@@ -103,46 +133,73 @@ export function UsageRouteScreen() {</>) : null}<ScrollView+ ref={scrollRef}contentInsetAdjustmentBehavior="automatic"showsVerticalScrollIndicator={false}className="flex-1"contentContainerClassName="gap-6 px-5 pt-4"contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}- refreshControl={<RefreshControl refreshing={refreshing} onRefresh={refreshWindow} />}+ refreshControl={+ <RefreshControl+ refreshing={showingLimits ? limits.refreshing : refreshingUsage}+ onRefresh={showingLimits ? () => void limits.refresh() : refreshWindow}+ />+ }>- <SegmentedControl- options={WINDOW_OPTIONS.map((option) => ({ value: option.days, label: option.label }))}- selected={windowDays}- onSelect={selectWindow}- />-- <UsageCoverageNotice environments={environments} merged={merged} isPartial={isPartial} />+ <SegmentedControl options={TAB_OPTIONS} selected={tab} onSelect={selectTab} role="tab" />- {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>+ {showingLimits ? (+ <UsageLimitsSection now={limits.now} failedLabels={limits.failedLabels} />) : (<>- <ChartCard+ {/* 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}- days={chartDays}- daily={chartTotals}- metric={metric}- onMetricChange={setMetric}- sinceDay={window.sinceDay}- untilDay={window.untilDay}- isPast24Hours={isPast24Hours}- timeZone={window.timeZone}+ isPartial={isPartial}/>- <ProviderSection merged={merged} metric={metric} />- <UsageLimitsSection />- <TotalsSection merged={merged} isPast24Hours={isPast24Hours} />- <ModelsSection merged={merged} />+ {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}+ />+ <ProviderSection merged={merged} metric={metric} />+ <TotalsSection merged={merged} isPast24Hours={isPast24Hours} />+ <ModelsSection merged={merged} />+ </>+ )}</>)}</ScrollView>@@ -151,30 +208,48 @@ export function UsageRouteScreen() {}function SegmentedControl<Value extends number | string>(props: {- readonly options: readonly { readonly value: Value; readonly label: string }[];+ readonly options: readonly {+ readonly value: Value;+ readonly label: string;+ readonly accessibilityLabel?: string;+ }[];readonly selected: Value;readonly onSelect: (value: Value) => void;+ /** The tab bar is full height; filters under it are shorter so it stays primary. */+ readonly size?: "default" | "compact";+ /** "tab" for the view switcher; filters stay plain buttons. */+ readonly role?: "tab" | "button";+ readonly className?: string;}) {+ const compact = props.size === "compact";return (- <View className="flex-row overflow-hidden rounded-full border-continuous bg-card">+ <View+ accessibilityRole={props.role === "tab" ? "tablist" : undefined}+ className={cn(+ "flex-row overflow-hidden rounded-full border-continuous bg-card",+ props.className,+ )}+ >{props.options.map((option) => {const active = option.value === props.selected;return (<Pressablekey={String(option.value)}- accessibilityRole="button"+ accessibilityRole={props.role ?? "button"}+ accessibilityLabel={option.accessibilityLabel}accessibilityState={{ selected: active }}onPress={() => props.onSelect(option.value)}- className={- active- ? "flex-1 items-center rounded-full bg-subtle-strong py-2"- : "flex-1 items-center py-2"- }+ className={cn(+ "flex-1 items-center justify-center rounded-full",+ compact ? "h-9" : "h-11",+ active && "bg-subtle-strong",+ )}><Text- className={- active ? "text-sm font-t3-medium text-foreground" : "text-sm text-foreground-muted"- }+ className={cn(+ compact ? "text-xs" : "text-sm",+ active ? "font-t3-medium text-foreground" : "text-foreground-muted",+ )}>{option.label}</Text>@@ -191,7 +266,6 @@ function ChartCard(props: {readonly days: readonly string[];readonly daily: readonly DailyTotals[];readonly metric: UsageChartMetric;- readonly onMetricChange: (metric: UsageChartMetric) => void;readonly sinceDay: string;readonly untilDay: string;readonly isPast24Hours: boolean;@@ -203,21 +277,18 @@ function ChartCard(props: {return (<View className="gap-4 rounded-[24px] border-continuous bg-card p-4">- <View className="flex-row items-start justify-between gap-3">- <View className="min-w-0 flex-1 gap-0.5">- <Text className="text-sm text-foreground-muted">- {metric === "cost" ? "Raw token cost" : "Processed tokens"}- </Text>- <Text className="text-4xl font-t3-bold tabular-nums text-foreground">- {metric === "cost" ? `${formatUsd(merged.costUsd)}*` : formatTokens(merged.totalTokens)}- </Text>- <Text className="text-sm text-foreground-muted">- {metric === "cost"- ? "* if billed at full API rate"- : `Across ${formatCount(merged.sessions)} sessions`}- </Text>- </View>- <MetricToggle metric={metric} onChange={props.onMetricChange} />+ <View className="gap-0.5">+ <Text className="text-sm text-foreground-muted">+ {metric === "cost" ? "Raw token cost" : "Processed tokens"}+ </Text>+ <Text className="text-4xl font-t3-bold tabular-nums text-foreground">+ {metric === "cost" ? `${formatUsd(merged.costUsd)}*` : formatTokens(merged.totalTokens)}+ </Text>+ <Text className="text-sm text-foreground-muted">+ {metric === "cost"+ ? "* if billed at full API rate"+ : `Across ${formatCount(merged.sessions)} sessions`}+ </Text></View>{hasActivity ? (@@ -262,38 +333,6 @@ function ChartCard(props: {);}-function MetricToggle(props: {- readonly metric: UsageChartMetric;- readonly onChange: (metric: UsageChartMetric) => void;-}) {- return (- <View className="flex-row overflow-hidden rounded-full bg-subtle">- {(["cost", "tokens"] as const).map((option) => {- const active = option === props.metric;- return (- <Pressable- key={option}- accessibilityRole="button"- accessibilityState={{ selected: active }}- onPress={() => props.onChange(option)}- className={active ? "rounded-full bg-subtle-strong px-3 py-1.5" : "px-3 py-1.5"}- >- <Text- className={- active- ? "text-xs font-t3-medium uppercase text-foreground"- : "text-xs uppercase text-foreground-muted"- }- >- {option}- </Text>- </Pressable>- );- })}- </View>- );-}-function ProviderSection(props: {readonly merged: MergedUsage;readonly metric: UsageChartMetric;diff --git a/docs/user/usage.md b/docs/user/usage.mdindex 8523ab81099..3a61222be82 100644--- a/docs/user/usage.md+++ b/docs/user/usage.md@@ -18,6 +18,8 @@ update model pricing.compares quota consumed with time elapsed in each window, so you can judge your pace before thenext reset.+If a window looks stale, refresh Limits to re-check every provider and hub.+API-key accounts may not report subscription limits. This also applies to Claude connectionsusing a proxy through `ANTHROPIC_AUTH_TOKEN`.