The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { ChatGptUsageButton } from "../settings/ChatGptUsageButton"; |
| 2 | import { usesChatGptSharing } from "@t3tools/shared/usageLimits"; |
| 3 | import { RefreshIcon } from "~/components/ui/refresh-icon"; |
| 4 | import { useAtomValue } from "@effect/atom-react"; |
| 5 | import { Atom } from "effect/reactivity"; |
| 6 | import { |
| 7 | USAGE_CONTRACT_VERSION, |
| 8 | type EnvironmentId, |
| 9 | type UsageProviderKind, |
| 10 | type UsageSummaryInput, |
| 11 | } from "@t3tools/contracts"; |
| 12 | import { CircleAlertIcon, ChevronDownIcon, InfoIcon, SlidersHorizontalIcon } from "lucide-react"; |
| 13 | import { T, useGT, useLocale, useMessages, Var } from "gt-react"; |
| 14 | import { useEffect, useEffectEvent, useRef, useState } from "react"; |
| 15 | import { settlePromise } from "@t3tools/client-runtime/state/runtime"; |
| 16 | import * as AsyncResult from "effect/reactivity/AsyncResult"; |
| 17 | import * as Cause from "effect/Cause"; |
| 18 | import { refreshUsageLimits } from "@t3tools/client-runtime/state/usage"; |
| 19 | import { |
| 20 | updatingProvidersLabel, |
| 21 | usageEnvironmentProgress, |
| 22 | usageLoadingState, |
| 23 | } from "@t3tools/client-runtime/state/usage-progress"; |
| 24 | |
| 25 | import { |
| 26 | isCompatibleUsageContractVersion, |
| 27 | isModelCostUnknown, |
| 28 | type DailyTotals, |
| 29 | type HourlyTotals, |
| 30 | type MergedUsage, |
| 31 | } from "@t3tools/shared/usageMerge"; |
| 32 | |
| 33 | import { cn } from "../../lib/utils"; |
| 34 | import { usePrimarySettings } from "../../hooks/useSettings"; |
| 35 | import { resolveHour12 } from "../../timestampFormat"; |
| 36 | import { appAtomRegistry } from "~/rpc/atomRegistry"; |
| 37 | import { environmentPresentations } from "../../state/presentation"; |
| 38 | import { primaryServerKeybindingsAtom, serverEnvironment } from "../../state/server"; |
| 39 | import { isCommandPaletteOpen } from "../../commandPaletteBus"; |
| 40 | import { isModelPickerOpen } from "../../modelPickerVisibility"; |
| 41 | import { shortcutLabelForCommand } from "../../keybindings"; |
| 42 | import { useUsage, type EnvironmentUsageStatus } from "../../state/usage"; |
| 43 | import { useAtomCommand } from "../../state/use-atom-command"; |
| 44 | import { |
| 45 | enumerateDays, |
| 46 | enumerateHourStarts, |
| 47 | formatCount, |
| 48 | formatDateTimeShort, |
| 49 | formatDayShort, |
| 50 | formatHourShort, |
| 51 | formatPercent, |
| 52 | formatTokens, |
| 53 | formatUsd, |
| 54 | makeWindow, |
| 55 | } from "@t3tools/shared/usageFormat"; |
| 56 | import { formatUsageContractMismatch, usageSourceMessages } from "@t3tools/shared/usageFormatCopy"; |
| 57 | import { Button, InlineButton } from "../ui/button"; |
| 58 | import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; |
| 59 | import { |
| 60 | Menu, |
| 61 | MenuCheckboxItem, |
| 62 | MenuItem, |
| 63 | MenuPopup, |
| 64 | MenuSeparator, |
| 65 | MenuTrigger, |
| 66 | } from "../ui/menu"; |
| 67 | import { ScrollArea } from "../ui/scroll-area"; |
| 68 | import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; |
| 69 | import { AppRouteModal, AppRouteModalClose } from "../AppRouteModal"; |
| 70 | import { Skeleton } from "../ui/skeleton"; |
| 71 | import { Toggle, ToggleGroup } from "../ui/toggle-group"; |
| 72 | import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; |
| 73 | import { |
| 74 | WorkspaceBreadcrumb, |
| 75 | WorkspaceBreadcrumbItem, |
| 76 | WorkspaceBreadcrumbSeparator, |
| 77 | WorkspaceBreadcrumbText, |
| 78 | } from "../WorkspaceBreadcrumb"; |
| 79 | import { WorkspacePageContainer } from "../WorkspacePageContainer"; |
| 80 | import { UsageLimitsSection } from "./UsageLimits"; |
| 81 | import { UsagePriceOverrides } from "./UsagePriceOverrides"; |
| 82 | import { UsageProviderChart } from "./UsageProviderChart"; |
| 83 | import { SpeedPremium, UsageModelDialog } from "./UsageModelDialog"; |
| 84 | import { UsageShareBar } from "./UsageShareBar"; |
| 85 | import { |
| 86 | costTypeSegments, |
| 87 | modelShare, |
| 88 | sortModelsByTokens, |
| 89 | speedCostSegments, |
| 90 | tokenTypeSegments, |
| 91 | } from "./usageBreakdown"; |
| 92 | import { |
| 93 | METRIC_OPTIONS, |
| 94 | WINDOW_OPTIONS, |
| 95 | resolveUsageShortcut, |
| 96 | type UsageMetric, |
| 97 | } from "./usageShortcuts"; |
| 98 | import { |
| 99 | PROVIDER_ORDER, |
| 100 | PROVIDER_PRESENTATION, |
| 101 | providersWithUsage, |
| 102 | rankProvidersByMetric, |
| 103 | } from "./usageProviders"; |
| 104 | import { |
| 105 | readUsagePagePreferences, |
| 106 | saveUsagePagePreferences, |
| 107 | type UsagePagePreferences, |
| 108 | } from "./usagePagePreferences"; |
| 109 | |
| 110 | function isUsageMetric(value: string | null | undefined): value is UsageMetric { |
| 111 | return METRIC_OPTIONS.some((option) => option.value === value); |
| 112 | } |
| 113 | |
| 114 | function isUsageWindowDays(value: number): value is UsagePagePreferences["windowDays"] { |
| 115 | return WINDOW_OPTIONS.some((option) => option.days === value); |
| 116 | } |
| 117 | |
| 118 | const providerLabel = (provider: UsageProviderKind) => PROVIDER_PRESENTATION[provider].label; |
| 119 | |
| 120 | function usageLoading( |
| 121 | showingKept: boolean, |
| 122 | selectedEnvironments: Parameters<typeof usageLoadingState>[0], |
| 123 | refreshingUsage: boolean, |
| 124 | hiddenProviders: ReadonlySet<UsageProviderKind>, |
| 125 | ) { |
| 126 | if (showingKept) { |
| 127 | return { partial: true, everyProvider: true, providers: new Set<UsageProviderKind>() }; |
| 128 | } |
| 129 | const state = usageLoadingState(selectedEnvironments, refreshingUsage); |
| 130 | const providers = new Set([...state.providers].filter((p) => !hiddenProviders.has(p))); |
| 131 | return { |
| 132 | partial: state.everyProvider || providers.size > 0, |
| 133 | everyProvider: state.everyProvider, |
| 134 | providers, |
| 135 | }; |
| 136 | } |
| 137 | |
| 138 | /** Keep dialog selection outside UsagePage so opening/closing rerenders only its host. */ |
| 139 | const selectedUsageModelKeyAtom = Atom.make<string | null>(null).pipe( |
| 140 | Atom.keepAlive, |
| 141 | Atom.withLabel("usage:selected-model-key"), |
| 142 | ); |
| 143 | |
| 144 | function selectUsageModel(key: string | null): void { |
| 145 | appAtomRegistry.set(selectedUsageModelKeyAtom, key); |
| 146 | } |
| 147 | |
| 148 | function UsageModelDialogHost({ |
| 149 | models, |
| 150 | onSetPrice, |
| 151 | ...dialogProps |
| 152 | }: Omit<Parameters<typeof UsageModelDialog>[0], "model" | "onSetPrice" | "onClose"> & { |
| 153 | readonly models: MergedUsage["models"]; |
| 154 | readonly onSetPrice: (model: string) => void; |
| 155 | }) { |
| 156 | const selectedKey = useAtomValue(selectedUsageModelKeyAtom); |
| 157 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the shared selected-model atom on unmount |
| 158 | useEffect(() => () => selectUsageModel(null), []); |
| 159 | const model = |
| 160 | selectedKey === null |
| 161 | ? undefined |
| 162 | : models.find((candidate) => `${candidate.provider}:${candidate.model}` === selectedKey); |
| 163 | if (model === undefined) return null; |
| 164 | return ( |
| 165 | <UsageModelDialog |
| 166 | {...dialogProps} |
| 167 | model={model} |
| 168 | onSetPrice={() => { |
| 169 | selectUsageModel(null); |
| 170 | onSetPrice(model.model); |
| 171 | }} |
| 172 | onClose={() => selectUsageModel(null)} |
| 173 | /> |
| 174 | ); |
| 175 | } |
| 176 | |
| 177 | export function UsagePage() { |
| 178 | const [preferences, setPreferences] = useState(readUsagePagePreferences); |
| 179 | const keybindings = useAtomValue(primaryServerKeybindingsAtom); |
| 180 | const hour12 = usePrimarySettings((settings) => resolveHour12(settings.timestampFormat)); |
| 181 | const gt = useGT(); |
| 182 | const locale = useLocale(); |
| 183 | const m = useMessages(); |
| 184 | const shortcutTitle = ( |
| 185 | option: (typeof METRIC_OPTIONS)[number] | (typeof WINDOW_OPTIONS)[number], |
| 186 | ) => { |
| 187 | const shortcut = shortcutLabelForCommand(keybindings, option.command, { |
| 188 | context: { usagePageOpen: true }, |
| 189 | }); |
| 190 | return shortcut |
| 191 | ? gt("{label} ({shortcut})", { label: m(option.label), shortcut }) |
| 192 | : m(option.label); |
| 193 | }; |
| 194 | const [windowSelection, setWindowSelection] = useState(() => ({ |
| 195 | days: preferences.windowDays, |
| 196 | window: makeWindow( |
| 197 | preferences.windowDays, |
| 198 | undefined, |
| 199 | preferences.windowDays === 1 ? "hour" : "day", |
| 200 | ), |
| 201 | })); |
| 202 | const metric = preferences.metric; |
| 203 | const showingLimits = metric === "limits"; |
| 204 | const [isRefreshing, setIsRefreshing] = useState(false); |
| 205 | const [limitsNow, setLimitsNow] = useState(() => Date.now()); |
| 206 | const refreshingRef = useRef(false); |
| 207 | const [priceDialog, setPriceDialog] = useState<{ readonly model?: string } | null>(null); |
| 208 | const [selectedEnvironmentIds, setSelectedEnvironmentIds] = |
| 209 | useState<ReadonlySet<EnvironmentId> | null>(null); |
| 210 | const hiddenProviders = new Set(preferences.hiddenProviders); |
| 211 | const { days: windowDays, window } = windowSelection; |
| 212 | const isPast24Hours = windowDays === 1; |
| 213 | const { |
| 214 | merged: answeredUsage, |
| 215 | environments, |
| 216 | selectedEnvironments, |
| 217 | shown, |
| 218 | isPartial, |
| 219 | refresh, |
| 220 | } = useUsage(window, selectedEnvironmentIds, hiddenProviders); |
| 221 | const merged = shown?.merged ?? answeredUsage; |
| 222 | const shownWindow = shown?.window ?? window; |
| 223 | const shownHourly = shownWindow.resolution === "hour"; |
| 224 | const refreshingUsage = isRefreshing && !showingLimits; |
| 225 | const showingKept = shown !== null && shown.window !== window; |
| 226 | const presentations = useAtomValue(environmentPresentations.presentationsAtom); |
| 227 | const presentationsWithProviders = useAtomValue( |
| 228 | environmentPresentations.presentationsWithProvidersAtom, |
| 229 | ); |
| 230 | const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, { |
| 231 | reportFailure: false, |
| 232 | }); |
| 233 | |
| 234 | const canReadDiagnostics = selectedEnvironments.some( |
| 235 | (environment) => environment.canReadDiagnostics, |
| 236 | ); |
| 237 | |
| 238 | const updatePreferences = (patch: Partial<UsagePagePreferences>) => { |
| 239 | const nextPreferences = { ...preferences, ...patch }; |
| 240 | setPreferences(nextPreferences); |
| 241 | saveUsagePagePreferences(nextPreferences); |
| 242 | }; |
| 243 | const selectWindow = (days: number) => { |
| 244 | if (!isUsageWindowDays(days)) return; |
| 245 | updatePreferences({ windowDays: days }); |
| 246 | setWindowSelection({ |
| 247 | days, |
| 248 | window: makeWindow(days, undefined, days === 1 ? "hour" : "day"), |
| 249 | }); |
| 250 | }; |
| 251 | const selectMetric = (nextMetric: UsageMetric) => { |
| 252 | if (nextMetric === "limits") setLimitsNow(Date.now()); |
| 253 | updatePreferences({ metric: nextMetric }); |
| 254 | }; |
| 255 | const refreshLimits = (automatic = false) => |
| 256 | // Settled so the timestamp still advances when a refresh throws. |
| 257 | settlePromise(() => |
| 258 | Promise.all( |
| 259 | Array.from(presentations, ([environmentId, presentation]) => { |
| 260 | if (selectedEnvironmentIds !== null && !selectedEnvironmentIds.has(environmentId)) return; |
| 261 | if (presentation.connection.phase === "connected" && presentation.serverConfig !== null) { |
| 262 | return refreshUsageLimits( |
| 263 | environmentId, |
| 264 | () => refreshProviders({ environmentId, input: {} }), |
| 265 | automatic, |
| 266 | ); |
| 267 | } |
| 268 | }), |
| 269 | ), |
| 270 | ).then((result) => { |
| 271 | setLimitsNow(Date.now()); |
| 272 | if (!AsyncResult.isSuccess(result)) throw Cause.squash(result.cause); |
| 273 | }); |
| 274 | const onUsageKeyDown = useEffectEvent((event: KeyboardEvent) => { |
| 275 | if ( |
| 276 | event.defaultPrevented || |
| 277 | event.repeat || |
| 278 | event.isComposing || |
| 279 | isCommandPaletteOpen() || |
| 280 | isModelPickerOpen() |
| 281 | ) |
| 282 | return; |
| 283 | |
| 284 | const command = resolveUsageShortcut(event, keybindings); |
| 285 | const metricOption = METRIC_OPTIONS.find((option) => option.command === command); |
| 286 | const periodOption = WINDOW_OPTIONS.find((option) => option.command === command); |
| 287 | if (!metricOption && !periodOption) return; |
| 288 | |
| 289 | event.preventDefault(); |
| 290 | event.stopPropagation(); |
| 291 | if (metricOption) selectMetric(metricOption.value); |
| 292 | if (periodOption && !showingLimits) selectWindow(periodOption.days); |
| 293 | }); |
| 294 | |
| 295 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window capture keydown listener for usage metric and period shortcuts |
| 296 | useEffect(() => { |
| 297 | globalThis.window.addEventListener("keydown", onUsageKeyDown, true); |
| 298 | return () => globalThis.window.removeEventListener("keydown", onUsageKeyDown, true); |
| 299 | }, []); |
| 300 | |
| 301 | const refreshWindow = () => { |
| 302 | if (refreshingRef.current) return; |
| 303 | |
| 304 | if (showingLimits) { |
| 305 | refreshingRef.current = true; |
| 306 | setIsRefreshing(true); |
| 307 | void refreshLimits().finally(() => { |
| 308 | refreshingRef.current = false; |
| 309 | setIsRefreshing(false); |
| 310 | }); |
| 311 | return; |
| 312 | } |
| 313 | const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day"); |
| 314 | if ( |
| 315 | nextWindow.sinceDay !== window.sinceDay || |
| 316 | nextWindow.untilDay !== window.untilDay || |
| 317 | nextWindow.sinceTime !== window.sinceTime || |
| 318 | nextWindow.untilTime !== window.untilTime |
| 319 | ) { |
| 320 | setWindowSelection({ days: windowDays, window: nextWindow }); |
| 321 | } |
| 322 | refreshingRef.current = true; |
| 323 | setIsRefreshing(true); |
| 324 | void refresh(nextWindow).finally(() => { |
| 325 | refreshingRef.current = false; |
| 326 | setIsRefreshing(false); |
| 327 | }); |
| 328 | }; |
| 329 | const connectedLimitsEnvironments = [...presentations] |
| 330 | .filter( |
| 331 | ([environmentId, presentation]) => |
| 332 | presentation.connection.phase === "connected" && |
| 333 | presentation.serverConfig !== null && |
| 334 | (selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId)), |
| 335 | ) |
| 336 | .map(([environmentId]) => environmentId) |
| 337 | .sort() |
| 338 | .join(","); |
| 339 | const autoRefreshLimits = useEffectEvent(() => { |
| 340 | void refreshLimits(true); |
| 341 | }); |
| 342 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes provider limits from the server when the connected environment set changes |
| 343 | useEffect(() => { |
| 344 | if (showingLimits && connectedLimitsEnvironments) autoRefreshLimits(); |
| 345 | }, [showingLimits, connectedLimitsEnvironments]); |
| 346 | |
| 347 | const days = enumerateDays(shownWindow.sinceDay, shownWindow.untilDay); |
| 348 | const hours = |
| 349 | shownWindow.sinceTime === undefined || shownWindow.untilTime === undefined |
| 350 | ? [] |
| 351 | : enumerateHourStarts(shownWindow.sinceTime, shownWindow.untilTime); |
| 352 | const showChatGptSharing = |
| 353 | !hiddenProviders.has("codex") && |
| 354 | [...presentationsWithProviders].some( |
| 355 | ([id, presentation]) => |
| 356 | (selectedEnvironmentIds === null || selectedEnvironmentIds.has(id)) && |
| 357 | (presentation.serverConfig?.providers ?? []).some(usesChatGptSharing), |
| 358 | ); |
| 359 | |
| 360 | const windowLabel = |
| 361 | shownHourly && shownWindow.sinceTime !== undefined && shownWindow.untilTime !== undefined |
| 362 | ? gt("{start} to {end}", { |
| 363 | start: formatDateTimeShort(shownWindow.sinceTime, shownWindow.timeZone, hour12, locale), |
| 364 | end: formatDateTimeShort(shownWindow.untilTime, shownWindow.timeZone, hour12, locale), |
| 365 | }) |
| 366 | : gt("{start} to {end}", { |
| 367 | start: formatDayShort(shownWindow.sinceDay, locale), |
| 368 | end: formatDayShort(shownWindow.untilDay, locale), |
| 369 | }); |
| 370 | const windowOptionLabel = WINDOW_OPTIONS.find((option) => option.days === windowDays)?.label; |
| 371 | const metricOptionLabel = METRIC_OPTIONS.find((option) => option.value === metric)?.label; |
| 372 | const topbarContent = ( |
| 373 | <div className="grid w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 py-2 @4xl/usage-header:flex"> |
| 374 | <WorkspaceBreadcrumb ariaLabel={gt("Usage breadcrumb")} className="min-w-0"> |
| 375 | <WorkspaceBreadcrumbItem> |
| 376 | <h1> |
| 377 | <T>Usage</T> |
| 378 | </h1> |
| 379 | </WorkspaceBreadcrumbItem> |
| 380 | <WorkspaceBreadcrumbSeparator /> |
| 381 | <WorkspaceBreadcrumbItem className="min-w-10 shrink"> |
| 382 | <UsageEnvironmentFilter |
| 383 | environments={environments} |
| 384 | selectedEnvironments={selectedEnvironments} |
| 385 | selectedEnvironmentIds={selectedEnvironmentIds} |
| 386 | onSelectionChange={setSelectedEnvironmentIds} |
| 387 | showUsageStatus={!showingLimits} |
| 388 | refreshing={refreshingUsage} |
| 389 | isPartial={isPartial} |
| 390 | duplicateSources={merged.duplicateSources} |
| 391 | contractMismatches={merged.contractMismatches} |
| 392 | onOpenModelPrices={() => setPriceDialog({})} |
| 393 | /> |
| 394 | </WorkspaceBreadcrumbItem> |
| 395 | <WorkspaceBreadcrumbSeparator /> |
| 396 | <WorkspaceBreadcrumbItem current className="min-w-10"> |
| 397 | <UsageProviderFilter |
| 398 | hiddenProviders={hiddenProviders} |
| 399 | onChange={(next) => updatePreferences({ hiddenProviders: next })} |
| 400 | /> |
| 401 | </WorkspaceBreadcrumbItem> |
| 402 | </WorkspaceBreadcrumb> |
| 403 | {!showingLimits ? ( |
| 404 | <span className="hidden min-w-0 truncate text-xs text-muted-foreground @7xl/usage-header:block"> |
| 405 | {windowLabel} |
| 406 | </span> |
| 407 | ) : null} |
| 408 | <div className="ms-auto hidden shrink-0 items-center justify-end gap-2 @4xl/usage-header:flex"> |
| 409 | {/* Limits are always current, so they have no period. The period sits before the metric |
| 410 | tabs so dropping it never moves them. */} |
| 411 | {showingLimits ? null : ( |
| 412 | <ToggleGroup |
| 413 | aria-label={gt("Usage period")} |
| 414 | variant="segmented" |
| 415 | value={[String(windowDays)]} |
| 416 | onValueChange={(next) => { |
| 417 | const value = next[0]; |
| 418 | if (value) selectWindow(Number(value)); |
| 419 | }} |
| 420 | > |
| 421 | {WINDOW_OPTIONS.map((option) => ( |
| 422 | <Toggle key={option.days} value={String(option.days)} title={shortcutTitle(option)}> |
| 423 | {m(option.label)} |
| 424 | </Toggle> |
| 425 | ))} |
| 426 | </ToggleGroup> |
| 427 | )} |
| 428 | <ToggleGroup |
| 429 | aria-label={gt("Usage metric")} |
| 430 | variant="segmented" |
| 431 | value={[metric]} |
| 432 | onValueChange={(next) => { |
| 433 | const value = next[0]; |
| 434 | if (isUsageMetric(value)) selectMetric(value); |
| 435 | }} |
| 436 | > |
| 437 | {METRIC_OPTIONS.map((option) => ( |
| 438 | <Toggle key={option.value} value={option.value} title={shortcutTitle(option)}> |
| 439 | {m(option.label)} |
| 440 | </Toggle> |
| 441 | ))} |
| 442 | </ToggleGroup> |
| 443 | <Button |
| 444 | onClick={refreshWindow} |
| 445 | aria-label={showingLimits ? gt("Refresh limits") : gt("Refresh usage")} |
| 446 | aria-busy={isRefreshing} |
| 447 | disabled={isRefreshing || (!showingLimits && !canReadDiagnostics)} |
| 448 | size="icon-sm" |
| 449 | variant="ghost" |
| 450 | > |
| 451 | <RefreshIcon size="sm" refreshing={isRefreshing} /> |
| 452 | </Button> |
| 453 | </div> |
| 454 | <div className="ms-auto flex shrink-0 items-center justify-end gap-1 @4xl/usage-header:hidden"> |
| 455 | {showingLimits ? null : ( |
| 456 | <Select value={String(windowDays)} onValueChange={(value) => selectWindow(Number(value))}> |
| 457 | <SelectTrigger |
| 458 | aria-label={gt("Usage period")} |
| 459 | size="compact" |
| 460 | variant="ghost" |
| 461 | className="w-auto min-w-0" |
| 462 | > |
| 463 | <SelectValue>{windowOptionLabel && m(windowOptionLabel)}</SelectValue> |
| 464 | </SelectTrigger> |
| 465 | <SelectPopup align="end" alignItemWithTrigger={false}> |
| 466 | {WINDOW_OPTIONS.map((option) => ( |
| 467 | <SelectItem |
| 468 | key={option.days} |
| 469 | value={String(option.days)} |
| 470 | title={shortcutTitle(option)} |
| 471 | > |
| 472 | {m(option.label)} |
| 473 | </SelectItem> |
| 474 | ))} |
| 475 | </SelectPopup> |
| 476 | </Select> |
| 477 | )} |
| 478 | <Select |
| 479 | value={metric} |
| 480 | onValueChange={(value) => { |
| 481 | if (isUsageMetric(value)) selectMetric(value); |
| 482 | }} |
| 483 | > |
| 484 | <SelectTrigger |
| 485 | aria-label={gt("Usage metric")} |
| 486 | size="compact" |
| 487 | variant="ghost" |
| 488 | className="w-auto min-w-0" |
| 489 | > |
| 490 | <SelectValue>{metricOptionLabel && m(metricOptionLabel)}</SelectValue> |
| 491 | </SelectTrigger> |
| 492 | <SelectPopup align="end" alignItemWithTrigger={false}> |
| 493 | {METRIC_OPTIONS.map((option) => ( |
| 494 | <SelectItem key={option.value} value={option.value} title={shortcutTitle(option)}> |
| 495 | {m(option.label)} |
| 496 | </SelectItem> |
| 497 | ))} |
| 498 | </SelectPopup> |
| 499 | </Select> |
| 500 | <Button |
| 501 | onClick={refreshWindow} |
| 502 | aria-label={showingLimits ? gt("Refresh limits") : gt("Refresh usage")} |
| 503 | aria-busy={isRefreshing} |
| 504 | disabled={isRefreshing || (!showingLimits && !canReadDiagnostics)} |
| 505 | size="icon-sm" |
| 506 | variant="ghost" |
| 507 | > |
| 508 | <RefreshIcon size="sm" refreshing={isRefreshing} /> |
| 509 | </Button> |
| 510 | </div> |
| 511 | </div> |
| 512 | ); |
| 513 | |
| 514 | return ( |
| 515 | <AppRouteModal label={gt("Usage")}> |
| 516 | <div className="flex min-h-0 min-w-0 flex-1 flex-col"> |
| 517 | <header className="@container/usage-header flex min-h-12 shrink-0 items-center gap-1 border-b ps-5 pe-2"> |
| 518 | {topbarContent} |
| 519 | <AppRouteModalClose /> |
| 520 | </header> |
| 521 | |
| 522 | <ScrollArea className="min-h-0 flex-1"> |
| 523 | <WorkspacePageContainer width="wide"> |
| 524 | {selectedEnvironments.length === 0 ? ( |
| 525 | <p className="text-sm text-muted-foreground"> |
| 526 | {environments.length === 0 |
| 527 | ? showingLimits |
| 528 | ? gt("Connect an environment to see limits.") |
| 529 | : gt("Connect an environment to see usage.") |
| 530 | : showingLimits |
| 531 | ? gt("Select an environment to see limits.") |
| 532 | : gt("Select an environment to see usage.")} |
| 533 | </p> |
| 534 | ) : showingLimits ? ( |
| 535 | <UsageLimitsSection |
| 536 | selectedEnvironmentIds={selectedEnvironmentIds} |
| 537 | hiddenProviders={hiddenProviders} |
| 538 | now={limitsNow} |
| 539 | /> |
| 540 | ) : shown === null ? ( |
| 541 | <UsageSkeleton /> |
| 542 | ) : !canReadDiagnostics ? ( |
| 543 | <div className="space-y-2 py-12 text-center text-sm text-muted-foreground"> |
| 544 | {selectedEnvironments.map((environment) => ( |
| 545 | <p key={environment.environmentId}> |
| 546 | {selectedEnvironments.length > 1 |
| 547 | ? gt("{environment}: {error}", { |
| 548 | environment: environment.label, |
| 549 | error: environment.error, |
| 550 | }) |
| 551 | : environment.error} |
| 552 | </p> |
| 553 | ))} |
| 554 | </div> |
| 555 | ) : ( |
| 556 | <UsageOverview |
| 557 | merged={merged} |
| 558 | shownWindow={shownWindow} |
| 559 | hour12={hour12} |
| 560 | days={days} |
| 561 | hours={hours} |
| 562 | showingKept={showingKept} |
| 563 | metric={metric === "tokens" ? "tokens" : "cost"} |
| 564 | selectedEnvironments={selectedEnvironments} |
| 565 | hiddenProviders={hiddenProviders} |
| 566 | refreshingUsage={refreshingUsage} |
| 567 | showChatGptSharing={showChatGptSharing} |
| 568 | onSelectModel={selectUsageModel} |
| 569 | /> |
| 570 | )} |
| 571 | </WorkspacePageContainer> |
| 572 | </ScrollArea> |
| 573 | </div> |
| 574 | {showingLimits ? null : ( |
| 575 | <UsageModelDialogHost |
| 576 | models={merged.models} |
| 577 | environments={selectedEnvironments} |
| 578 | metric={metric === "tokens" ? "tokens" : "cost"} |
| 579 | chartWindow={{ |
| 580 | days, |
| 581 | hours, |
| 582 | resolution: shownHourly ? "hour" : "day", |
| 583 | timeZone: shownWindow.timeZone, |
| 584 | referenceTime: shownWindow.untilTime, |
| 585 | hour12, |
| 586 | }} |
| 587 | onSetPrice={(model) => setPriceDialog({ model })} |
| 588 | /> |
| 589 | )} |
| 590 | {priceDialog ? ( |
| 591 | <UsagePriceOverrides |
| 592 | usage={environments} |
| 593 | initialSelectedEnvironmentIds={selectedEnvironmentIds} |
| 594 | initialModel={priceDialog.model} |
| 595 | onOpenChange={(open) => { |
| 596 | if (!open) setPriceDialog(null); |
| 597 | }} |
| 598 | /> |
| 599 | ) : null} |
| 600 | </AppRouteModal> |
| 601 | ); |
| 602 | } |
| 603 | |
| 604 | function UsageOverview({ |
| 605 | merged, |
| 606 | shownWindow, |
| 607 | hour12, |
| 608 | days, |
| 609 | hours, |
| 610 | showingKept, |
| 611 | metric, |
| 612 | selectedEnvironments, |
| 613 | hiddenProviders, |
| 614 | refreshingUsage, |
| 615 | showChatGptSharing, |
| 616 | onSelectModel, |
| 617 | }: { |
| 618 | readonly merged: MergedUsage; |
| 619 | readonly shownWindow: UsageSummaryInput; |
| 620 | readonly hour12: boolean; |
| 621 | readonly days: readonly string[]; |
| 622 | readonly hours: readonly string[]; |
| 623 | readonly showingKept: boolean; |
| 624 | readonly metric: "tokens" | "cost"; |
| 625 | readonly selectedEnvironments: readonly EnvironmentUsageStatus[]; |
| 626 | readonly hiddenProviders: ReadonlySet<UsageProviderKind>; |
| 627 | readonly refreshingUsage: boolean; |
| 628 | readonly showChatGptSharing: boolean; |
| 629 | readonly onSelectModel: (key: string) => void; |
| 630 | }) { |
| 631 | const gt = useGT(); |
| 632 | const locale = useLocale(); |
| 633 | const m = useMessages(); |
| 634 | const [breakdown, setBreakdown] = useState<"model" | "time">("model"); |
| 635 | const shownHourly = shownWindow.resolution === "hour"; |
| 636 | const loading = usageLoading(showingKept, selectedEnvironments, refreshingUsage, hiddenProviders); |
| 637 | // Copy the primitive; JSX reads of loading.partial would merge all derivations into one compiler cache |
| 638 | // scope. |
| 639 | const loadingPartial = loading.partial === true; |
| 640 | const loadingProviders = new Set( |
| 641 | PROVIDER_ORDER.filter((provider) => loading.everyProvider || loading.providers.has(provider)), |
| 642 | ); |
| 643 | const providersWithData = new Set(providersWithUsage(merged.providers)); |
| 644 | // Only loading.providers excludes hidden providers without data. Filter a fresh array so the compiler can |
| 645 | // cache independently. |
| 646 | const activeProviders = [...PROVIDER_ORDER].filter( |
| 647 | (provider) => providersWithData.has(provider) || loading.providers.has(provider), |
| 648 | ); |
| 649 | const chartLoadingProviders = new Set( |
| 650 | activeProviders.filter((provider) => loadingProviders.has(provider)), |
| 651 | ); |
| 652 | const sourceMessages = usageSourceMessages( |
| 653 | selectedEnvironments.flatMap( |
| 654 | (environment) => |
| 655 | environment.summary?.sources.filter( |
| 656 | (source) => !hiddenProviders.has(source.fingerprint.provider), |
| 657 | ) ?? [], |
| 658 | ), |
| 659 | m, |
| 660 | ); |
| 661 | const breakdownPeriods: readonly (DailyTotals | HourlyTotals)[] = ( |
| 662 | shownHourly ? merged.hourly : merged.daily |
| 663 | ).toReversed(); |
| 664 | const breakdownModels = |
| 665 | breakdown === "model" && metric === "tokens" |
| 666 | ? sortModelsByTokens(merged.models) |
| 667 | : merged.models; |
| 668 | const breakdownPeak = breakdownModels.reduce( |
| 669 | (peak, model) => Math.max(peak, metric === "tokens" ? model.totalTokens : model.costUsd), |
| 670 | 0, |
| 671 | ); |
| 672 | const rankedProviders = rankProvidersByMetric(activeProviders, merged.providers, metric); |
| 673 | |
| 674 | return ( |
| 675 | <div aria-busy={loadingPartial} className="flex flex-col gap-6"> |
| 676 | {sourceMessages.map((message) => ( |
| 677 | <p key={message} className="mb-4 text-sm text-muted-foreground"> |
| 678 | {message} |
| 679 | </p> |
| 680 | ))} |
| 681 | <section className="grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]"> |
| 682 | <div className="flex min-w-0 flex-col gap-5"> |
| 683 | <div className="flex flex-col gap-1"> |
| 684 | <p |
| 685 | className={cn( |
| 686 | "text-4xl font-semibold text-foreground tabular-nums", |
| 687 | figureClass(loadingPartial), |
| 688 | )} |
| 689 | > |
| 690 | {metric === "cost" |
| 691 | ? formatUsd(merged.costUsd, locale) |
| 692 | : formatTokens(merged.totalTokens)} |
| 693 | </p> |
| 694 | <p className="inline-flex items-center gap-1 text-xs text-muted-foreground"> |
| 695 | <span> |
| 696 | <span className={figureClass(loadingPartial)}> |
| 697 | {gt("{count, plural, one {{formatted} sessions} other {{formatted} sessions}}", { |
| 698 | count: merged.sessions, |
| 699 | formatted: formatCount(merged.sessions, locale), |
| 700 | })} |
| 701 | </span> |
| 702 | {metric === "cost" && ` · ${gt("API estimate")}`} |
| 703 | </span> |
| 704 | {metric === "cost" && merged.costQuality.unpricedShare > 0 && ( |
| 705 | <Popover> |
| 706 | <PopoverTrigger |
| 707 | openOnHover |
| 708 | render={<InlineButton tone="muted" />} |
| 709 | aria-label={gt("Unpriced usage details")} |
| 710 | > |
| 711 | <InfoIcon className="size-3" aria-hidden /> |
| 712 | </PopoverTrigger> |
| 713 | <PopoverPopup side="top" tooltipStyle> |
| 714 | <T> |
| 715 | API estimate excludes{" "} |
| 716 | <Var>{formatPercent(merged.costQuality.unpricedShare)}</Var> unpriced records. |
| 717 | </T> |
| 718 | </PopoverPopup> |
| 719 | </Popover> |
| 720 | )} |
| 721 | </p> |
| 722 | </div> |
| 723 | |
| 724 | {showChatGptSharing ? ( |
| 725 | <div className="flex items-center justify-between gap-2 text-xs text-muted-foreground"> |
| 726 | <span> |
| 727 | <T>ChatGPT shared usage</T> |
| 728 | </span> |
| 729 | <ChatGptUsageButton size="xs" /> |
| 730 | </div> |
| 731 | ) : null} |
| 732 | |
| 733 | {rankedProviders.map((provider) => { |
| 734 | const totals = merged.providers.find((entry) => entry.provider === provider); |
| 735 | const share = metric === "cost" ? (totals?.costShare ?? 0) : (totals?.tokenShare ?? 0); |
| 736 | const providerSessions = totals?.sessions ?? 0; |
| 737 | const sessionLabel = gt( |
| 738 | "{count, plural, one {{formatted} session} other {{formatted} sessions}}", |
| 739 | { count: providerSessions, formatted: formatCount(providerSessions, locale) }, |
| 740 | ); |
| 741 | const providerLoading = loadingProviders.has(provider); |
| 742 | const awaitingData = providerLoading && !providersWithData.has(provider); |
| 743 | return ( |
| 744 | <div key={provider} className="flex flex-col gap-1"> |
| 745 | <dl className="flex items-baseline justify-between gap-4"> |
| 746 | <dt className="flex min-w-0 items-center gap-2 text-sm text-foreground"> |
| 747 | <span |
| 748 | aria-hidden |
| 749 | className="size-2 shrink-0 rounded-full" |
| 750 | style={{ |
| 751 | backgroundColor: PROVIDER_PRESENTATION[provider].color, |
| 752 | }} |
| 753 | /> |
| 754 | <ProviderMark provider={provider} className="size-4" /> |
| 755 | <span className="flex min-w-0 items-baseline gap-1.5"> |
| 756 | <span className="truncate">{PROVIDER_PRESENTATION[provider].label}</span> |
| 757 | <span |
| 758 | className={cn( |
| 759 | "shrink-0 whitespace-nowrap text-2xs text-muted-foreground tabular-nums", |
| 760 | figureClass(providerLoading), |
| 761 | awaitingData && "invisible", |
| 762 | )} |
| 763 | > |
| 764 | {sessionLabel} |
| 765 | </span> |
| 766 | </span> |
| 767 | </dt> |
| 768 | <dd |
| 769 | className={cn( |
| 770 | "shrink-0 text-sm font-medium text-foreground tabular-nums", |
| 771 | figureClass(providerLoading), |
| 772 | )} |
| 773 | > |
| 774 | {awaitingData |
| 775 | ? "-" |
| 776 | : metric === "cost" |
| 777 | ? formatUsd(totals?.costUsd ?? 0, locale) |
| 778 | : formatTokens(totals?.totalTokens ?? 0)} |
| 779 | </dd> |
| 780 | </dl> |
| 781 | <p |
| 782 | className={cn( |
| 783 | "text-xs text-muted-foreground", |
| 784 | figureClass(providerLoading), |
| 785 | awaitingData && "invisible", |
| 786 | )} |
| 787 | > |
| 788 | {metric === "cost" |
| 789 | ? gt("{share} of cost · {tokens} tokens", { |
| 790 | share: formatPercent(share), |
| 791 | tokens: formatTokens(totals?.totalTokens ?? 0), |
| 792 | }) |
| 793 | : gt("{share} of tokens · {cost}", { |
| 794 | share: formatPercent(share), |
| 795 | cost: formatUsd(totals?.costUsd ?? 0, locale), |
| 796 | })} |
| 797 | </p> |
| 798 | </div> |
| 799 | ); |
| 800 | })} |
| 801 | </div> |
| 802 | |
| 803 | <div className="flex min-w-0 flex-col gap-3"> |
| 804 | <h2 className="text-sm font-medium text-foreground"> |
| 805 | {shownHourly |
| 806 | ? metric === "tokens" |
| 807 | ? gt("Hourly processed tokens") |
| 808 | : gt("Hourly cost") |
| 809 | : metric === "tokens" |
| 810 | ? gt("Daily processed tokens") |
| 811 | : gt("Daily cost")} |
| 812 | </h2> |
| 813 | <UsageProviderChart |
| 814 | providers={activeProviders} |
| 815 | loadingProviders={chartLoadingProviders} |
| 816 | days={days} |
| 817 | daily={merged.daily} |
| 818 | hours={hours} |
| 819 | hourly={merged.hourly} |
| 820 | metric={metric} |
| 821 | referenceTime={shownWindow.untilTime} |
| 822 | resolution={shownHourly ? "hour" : "day"} |
| 823 | timeZone={shownWindow.timeZone} |
| 824 | hour12={hour12} |
| 825 | /> |
| 826 | </div> |
| 827 | </section> |
| 828 | |
| 829 | <section className="flex flex-col gap-2"> |
| 830 | <h2 className="text-sm font-medium text-foreground"> |
| 831 | <T>Totals</T> |
| 832 | </h2> |
| 833 | <dl className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5"> |
| 834 | <Metric |
| 835 | loading={loadingPartial} |
| 836 | label={gt("Processed tokens")} |
| 837 | value={formatTokens(merged.totalTokens)} |
| 838 | /> |
| 839 | <Metric |
| 840 | loading={loadingPartial} |
| 841 | label={gt("Cached input")} |
| 842 | value={formatTokens(merged.cachedInputTokens)} |
| 843 | /> |
| 844 | <Metric |
| 845 | loading={loadingPartial} |
| 846 | label={gt("Uncached input")} |
| 847 | value={formatTokens(merged.uncachedInputTokens)} |
| 848 | /> |
| 849 | <Metric |
| 850 | loading={loadingPartial} |
| 851 | label={gt("Output", { $context: "output tokens" })} |
| 852 | value={formatTokens(merged.outputTokens)} |
| 853 | /> |
| 854 | <Metric |
| 855 | loading={loadingPartial} |
| 856 | label={gt("Cache savings")} |
| 857 | value={formatUsd(merged.costQuality.cacheSavingsUsd, locale)} |
| 858 | /> |
| 859 | </dl> |
| 860 | </section> |
| 861 | |
| 862 | {merged.totalTokens > 0 ? ( |
| 863 | <section |
| 864 | className={cn("grid gap-x-12 gap-y-8 lg:grid-cols-2", figureClass(loadingPartial))} |
| 865 | > |
| 866 | {metric === "tokens" ? ( |
| 867 | <UsageShareBar |
| 868 | label={gt("Tokens by type")} |
| 869 | segments={tokenTypeSegments(merged)} |
| 870 | format={formatTokens} |
| 871 | /> |
| 872 | ) : ( |
| 873 | <> |
| 874 | <UsageShareBar |
| 875 | label={gt("Cost by type")} |
| 876 | segments={costTypeSegments(merged.categoryCost)} |
| 877 | format={(value: number) => formatUsd(value, locale)} |
| 878 | /> |
| 879 | {merged.speedCost.fast + merged.speedCost.ultrafast > 0 ? ( |
| 880 | <UsageShareBar |
| 881 | label={gt("Cost by speed")} |
| 882 | segments={speedCostSegments(merged.speedCost)} |
| 883 | format={(value: number) => formatUsd(value, locale)} |
| 884 | aside={<SpeedPremium premiumUsd={merged.speedCost.premium} />} |
| 885 | /> |
| 886 | ) : null} |
| 887 | </> |
| 888 | )} |
| 889 | </section> |
| 890 | ) : null} |
| 891 | |
| 892 | <section className="flex flex-col gap-3"> |
| 893 | <div className="flex items-center justify-between gap-3"> |
| 894 | <h2 className="text-sm font-medium text-foreground"> |
| 895 | <T>Breakdown</T> |
| 896 | </h2> |
| 897 | <ToggleGroup |
| 898 | aria-label={gt("Usage breakdown")} |
| 899 | variant="segmented" |
| 900 | value={[breakdown]} |
| 901 | onValueChange={(next) => { |
| 902 | const value = next[0]; |
| 903 | if (value === "model" || value === "time") setBreakdown(value); |
| 904 | }} |
| 905 | > |
| 906 | {( |
| 907 | [ |
| 908 | { value: "model", label: gt("Model") }, |
| 909 | { value: "time", label: shownHourly ? gt("Hour") : gt("Day") }, |
| 910 | ] as const |
| 911 | ).map((option) => ( |
| 912 | <Toggle key={option.value} value={option.value}> |
| 913 | {option.label} |
| 914 | </Toggle> |
| 915 | ))} |
| 916 | </ToggleGroup> |
| 917 | </div> |
| 918 | |
| 919 | {breakdown === "model" ? ( |
| 920 | <table className="w-full text-sm"> |
| 921 | <thead> |
| 922 | <tr className="border-b border-border text-right text-xs text-muted-foreground"> |
| 923 | <th className="py-2 pr-3 pl-2 text-left font-normal">#</th> |
| 924 | <th className="w-full py-2 text-left font-normal"> |
| 925 | <T>Model</T> |
| 926 | </th> |
| 927 | <th className="py-2 pl-6 font-normal"> |
| 928 | <T>Cost</T> |
| 929 | </th> |
| 930 | <th className="hidden py-2 pl-6 font-normal sm:table-cell"> |
| 931 | <T context="column heading, percentage share">Share</T> |
| 932 | </th> |
| 933 | <th className="py-2 pr-2 pl-6 font-normal"> |
| 934 | <T>Tokens</T> |
| 935 | </th> |
| 936 | </tr> |
| 937 | </thead> |
| 938 | <tbody> |
| 939 | {breakdownModels.length === 0 ? ( |
| 940 | <tr> |
| 941 | <td colSpan={5} className="py-6 text-center text-muted-foreground"> |
| 942 | <T>No activity in this window.</T> |
| 943 | </td> |
| 944 | </tr> |
| 945 | ) : ( |
| 946 | breakdownModels.map((model, index) => { |
| 947 | const key = `${model.provider}:${model.model}`; |
| 948 | const value = metric === "tokens" ? model.totalTokens : model.costUsd; |
| 949 | const hasBar = value > 0 && breakdownPeak > 0; |
| 950 | const share = modelShare(model, metric === "tokens" ? "tokens" : "cost"); |
| 951 | const rowFigures = figureClass(loadingProviders.has(model.provider)); |
| 952 | return ( |
| 953 | <tr |
| 954 | key={key} |
| 955 | className="relative border-b border-border/50 text-right whitespace-nowrap text-muted-foreground tabular-nums transition-colors hover:bg-muted/50 has-focus-visible:bg-muted/50" |
| 956 | > |
| 957 | <td className="py-2.5 pr-3 pl-2 text-left text-xs">{index + 1}</td> |
| 958 | <td className="py-2.5 text-left whitespace-normal"> |
| 959 | <button |
| 960 | type="button" |
| 961 | onClick={() => onSelectModel(key)} |
| 962 | className={cn( |
| 963 | "flex items-center gap-2 text-left text-foreground outline-none after:absolute after:inset-0", |
| 964 | !hasBar && "py-1", |
| 965 | )} |
| 966 | > |
| 967 | <ProviderMark provider={model.provider} className="size-3.5" /> |
| 968 | {model.model} |
| 969 | </button> |
| 970 | {hasBar ? ( |
| 971 | <div aria-hidden className={cn("mt-1.5 h-0.5 max-w-48", rowFigures)}> |
| 972 | <div |
| 973 | className="h-full rounded-full" |
| 974 | style={{ |
| 975 | width: `max(0.5rem, ${(value / breakdownPeak) * 100}%)`, |
| 976 | backgroundColor: PROVIDER_PRESENTATION[model.provider].color, |
| 977 | }} |
| 978 | /> |
| 979 | </div> |
| 980 | ) : null} |
| 981 | </td> |
| 982 | <td className={cn("py-2.5 pl-6 text-foreground", rowFigures)}> |
| 983 | {isModelCostUnknown(model) ? ( |
| 984 | <span className="text-muted-foreground"> |
| 985 | <T>Unpriced</T> |
| 986 | </span> |
| 987 | ) : ( |
| 988 | formatUsd(model.costUsd, locale) |
| 989 | )} |
| 990 | </td> |
| 991 | <td className={cn("hidden py-2.5 pl-6 sm:table-cell", rowFigures)}> |
| 992 | {share === null ? "" : formatPercent(share)} |
| 993 | </td> |
| 994 | <td className={cn("py-2.5 pr-2 pl-6", rowFigures)}> |
| 995 | {formatTokens(model.totalTokens)} |
| 996 | </td> |
| 997 | </tr> |
| 998 | ); |
| 999 | }) |
| 1000 | )} |
| 1001 | </tbody> |
| 1002 | </table> |
| 1003 | ) : ( |
| 1004 | <div |
| 1005 | className="overflow-x-auto outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring" |
| 1006 | role="region" |
| 1007 | aria-label={gt("Usage breakdown by time")} |
| 1008 | tabIndex={0} |
| 1009 | > |
| 1010 | <table className="w-full text-sm whitespace-nowrap"> |
| 1011 | <colgroup> |
| 1012 | <col className="w-2/5" /> |
| 1013 | </colgroup> |
| 1014 | <thead> |
| 1015 | <tr className="border-b border-border text-left text-xs text-muted-foreground"> |
| 1016 | <th className="py-2 pl-2 font-normal">{shownHourly ? gt("Hour") : gt("Day")}</th> |
| 1017 | {activeProviders.map((provider) => ( |
| 1018 | <th key={provider} className="py-2 pl-4 text-right font-normal"> |
| 1019 | {PROVIDER_PRESENTATION[provider].label} |
| 1020 | </th> |
| 1021 | ))} |
| 1022 | <th className="py-2 pl-4 text-right font-normal"> |
| 1023 | <T>Total</T> |
| 1024 | </th> |
| 1025 | <th className="py-2 pr-2 pl-4 text-right font-normal"> |
| 1026 | <T>Tokens</T> |
| 1027 | </th> |
| 1028 | </tr> |
| 1029 | </thead> |
| 1030 | <tbody> |
| 1031 | {breakdownPeriods.length === 0 ? ( |
| 1032 | <tr> |
| 1033 | <td |
| 1034 | colSpan={activeProviders.length + 3} |
| 1035 | className="py-6 text-center text-muted-foreground" |
| 1036 | > |
| 1037 | <T>No activity in this window.</T> |
| 1038 | </td> |
| 1039 | </tr> |
| 1040 | ) : ( |
| 1041 | breakdownPeriods.map((period) => ( |
| 1042 | <tr |
| 1043 | key={"hourStart" in period ? period.hourStart : period.day} |
| 1044 | className="border-b border-border/50 transition-colors hover:bg-muted/50" |
| 1045 | > |
| 1046 | <td className="py-2 pl-2 text-foreground"> |
| 1047 | {"hourStart" in period |
| 1048 | ? formatHourShort(period.hourStart, shownWindow.timeZone, hour12, locale) |
| 1049 | : formatDayShort(period.day, locale)} |
| 1050 | </td> |
| 1051 | {activeProviders.map((provider) => ( |
| 1052 | <td |
| 1053 | key={provider} |
| 1054 | className={cn( |
| 1055 | "py-2 pl-4 text-right text-muted-foreground tabular-nums", |
| 1056 | figureClass(loadingProviders.has(provider)), |
| 1057 | )} |
| 1058 | > |
| 1059 | {formatUsd(period.byProvider.get(provider)?.costUsd ?? 0, locale)} |
| 1060 | </td> |
| 1061 | ))} |
| 1062 | <td |
| 1063 | className={cn( |
| 1064 | "py-2 pl-4 text-right text-foreground tabular-nums", |
| 1065 | figureClass(loadingPartial), |
| 1066 | )} |
| 1067 | > |
| 1068 | {formatUsd(period.costUsd, locale)} |
| 1069 | </td> |
| 1070 | <td |
| 1071 | className={cn( |
| 1072 | "py-2 pr-2 pl-4 text-right text-muted-foreground tabular-nums", |
| 1073 | figureClass(loadingPartial), |
| 1074 | )} |
| 1075 | > |
| 1076 | {formatTokens(period.totalTokens)} |
| 1077 | </td> |
| 1078 | </tr> |
| 1079 | )) |
| 1080 | )} |
| 1081 | </tbody> |
| 1082 | </table> |
| 1083 | </div> |
| 1084 | )} |
| 1085 | </section> |
| 1086 | </div> |
| 1087 | ); |
| 1088 | } |
| 1089 | |
| 1090 | function ProviderMark({ |
| 1091 | provider, |
| 1092 | className, |
| 1093 | }: { |
| 1094 | readonly provider: UsageProviderKind; |
| 1095 | readonly className: string; |
| 1096 | }) { |
| 1097 | const presentation = PROVIDER_PRESENTATION[provider]; |
| 1098 | return ( |
| 1099 | <ProviderInstanceIcon |
| 1100 | driverKind={presentation.driverKind} |
| 1101 | displayName={presentation.label} |
| 1102 | iconClassName={className} |
| 1103 | /> |
| 1104 | ); |
| 1105 | } |
| 1106 | |
| 1107 | function figureClass(loading: boolean) { |
| 1108 | return cn("transition-opacity", loading && "opacity-40 delay-150"); |
| 1109 | } |
| 1110 | |
| 1111 | function Metric({ |
| 1112 | label, |
| 1113 | value, |
| 1114 | loading, |
| 1115 | }: { |
| 1116 | readonly label: string; |
| 1117 | readonly value: string; |
| 1118 | readonly loading: boolean; |
| 1119 | }) { |
| 1120 | return ( |
| 1121 | <div className="flex min-w-0 flex-col gap-0.5"> |
| 1122 | <dt className="text-xs text-muted-foreground">{label}</dt> |
| 1123 | <dd |
| 1124 | className={cn("text-base font-medium text-foreground tabular-nums", figureClass(loading))} |
| 1125 | > |
| 1126 | {value} |
| 1127 | </dd> |
| 1128 | </div> |
| 1129 | ); |
| 1130 | } |
| 1131 | |
| 1132 | function UsageCoverageNotice({ |
| 1133 | environments, |
| 1134 | duplicateSources, |
| 1135 | contractMismatches, |
| 1136 | }: { |
| 1137 | readonly environments: readonly EnvironmentUsageStatus[]; |
| 1138 | readonly duplicateSources: readonly string[]; |
| 1139 | readonly contractMismatches: MergedUsage["contractMismatches"]; |
| 1140 | }) { |
| 1141 | const gt = useGT(); |
| 1142 | const m = useMessages(); |
| 1143 | const failed = environments.filter((environment) => environment.error !== null); |
| 1144 | const mismatchByEnvironment = new Map( |
| 1145 | contractMismatches.map((mismatch) => [mismatch.environmentId, mismatch]), |
| 1146 | ); |
| 1147 | const incompatible = environments.flatMap((environment) => { |
| 1148 | const mismatch = mismatchByEnvironment.get(environment.environmentId); |
| 1149 | return mismatch === undefined ? [] : [{ environment, mismatch }]; |
| 1150 | }); |
| 1151 | if (failed.length === 0 && incompatible.length === 0 && duplicateSources.length === 0) { |
| 1152 | return null; |
| 1153 | } |
| 1154 | |
| 1155 | return ( |
| 1156 | <div className="flex flex-col gap-1 border-t border-border px-2 py-2 text-xs text-muted-foreground"> |
| 1157 | {failed.map((environment) => ( |
| 1158 | <span key={environment.label}> |
| 1159 | {gt("{environment}: {error}", { |
| 1160 | environment: environment.label, |
| 1161 | error: environment.error, |
| 1162 | })} |
| 1163 | </span> |
| 1164 | ))} |
| 1165 | {incompatible.map(({ environment, mismatch }) => ( |
| 1166 | <span key={environment.environmentId}> |
| 1167 | {formatUsageContractMismatch(environment.label, mismatch, m)} |
| 1168 | </span> |
| 1169 | ))} |
| 1170 | {duplicateSources.length > 0 ? ( |
| 1171 | <span> |
| 1172 | {gt("Counted once across environments sharing a transcript directory: {sources}", { |
| 1173 | sources: duplicateSources.join(", "), |
| 1174 | })} |
| 1175 | </span> |
| 1176 | ) : null} |
| 1177 | </div> |
| 1178 | ); |
| 1179 | } |
| 1180 | |
| 1181 | function UsageEnvironmentFilter({ |
| 1182 | environments, |
| 1183 | selectedEnvironments, |
| 1184 | selectedEnvironmentIds, |
| 1185 | onSelectionChange, |
| 1186 | showUsageStatus, |
| 1187 | refreshing, |
| 1188 | isPartial, |
| 1189 | duplicateSources, |
| 1190 | contractMismatches, |
| 1191 | onOpenModelPrices, |
| 1192 | }: { |
| 1193 | readonly environments: readonly EnvironmentUsageStatus[]; |
| 1194 | readonly selectedEnvironments: readonly EnvironmentUsageStatus[]; |
| 1195 | readonly selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null; |
| 1196 | readonly onSelectionChange: (ids: ReadonlySet<EnvironmentId> | null) => void; |
| 1197 | readonly showUsageStatus: boolean; |
| 1198 | readonly refreshing: boolean; |
| 1199 | readonly isPartial: boolean; |
| 1200 | readonly duplicateSources: readonly string[]; |
| 1201 | readonly contractMismatches: MergedUsage["contractMismatches"]; |
| 1202 | readonly onOpenModelPrices: () => void; |
| 1203 | }) { |
| 1204 | const gt = useGT(); |
| 1205 | const m = useMessages(); |
| 1206 | const allSelected = selectedEnvironmentIds === null; |
| 1207 | const label = allSelected |
| 1208 | ? gt("All environments") |
| 1209 | : selectedEnvironments.length === 1 |
| 1210 | ? selectedEnvironments[0]!.label |
| 1211 | : gt("{count, plural, one {{count} environments} other {{count} environments}}", { |
| 1212 | count: selectedEnvironments.length, |
| 1213 | }); |
| 1214 | const hasIssue = |
| 1215 | selectedEnvironments.some((environment) => environment.error !== null) || |
| 1216 | contractMismatches.length > 0; |
| 1217 | |
| 1218 | return ( |
| 1219 | <Menu> |
| 1220 | <MenuTrigger render={<InlineButton />} className="group/usage-environment min-w-0 max-w-full"> |
| 1221 | <WorkspaceBreadcrumbText>{label}</WorkspaceBreadcrumbText> |
| 1222 | <span className="flex size-3.5 shrink-0 items-center justify-center text-muted-foreground"> |
| 1223 | {showUsageStatus && hasIssue ? ( |
| 1224 | <CircleAlertIcon |
| 1225 | className="size-3.5 text-warning-foreground" |
| 1226 | aria-label={gt("Some environments could not report usage")} |
| 1227 | /> |
| 1228 | ) : ( |
| 1229 | <ChevronDownIcon |
| 1230 | className="size-3.5 opacity-60 transition-opacity group-hover/usage-environment:opacity-100 group-focus-visible/usage-environment:opacity-100 group-data-popup-open/usage-environment:opacity-100" |
| 1231 | aria-hidden |
| 1232 | /> |
| 1233 | )} |
| 1234 | </span> |
| 1235 | </MenuTrigger> |
| 1236 | <MenuPopup align="start"> |
| 1237 | <MenuCheckboxItem |
| 1238 | checked={allSelected} |
| 1239 | closeOnClick={false} |
| 1240 | onCheckedChange={(checked) => onSelectionChange(checked ? null : new Set())} |
| 1241 | > |
| 1242 | <T>All environments</T> |
| 1243 | </MenuCheckboxItem> |
| 1244 | <MenuSeparator /> |
| 1245 | {environments.map((environment) => { |
| 1246 | const checked = |
| 1247 | selectedEnvironmentIds === null || |
| 1248 | selectedEnvironmentIds.has(environment.environmentId); |
| 1249 | const progress = usageEnvironmentProgress(environment, refreshing); |
| 1250 | const status = |
| 1251 | environment.error !== null |
| 1252 | ? gt("Unavailable") |
| 1253 | : environment.summary !== null && |
| 1254 | !isCompatibleUsageContractVersion( |
| 1255 | environment.summary.contractVersion, |
| 1256 | USAGE_CONTRACT_VERSION, |
| 1257 | ) |
| 1258 | ? gt("Update required") |
| 1259 | : !environment.isConnected |
| 1260 | ? gt("Connecting…") |
| 1261 | : progress.phase === "loading" |
| 1262 | ? gt("Scanning…") |
| 1263 | : progress.phase === "stale" |
| 1264 | ? gt("Refreshing…") |
| 1265 | : progress.phase === "partway" |
| 1266 | ? updatingProvidersLabel(progress.providers, providerLabel, m) |
| 1267 | : gt("Ready", { $context: "environment usage status" }); |
| 1268 | return ( |
| 1269 | <MenuCheckboxItem |
| 1270 | key={environment.environmentId} |
| 1271 | checked={checked} |
| 1272 | closeOnClick={false} |
| 1273 | onCheckedChange={(nextChecked) => { |
| 1274 | const next = new Set(selectedEnvironments.map((entry) => entry.environmentId)); |
| 1275 | if (nextChecked) next.add(environment.environmentId); |
| 1276 | else next.delete(environment.environmentId); |
| 1277 | onSelectionChange(next.size === environments.length ? null : next); |
| 1278 | }} |
| 1279 | > |
| 1280 | <span className="flex min-w-0 items-center gap-3"> |
| 1281 | <span className="min-w-0 flex-1 truncate">{environment.label}</span> |
| 1282 | {showUsageStatus ? ( |
| 1283 | <span |
| 1284 | className={cn( |
| 1285 | "shrink-0 text-xs text-muted-foreground", |
| 1286 | environment.error !== null && "text-destructive", |
| 1287 | )} |
| 1288 | > |
| 1289 | {status} |
| 1290 | </span> |
| 1291 | ) : null} |
| 1292 | </span> |
| 1293 | </MenuCheckboxItem> |
| 1294 | ); |
| 1295 | })} |
| 1296 | {environments.length === 0 ? ( |
| 1297 | <p className="px-2 py-2 text-xs text-muted-foreground"> |
| 1298 | <T>No environments connected.</T> |
| 1299 | </p> |
| 1300 | ) : null} |
| 1301 | {showUsageStatus && isPartial ? ( |
| 1302 | <p className="px-2 py-2 text-xs text-muted-foreground"> |
| 1303 | <T>Totals are partial while selected environments scan.</T> |
| 1304 | </p> |
| 1305 | ) : null} |
| 1306 | {showUsageStatus ? ( |
| 1307 | <UsageCoverageNotice |
| 1308 | environments={selectedEnvironments} |
| 1309 | duplicateSources={duplicateSources} |
| 1310 | contractMismatches={contractMismatches} |
| 1311 | /> |
| 1312 | ) : null} |
| 1313 | <MenuSeparator /> |
| 1314 | <MenuItem onClick={onOpenModelPrices}> |
| 1315 | <SlidersHorizontalIcon aria-hidden /> |
| 1316 | <T>Model prices</T> |
| 1317 | </MenuItem> |
| 1318 | </MenuPopup> |
| 1319 | </Menu> |
| 1320 | ); |
| 1321 | } |
| 1322 | |
| 1323 | function UsageProviderFilter({ |
| 1324 | hiddenProviders, |
| 1325 | onChange, |
| 1326 | }: { |
| 1327 | readonly hiddenProviders: ReadonlySet<UsageProviderKind>; |
| 1328 | readonly onChange: (hiddenProviders: readonly UsageProviderKind[]) => void; |
| 1329 | }) { |
| 1330 | const gt = useGT(); |
| 1331 | const visible = PROVIDER_ORDER.filter((provider) => !hiddenProviders.has(provider)); |
| 1332 | const label = |
| 1333 | visible.length === PROVIDER_ORDER.length |
| 1334 | ? gt("All providers") |
| 1335 | : visible.length === 0 |
| 1336 | ? gt("No providers") |
| 1337 | : visible.length === 1 |
| 1338 | ? PROVIDER_PRESENTATION[visible[0]!].label |
| 1339 | : gt("{count, plural, one {{count} providers} other {{count} providers}}", { |
| 1340 | count: visible.length, |
| 1341 | }); |
| 1342 | |
| 1343 | return ( |
| 1344 | <Menu> |
| 1345 | <MenuTrigger render={<InlineButton />} className="group/usage-provider min-w-0 max-w-full"> |
| 1346 | <span className="min-w-0 truncate">{label}</span> |
| 1347 | <ChevronDownIcon |
| 1348 | className="size-3.5 shrink-0 text-muted-foreground opacity-60 transition-opacity group-hover/usage-provider:opacity-100 group-focus-visible/usage-provider:opacity-100 group-data-popup-open/usage-provider:opacity-100" |
| 1349 | aria-hidden |
| 1350 | /> |
| 1351 | </MenuTrigger> |
| 1352 | <MenuPopup align="start"> |
| 1353 | <MenuCheckboxItem |
| 1354 | checked={hiddenProviders.size === 0} |
| 1355 | closeOnClick={false} |
| 1356 | onCheckedChange={(checked) => onChange(checked ? [] : PROVIDER_ORDER)} |
| 1357 | > |
| 1358 | <T>All providers</T> |
| 1359 | </MenuCheckboxItem> |
| 1360 | <MenuSeparator /> |
| 1361 | {PROVIDER_ORDER.map((provider) => ( |
| 1362 | <MenuCheckboxItem |
| 1363 | key={provider} |
| 1364 | checked={!hiddenProviders.has(provider)} |
| 1365 | closeOnClick={false} |
| 1366 | onCheckedChange={(checked) => |
| 1367 | onChange( |
| 1368 | PROVIDER_ORDER.filter((entry) => |
| 1369 | entry === provider ? !checked : hiddenProviders.has(entry), |
| 1370 | ), |
| 1371 | ) |
| 1372 | } |
| 1373 | > |
| 1374 | <span className="flex min-w-0 items-center gap-2"> |
| 1375 | <ProviderMark provider={provider} className="size-3.5" /> |
| 1376 | <span className="truncate">{PROVIDER_PRESENTATION[provider].label}</span> |
| 1377 | </span> |
| 1378 | </MenuCheckboxItem> |
| 1379 | ))} |
| 1380 | </MenuPopup> |
| 1381 | </Menu> |
| 1382 | ); |
| 1383 | } |
| 1384 | |
| 1385 | function UsageSkeleton() { |
| 1386 | const gt = useGT(); |
| 1387 | return ( |
| 1388 | <> |
| 1389 | <section className="grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]"> |
| 1390 | <div className="flex flex-col gap-5"> |
| 1391 | <div className="flex flex-col gap-1"> |
| 1392 | <Skeleton className="h-10 w-36" /> |
| 1393 | <Skeleton className="h-4 w-32" /> |
| 1394 | </div> |
| 1395 | {PROVIDER_ORDER.map((provider) => ( |
| 1396 | <div key={provider} className="flex flex-col gap-1"> |
| 1397 | <div className="flex min-h-5 items-center justify-between gap-4"> |
| 1398 | <span className="flex items-center gap-2"> |
| 1399 | <Skeleton shape="pill" className="size-2 shrink-0" /> |
| 1400 | <Skeleton shape="pill" className="size-4 shrink-0" /> |
| 1401 | <Skeleton className="h-3.5 w-20" /> |
| 1402 | </span> |
| 1403 | <Skeleton className="h-3.5 w-14" /> |
| 1404 | </div> |
| 1405 | <Skeleton className="h-4 w-36" /> |
| 1406 | </div> |
| 1407 | ))} |
| 1408 | </div> |
| 1409 | |
| 1410 | <div className="flex flex-col gap-3"> |
| 1411 | <Skeleton className="h-5 w-24" /> |
| 1412 | <div className="flex flex-col gap-1"> |
| 1413 | <Skeleton className="ml-16 h-56" /> |
| 1414 | <Skeleton className="ml-16 h-4" /> |
| 1415 | </div> |
| 1416 | </div> |
| 1417 | </section> |
| 1418 | |
| 1419 | <section className="flex flex-col gap-2"> |
| 1420 | <h2 className="text-sm font-medium text-foreground"> |
| 1421 | <T>Totals</T> |
| 1422 | </h2> |
| 1423 | <MetricSkeletons |
| 1424 | labels={[ |
| 1425 | gt("Processed tokens"), |
| 1426 | gt("Cached input"), |
| 1427 | gt("Uncached input"), |
| 1428 | gt("Output", { $context: "output tokens" }), |
| 1429 | gt("Cache savings"), |
| 1430 | ]} |
| 1431 | /> |
| 1432 | </section> |
| 1433 | |
| 1434 | <section className="grid gap-x-12 gap-y-8 lg:grid-cols-2"> |
| 1435 | <div className="flex flex-col gap-2.5"> |
| 1436 | <Skeleton className="h-5 w-28" /> |
| 1437 | <Skeleton className="h-2" /> |
| 1438 | <Skeleton className="h-4 w-72" /> |
| 1439 | </div> |
| 1440 | </section> |
| 1441 | |
| 1442 | <section className="flex flex-col gap-3"> |
| 1443 | <div className="flex items-center justify-between gap-3"> |
| 1444 | <h2 className="text-sm font-medium text-foreground"> |
| 1445 | <T>Breakdown</T> |
| 1446 | </h2> |
| 1447 | <Skeleton shape="card" className="h-7 w-28" /> |
| 1448 | </div> |
| 1449 | <Skeleton className="h-44" /> |
| 1450 | </section> |
| 1451 | </> |
| 1452 | ); |
| 1453 | } |
| 1454 | |
| 1455 | function MetricSkeletons({ labels }: { readonly labels: readonly string[] }) { |
| 1456 | return ( |
| 1457 | <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5"> |
| 1458 | {labels.map((label) => ( |
| 1459 | <div key={label} className="flex flex-col gap-0.5"> |
| 1460 | <span className="text-xs text-muted-foreground">{label}</span> |
| 1461 | <Skeleton className="h-6 w-16" /> |
| 1462 | </div> |
| 1463 | ))} |
| 1464 | </div> |
| 1465 | ); |
| 1466 | } |