Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

Add cross-platform mobile usage dashboard (#5743)

Julius Marminge1a003e383ac6
diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx
index 1516b7cbc..da1be88a8 100644
--- a/apps/mobile/src/Stack.tsx
+++ b/apps/mobile/src/Stack.tsx
@@ -48,6 +48,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 { UsageRouteScreen } from "./features/usage/UsageRouteScreen";
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";
import {
@@ -190,6 +191,13 @@ const SettingsSheetStack = createNativeStackNavigator({
title: "Client Storage",
},
}),
+ SettingsUsage: createNativeStackScreen({
+ screen: UsageRouteScreen,
+ linking: "usage",
+ options: {
+ title: "Usage",
+ },
+ }),
SettingsAuth: createNativeStackScreen({
screen: SettingsAuthRouteScreen,
linking: "auth",
diff --git a/apps/mobile/src/components/AppSymbol.tsx b/apps/mobile/src/components/AppSymbol.tsx
index b1e83607d..89dc0cc04 100644
--- a/apps/mobile/src/components/AppSymbol.tsx
+++ b/apps/mobile/src/components/AppSymbol.tsx
@@ -14,6 +14,7 @@ import {
IconBellRinging,
IconBolt,
IconCamera,
+ IconChartBar,
IconCheck,
IconChevronDown,
IconCode,
@@ -97,6 +98,7 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
"bolt.circle": IconBolt,
"bolt.horizontal.circle": IconBolt,
camera: IconCamera,
+ "chart.bar.xaxis": IconChartBar,
checkmark: IconCheck,
"checkmark.circle": IconCircleCheck,
clock: IconClock,
diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx
index 8bfff6a87..90e5af199 100644
--- a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx
@@ -533,6 +533,7 @@ function GeneralSettingsSection() {
return (
<SettingsSection title="General">
<SettingsRow icon="folder" label="Project Grouping" target="SettingsProjectGrouping" />
+ <SettingsRow icon="chart.bar.xaxis" label="Usage" target="SettingsUsage" />
</SettingsSection>
);
}
diff --git a/apps/mobile/src/features/settings/components/settings-sheet-targets.ts b/apps/mobile/src/features/settings/components/settings-sheet-targets.ts
index df012c903..7189fdc2e 100644
--- a/apps/mobile/src/features/settings/components/settings-sheet-targets.ts
+++ b/apps/mobile/src/features/settings/components/settings-sheet-targets.ts
@@ -3,6 +3,7 @@ export type SettingsSheetTarget =
| "SettingsArchive"
| "SettingsAppearance"
| "SettingsProjectGrouping"
- | "SettingsClientStorage";
+ | "SettingsClientStorage"
+ | "SettingsUsage";
export type SettingsLegalDocumentTarget = "SettingsLegal";
diff --git a/apps/mobile/src/features/usage/UsageDailyChart.ios.tsx b/apps/mobile/src/features/usage/UsageDailyChart.ios.tsx
new file mode 100644
index 000000000..f5924bd83
--- /dev/null
+++ b/apps/mobile/src/features/usage/UsageDailyChart.ios.tsx
@@ -0,0 +1,50 @@
+import { Chart, Host, type ChartDataPoint } from "@expo/ui/swift-ui";
+import { frame } from "@expo/ui/swift-ui/modifiers";
+import { useMemo } from "react";
+
+import type { DailyTotals } from "@t3tools/shared/usageMerge";
+
+import { buildChartDays, type UsageChartMetric } from "./usageChartData";
+import { useProviderColors } from "./usageProviders";
+
+export interface UsageDailyChartProps {
+ readonly days: readonly string[];
+ readonly daily: readonly DailyTotals[];
+ readonly metric: UsageChartMetric;
+ readonly height: number;
+}
+
+/**
+ * Native Swift Charts daily bars. Points sharing an x value stack, so emitting
+ * one point per provider per day yields per-provider bands whose stack height
+ * is the day's total; changes animate natively.
+ *
+ * Axes are hidden: 30-90 categorical day labels cannot fit on a phone, so the
+ * screen renders its own edge labels under the chart instead.
+ */
+export function UsageDailyChart({ days, daily, metric, height }: UsageDailyChartProps) {
+ const colors = useProviderColors();
+
+ const data = useMemo((): ChartDataPoint[] => {
+ return buildChartDays(days, daily, metric).flatMap((day) =>
+ day.values.map((entry) => ({
+ x: day.day,
+ y: entry.value,
+ color: colors[entry.provider],
+ })),
+ );
+ }, [days, daily, metric, colors]);
+
+ return (
+ <Host style={{ height, width: "100%" }}>
+ <Chart
+ type="bar"
+ data={data}
+ animate
+ showGrid={false}
+ barStyle={{ cornerRadius: 2 }}
+ modifiers={[frame({ height })]}
+ />
+ </Host>
+ );
+}
diff --git a/apps/mobile/src/features/usage/UsageDailyChart.tsx b/apps/mobile/src/features/usage/UsageDailyChart.tsx
new file mode 100644
index 000000000..55e2de315
--- /dev/null
+++ b/apps/mobile/src/features/usage/UsageDailyChart.tsx
@@ -0,0 +1,44 @@
+import { useMemo } from "react";
+import { View } from "react-native";
+
+import type { DailyTotals } from "@t3tools/shared/usageMerge";
+
+import { buildChartDays, type UsageChartMetric } from "./usageChartData";
+import { useProviderColors } from "./usageProviders";
+
+export interface UsageDailyChartProps {
+ readonly days: readonly string[];
+ readonly daily: readonly DailyTotals[];
+ readonly metric: UsageChartMetric;
+ readonly height: number;
+}
+
+/**
+ * Stacked daily bars drawn with plain views. Android and any platform without
+ * Swift Charts land here; iOS resolves `UsageDailyChart.ios.tsx` instead.
+ */
+export function UsageDailyChart({ days, daily, metric, height }: UsageDailyChartProps) {
+ const colors = useProviderColors();
+ const chartDays = useMemo(() => buildChartDays(days, daily, metric), [days, daily, metric]);
+ const max = chartDays.reduce((peak, day) => Math.max(peak, day.total), 0);
+
+ return (
+ <View style={{ height }} className="flex-row items-end gap-px">
+ {/* column-reverse stacks the bottom-first provider values upward
+ without reversing the array (Hermes lacks Array#toReversed). */}
+ {chartDays.map((day) => (
+ <View key={day.day} className="h-full flex-1 flex-col-reverse overflow-hidden rounded-sm">
+ {day.values.map((entry) => (
+ <View
+ key={entry.provider}
+ style={{
+ height: max === 0 ? 0 : (entry.value / max) * height,
+ backgroundColor: colors[entry.provider],
+ }}
+ />
+ ))}
+ </View>
+ ))}
+ </View>
+ );
+}
diff --git a/apps/mobile/src/features/usage/UsageRouteScreen.tsx b/apps/mobile/src/features/usage/UsageRouteScreen.tsx
new file mode 100644
index 000000000..54a9ac7bc
--- /dev/null
+++ b/apps/mobile/src/features/usage/UsageRouteScreen.tsx
@@ -0,0 +1,442 @@
+import { useNavigation } from "@react-navigation/native";
+import type { MergedUsage } from "@t3tools/shared/usageMerge";
+import {
+ enumerateDays,
+ formatCount,
+ formatDayShort,
+ formatPercent,
+ formatTokens,
+ formatUsd,
+ makeWindow,
+} from "@t3tools/shared/usageFormat";
+import { 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 { NativeStackScreenOptions } from "../../native/StackHeader";
+import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
+import { SettingsSection } from "../settings/components/SettingsSection";
+import { UsageDailyChart } from "./UsageDailyChart";
+import type { UsageChartMetric } from "./usageChartData";
+import { PROVIDER_LABEL, useProviderColors } from "./usageProviders";
+
+const WINDOW_OPTIONS = [
+ { days: 7, label: "7 days" },
+ { days: 30, label: "30 days" },
+ { days: 90, label: "90 days" },
+] as const;
+
+const CHART_HEIGHT = 180;
+
+export function UsageRouteScreen() {
+ const navigation = useNavigation();
+ const insets = useSafeAreaInsets();
+ const [windowDays, setWindowDays] = useState<number>(30);
+ const [metric, setMetric] = useState<UsageChartMetric>("cost");
+
+ // Recomputed only when the window length changes, so a re-render does not
+ // shift the range and refetch every environment.
+ const window = useMemo(() => makeWindow(windowDays), [windowDays]);
+ const { merged, environments, isPending, isPartial, refresh } = useUsage(window);
+
+ const days = useMemo(
+ () => enumerateDays(window.sinceDay, window.untilDay),
+ [window.sinceDay, window.untilDay],
+ );
+
+ // The pull spinner tracks re-scans of environments that have answered
+ // before. The initial scan renders its own placeholder, and an unreachable
+ // environment stays pending forever — neither may pin the spinner on.
+ const refreshing = environments.some((entry) => entry.isPending && entry.summary !== null);
+
+ return (
+ <View collapsable={false} className="flex-1 bg-sheet">
+ {Platform.OS === "android" ? (
+ <>
+ <NativeStackScreenOptions options={{ headerShown: false }} />
+ <AndroidScreenHeader title="Usage" onBack={() => navigation.goBack()} />
+ </>
+ ) : null}
+ <ScrollView
+ 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={refresh} />}
+ >
+ <SegmentedControl
+ options={WINDOW_OPTIONS.map((option) => ({ value: option.days, label: option.label }))}
+ selected={windowDays}
+ onSelect={setWindowDays}
+ />
+
+ <UsageCoverageNotice environments={environments} merged={merged} isPartial={isPartial} />
+
+ {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={days}
+ metric={metric}
+ onMetricChange={setMetric}
+ sinceDay={window.sinceDay}
+ untilDay={window.untilDay}
+ />
+ <ProviderSection merged={merged} metric={metric} />
+ <TotalsSection merged={merged} />
+ <ModelsSection merged={merged} />
+ </>
+ )}
+ </ScrollView>
+ </View>
+ );
+}
+
+function SegmentedControl<Value extends number | string>(props: {
+ readonly options: readonly { readonly value: Value; readonly label: string }[];
+ readonly selected: Value;
+ readonly onSelect: (value: Value) => void;
+}) {
+ return (
+ <View className="flex-row overflow-hidden rounded-full border-continuous bg-card">
+ {props.options.map((option) => {
+ const active = option.value === props.selected;
+ return (
+ <Pressable
+ key={String(option.value)}
+ accessibilityRole="button"
+ 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"
+ }
+ >
+ <Text
+ className={
+ active ? "text-sm font-t3-medium text-foreground" : "text-sm text-foreground-muted"
+ }
+ >
+ {option.label}
+ </Text>
+ </Pressable>
+ );
+ })}
+ </View>
+ );
+}
+
+/** Headline figure, the animated daily chart, and its legend, in one card. */
+function ChartCard(props: {
+ readonly merged: MergedUsage;
+ readonly days: readonly string[];
+ readonly metric: UsageChartMetric;
+ readonly onMetricChange: (metric: UsageChartMetric) => void;
+ readonly sinceDay: string;
+ readonly untilDay: string;
+}) {
+ const { merged, metric } = props;
+ const colors = useProviderColors();
+ const hasActivity = merged.daily.some((day) => day.totalTokens > 0);
+
+ 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>
+
+ {hasActivity ? (
+ <UsageDailyChart
+ days={props.days}
+ daily={merged.daily}
+ metric={metric}
+ height={CHART_HEIGHT}
+ />
+ ) : (
+ <View style={{ height: CHART_HEIGHT }} className="items-center justify-center">
+ <Text className="text-base text-foreground-muted">No activity in this window.</Text>
+ </View>
+ )}
+
+ <View className="flex-row items-center justify-between">
+ <Text className="text-xs text-foreground-tertiary">{formatDayShort(props.sinceDay)}</Text>
+ <View className="flex-row items-center gap-4">
+ {merged.providers.map((provider) => (
+ <View key={provider.provider} className="flex-row items-center gap-1.5">
+ <View
+ className="size-2 rounded-full"
+ style={{ backgroundColor: colors[provider.provider] }}
+ />
+ <Text className="text-xs text-foreground-muted">
+ {PROVIDER_LABEL[provider.provider]}
+ </Text>
+ </View>
+ ))}
+ </View>
+ <Text className="text-xs text-foreground-tertiary">{formatDayShort(props.untilDay)}</Text>
+ </View>
+ </View>
+ );
+}
+
+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;
+}) {
+ const { merged, metric } = props;
+ const colors = useProviderColors();
+ if (merged.providers.length === 0) return null;
+
+ // Ranked by whatever the toggle is showing, so the rows always descend.
+ // .sort() on a copy, not .toSorted(): Hermes doesn't ship the ES2023 method.
+ const ordered = [...merged.providers].sort((a, b) =>
+ metric === "cost" ? b.costUsd - a.costUsd : b.totalTokens - a.totalTokens,
+ );
+
+ return (
+ <SettingsSection title="Providers" card>
+ {ordered.map((provider, index) => {
+ const share = metric === "cost" ? provider.costShare : provider.tokenShare;
+ return (
+ <View
+ key={provider.provider}
+ className={index === 0 ? "gap-2 p-4" : "gap-2 border-t border-border-subtle p-4"}
+ >
+ <View className="flex-row items-baseline justify-between gap-3">
+ <View className="flex-row items-center gap-2">
+ <View
+ className="size-2.5 rounded-full"
+ style={{ backgroundColor: colors[provider.provider] }}
+ />
+ <Text className="text-lg text-foreground">{PROVIDER_LABEL[provider.provider]}</Text>
+ </View>
+ <Text className="text-lg tabular-nums text-foreground">
+ {metric === "cost"
+ ? formatUsd(provider.costUsd)
+ : formatTokens(provider.totalTokens)}
+ </Text>
+ </View>
+ <View className="h-1 flex-row overflow-hidden rounded-full bg-subtle">
+ <View
+ className="h-full rounded-full"
+ style={{ flex: share, backgroundColor: colors[provider.provider] }}
+ />
+ <View style={{ flex: 1 - share }} />
+ </View>
+ <Text className="text-sm text-foreground-muted">
+ {metric === "cost"
+ ? `${formatPercent(share)} of cost · ${formatTokens(provider.totalTokens)} tokens`
+ : `${formatPercent(share)} of tokens · ${formatUsd(provider.costUsd)}`}
+ </Text>
+ </View>
+ );
+ })}
+ </SettingsSection>
+ );
+}
+
+function TotalsSection(props: { readonly merged: MergedUsage }) {
+ const { merged } = props;
+ const activeDays = merged.daily.filter((day) => day.totalTokens > 0).length;
+ const dailyAverage = activeDays === 0 ? 0 : merged.totalTokens / activeDays;
+ const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens;
+ const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput;
+
+ return (
+ <SettingsSection title="Totals" card>
+ <View className="flex-row flex-wrap">
+ <MetricCell
+ label="Processed tokens"
+ value={formatTokens(merged.totalTokens)}
+ detail={`${formatTokens(dailyAverage)} per active day`}
+ />
+ <MetricCell
+ label="Cache savings"
+ value={formatUsd(merged.costQuality.cacheSavingsUsd)}
+ detail={
+ merged.costUsd > 0
+ ? `${(merged.costQuality.cacheSavingsUsd / merged.costUsd).toFixed(1)}x the raw cost`
+ : "vs full input rates"
+ }
+ />
+ <MetricCell
+ label="Cached input"
+ value={formatTokens(merged.cachedInputTokens)}
+ detail={`${formatPercent(cachedShare)} of observed input`}
+ />
+ <MetricCell
+ label="Uncached input"
+ value={formatTokens(merged.uncachedInputTokens)}
+ detail={`${formatTokens(merged.cacheCreationTokens)} cache writes`}
+ />
+ <MetricCell
+ label="Output"
+ value={formatTokens(merged.outputTokens)}
+ detail={`incl. ${formatTokens(merged.reasoningTokens)} reasoning`}
+ />
+ <MetricCell
+ label="Unpriced"
+ value={formatPercent(merged.costQuality.unpricedShare)}
+ detail="of records, excluded from cost"
+ />
+ </View>
+ </SettingsSection>
+ );
+}
+
+function MetricCell(props: {
+ readonly label: string;
+ readonly value: string;
+ readonly detail: string;
+}) {
+ return (
+ <View className="w-1/2 gap-0.5 p-4">
+ <Text className="text-sm text-foreground-muted">{props.label}</Text>
+ <Text className="text-xl font-t3-medium tabular-nums text-foreground">{props.value}</Text>
+ <Text className="text-xs text-foreground-tertiary">{props.detail}</Text>
+ </View>
+ );
+}
+
+function ModelsSection(props: { readonly merged: MergedUsage }) {
+ const { merged } = props;
+ const colors = useProviderColors();
+ if (merged.models.length === 0) return null;
+
+ return (
+ <SettingsSection title="By model" card>
+ {merged.models.map((model, index) => (
+ <View
+ key={`${model.provider}:${model.model}`}
+ className={
+ index === 0
+ ? "flex-row items-center gap-3 p-4"
+ : "flex-row items-center gap-3 border-t border-border-subtle p-4"
+ }
+ >
+ <View
+ className="size-2.5 shrink-0 rounded-full"
+ style={{ backgroundColor: colors[model.provider] }}
+ />
+ <View className="min-w-0 flex-1 gap-0.5">
+ <Text className="text-base text-foreground" numberOfLines={1}>
+ {model.model}
+ </Text>
+ <Text className="text-sm text-foreground-muted">
+ {formatPercent(model.costShare)} of cost · {formatTokens(model.totalTokens)} tokens
+ </Text>
+ </View>
+ <Text className="text-base tabular-nums text-foreground">{formatUsd(model.costUsd)}</Text>
+ </View>
+ ))}
+ </SettingsSection>
+ );
+}
+
+/**
+ * Says plainly when the totals are incomplete: an environment still answering,
+ * 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>
+ );
+}
diff --git a/apps/mobile/src/features/usage/usageChartData.ts b/apps/mobile/src/features/usage/usageChartData.ts
new file mode 100644
index 000000000..b7b996440
--- /dev/null
+++ b/apps/mobile/src/features/usage/usageChartData.ts
@@ -0,0 +1,41 @@
+/**
+ * Shapes merged daily totals into the per-day provider stacks both chart
+ * implementations (Swift Charts on iOS, plain views elsewhere) render.
+ *
+ * @module usageChartData
+ */
+import type { UsageProviderKind } from "@t3tools/contracts";
+import type { DailyTotals } from "@t3tools/shared/usageMerge";
+
+import { PROVIDER_ORDER } from "./usageProviders";
+
+export type UsageChartMetric = "cost" | "tokens";
+
+export interface UsageChartDay {
+ readonly day: string;
+ /** In {@link PROVIDER_ORDER}, i.e. bottom of the stack first. */
+ readonly values: readonly { readonly provider: UsageProviderKind; readonly value: number }[];
+ readonly total: number;
+}
+
+/** One entry per day in the window, zero-filled where nothing happened. */
+export function buildChartDays(
+ days: readonly string[],
+ daily: readonly DailyTotals[],
+ metric: UsageChartMetric,
+): readonly UsageChartDay[] {
+ const byDay = new Map(daily.map((totals) => [totals.day, totals]));
+ return days.map((day) => {
+ const totals = byDay.get(day);
+ const values = PROVIDER_ORDER.map((provider) => {
+ const entry = totals?.byProvider.get(provider);
+ const value = entry === undefined ? 0 : metric === "cost" ? entry.costUsd : entry.totalTokens;
+ return { provider, value };
+ });
+ return {
+ day,
+ values,
+ total: values.reduce((sum, entry) => sum + entry.value, 0),
+ };
+ });
+}
diff --git a/apps/mobile/src/features/usage/usageProviders.ts b/apps/mobile/src/features/usage/usageProviders.ts
new file mode 100644
index 000000000..3e2d027a9
--- /dev/null
+++ b/apps/mobile/src/features/usage/usageProviders.ts
@@ -0,0 +1,25 @@
+import type { UsageProviderKind } from "@t3tools/contracts";
+import { useColorScheme } from "react-native";
+
+/**
+ * Series and table order. The chart stacks providers from the bottom in this
+ * order, so it also fixes which band sits on top of the bars.
+ */
+export const PROVIDER_ORDER: readonly UsageProviderKind[] = ["codex", "claude"];
+
+export const PROVIDER_LABEL: Record<UsageProviderKind, string> = {
+ claude: "Claude Code",
+ codex: "Codex",
+};
+
+/**
+ * Claude's brand orange holds in both themes; Codex is neutral and must flip
+ * with the theme or its bars vanish against the matching background.
+ */
+export function useProviderColors(): Record<UsageProviderKind, string> {
+ const scheme = useColorScheme();
+ return {
+ claude: "#d97757",
+ codex: scheme === "dark" ? "#e6e6e6" : "#3c3c43",
+ };
+}
diff --git a/apps/mobile/src/state/usage.ts b/apps/mobile/src/state/usage.ts
new file mode 100644
index 000000000..91cefda07
--- /dev/null
+++ b/apps/mobile/src/state/usage.ts
@@ -0,0 +1,129 @@
+/**
+ * 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.
+ *
+ * Mirror of `apps/web/src/state/usage.ts` over mobile's atom wiring; the merge
+ * rules themselves live in `@t3tools/shared/usageMerge`.
+ *
+ * @module state/usage
+ */
+import { useAtomValue } from "@effect/atom-react";
+import {
+ USAGE_CONTRACT_VERSION,
+ type EnvironmentId,
+ 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 { appAtomRegistry } from "./atom-registry";
+import { environmentPresentations } from "./presentation";
+import { serverEnvironment } from "./server";
+
+export interface EnvironmentUsageStatus {
+ readonly environmentId: EnvironmentId;
+ readonly label: string;
+ readonly isPending: boolean;
+ 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);
+
+ const statuses: EnvironmentUsageStatus[] = [];
+ for (const [environmentId, presentation] of presentations) {
+ 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,
+ summary: Option.getOrNull(AsyncResult.value(result)),
+ });
+ }
+ return statuses;
+ }).pipe(Atom.withLabel(`mobile-usage:window:${windowKey}`)),
+);
+
+export interface UsageView {
+ readonly merged: MergedUsage;
+ readonly environments: 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
+ * 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(
+ () =>
+ JSON.stringify({
+ sinceDay: input.sinceDay,
+ untilDay: input.untilDay,
+ timeZone: input.timeZone,
+ }),
+ [input.sinceDay, input.untilDay, input.timeZone],
+ );
+ const atom = usageByWindowAtom(windowKey);
+ const environments = useAtomValue(atom);
+
+ // Refreshing only the derived atom would re-read the per-environment SWR
+ // queries within their stale window and change nothing. Refresh each
+ // environment's query so pull-to-refresh always rescans.
+ const refresh = useCallback(() => {
+ const input = JSON.parse(windowKey) as UsageSummaryInput;
+ for (const environment of environments) {
+ appAtomRegistry.refresh(
+ serverEnvironment.usageSummary({ environmentId: environment.environmentId, input }),
+ );
+ }
+ }, [environments, windowKey]);
+
+ const merged = useMemo(() => {
+ const answered: EnvironmentUsage[] = environments.flatMap((environment) =>
+ environment.summary === null
+ ? []
+ : [
+ {
+ environmentId: environment.environmentId,
+ label: environment.label,
+ summary: environment.summary,
+ },
+ ],
+ );
+ 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;
+
+ return {
+ merged,
+ environments,
+ isPending: answeredCount === 0 && stillReporting > 0,
+ isPartial: answeredCount > 0 && stillReporting > 0,
+ refresh,
+ };
+}
diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx
index 1a5b53904..b5b762aea 100644
--- a/apps/web/src/components/usage/UsagePage.tsx
+++ b/apps/web/src/components/usage/UsagePage.tsx
@@ -13,7 +13,7 @@ import {
formatTokens,
formatUsd,
makeWindow,
-} from "../../usage/usageFormat";
+} from "@t3tools/shared/usageFormat";
import { ScrollArea } from "../ui/scroll-area";
import { UsageChartLegend, UsageProviderChart, type UsageChartMetric } from "./UsageProviderChart";
import { PROVIDER_COLOR, PROVIDER_LABEL, PROVIDER_MARK, PROVIDER_ORDER } from "./usageProviders";
diff --git a/apps/web/src/components/usage/UsageProviderChart.tsx b/apps/web/src/components/usage/UsageProviderChart.tsx
index 1d5410eba..8f31d348e 100644
--- a/apps/web/src/components/usage/UsageProviderChart.tsx
+++ b/apps/web/src/components/usage/UsageProviderChart.tsx
@@ -1,8 +1,8 @@
import type { UsageProviderKind } from "@t3tools/contracts";
import { useCallback, useMemo, useRef, useState } from "react";
-import type { DailyTotals } from "../../usage/usageMerge";
-import { formatDayShort, formatTokens, formatUsd } from "../../usage/usageFormat";
+import type { DailyTotals } from "@t3tools/shared/usageMerge";
+import { formatDayShort, formatTokens, formatUsd } from "@t3tools/shared/usageFormat";
import { PROVIDER_COLOR, PROVIDER_LABEL, PROVIDER_MARK, PROVIDER_ORDER } from "./usageProviders";
const VIEW_WIDTH = 960;
diff --git a/apps/web/src/state/usage.ts b/apps/web/src/state/usage.ts
index 57114ade1..9d65b6ad6 100644
--- a/apps/web/src/state/usage.ts
+++ b/apps/web/src/state/usage.ts
@@ -17,7 +17,7 @@ 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 "../usage/usageMerge";
+import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { environmentPresentations } from "./presentation";
import { serverEnvironment } from "./server";
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 1cffab6c2..f669bd0a4 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -210,6 +210,14 @@
"./devProxy": {
"types": "./src/devProxy.ts",
"import": "./src/devProxy.ts"
+ },
+ "./usageMerge": {
+ "types": "./src/usageMerge.ts",
+ "import": "./src/usageMerge.ts"
+ },
+ "./usageFormat": {
+ "types": "./src/usageFormat.ts",
+ "import": "./src/usageFormat.ts"
}
},
"scripts": {
diff --git a/apps/web/src/usage/usageFormat.ts b/packages/shared/src/usageFormat.ts
similarity index 96%
rename from apps/web/src/usage/usageFormat.ts
rename to packages/shared/src/usageFormat.ts
index c7c216058..21e11fee7 100644
--- a/apps/web/src/usage/usageFormat.ts
+++ b/packages/shared/src/usageFormat.ts
@@ -1,3 +1,4 @@
+// @effect-diagnostics globalDate:off -- Usage windows are calendar days in the viewer's zone, derived from wall-clock "now" via Intl.
/**
* Display formatting for the usage page.
*
diff --git a/apps/web/src/usage/usageMerge.test.ts b/packages/shared/src/usageMerge.test.ts
similarity index 99%
rename from apps/web/src/usage/usageMerge.test.ts
rename to packages/shared/src/usageMerge.test.ts
index 7e44631cf..3c377a33f 100644
--- a/apps/web/src/usage/usageMerge.test.ts
+++ b/packages/shared/src/usageMerge.test.ts
@@ -8,7 +8,7 @@ import {
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
-import { mergeUsage, type EnvironmentUsage } from "./usageMerge";
+import { mergeUsage, type EnvironmentUsage } from "./usageMerge.ts";
function bucket(overrides: Partial<UsageBucket> = {}): UsageBucket {
return {
diff --git a/apps/web/src/usage/usageMerge.ts b/packages/shared/src/usageMerge.ts
similarity index 100%
rename from apps/web/src/usage/usageMerge.ts
rename to packages/shared/src/usageMerge.ts