The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; |
| 2 | import { ChatGptUsageSummary } from "./ChatGptUsageSummary"; |
| 3 | import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView"; |
| 4 | import { EnvironmentId, USAGE_CONTRACT_VERSION, type UsageProviderKind } from "@t3tools/contracts"; |
| 5 | import { type RouteProp, useIsFocused, useRoute } from "@react-navigation/native"; |
| 6 | import { |
| 7 | updatingProvidersLabel, |
| 8 | usageEnvironmentProgress, |
| 9 | usageProgress, |
| 10 | } from "@t3tools/client-runtime/state/usage-progress"; |
| 11 | import { |
| 12 | isCompatibleUsageContractVersion, |
| 13 | isModelCostUnknown, |
| 14 | type DailyTotals, |
| 15 | type MergedUsage, |
| 16 | } from "@t3tools/shared/usageMerge"; |
| 17 | import { |
| 18 | enumerateDays, |
| 19 | enumerateHourStarts, |
| 20 | formatCount, |
| 21 | formatPercent, |
| 22 | formatTokens, |
| 23 | formatUsd, |
| 24 | makeWindow, |
| 25 | } from "@t3tools/shared/usageFormat"; |
| 26 | import { formatUsageContractMismatch, usageSourceMessages } from "@t3tools/shared/usageFormatCopy"; |
| 27 | import { msg, T, useGT, useLocale, useMessages, Var } from "gt-react-native"; |
| 28 | import { use, useRef, useState, type ReactNode } from "react"; |
| 29 | import { View } from "react-native"; |
| 30 | import { RefreshControl } from "../../components/ui/RefreshControl"; |
| 31 | import Animated, { FadeIn, ReduceMotion } from "react-native-reanimated"; |
| 32 | import { useSafeAreaInsets } from "react-native-safe-area-context"; |
| 33 | |
| 34 | import { SegmentedControl } from "../../components/ui/SegmentedControl"; |
| 35 | import { useReduceMotionEnabled } from "../../lib/appState"; |
| 36 | import { AppText as Text } from "../../components/ui/AppText"; |
| 37 | import { useWorkspaceSettledContentWidth } from "../layout/workspace-content-width"; |
| 38 | import { cn } from "../../lib/cn"; |
| 39 | import type { MessageResolver } from "../../i18n/messages"; |
| 40 | import { SettingsScreen } from "../settings/components/SettingsScreen"; |
| 41 | import { NativeWorkspaceTabActivityContext } from "../../native/v5-workspace-context"; |
| 42 | import { useUsage, type EnvironmentUsageStatus } from "../../state/usage"; |
| 43 | import { SettingsSection } from "../settings/components/SettingsSection"; |
| 44 | import { usageAxisDayLabel, usageAxisHourLabel } from "./usageAxisLabels"; |
| 45 | import { UsageDailyChart } from "./UsageDailyChart"; |
| 46 | import { toggleUsageEnvironment } from "./usageEnvironmentSelection"; |
| 47 | import { useRefreshLimits } from "./UsageLimitsSection"; |
| 48 | import { UsageLimitsSection } from "./UsageLimitsPooled"; |
| 49 | import type { UsageChartMetric } from "./usageChartData"; |
| 50 | import { PROVIDER_LABEL, useProviderColors, useUsageMixColors } from "./usageProviders"; |
| 51 | |
| 52 | type UsageView = UsageChartMetric | "limits"; |
| 53 | const VIEW_OPTIONS = [ |
| 54 | { value: "cost", label: msg("Cost", { $context: "usage view tab" }) }, |
| 55 | { value: "tokens", label: msg("Tokens", { $context: "usage view tab" }) }, |
| 56 | { value: "limits", label: msg("Limits", { $context: "usage view tab, subscription limits" }) }, |
| 57 | ] as const satisfies readonly { value: UsageView; label: string }[]; |
| 58 | |
| 59 | const WINDOW_OPTIONS = [ |
| 60 | { |
| 61 | value: 1, |
| 62 | label: msg("24h", { $context: "short label for the past 24 hours" }), |
| 63 | accessibilityLabel: msg("Past 24 hours"), |
| 64 | }, |
| 65 | { |
| 66 | value: 7, |
| 67 | label: msg("7d", { $context: "short label for the past 7 days" }), |
| 68 | accessibilityLabel: msg("Past 7 days"), |
| 69 | }, |
| 70 | { |
| 71 | value: 30, |
| 72 | label: msg("30d", { $context: "short label for the past 30 days" }), |
| 73 | accessibilityLabel: msg("Past 30 days"), |
| 74 | }, |
| 75 | { |
| 76 | value: 90, |
| 77 | label: msg("90d", { $context: "short label for the past 90 days" }), |
| 78 | accessibilityLabel: msg("Past 90 days"), |
| 79 | }, |
| 80 | ] as const; |
| 81 | |
| 82 | const CHART_HEIGHT = 180; |
| 83 | const WIDE_CHART_HEIGHT = 260; |
| 84 | // Below this the page keeps the phone's single column. |
| 85 | const WIDE_WIDTH = 600; |
| 86 | const MAX_CONTENT_WIDTH = 1080; |
| 87 | const providerLabel = (provider: UsageProviderKind) => PROVIDER_LABEL[provider]; |
| 88 | |
| 89 | export function UsageRouteScreen(props: { readonly workspace?: boolean }) { |
| 90 | const route = useRoute<RouteProp<{ Usage: { tab?: string } | undefined }, "Usage">>(); |
| 91 | return <UsageScreen workspace={props.workspace} tabParam={route.params?.tab} />; |
| 92 | } |
| 93 | |
| 94 | function UsageScreen(props: { |
| 95 | readonly workspace?: boolean; |
| 96 | readonly tabParam: string | undefined; |
| 97 | }) { |
| 98 | const gt = useGT(); |
| 99 | const m = useMessages(); |
| 100 | const viewOptions = VIEW_OPTIONS.map((option) => ({ ...option, label: m(option.label) })); |
| 101 | const windowOptions = WINDOW_OPTIONS.map((option) => ({ |
| 102 | ...option, |
| 103 | label: m(option.label), |
| 104 | accessibilityLabel: m(option.accessibilityLabel), |
| 105 | })); |
| 106 | const insets = useSafeAreaInsets(); |
| 107 | const headerOnly = use(NativeWorkspaceTabActivityContext)?.headerOnly === true; |
| 108 | const [selection, setSelection] = useState(() => ({ |
| 109 | params: props.tabParam, |
| 110 | view: (props.tabParam === "usage" ? "cost" : "limits") as UsageView, |
| 111 | })); |
| 112 | if (selection.params !== props.tabParam) { |
| 113 | setSelection({ |
| 114 | params: props.tabParam, |
| 115 | view: props.tabParam === "usage" ? "cost" : "limits", |
| 116 | }); |
| 117 | } |
| 118 | const { view } = selection; |
| 119 | const setView = (view: UsageView) => setSelection({ params: props.tabParam, view }); |
| 120 | const [measuredWidth, setWidth] = useState(0); |
| 121 | // A workspace pane knows its width in the render that resizes it; measuring lags a frame. |
| 122 | const width = useWorkspaceSettledContentWidth() ?? measuredWidth; |
| 123 | const wide = width >= WIDE_WIDTH; |
| 124 | const [windowSelection, setWindowSelection] = useState(() => ({ |
| 125 | days: 30, |
| 126 | window: makeWindow(30), |
| 127 | })); |
| 128 | const { days: windowDays, window } = windowSelection; |
| 129 | const isPast24Hours = windowDays === 1; |
| 130 | const [selectedEnvironmentIds, setSelectedEnvironmentIds] = |
| 131 | useState<ReadonlySet<EnvironmentId> | null>(null); |
| 132 | const { merged, environments, selectedEnvironments, isPending, refresh } = useUsage( |
| 133 | window, |
| 134 | selectedEnvironmentIds, |
| 135 | !headerOnly, |
| 136 | ); |
| 137 | const isFocused = useIsFocused(); |
| 138 | const limits = useRefreshLimits( |
| 139 | selectedEnvironmentIds, |
| 140 | isFocused && view === "limits" && !headerOnly, |
| 141 | ); |
| 142 | const sourceMessages = usageSourceMessages( |
| 143 | selectedEnvironments.flatMap((environment) => environment.summary?.sources ?? []), |
| 144 | m, |
| 145 | ); |
| 146 | const canReadDiagnostics = selectedEnvironments.some( |
| 147 | (environment) => environment.canReadDiagnostics, |
| 148 | ); |
| 149 | |
| 150 | const days = enumerateDays(window.sinceDay, window.untilDay); |
| 151 | const chartDays = |
| 152 | isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined |
| 153 | ? enumerateHourStarts(window.sinceTime, window.untilTime) |
| 154 | : days; |
| 155 | const chartTotals: readonly DailyTotals[] = isPast24Hours |
| 156 | ? merged.hourly.map((hour) => ({ |
| 157 | day: hour.hourStart, |
| 158 | costUsd: hour.costUsd, |
| 159 | totalTokens: hour.totalTokens, |
| 160 | byProvider: hour.byProvider, |
| 161 | })) |
| 162 | : merged.daily; |
| 163 | |
| 164 | const [refreshingUsage, setRefreshingUsage] = useState(false); |
| 165 | const refreshingRef = useRef(false); |
| 166 | const showingLimits = view === "limits"; |
| 167 | const metric: UsageChartMetric = view === "tokens" ? "tokens" : "cost"; |
| 168 | const progress = usageProgress( |
| 169 | selectedEnvironments, |
| 170 | { |
| 171 | refreshing: refreshingUsage, |
| 172 | providerLabel, |
| 173 | }, |
| 174 | m, |
| 175 | ); |
| 176 | const selectWindow = (days: number) => { |
| 177 | setWindowSelection({ |
| 178 | days, |
| 179 | window: makeWindow(days, undefined, days === 1 ? "hour" : "day"), |
| 180 | }); |
| 181 | }; |
| 182 | const refreshWindow = () => { |
| 183 | if (refreshingRef.current) return; |
| 184 | const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day"); |
| 185 | if ( |
| 186 | nextWindow.sinceDay !== window.sinceDay || |
| 187 | nextWindow.untilDay !== window.untilDay || |
| 188 | nextWindow.sinceTime !== window.sinceTime || |
| 189 | nextWindow.untilTime !== window.untilTime |
| 190 | ) { |
| 191 | setWindowSelection({ days: windowDays, window: nextWindow }); |
| 192 | } |
| 193 | refreshingRef.current = true; |
| 194 | setRefreshingUsage(true); |
| 195 | void refresh(nextWindow).finally(() => { |
| 196 | refreshingRef.current = false; |
| 197 | setRefreshingUsage(false); |
| 198 | }); |
| 199 | }; |
| 200 | |
| 201 | const chart = { |
| 202 | merged, |
| 203 | days: chartDays, |
| 204 | daily: chartTotals, |
| 205 | metric, |
| 206 | sinceDay: window.sinceDay, |
| 207 | untilDay: window.untilDay, |
| 208 | isPast24Hours, |
| 209 | timeZone: window.timeZone, |
| 210 | }; |
| 211 | const providers = <ProviderSection merged={merged} metric={metric} compact={wide} />; |
| 212 | |
| 213 | const showEnvironmentFilter = environments.length > 0 || selectedEnvironmentIds !== null; |
| 214 | const selectEnvironment = (value: string) => { |
| 215 | if (value === "all") { |
| 216 | setSelectedEnvironmentIds(null); |
| 217 | return; |
| 218 | } |
| 219 | const id = EnvironmentId.make(value); |
| 220 | setSelectedEnvironmentIds((selected) => toggleUsageEnvironment(selected, environments, id)); |
| 221 | }; |
| 222 | const environmentMenu = { |
| 223 | title: gt("Filter usage environments"), |
| 224 | icon: |
| 225 | selectedEnvironmentIds === null |
| 226 | ? ("line.3.horizontal.decrease" as const) |
| 227 | : ("line.3.horizontal.decrease.circle.fill" as const), |
| 228 | items: [ |
| 229 | { |
| 230 | id: "all", |
| 231 | title: gt("All environments"), |
| 232 | selected: selectedEnvironmentIds === null, |
| 233 | onPress: () => selectEnvironment("all"), |
| 234 | }, |
| 235 | ...environments.map((environment) => ({ |
| 236 | id: environment.environmentId, |
| 237 | title: environment.label, |
| 238 | subtitle: usageEnvironmentStatus(environment, refreshingUsage, m), |
| 239 | selected: |
| 240 | selectedEnvironmentIds === null || selectedEnvironmentIds.has(environment.environmentId), |
| 241 | onPress: () => selectEnvironment(environment.environmentId), |
| 242 | })), |
| 243 | ], |
| 244 | }; |
| 245 | |
| 246 | return ( |
| 247 | <SettingsScreen |
| 248 | title={gt("Usage", { $context: "screen title" })} |
| 249 | menus={showEnvironmentFilter ? [environmentMenu] : undefined} |
| 250 | workspaceRoot={props.workspace} |
| 251 | > |
| 252 | {headerOnly ? null : ( |
| 253 | <ScrollView |
| 254 | contentInsetAdjustmentBehavior="automatic" |
| 255 | showsVerticalScrollIndicator={false} |
| 256 | className="flex-1" |
| 257 | contentContainerClassName="px-5 pt-4" |
| 258 | contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }} |
| 259 | onLayout={(event) => setWidth(event.nativeEvent.layout.width)} |
| 260 | refreshControl={ |
| 261 | showingLimits || canReadDiagnostics ? ( |
| 262 | <RefreshControl |
| 263 | refreshing={showingLimits ? limits.refreshing : refreshingUsage} |
| 264 | onRefresh={showingLimits ? () => void limits.refresh() : refreshWindow} |
| 265 | /> |
| 266 | ) : undefined |
| 267 | } |
| 268 | > |
| 269 | <View className="w-full gap-6 self-center" style={{ maxWidth: MAX_CONTENT_WIDTH }}> |
| 270 | {wide ? ( |
| 271 | <View className="flex-row items-center gap-3"> |
| 272 | {showingLimits ? ( |
| 273 | <View className="flex-1" /> |
| 274 | ) : ( |
| 275 | <SegmentedControl |
| 276 | options={windowOptions} |
| 277 | selected={windowDays} |
| 278 | onSelect={selectWindow} |
| 279 | size="compact" |
| 280 | className="flex-1" |
| 281 | /> |
| 282 | )} |
| 283 | <SegmentedControl |
| 284 | options={viewOptions} |
| 285 | selected={view} |
| 286 | onSelect={setView} |
| 287 | size="compact" |
| 288 | role="tab" |
| 289 | className="flex-1" |
| 290 | /> |
| 291 | </View> |
| 292 | ) : ( |
| 293 | <SegmentedControl |
| 294 | options={viewOptions} |
| 295 | selected={view} |
| 296 | onSelect={setView} |
| 297 | role="tab" |
| 298 | /> |
| 299 | )} |
| 300 | <Animated.View |
| 301 | key={showingLimits ? "limits" : "usage"} |
| 302 | entering={FadeIn.duration(160).reduceMotion(ReduceMotion.System)} |
| 303 | className="gap-6" |
| 304 | > |
| 305 | {showingLimits ? ( |
| 306 | <UsageLimitsSection |
| 307 | now={limits.now} |
| 308 | failedLabels={limits.failedLabels} |
| 309 | selectedEnvironmentIds={selectedEnvironmentIds} |
| 310 | wide={wide} |
| 311 | /> |
| 312 | ) : ( |
| 313 | <> |
| 314 | {wide ? null : ( |
| 315 | <SegmentedControl |
| 316 | options={windowOptions} |
| 317 | selected={windowDays} |
| 318 | onSelect={selectWindow} |
| 319 | size="compact" |
| 320 | /> |
| 321 | )} |
| 322 | <ChatGptUsageSummary selectedEnvironmentIds={selectedEnvironmentIds} /> |
| 323 | {merged.duplicateSources.length > 0 ? ( |
| 324 | <Text className="text-sm text-foreground-muted"> |
| 325 | <T> |
| 326 | Counted once across environments sharing a transcript directory:{" "} |
| 327 | <Var>{merged.duplicateSources.join(", ")}</Var> |
| 328 | </T> |
| 329 | </Text> |
| 330 | ) : null} |
| 331 | {isPending ? ( |
| 332 | <Text className="py-16 text-center text-base text-foreground-muted"> |
| 333 | <T>Scanning provider transcripts…</T> |
| 334 | </Text> |
| 335 | ) : selectedEnvironments.length === 0 ? ( |
| 336 | <Text className="py-16 text-center text-base text-foreground-muted"> |
| 337 | {environments.length === 0 |
| 338 | ? gt("Connect an environment to see usage.") |
| 339 | : gt("Select an environment to see usage.")} |
| 340 | </Text> |
| 341 | ) : !canReadDiagnostics ? ( |
| 342 | <View className="gap-2 py-16"> |
| 343 | {selectedEnvironments.map((environment) => ( |
| 344 | <Text |
| 345 | key={environment.environmentId} |
| 346 | className="text-center text-base text-foreground-muted" |
| 347 | > |
| 348 | {selectedEnvironments.length > 1 ? `${environment.label}: ` : null} |
| 349 | {environment.error} |
| 350 | </Text> |
| 351 | ))} |
| 352 | </View> |
| 353 | ) : ( |
| 354 | <> |
| 355 | {sourceMessages.map((message) => ( |
| 356 | <Text key={message} className="text-sm text-foreground-muted"> |
| 357 | {message} |
| 358 | </Text> |
| 359 | ))} |
| 360 | <UsageUpdating dimmed={progress.dimmed} label={progress.label}> |
| 361 | {wide ? ( |
| 362 | <View className="flex-row gap-6"> |
| 363 | <View className="w-72 gap-6"> |
| 364 | <View className="rounded-[24px] border-continuous bg-grouped-card p-4"> |
| 365 | <UsageSummary merged={merged} metric={metric} /> |
| 366 | </View> |
| 367 | {providers} |
| 368 | </View> |
| 369 | <View className="min-w-0 flex-1"> |
| 370 | <ChartCard |
| 371 | {...chart} |
| 372 | height={WIDE_CHART_HEIGHT} |
| 373 | fill |
| 374 | title={ |
| 375 | isPast24Hours |
| 376 | ? metric === "cost" |
| 377 | ? gt("Hourly cost") |
| 378 | : gt("Hourly processed tokens") |
| 379 | : metric === "cost" |
| 380 | ? gt("Daily cost") |
| 381 | : gt("Daily processed tokens") |
| 382 | } |
| 383 | /> |
| 384 | </View> |
| 385 | </View> |
| 386 | ) : ( |
| 387 | <> |
| 388 | <ChartCard {...chart} height={CHART_HEIGHT} /> |
| 389 | {providers} |
| 390 | </> |
| 391 | )} |
| 392 | <TotalsSection |
| 393 | merged={merged} |
| 394 | isPast24Hours={isPast24Hours} |
| 395 | columns={width >= 900 ? 6 : wide ? 3 : 2} |
| 396 | /> |
| 397 | <CostSection merged={merged} wide={wide} /> |
| 398 | <ModelsSection merged={merged} metric={metric} columns={wide ? 2 : 1} /> |
| 399 | </UsageUpdating> |
| 400 | </> |
| 401 | )} |
| 402 | </> |
| 403 | )} |
| 404 | </Animated.View> |
| 405 | </View> |
| 406 | </ScrollView> |
| 407 | )} |
| 408 | </SettingsScreen> |
| 409 | ); |
| 410 | } |
| 411 | |
| 412 | function UsageUpdating({ |
| 413 | dimmed, |
| 414 | label, |
| 415 | children, |
| 416 | }: { |
| 417 | readonly dimmed: boolean; |
| 418 | readonly label: string | null; |
| 419 | readonly children: ReactNode; |
| 420 | }) { |
| 421 | const reduceMotion = useReduceMotionEnabled(); |
| 422 | // The delay keeps a quick refresh from flashing the content. |
| 423 | const dimStyle = { |
| 424 | opacity: dimmed ? 0.5 : 1, |
| 425 | transitionProperty: "opacity", |
| 426 | transitionDuration: reduceMotion ? 0 : 150, |
| 427 | transitionDelay: dimmed ? 150 : 0, |
| 428 | } as const; |
| 429 | |
| 430 | return ( |
| 431 | <View> |
| 432 | <Animated.View style={dimStyle} className="gap-6" accessibilityState={{ busy: dimmed }}> |
| 433 | {children} |
| 434 | </Animated.View> |
| 435 | {label !== null ? ( |
| 436 | <Animated.View |
| 437 | entering={FadeIn.delay(150).duration(150).reduceMotion(ReduceMotion.System)} |
| 438 | accessibilityLiveRegion="polite" |
| 439 | pointerEvents="none" |
| 440 | className="absolute right-4 top-4 h-5 max-w-[55%] flex-row items-center gap-1.5" |
| 441 | > |
| 442 | <AppActivityIndicator size="small" colorClassName="accent-adaptive-sky-600-400" /> |
| 443 | <Text className="shrink text-sm text-adaptive-sky-600-400" numberOfLines={1}> |
| 444 | {label} |
| 445 | </Text> |
| 446 | </Animated.View> |
| 447 | ) : null} |
| 448 | </View> |
| 449 | ); |
| 450 | } |
| 451 | |
| 452 | function ChartCard(props: { |
| 453 | readonly merged: MergedUsage; |
| 454 | readonly days: readonly string[]; |
| 455 | readonly daily: readonly DailyTotals[]; |
| 456 | readonly metric: UsageChartMetric; |
| 457 | readonly sinceDay: string; |
| 458 | readonly untilDay: string; |
| 459 | readonly isPast24Hours: boolean; |
| 460 | readonly timeZone: string; |
| 461 | readonly height: number; |
| 462 | /** Replaces the summary when it sits beside the chart. */ |
| 463 | readonly title?: string; |
| 464 | /** Grows the chart past `height` to match a taller neighbouring column. */ |
| 465 | readonly fill?: boolean; |
| 466 | }) { |
| 467 | const { merged, metric } = props; |
| 468 | const colors = useProviderColors(); |
| 469 | const locale = useLocale(); |
| 470 | const hasActivity = props.daily.some((period) => period.totalTokens > 0); |
| 471 | const [fillHeight, setFillHeight] = useState(0); |
| 472 | const height = props.fill ? Math.max(fillHeight, props.height) : props.height; |
| 473 | const chart = hasActivity ? ( |
| 474 | <UsageDailyChart days={props.days} daily={props.daily} metric={metric} height={height} /> |
| 475 | ) : ( |
| 476 | <View style={{ height }} className="items-center justify-center"> |
| 477 | <Text className="text-base text-foreground-muted"> |
| 478 | <T>No activity in this window.</T> |
| 479 | </Text> |
| 480 | </View> |
| 481 | ); |
| 482 | |
| 483 | return ( |
| 484 | <View |
| 485 | className={`gap-4 rounded-[24px] border-continuous bg-grouped-card p-4${props.fill ? " flex-1" : ""}`} |
| 486 | > |
| 487 | {props.title ? ( |
| 488 | <Text className="text-sm font-t3-medium text-foreground">{props.title}</Text> |
| 489 | ) : ( |
| 490 | <UsageSummary merged={merged} metric={metric} /> |
| 491 | )} |
| 492 | |
| 493 | {props.fill ? ( |
| 494 | // Absolute so the measured slot can shrink again when the neighbour gets shorter. |
| 495 | <View |
| 496 | className="flex-1" |
| 497 | style={{ minHeight: props.height }} |
| 498 | onLayout={(event) => setFillHeight(event.nativeEvent.layout.height)} |
| 499 | > |
| 500 | <View className="absolute inset-0">{chart}</View> |
| 501 | </View> |
| 502 | ) : ( |
| 503 | chart |
| 504 | )} |
| 505 | |
| 506 | <View className="gap-2"> |
| 507 | <View className="flex-row items-center justify-between"> |
| 508 | <Text className="text-xs text-foreground-tertiary"> |
| 509 | {props.isPast24Hours |
| 510 | ? usageAxisHourLabel(props.days[0] ?? "", locale, props.timeZone) |
| 511 | : usageAxisDayLabel(props.sinceDay, locale)} |
| 512 | </Text> |
| 513 | <Text className="text-xs text-foreground-tertiary"> |
| 514 | {props.isPast24Hours |
| 515 | ? usageAxisHourLabel(props.days[props.days.length - 1] ?? "", locale, props.timeZone) |
| 516 | : usageAxisDayLabel(props.untilDay, locale)} |
| 517 | </Text> |
| 518 | </View> |
| 519 | <View className="flex-row flex-wrap items-center gap-x-4 gap-y-1"> |
| 520 | {merged.providers.map((provider) => ( |
| 521 | <View key={provider.provider} className="flex-row items-center gap-1.5"> |
| 522 | <View |
| 523 | className="size-2 rounded-full" |
| 524 | style={{ backgroundColor: colors[provider.provider] }} |
| 525 | /> |
| 526 | <Text className="text-xs text-foreground-muted"> |
| 527 | {PROVIDER_LABEL[provider.provider]} |
| 528 | </Text> |
| 529 | </View> |
| 530 | ))} |
| 531 | </View> |
| 532 | </View> |
| 533 | </View> |
| 534 | ); |
| 535 | } |
| 536 | |
| 537 | function UsageSummary(props: { readonly merged: MergedUsage; readonly metric: UsageChartMetric }) { |
| 538 | const { merged, metric } = props; |
| 539 | const gt = useGT(); |
| 540 | return ( |
| 541 | <View className="gap-0.5"> |
| 542 | <Text className="text-sm text-foreground-muted"> |
| 543 | {metric === "cost" ? gt("Raw token cost") : gt("Processed tokens")} |
| 544 | </Text> |
| 545 | <Text className="text-4xl font-t3-bold tabular-nums text-foreground"> |
| 546 | {metric === "cost" ? `${formatUsd(merged.costUsd)}*` : formatTokens(merged.totalTokens)} |
| 547 | </Text> |
| 548 | <Text className="text-sm text-foreground-muted"> |
| 549 | {metric === "cost" |
| 550 | ? gt("* if billed at full API rate") |
| 551 | : gt("{count, plural, other {Across {sessions} sessions}}", { |
| 552 | count: merged.sessions, |
| 553 | sessions: formatCount(merged.sessions), |
| 554 | })} |
| 555 | </Text> |
| 556 | </View> |
| 557 | ); |
| 558 | } |
| 559 | |
| 560 | function ProviderSection(props: { |
| 561 | readonly merged: MergedUsage; |
| 562 | readonly metric: UsageChartMetric; |
| 563 | /** Drops the share bar so the list fits beside the chart. */ |
| 564 | readonly compact: boolean; |
| 565 | }) { |
| 566 | const { merged, metric } = props; |
| 567 | const colors = useProviderColors(); |
| 568 | const gt = useGT(); |
| 569 | if (merged.providers.length === 0) return null; |
| 570 | |
| 571 | // Hermes lacks toSorted. |
| 572 | const ordered = [...merged.providers].sort((a, b) => |
| 573 | metric === "cost" ? b.costUsd - a.costUsd : b.totalTokens - a.totalTokens, |
| 574 | ); |
| 575 | |
| 576 | return ( |
| 577 | <SettingsSection title={gt("Providers")}> |
| 578 | {ordered.map((provider, index) => { |
| 579 | const share = metric === "cost" ? provider.costShare : provider.tokenShare; |
| 580 | return ( |
| 581 | <View |
| 582 | key={provider.provider} |
| 583 | className={cn( |
| 584 | props.compact ? "gap-0.5 px-4 py-3" : "gap-2 p-4", |
| 585 | index > 0 && "border-t border-border-subtle", |
| 586 | )} |
| 587 | > |
| 588 | <View className="flex-row items-baseline justify-between gap-3"> |
| 589 | <View className="flex-row items-center gap-2"> |
| 590 | <View |
| 591 | className="size-2.5 rounded-full" |
| 592 | style={{ backgroundColor: colors[provider.provider] }} |
| 593 | /> |
| 594 | <Text |
| 595 | className={ |
| 596 | props.compact ? "text-base text-foreground" : "text-lg text-foreground" |
| 597 | } |
| 598 | > |
| 599 | {PROVIDER_LABEL[provider.provider]} |
| 600 | </Text> |
| 601 | </View> |
| 602 | <Text |
| 603 | className={ |
| 604 | props.compact |
| 605 | ? "text-base tabular-nums text-foreground" |
| 606 | : "text-lg tabular-nums text-foreground" |
| 607 | } |
| 608 | > |
| 609 | {metric === "cost" |
| 610 | ? formatUsd(provider.costUsd) |
| 611 | : formatTokens(provider.totalTokens)} |
| 612 | </Text> |
| 613 | </View> |
| 614 | {props.compact ? null : ( |
| 615 | <View className="h-1 flex-row overflow-hidden rounded-full bg-subtle"> |
| 616 | <View |
| 617 | className="h-full rounded-full" |
| 618 | style={{ flex: share, backgroundColor: colors[provider.provider] }} |
| 619 | /> |
| 620 | <View style={{ flex: 1 - share }} /> |
| 621 | </View> |
| 622 | )} |
| 623 | <Text className="text-sm text-foreground-muted"> |
| 624 | {metric === "cost" |
| 625 | ? gt("{share} of cost · {tokens} tokens", { |
| 626 | share: formatPercent(share), |
| 627 | tokens: formatTokens(provider.totalTokens), |
| 628 | }) |
| 629 | : gt("{share} of tokens · {cost}", { |
| 630 | share: formatPercent(share), |
| 631 | cost: formatUsd(provider.costUsd), |
| 632 | })} |
| 633 | </Text> |
| 634 | </View> |
| 635 | ); |
| 636 | })} |
| 637 | </SettingsSection> |
| 638 | ); |
| 639 | } |
| 640 | |
| 641 | function TotalsSection(props: { |
| 642 | readonly merged: MergedUsage; |
| 643 | readonly isPast24Hours: boolean; |
| 644 | readonly columns: number; |
| 645 | }) { |
| 646 | const { merged } = props; |
| 647 | const gt = useGT(); |
| 648 | const activePeriods = (props.isPast24Hours ? merged.hourly : merged.daily).filter( |
| 649 | (period) => period.totalTokens > 0, |
| 650 | ).length; |
| 651 | const periodAverage = activePeriods === 0 ? 0 : merged.totalTokens / activePeriods; |
| 652 | const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens; |
| 653 | const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput; |
| 654 | |
| 655 | return ( |
| 656 | <SettingsSection title={gt("Totals")}> |
| 657 | <View className="flex-row flex-wrap"> |
| 658 | <MetricCell |
| 659 | columns={props.columns} |
| 660 | label={gt("Processed tokens")} |
| 661 | value={formatTokens(merged.totalTokens)} |
| 662 | detail={ |
| 663 | props.isPast24Hours |
| 664 | ? gt("{tokens} per active hour", { tokens: formatTokens(periodAverage) }) |
| 665 | : gt("{tokens} per active day", { tokens: formatTokens(periodAverage) }) |
| 666 | } |
| 667 | /> |
| 668 | <MetricCell |
| 669 | columns={props.columns} |
| 670 | label={gt("Cache savings")} |
| 671 | value={formatUsd(merged.costQuality.cacheSavingsUsd)} |
| 672 | detail={ |
| 673 | merged.costUsd > 0 |
| 674 | ? gt("{ratio}x the raw cost", { |
| 675 | ratio: (merged.costQuality.cacheSavingsUsd / merged.costUsd).toFixed(1), |
| 676 | }) |
| 677 | : gt("vs full input rates", { |
| 678 | $context: |
| 679 | "detail under the cache savings amount, compared with full input prices", |
| 680 | }) |
| 681 | } |
| 682 | /> |
| 683 | <MetricCell |
| 684 | columns={props.columns} |
| 685 | label={gt("Cached input")} |
| 686 | value={formatTokens(merged.cachedInputTokens)} |
| 687 | detail={gt("{share} of observed input", { share: formatPercent(cachedShare) })} |
| 688 | /> |
| 689 | <MetricCell |
| 690 | columns={props.columns} |
| 691 | label={gt("Uncached input")} |
| 692 | value={formatTokens(merged.uncachedInputTokens)} |
| 693 | detail={gt("{tokens} cache writes", { tokens: formatTokens(merged.cacheCreationTokens) })} |
| 694 | /> |
| 695 | <MetricCell |
| 696 | columns={props.columns} |
| 697 | label={gt("Output", { $context: "output tokens" })} |
| 698 | value={formatTokens(merged.outputTokens)} |
| 699 | detail={gt("incl. {tokens} reasoning", { tokens: formatTokens(merged.reasoningTokens) })} |
| 700 | /> |
| 701 | <MetricCell |
| 702 | columns={props.columns} |
| 703 | label={gt("Unpriced", { $context: "share of usage records with no known price" })} |
| 704 | value={formatPercent(merged.costQuality.unpricedShare)} |
| 705 | detail={gt("of records, excluded from cost", { |
| 706 | $context: "detail under a percentage of usage records that have no known price", |
| 707 | })} |
| 708 | /> |
| 709 | </View> |
| 710 | </SettingsSection> |
| 711 | ); |
| 712 | } |
| 713 | |
| 714 | function CostSection(props: { readonly merged: MergedUsage; readonly wide: boolean }) { |
| 715 | const { categoryCost, speedCost } = props.merged; |
| 716 | const colors = useUsageMixColors(); |
| 717 | const gt = useGT(); |
| 718 | const byType = [ |
| 719 | { |
| 720 | label: gt("Input", { $context: "input tokens" }), |
| 721 | value: categoryCost.input, |
| 722 | color: colors.input, |
| 723 | }, |
| 724 | { label: gt("Cache read"), value: categoryCost.cacheRead, color: colors.cacheRead }, |
| 725 | { label: gt("Cache write"), value: categoryCost.cacheWrite, color: colors.cacheWrite }, |
| 726 | { |
| 727 | label: gt("Output", { $context: "output tokens" }), |
| 728 | value: categoryCost.output, |
| 729 | color: colors.output, |
| 730 | }, |
| 731 | // Reported cost with no rates to split it, or from older servers. Below a |
| 732 | // cent it is rounding, not usage. |
| 733 | { |
| 734 | label: gt("Other", { $context: "cost category" }), |
| 735 | value: categoryCost.unsplit >= 0.005 ? categoryCost.unsplit : 0, |
| 736 | color: colors.other, |
| 737 | }, |
| 738 | ]; |
| 739 | const bySpeed = [ |
| 740 | { |
| 741 | label: gt("Standard", { $context: "model speed tier" }), |
| 742 | value: speedCost.standard, |
| 743 | color: colors.standard, |
| 744 | }, |
| 745 | { |
| 746 | label: gt("Fast", { $context: "model speed tier" }), |
| 747 | value: speedCost.fast, |
| 748 | color: colors.fast, |
| 749 | }, |
| 750 | { |
| 751 | label: gt("Ultrafast", { $context: "model speed tier" }), |
| 752 | value: speedCost.ultrafast, |
| 753 | color: colors.ultrafast, |
| 754 | }, |
| 755 | ]; |
| 756 | if (props.merged.costUsd <= 0) return null; |
| 757 | |
| 758 | return ( |
| 759 | <SettingsSection title={gt("Cost", { $context: "section heading" })}> |
| 760 | <View className={props.wide ? "flex-row" : undefined}> |
| 761 | <View className={props.wide ? "min-w-0 flex-1" : undefined}> |
| 762 | <ShareBar label={gt("By type")} segments={byType} /> |
| 763 | </View> |
| 764 | {speedCost.fast + speedCost.ultrafast > 0 ? ( |
| 765 | <View |
| 766 | className={ |
| 767 | props.wide |
| 768 | ? "min-w-0 flex-1 border-l border-border-subtle" |
| 769 | : "border-t border-border-subtle" |
| 770 | } |
| 771 | > |
| 772 | <ShareBar |
| 773 | label={gt("By speed")} |
| 774 | segments={bySpeed} |
| 775 | aside={gt("{cost} premium", { cost: formatUsd(speedCost.premium) })} |
| 776 | /> |
| 777 | </View> |
| 778 | ) : null} |
| 779 | </View> |
| 780 | </SettingsSection> |
| 781 | ); |
| 782 | } |
| 783 | |
| 784 | function ShareBar(props: { |
| 785 | readonly label: string; |
| 786 | readonly segments: readonly { label: string; value: number; color: string }[]; |
| 787 | readonly aside?: string; |
| 788 | }) { |
| 789 | const visible = props.segments.filter((segment) => segment.value > 0); |
| 790 | if (visible.length === 0) return null; |
| 791 | |
| 792 | return ( |
| 793 | <View className="gap-3 p-4"> |
| 794 | <View className="flex-row items-baseline justify-between gap-3"> |
| 795 | <Text className="text-sm text-foreground-muted">{props.label}</Text> |
| 796 | {props.aside ? ( |
| 797 | <Text className="text-sm tabular-nums text-foreground-muted">{props.aside}</Text> |
| 798 | ) : null} |
| 799 | </View> |
| 800 | <View className="h-2 flex-row gap-0.5"> |
| 801 | {visible.map((segment) => ( |
| 802 | <View |
| 803 | key={segment.label} |
| 804 | className="h-full rounded-sm" |
| 805 | style={{ flex: segment.value, backgroundColor: segment.color }} |
| 806 | /> |
| 807 | ))} |
| 808 | </View> |
| 809 | <View className="flex-row flex-wrap gap-x-4 gap-y-1.5"> |
| 810 | {visible.map((segment) => ( |
| 811 | <View key={segment.label} className="flex-row items-center gap-1.5"> |
| 812 | <View className="size-2 rounded-sm" style={{ backgroundColor: segment.color }} /> |
| 813 | <Text className="text-sm text-foreground-muted">{segment.label}</Text> |
| 814 | <Text className="text-sm tabular-nums text-foreground">{formatUsd(segment.value)}</Text> |
| 815 | </View> |
| 816 | ))} |
| 817 | </View> |
| 818 | </View> |
| 819 | ); |
| 820 | } |
| 821 | |
| 822 | function MetricCell(props: { |
| 823 | readonly label: string; |
| 824 | readonly value: string; |
| 825 | readonly detail: string; |
| 826 | readonly columns: number; |
| 827 | }) { |
| 828 | return ( |
| 829 | <View className="gap-0.5 p-4" style={{ width: `${100 / props.columns}%` }}> |
| 830 | <Text className="text-sm text-foreground-muted">{props.label}</Text> |
| 831 | <Text className="text-xl font-t3-medium tabular-nums text-foreground">{props.value}</Text> |
| 832 | <Text className="text-xs text-foreground-tertiary">{props.detail}</Text> |
| 833 | </View> |
| 834 | ); |
| 835 | } |
| 836 | |
| 837 | function ModelsSection(props: { |
| 838 | readonly merged: MergedUsage; |
| 839 | readonly metric: UsageChartMetric; |
| 840 | readonly columns: 1 | 2; |
| 841 | }) { |
| 842 | const { merged, metric } = props; |
| 843 | const colors = useProviderColors(); |
| 844 | const gt = useGT(); |
| 845 | if (merged.models.length === 0) return null; |
| 846 | |
| 847 | // Hermes lacks toSorted. |
| 848 | const ordered = [...merged.models].sort((a, b) => |
| 849 | metric === "cost" |
| 850 | ? b.costUsd - a.costUsd || b.totalTokens - a.totalTokens |
| 851 | : b.totalTokens - a.totalTokens || b.costUsd - a.costUsd, |
| 852 | ); |
| 853 | |
| 854 | return ( |
| 855 | <SettingsSection title={gt("By model")}> |
| 856 | <View className="flex-row flex-wrap"> |
| 857 | {ordered.map((model, index) => ( |
| 858 | <View |
| 859 | key={`${model.provider}:${model.model}`} |
| 860 | className={cn( |
| 861 | "flex-row items-center gap-3 p-4", |
| 862 | index >= props.columns && "border-t border-border-subtle", |
| 863 | index % props.columns === 1 && "border-l border-border-subtle", |
| 864 | )} |
| 865 | style={{ width: `${100 / props.columns}%` }} |
| 866 | > |
| 867 | <View |
| 868 | className="size-2.5 shrink-0 rounded-full" |
| 869 | style={{ backgroundColor: colors[model.provider] }} |
| 870 | /> |
| 871 | <View className="min-w-0 flex-1 gap-0.5"> |
| 872 | <Text className="text-base text-foreground" numberOfLines={1}> |
| 873 | {model.model} |
| 874 | </Text> |
| 875 | <Text className="text-sm text-foreground-muted"> |
| 876 | {metric === "tokens" |
| 877 | ? isModelCostUnknown(model) |
| 878 | ? gt("{share} of tokens · no known rates", { |
| 879 | share: formatPercent(model.tokenShare), |
| 880 | }) |
| 881 | : gt("{share} of tokens · {cost}", { |
| 882 | share: formatPercent(model.tokenShare), |
| 883 | cost: formatUsd(model.costUsd), |
| 884 | }) |
| 885 | : isModelCostUnknown(model) |
| 886 | ? gt("no known rates · {tokens} tokens", { |
| 887 | tokens: formatTokens(model.totalTokens), |
| 888 | }) |
| 889 | : gt("{share} of cost · {tokens} tokens", { |
| 890 | share: formatPercent(model.costShare), |
| 891 | tokens: formatTokens(model.totalTokens), |
| 892 | })} |
| 893 | </Text> |
| 894 | </View> |
| 895 | <Text className="text-base tabular-nums text-foreground"> |
| 896 | {metric === "tokens" |
| 897 | ? formatTokens(model.totalTokens) |
| 898 | : isModelCostUnknown(model) |
| 899 | ? gt("Unpriced", { $context: "model with no known price" }) |
| 900 | : formatUsd(model.costUsd)} |
| 901 | </Text> |
| 902 | </View> |
| 903 | ))} |
| 904 | </View> |
| 905 | </SettingsSection> |
| 906 | ); |
| 907 | } |
| 908 | |
| 909 | function usageEnvironmentStatus( |
| 910 | environment: EnvironmentUsageStatus, |
| 911 | refreshing: boolean, |
| 912 | resolve: MessageResolver, |
| 913 | ): string { |
| 914 | if ( |
| 915 | environment.summary && |
| 916 | !isCompatibleUsageContractVersion(environment.summary.contractVersion, USAGE_CONTRACT_VERSION) |
| 917 | ) { |
| 918 | return formatUsageContractMismatch( |
| 919 | environment.label, |
| 920 | { |
| 921 | direction: |
| 922 | environment.summary.contractVersion < USAGE_CONTRACT_VERSION |
| 923 | ? "serverBehind" |
| 924 | : "clientBehind", |
| 925 | }, |
| 926 | resolve, |
| 927 | ); |
| 928 | } |
| 929 | if (environment.error) |
| 930 | return environment.summary |
| 931 | ? resolve(msg("{error} Showing saved totals.", { error: environment.error })) |
| 932 | : environment.error; |
| 933 | if (!environment.isConnected) |
| 934 | return environment.summary |
| 935 | ? resolve(msg("Disconnected · showing saved usage")) |
| 936 | : resolve(msg("Waiting for connection…")); |
| 937 | const progress = usageEnvironmentProgress(environment, refreshing); |
| 938 | if (progress.phase === "loading") return resolve(msg("Loading usage…")); |
| 939 | if (progress.phase === "stale") return resolve(msg("Updating usage…")); |
| 940 | if (progress.phase === "partway") |
| 941 | return updatingProvidersLabel(progress.providers, providerLabel, resolve); |
| 942 | return resolve(msg("Usage up to date")); |
| 943 | } |