import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; import { ChatGptUsageSummary } from "./ChatGptUsageSummary"; import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView"; import { EnvironmentId, USAGE_CONTRACT_VERSION, type UsageProviderKind, type UsageSummaryInput, } from "@t3tools/contracts"; import { type RouteProp, useIsFocused, useRoute } from "@react-navigation/native"; import { updatingProvidersLabel, usageEnvironmentProgress, usageProgress, } from "@t3tools/client-runtime/state/usage-progress"; import { isCompatibleUsageContractVersion, isModelCostUnknown, type DailyTotals, type MergedUsage, } from "@t3tools/shared/usageMerge"; import { enumerateDays, enumerateHourStarts, formatCount, formatDayRange, formatPercent, formatTokens, formatUsageMonth, formatUsd, makePeriodWindow, parseUsagePeriod, selectableUsageMonths, type UsageMonthKey, type UsagePeriod, } from "@t3tools/shared/usageFormat"; import type { MenuAction } from "@react-native-menu/menu"; import { formatUsageContractMismatch, usageSourceMessages } from "@t3tools/shared/usageFormatCopy"; import { msg, T, useGT, useLocale, useMessages, Var } from "gt-react-native"; import { use, useRef, useState, type ReactNode } from "react"; import { View } from "react-native"; import { RefreshControl } from "../../components/ui/RefreshControl"; import Animated, { FadeIn, ReduceMotion } from "react-native-reanimated"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { SegmentedControl } from "../../components/ui/SegmentedControl"; import { ControlPill } from "../../components/ui/ControlPill"; import { Menu } from "../../components/ui/Menu"; import { useReduceMotionEnabled } from "../../lib/appState"; import { AppText as Text } from "../../components/ui/AppText"; import { useWorkspaceSettledContentWidth } from "../layout/workspace-content-width"; import { cn } from "../../lib/cn"; import type { MessageResolver } from "../../i18n/messages"; import { SettingsScreen } from "../settings/components/SettingsScreen"; import { NativeWorkspaceTabActivityContext } from "../../native/v5-workspace-context"; import { useUsage, type EnvironmentUsageStatus } from "../../state/usage"; import { SettingsSection } from "../settings/components/SettingsSection"; import { usageAxisDayLabel, usageAxisHourLabel } from "./usageAxisLabels"; import { UsageDailyChart } from "./UsageDailyChart"; import { toggleUsageEnvironment } from "./usageEnvironmentSelection"; import { useRefreshLimits } from "./UsageLimitsSection"; import { UsageLimitsSection } from "./UsageLimitsPooled"; import type { UsageChartMetric } from "./usageChartData"; import { PROVIDER_LABEL, useProviderColors, useUsageMixColors } from "./usageProviders"; type UsageView = UsageChartMetric | "limits"; const VIEW_OPTIONS = [ { value: "cost", label: msg("Cost", { $context: "usage view tab" }) }, { value: "tokens", label: msg("Tokens", { $context: "usage view tab" }) }, { value: "limits", label: msg("Limits", { $context: "usage view tab, subscription limits" }) }, ] as const satisfies readonly { value: UsageView; label: string }[]; const WINDOW_OPTIONS = [ { value: 1, label: msg("24h", { $context: "short label for the past 24 hours" }), accessibilityLabel: msg("Past 24 hours"), }, { value: 7, label: msg("7d", { $context: "short label for the past 7 days" }), accessibilityLabel: msg("Past 7 days"), }, { value: 30, label: msg("30d", { $context: "short label for the past 30 days" }), accessibilityLabel: msg("Past 30 days"), }, { value: 90, label: msg("90d", { $context: "short label for the past 90 days" }), accessibilityLabel: msg("Past 90 days"), }, { value: "month", label: msg("Month", { $context: "short label for the current calendar month" }), accessibilityLabel: msg("This month"), }, ] as const; const CHART_HEIGHT = 180; const WIDE_CHART_HEIGHT = 260; // Below this the page keeps the phone's single column. const WIDE_WIDTH = 600; const MAX_CONTENT_WIDTH = 1080; const providerLabel = (provider: UsageProviderKind) => PROVIDER_LABEL[provider]; export function UsageRouteScreen(props: { readonly workspace?: boolean }) { const route = useRoute>(); return ; } function UsageScreen(props: { readonly workspace?: boolean; readonly tabParam: string | undefined; }) { const gt = useGT(); const m = useMessages(); const viewOptions = VIEW_OPTIONS.map((option) => ({ ...option, label: m(option.label) })); const windowOptions = WINDOW_OPTIONS.map((option) => ({ ...option, label: m(option.label), accessibilityLabel: m(option.accessibilityLabel), })); const insets = useSafeAreaInsets(); const headerOnly = use(NativeWorkspaceTabActivityContext)?.headerOnly === true; const [selection, setSelection] = useState(() => ({ params: props.tabParam, view: (props.tabParam === "usage" ? "cost" : "limits") as UsageView, })); if (selection.params !== props.tabParam) { setSelection({ params: props.tabParam, view: props.tabParam === "usage" ? "cost" : "limits", }); } const { view } = selection; const setView = (view: UsageView) => setSelection({ params: props.tabParam, view }); const [measuredWidth, setWidth] = useState(0); // A workspace pane knows its width in the render that resizes it; measuring lags a frame. const width = useWorkspaceSettledContentWidth() ?? measuredWidth; const wide = width >= WIDE_WIDTH; const [windowSelection, setWindowSelection] = useState<{ readonly period: UsagePeriod; readonly window: UsageSummaryInput; }>(() => ({ period: 30, window: makePeriodWindow(30) })); const { period, window } = windowSelection; const isPast24Hours = period === 1; const isMonthPeriod = typeof period === "string"; const [selectedEnvironmentIds, setSelectedEnvironmentIds] = useState | null>(null); const { merged, environments, selectedEnvironments, isPending, refresh } = useUsage( window, selectedEnvironmentIds, !headerOnly, ); const isFocused = useIsFocused(); const limits = useRefreshLimits( selectedEnvironmentIds, isFocused && view === "limits" && !headerOnly, ); const sourceMessages = usageSourceMessages( selectedEnvironments.flatMap((environment) => environment.summary?.sources ?? []), m, ); const canReadDiagnostics = selectedEnvironments.some( (environment) => environment.canReadDiagnostics, ); const days = enumerateDays(window.sinceDay, window.untilDay); const chartDays = isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined ? enumerateHourStarts(window.sinceTime, window.untilTime) : days; const chartTotals: readonly DailyTotals[] = isPast24Hours ? merged.hourly.map((hour) => ({ day: hour.hourStart, costUsd: hour.costUsd, totalTokens: hour.totalTokens, byProvider: hour.byProvider, })) : merged.daily; const [refreshingUsage, setRefreshingUsage] = useState(false); const refreshingRef = useRef(false); const showingLimits = view === "limits"; const metric: UsageChartMetric = view === "tokens" ? "tokens" : "cost"; const progress = usageProgress( selectedEnvironments, { refreshing: refreshingUsage, providerLabel, }, m, ); const selectPeriod = (period: UsagePeriod) => { setWindowSelection({ period, window: makePeriodWindow(period) }); }; const refreshWindow = () => { if (refreshingRef.current) return; const nextWindow = makePeriodWindow(period); if ( nextWindow.sinceDay !== window.sinceDay || nextWindow.untilDay !== window.untilDay || nextWindow.sinceTime !== window.sinceTime || nextWindow.untilTime !== window.untilTime ) { setWindowSelection({ period, window: nextWindow }); } refreshingRef.current = true; setRefreshingUsage(true); void refresh(nextWindow).finally(() => { refreshingRef.current = false; setRefreshingUsage(false); }); }; const chart = { merged, days: chartDays, daily: chartTotals, metric, sinceDay: window.sinceDay, untilDay: window.untilDay, isPast24Hours, timeZone: window.timeZone, }; const providers = ; const monthPicker = isMonthPeriod && !showingLimits ? ( ) : null; const showEnvironmentFilter = environments.length > 0 || selectedEnvironmentIds !== null; const selectEnvironment = (value: string) => { if (value === "all") { setSelectedEnvironmentIds(null); return; } const id = EnvironmentId.make(value); setSelectedEnvironmentIds((selected) => toggleUsageEnvironment(selected, environments, id)); }; const environmentMenu = { title: gt("Filter usage environments"), icon: selectedEnvironmentIds === null ? ("line.3.horizontal.decrease" as const) : ("line.3.horizontal.decrease.circle.fill" as const), items: [ { id: "all", title: gt("All environments"), selected: selectedEnvironmentIds === null, onPress: () => selectEnvironment("all"), }, ...environments.map((environment) => ({ id: environment.environmentId, title: environment.label, subtitle: usageEnvironmentStatus(environment, refreshingUsage, m), selected: selectedEnvironmentIds === null || selectedEnvironmentIds.has(environment.environmentId), onPress: () => selectEnvironment(environment.environmentId), })), ], }; return ( {headerOnly ? null : ( setWidth(event.nativeEvent.layout.width)} refreshControl={ showingLimits || canReadDiagnostics ? ( void limits.refresh() : refreshWindow} /> ) : undefined } > {wide ? ( {showingLimits ? ( ) : ( )} ) : ( )} {wide ? monthPicker : null} {showingLimits ? ( ) : ( <> {wide ? null : ( )} {monthPicker} {merged.duplicateSources.length > 0 ? ( Counted once across environments sharing a transcript directory:{" "} {merged.duplicateSources.join(", ")} ) : null} {isPending ? ( Scanning provider transcripts… ) : selectedEnvironments.length === 0 ? ( {environments.length === 0 ? gt("Connect an environment to see usage.") : gt("Select an environment to see usage.")} ) : !canReadDiagnostics ? ( {selectedEnvironments.map((environment) => ( {selectedEnvironments.length > 1 ? `${environment.label}: ` : null} {environment.error} ))} ) : ( <> {sourceMessages.map((message) => ( {message} ))} {wide ? ( {providers} ) : ( <> {providers} )} = 900 ? 6 : wide ? 3 : 2} /> )} )} )} ); } function UsageMonthPicker(props: { readonly period: "month" | UsageMonthKey; readonly sinceDay: string; readonly untilDay: string; readonly onSelect: (period: UsagePeriod) => void; }) { const gt = useGT(); const locale = useLocale(); const monthKeys = selectableUsageMonths(); const thisMonth = gt("This month"); const chooseMonth = gt("Choose month"); const actions: MenuAction[] = [ { id: "month", title: thisMonth, state: props.period === "month" ? "on" : "off" }, ...monthKeys.slice(1).map((key): MenuAction => ({ id: key, title: formatUsageMonth(key, true, locale), state: props.period === key ? "on" : "off", })), ]; return ( { const next = parseUsagePeriod(nativeEvent.event); if (next !== undefined) props.onSelect(next); }} > {formatDayRange(props.sinceDay, props.untilDay, locale)} ); } function UsageUpdating({ dimmed, label, children, }: { readonly dimmed: boolean; readonly label: string | null; readonly children: ReactNode; }) { const reduceMotion = useReduceMotionEnabled(); // The delay keeps a quick refresh from flashing the content. const dimStyle = { opacity: dimmed ? 0.5 : 1, transitionProperty: "opacity", transitionDuration: reduceMotion ? 0 : 150, transitionDelay: dimmed ? 150 : 0, } as const; return ( {children} {label !== null ? ( {label} ) : null} ); } function ChartCard(props: { readonly merged: MergedUsage; readonly days: readonly string[]; readonly daily: readonly DailyTotals[]; readonly metric: UsageChartMetric; readonly sinceDay: string; readonly untilDay: string; readonly isPast24Hours: boolean; readonly timeZone: string; readonly height: number; /** Replaces the summary when it sits beside the chart. */ readonly title?: string; /** Grows the chart past `height` to match a taller neighbouring column. */ readonly fill?: boolean; }) { const { merged, metric } = props; const colors = useProviderColors(); const locale = useLocale(); const hasActivity = props.daily.some((period) => period.totalTokens > 0); const [fillHeight, setFillHeight] = useState(0); const height = props.fill ? Math.max(fillHeight, props.height) : props.height; const chart = hasActivity ? ( ) : ( No activity in this window. ); return ( {props.title ? ( {props.title} ) : ( )} {props.fill ? ( // Absolute so the measured slot can shrink again when the neighbour gets shorter. setFillHeight(event.nativeEvent.layout.height)} > {chart} ) : ( chart )} {props.isPast24Hours ? usageAxisHourLabel(props.days[0] ?? "", locale, props.timeZone) : usageAxisDayLabel(props.sinceDay, locale)} {props.isPast24Hours ? usageAxisHourLabel(props.days[props.days.length - 1] ?? "", locale, props.timeZone) : usageAxisDayLabel(props.untilDay, locale)} {merged.providers.map((provider) => ( {PROVIDER_LABEL[provider.provider]} ))} ); } function UsageSummary(props: { readonly merged: MergedUsage; readonly metric: UsageChartMetric }) { const { merged, metric } = props; const gt = useGT(); return ( {metric === "cost" ? gt("Raw token cost") : gt("Processed tokens")} {metric === "cost" ? `${formatUsd(merged.costUsd)}*` : formatTokens(merged.totalTokens)} {metric === "cost" ? gt("* if billed at full API rate") : gt("{count, plural, other {Across {sessions} sessions}}", { count: merged.sessions, sessions: formatCount(merged.sessions), })} ); } function ProviderSection(props: { readonly merged: MergedUsage; readonly metric: UsageChartMetric; /** Drops the share bar so the list fits beside the chart. */ readonly compact: boolean; }) { const { merged, metric } = props; const colors = useProviderColors(); const gt = useGT(); if (merged.providers.length === 0) return null; // Hermes lacks toSorted. 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 ( 0 && "border-t border-border-subtle", )} > {PROVIDER_LABEL[provider.provider]} {metric === "cost" ? formatUsd(provider.costUsd) : formatTokens(provider.totalTokens)} {props.compact ? null : ( )} {metric === "cost" ? gt("{share} of cost · {tokens} tokens", { share: formatPercent(share), tokens: formatTokens(provider.totalTokens), }) : gt("{share} of tokens · {cost}", { share: formatPercent(share), cost: formatUsd(provider.costUsd), })} ); })} ); } function TotalsSection(props: { readonly merged: MergedUsage; readonly isPast24Hours: boolean; readonly columns: number; }) { const { merged } = props; const gt = useGT(); const activePeriods = (props.isPast24Hours ? merged.hourly : merged.daily).filter( (period) => period.totalTokens > 0, ).length; const periodAverage = activePeriods === 0 ? 0 : merged.totalTokens / activePeriods; const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens; const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput; return ( 0 ? gt("{ratio}x the raw cost", { ratio: (merged.costQuality.cacheSavingsUsd / merged.costUsd).toFixed(1), }) : gt("vs full input rates", { $context: "detail under the cache savings amount, compared with full input prices", }) } /> ); } function CostSection(props: { readonly merged: MergedUsage; readonly wide: boolean }) { const { categoryCost, speedCost } = props.merged; const colors = useUsageMixColors(); const gt = useGT(); const byType = [ { label: gt("Input", { $context: "input tokens" }), value: categoryCost.input, color: colors.input, }, { label: gt("Cache read"), value: categoryCost.cacheRead, color: colors.cacheRead }, { label: gt("Cache write"), value: categoryCost.cacheWrite, color: colors.cacheWrite }, { label: gt("Output", { $context: "output tokens" }), value: categoryCost.output, color: colors.output, }, // Reported cost with no rates to split it, or from older servers. Below a // cent it is rounding, not usage. { label: gt("Other", { $context: "cost category" }), value: categoryCost.unsplit >= 0.005 ? categoryCost.unsplit : 0, color: colors.other, }, ]; const bySpeed = [ { label: gt("Standard", { $context: "model speed tier" }), value: speedCost.standard, color: colors.standard, }, { label: gt("Fast", { $context: "model speed tier" }), value: speedCost.fast, color: colors.fast, }, { label: gt("Ultrafast", { $context: "model speed tier" }), value: speedCost.ultrafast, color: colors.ultrafast, }, ]; if (props.merged.costUsd <= 0) return null; return ( {speedCost.fast + speedCost.ultrafast > 0 ? ( ) : null} ); } function ShareBar(props: { readonly label: string; readonly segments: readonly { label: string; value: number; color: string }[]; readonly aside?: string; }) { const visible = props.segments.filter((segment) => segment.value > 0); if (visible.length === 0) return null; return ( {props.label} {props.aside ? ( {props.aside} ) : null} {visible.map((segment) => ( ))} {visible.map((segment) => ( {segment.label} {formatUsd(segment.value)} ))} ); } function MetricCell(props: { readonly label: string; readonly value: string; readonly detail: string; readonly columns: number; }) { return ( {props.label} {props.value} {props.detail} ); } function ModelsSection(props: { readonly merged: MergedUsage; readonly metric: UsageChartMetric; readonly columns: 1 | 2; }) { const { merged, metric } = props; const colors = useProviderColors(); const gt = useGT(); if (merged.models.length === 0) return null; // Hermes lacks toSorted. const ordered = [...merged.models].sort((a, b) => metric === "cost" ? b.costUsd - a.costUsd || b.totalTokens - a.totalTokens : b.totalTokens - a.totalTokens || b.costUsd - a.costUsd, ); return ( {ordered.map((model, index) => ( = props.columns && "border-t border-border-subtle", index % props.columns === 1 && "border-l border-border-subtle", )} style={{ width: `${100 / props.columns}%` }} > {model.model} {metric === "tokens" ? isModelCostUnknown(model) ? gt("{share} of tokens · no known rates", { share: formatPercent(model.tokenShare), }) : gt("{share} of tokens · {cost}", { share: formatPercent(model.tokenShare), cost: formatUsd(model.costUsd), }) : isModelCostUnknown(model) ? gt("no known rates · {tokens} tokens", { tokens: formatTokens(model.totalTokens), }) : gt("{share} of cost · {tokens} tokens", { share: formatPercent(model.costShare), tokens: formatTokens(model.totalTokens), })} {metric === "tokens" ? formatTokens(model.totalTokens) : isModelCostUnknown(model) ? gt("Unpriced", { $context: "model with no known price" }) : formatUsd(model.costUsd)} ))} ); } function usageEnvironmentStatus( environment: EnvironmentUsageStatus, refreshing: boolean, resolve: MessageResolver, ): string { if ( environment.summary && !isCompatibleUsageContractVersion(environment.summary.contractVersion, USAGE_CONTRACT_VERSION) ) { return formatUsageContractMismatch( environment.label, { direction: environment.summary.contractVersion < USAGE_CONTRACT_VERSION ? "serverBehind" : "clientBehind", }, resolve, ); } if (environment.error) return environment.summary ? resolve(msg("{error} Showing saved totals.", { error: environment.error })) : environment.error; if (!environment.isConnected) return environment.summary ? resolve(msg("Disconnected · showing saved usage")) : resolve(msg("Waiting for connection…")); const progress = usageEnvironmentProgress(environment, refreshing); if (progress.phase === "loading") return resolve(msg("Loading usage…")); if (progress.phase === "stale") return resolve(msg("Updating usage…")); if (progress.phase === "partway") return updatingProvidersLabel(progress.providers, providerLabel, resolve); return resolve(msg("Usage up to date")); }