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(30); const [metric, setMetric] = useState("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 ( {Platform.OS === "android" ? ( <> navigation.goBack()} /> ) : null} } > ({ value: option.days, label: option.label }))} selected={windowDays} onSelect={setWindowDays} /> {isPending ? ( Scanning provider transcripts… ) : environments.length === 0 ? ( Connect an environment to see usage. ) : ( <> )} ); } function SegmentedControl(props: { readonly options: readonly { readonly value: Value; readonly label: string }[]; readonly selected: Value; readonly onSelect: (value: Value) => void; }) { return ( {props.options.map((option) => { const active = option.value === props.selected; return ( props.onSelect(option.value)} className={ active ? "flex-1 items-center rounded-full bg-subtle-strong py-2" : "flex-1 items-center py-2" } > {option.label} ); })} ); } /** 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 ( {metric === "cost" ? "Raw token cost" : "Processed tokens"} {metric === "cost" ? `${formatUsd(merged.costUsd)}*` : formatTokens(merged.totalTokens)} {metric === "cost" ? "* if billed at full API rate" : `Across ${formatCount(merged.sessions)} sessions`} {hasActivity ? ( ) : ( No activity in this window. )} {formatDayShort(props.sinceDay)} {merged.providers.map((provider) => ( {PROVIDER_LABEL[provider.provider]} ))} {formatDayShort(props.untilDay)} ); } function MetricToggle(props: { readonly metric: UsageChartMetric; readonly onChange: (metric: UsageChartMetric) => void; }) { return ( {(["cost", "tokens"] as const).map((option) => { const active = option === props.metric; return ( props.onChange(option)} className={active ? "rounded-full bg-subtle-strong px-3 py-1.5" : "px-3 py-1.5"} > {option} ); })} ); } 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 ( {ordered.map((provider, index) => { const share = metric === "cost" ? provider.costShare : provider.tokenShare; return ( {PROVIDER_LABEL[provider.provider]} {metric === "cost" ? formatUsd(provider.costUsd) : formatTokens(provider.totalTokens)} {metric === "cost" ? `${formatPercent(share)} of cost · ${formatTokens(provider.totalTokens)} tokens` : `${formatPercent(share)} of tokens · ${formatUsd(provider.costUsd)}`} ); })} ); } 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 ( 0 ? `${(merged.costQuality.cacheSavingsUsd / merged.costUsd).toFixed(1)}x the raw cost` : "vs full input rates" } /> ); } function MetricCell(props: { readonly label: string; readonly value: string; readonly detail: string; }) { return ( {props.label} {props.value} {props.detail} ); } function ModelsSection(props: { readonly merged: MergedUsage }) { const { merged } = props; const colors = useProviderColors(); if (merged.models.length === 0) return null; return ( {merged.models.map((model, index) => ( {model.model} {formatPercent(model.costShare)} of cost · {formatTokens(model.totalTokens)} tokens {formatUsd(model.costUsd)} ))} ); } /** * 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 ( {props.isPartial ? ( Some environments are still reporting. Totals are partial. ) : null} {failed.map((environment) => ( {environment.label} could not report usage. ))} {stale.map((environment) => ( {environment.label} runs an older server version and is excluded from totals. ))} {duplicateSources.length > 0 ? ( Counted once across environments sharing a transcript directory:{" "} {duplicateSources.join(", ")} ) : null} ); }