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 { |
| 2 | AuthProvidersManageScope, |
| 3 | type EnvironmentId, |
| 4 | type ProviderConsumeResetCreditOutcome, |
| 5 | ProviderConsumeResetCreditInput, |
| 6 | ServerProvider, |
| 7 | ServerProviderResetCredits, |
| 8 | ServerProviderUsageWindow, |
| 9 | UsageProviderKind, |
| 10 | } from "@t3tools/contracts"; |
| 11 | import { useAtomValue } from "@effect/atom-react"; |
| 12 | import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display"; |
| 13 | import { |
| 14 | type LimitPace, |
| 15 | paceOf, |
| 16 | paceRemainingPercent, |
| 17 | remainingPercent, |
| 18 | type ResetCreditChoice, |
| 19 | } from "@t3tools/shared/usageLimits"; |
| 20 | import { GaugeIcon, TrendingDownIcon, TrendingUpIcon } from "lucide-react"; |
| 21 | import { msg, T, useGT, useMessages } from "gt-react"; |
| 22 | import { Fragment, useLayoutEffect, useState } from "react"; |
| 23 | |
| 24 | import { usePrimarySettings } from "../../hooks/useSettings"; |
| 25 | import { observeResize } from "../../lib/observeResize"; |
| 26 | import { environmentPresentations } from "../../state/presentation"; |
| 27 | import { useEnvironmentScope, readEnvironmentScope } from "../../state/session"; |
| 28 | import { serverEnvironment } from "../../state/server"; |
| 29 | import { useAtomCommand } from "../../state/use-atom-command"; |
| 30 | import { formatUpcomingTimestamp } from "../../timestampFormat"; |
| 31 | import { |
| 32 | AlertDialog, |
| 33 | AlertDialogClose, |
| 34 | AlertDialogDescription, |
| 35 | AlertDialogFooter, |
| 36 | AlertDialogHeader, |
| 37 | AlertDialogPopup, |
| 38 | AlertDialogTitle, |
| 39 | } from "../ui/alert-dialog"; |
| 40 | import { Button } from "../ui/button"; |
| 41 | import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; |
| 42 | import { UsageLimitsPooled } from "./UsageLimitsPooled"; |
| 43 | import { formatResetsIn, resetCreditChoices } from "@t3tools/shared/usageLimitsCopy"; |
| 44 | import { PROVIDER_PRESENTATION } from "./usageProviders"; |
| 45 | |
| 46 | const PACE: Record<LimitPace, { readonly label: string; readonly icon: typeof GaugeIcon }> = { |
| 47 | ahead: { |
| 48 | label: msg("Ahead of pace: spending faster than the window elapses"), |
| 49 | icon: TrendingUpIcon, |
| 50 | }, |
| 51 | on: { label: msg("On pace with the window"), icon: GaugeIcon }, |
| 52 | under: { |
| 53 | label: msg("Under pace: headroom left for the rest of the window"), |
| 54 | icon: TrendingDownIcon, |
| 55 | }, |
| 56 | }; |
| 57 | |
| 58 | export function barColor(driver: ServerProvider["driver"]): string { |
| 59 | const presentation = Object.values(PROVIDER_PRESENTATION).find( |
| 60 | (entry) => entry.driverKind === driver, |
| 61 | ); |
| 62 | return presentation?.color ?? "var(--foreground)"; |
| 63 | } |
| 64 | |
| 65 | export function PaceIcon({ pace }: { readonly pace: LimitPace }) { |
| 66 | const Icon = PACE[pace].icon; |
| 67 | const m = useMessages(); |
| 68 | return ( |
| 69 | <Tooltip> |
| 70 | <TooltipTrigger |
| 71 | render={ |
| 72 | <span |
| 73 | role="img" |
| 74 | aria-label={m(PACE[pace].label)} |
| 75 | className="inline-flex text-muted-foreground" |
| 76 | /> |
| 77 | } |
| 78 | > |
| 79 | <Icon className="size-3.5" aria-hidden /> |
| 80 | </TooltipTrigger> |
| 81 | <TooltipPopup side="top">{m(PACE[pace].label)}</TooltipPopup> |
| 82 | </Tooltip> |
| 83 | ); |
| 84 | } |
| 85 | |
| 86 | // The tick sits in a transparent gap cut from the bar, clamped so it stays inside at 0% and 100%. |
| 87 | // The gap is a clip-path slot rather than a mask: a mask composites its layer and re-antialiases |
| 88 | // the bar's rounded ends, and the polygon reaches 1px past the box so only the slot edges clip. |
| 89 | function paceMarkStyles(timeLeft: number | null) { |
| 90 | if (timeLeft === null) return null; |
| 91 | const at = `clamp(3px, ${timeLeft}%, calc(100% - 3px))`; |
| 92 | const [left, right] = [`calc(${at} - 3px)`, `calc(${at} + 3px)`]; |
| 93 | const [near, far] = ["-1px", "calc(100% + 1px)"]; |
| 94 | return { |
| 95 | tick: { left: at }, |
| 96 | gap: { |
| 97 | clipPath: `polygon(${near} ${near}, ${left} ${near}, ${left} ${far}, ${right} ${far}, ${right} ${near}, ${far} ${near}, ${far} ${far}, ${near} ${far})`, |
| 98 | }, |
| 99 | // For a track painted on an element that also draws focus rings, which a clip would cut. |
| 100 | gappedTrack: { |
| 101 | backgroundColor: "transparent", |
| 102 | backgroundImage: `linear-gradient(to right, var(--color-muted) ${left}, transparent ${left}, transparent ${right}, var(--color-muted) ${right})`, |
| 103 | }, |
| 104 | }; |
| 105 | } |
| 106 | |
| 107 | /** |
| 108 | * Pace mark styles for the bar given the returned ref. Below 6px there is no room for the gap |
| 109 | * and tick, so the bar draws neither, as the mobile bars do. |
| 110 | */ |
| 111 | export function usePaceMark(timeLeft: number | null) { |
| 112 | const [bar, setBar] = useState<HTMLElement | null>(null); |
| 113 | const [roomy, setRoomy] = useState(false); |
| 114 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the bar DOM width before paint and remeasures through a ResizeObserver |
| 115 | useLayoutEffect(() => { |
| 116 | if (!bar) return; |
| 117 | const measure = () => setRoomy(bar.getBoundingClientRect().width >= 6); |
| 118 | measure(); |
| 119 | return observeResize(bar, measure); |
| 120 | }, [bar]); |
| 121 | return [setBar, roomy ? paceMarkStyles(timeLeft) : null] as const; |
| 122 | } |
| 123 | |
| 124 | function WindowBar({ |
| 125 | color, |
| 126 | window, |
| 127 | now, |
| 128 | }: { |
| 129 | readonly color: string; |
| 130 | readonly window: ServerProviderUsageWindow; |
| 131 | readonly now: number; |
| 132 | }) { |
| 133 | const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat); |
| 134 | const gt = useGT(); |
| 135 | const m = useMessages(); |
| 136 | const remaining = remainingPercent(window); |
| 137 | const timeLeft = paceRemainingPercent(window, now); |
| 138 | const [barRef, paceMark] = usePaceMark(timeLeft); |
| 139 | const resetsIn = formatResetsIn(window, now, m); |
| 140 | const resetsAt = window.resetsAt |
| 141 | ? formatUpcomingTimestamp(window.resetsAt, timestampFormat, now, undefined, m) |
| 142 | : null; |
| 143 | const label = window.label; |
| 144 | const summary = |
| 145 | timeLeft === null |
| 146 | ? resetsIn |
| 147 | ? gt("{label}: {remaining}% left, {resetsIn}", { label, remaining, resetsIn }) |
| 148 | : gt("{label}: {remaining}% left", { label, remaining }) |
| 149 | : resetsIn |
| 150 | ? gt("{label}: {remaining}% left, {timeLeft}% of the window left, {resetsIn}", { |
| 151 | label, |
| 152 | remaining, |
| 153 | timeLeft, |
| 154 | resetsIn, |
| 155 | }) |
| 156 | : gt("{label}: {remaining}% left, {timeLeft}% of the window left", { |
| 157 | label, |
| 158 | remaining, |
| 159 | timeLeft, |
| 160 | }); |
| 161 | |
| 162 | return ( |
| 163 | <Tooltip> |
| 164 | <TooltipTrigger |
| 165 | render={ |
| 166 | <div |
| 167 | ref={barRef} |
| 168 | role="img" |
| 169 | aria-label={summary} |
| 170 | tabIndex={0} |
| 171 | className="relative h-6 cursor-default rounded-full outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background" |
| 172 | /> |
| 173 | } |
| 174 | > |
| 175 | {/* Clip both layers so the gap exposes even a translucent composer surface. */} |
| 176 | <div className="absolute inset-0" style={paceMark?.gap}> |
| 177 | <div className="absolute inset-x-0 inset-y-1.5 rounded-full bg-muted" /> |
| 178 | {remaining > 0 ? ( |
| 179 | <div |
| 180 | className="absolute inset-y-1.5 left-0 rounded-full" |
| 181 | style={{ width: `${remaining}%`, backgroundColor: color }} |
| 182 | /> |
| 183 | ) : null} |
| 184 | </div> |
| 185 | {paceMark ? ( |
| 186 | <span |
| 187 | aria-hidden |
| 188 | className="absolute inset-y-1 w-0.5 -translate-x-1/2 rounded-full bg-foreground" |
| 189 | style={paceMark.tick} |
| 190 | /> |
| 191 | ) : null} |
| 192 | </TooltipTrigger> |
| 193 | <TooltipPopup side="top"> |
| 194 | <div className="flex flex-col gap-0.5"> |
| 195 | <span className="text-foreground"> |
| 196 | {timeLeft !== null |
| 197 | ? gt("{remaining}% left · {timeLeft}% of the window left", { remaining, timeLeft }) |
| 198 | : gt("{remaining}% left", { remaining })} |
| 199 | </span> |
| 200 | {timeLeft !== null ? ( |
| 201 | <span className="text-muted-foreground"> |
| 202 | <T>The line is where even spending would be.</T> |
| 203 | </span> |
| 204 | ) : null} |
| 205 | {resetsAt ? ( |
| 206 | <span className="text-muted-foreground"> |
| 207 | {resetsIn |
| 208 | ? gt("Resets {resetsAt} · {resetsIn}", { resetsAt, resetsIn }) |
| 209 | : gt("Resets {resetsAt}", { resetsAt })} |
| 210 | </span> |
| 211 | ) : null} |
| 212 | </div> |
| 213 | </TooltipPopup> |
| 214 | </Tooltip> |
| 215 | ); |
| 216 | } |
| 217 | |
| 218 | export function LimitWindows({ |
| 219 | driver, |
| 220 | accentColor, |
| 221 | windows, |
| 222 | now, |
| 223 | compact = false, |
| 224 | }: { |
| 225 | readonly driver: ServerProvider["driver"]; |
| 226 | readonly accentColor?: string | undefined; |
| 227 | readonly windows: ReadonlyArray<ServerProviderUsageWindow>; |
| 228 | readonly now: number; |
| 229 | readonly compact?: boolean; |
| 230 | }) { |
| 231 | const color = normalizeProviderAccentColor(accentColor) ?? barColor(driver); |
| 232 | const gt = useGT(); |
| 233 | const m = useMessages(); |
| 234 | return ( |
| 235 | <div |
| 236 | className={ |
| 237 | compact |
| 238 | ? "grid grid-cols-[minmax(0,9rem)_minmax(3rem,1fr)_auto] gap-x-3 gap-y-0.5" |
| 239 | : "grid grid-cols-[11rem_minmax(0,1fr)_7rem] gap-x-4 gap-y-1" |
| 240 | } |
| 241 | > |
| 242 | {windows.map((window) => { |
| 243 | const pace = paceOf(window, now); |
| 244 | const resetsIn = formatResetsIn(window, now, m); |
| 245 | return ( |
| 246 | <Fragment key={window.id}> |
| 247 | <span className="flex min-w-0 items-center gap-2 text-xs"> |
| 248 | <span className="truncate text-muted-foreground">{window.label}</span> |
| 249 | <span className="ms-auto shrink-0 font-medium text-foreground tabular-nums"> |
| 250 | {gt("{remaining}% left", { remaining: remainingPercent(window) })} |
| 251 | </span> |
| 252 | </span> |
| 253 | <WindowBar color={color} window={window} now={now} /> |
| 254 | <span className="flex items-center gap-2 text-xs whitespace-nowrap text-muted-foreground tabular-nums"> |
| 255 | {pace ? <PaceIcon pace={pace} /> : null} |
| 256 | <span className="ms-auto shrink-0">{resetsIn ?? ""}</span> |
| 257 | </span> |
| 258 | </Fragment> |
| 259 | ); |
| 260 | })} |
| 261 | </div> |
| 262 | ); |
| 263 | } |
| 264 | |
| 265 | const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = { |
| 266 | reset: msg("Reset applied. Your windows have cleared."), |
| 267 | nothingToReset: msg("Nothing to reset right now."), |
| 268 | noCredit: msg("No reset credit left."), |
| 269 | alreadyRedeemed: msg("That credit was already redeemed."), |
| 270 | }; |
| 271 | |
| 272 | export function useResetCredit(environmentId: EnvironmentId) { |
| 273 | const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope); |
| 274 | const consume = useAtomCommand(serverEnvironment.consumeResetCredit, { reportFailure: false }); |
| 275 | const m = useMessages(); |
| 276 | // Kept after close so the dialog's text survives its exit animation. |
| 277 | const [choice, setChoice] = useState<ResetCreditChoice | null>(null); |
| 278 | const [confirming, setConfirming] = useState(false); |
| 279 | const [busy, setBusy] = useState(false); |
| 280 | const [status, setStatus] = useState<string | null>(null); |
| 281 | |
| 282 | const redeem = async () => { |
| 283 | setConfirming(false); |
| 284 | if (!choice || !readEnvironmentScope(environmentId, AuthProvidersManageScope)) return; |
| 285 | setBusy(true); |
| 286 | setStatus(null); |
| 287 | const result = await consume({ environmentId, input: choice.input }); |
| 288 | setBusy(false); |
| 289 | if (result._tag === "Success") { |
| 290 | setStatus(result.value.warning ?? m(OUTCOME_TEXT[result.value.outcome])); |
| 291 | return; |
| 292 | } |
| 293 | setStatus( |
| 294 | "error" in result.cause && result.cause.error instanceof Error |
| 295 | ? result.cause.error.message |
| 296 | : m(msg("Could not use the reset credit.")), |
| 297 | ); |
| 298 | }; |
| 299 | |
| 300 | const confirm = (next: ResetCreditChoice) => { |
| 301 | if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return; |
| 302 | setChoice(next); |
| 303 | setConfirming(true); |
| 304 | }; |
| 305 | |
| 306 | return { canManageProviders, choice, confirming, setConfirming, confirm, busy, status, redeem }; |
| 307 | } |
| 308 | |
| 309 | /** Require confirmation because redemption spends credits. Mount outside popovers, which stack above |
| 310 | * dialogs and unmount on close. */ |
| 311 | export function ResetCreditDialog({ |
| 312 | open, |
| 313 | onOpenChange, |
| 314 | choice, |
| 315 | onConfirm, |
| 316 | disabled = false, |
| 317 | }: { |
| 318 | readonly open: boolean; |
| 319 | readonly onOpenChange: (open: boolean) => void; |
| 320 | readonly choice: ResetCreditChoice | null; |
| 321 | readonly onConfirm: () => void; |
| 322 | readonly disabled?: boolean; |
| 323 | }) { |
| 324 | return ( |
| 325 | <AlertDialog open={open} onOpenChange={onOpenChange}> |
| 326 | <AlertDialogPopup> |
| 327 | <AlertDialogHeader> |
| 328 | <AlertDialogTitle> |
| 329 | <T>Use a reset credit?</T> |
| 330 | </AlertDialogTitle> |
| 331 | <AlertDialogDescription>{choice?.confirmDescription}</AlertDialogDescription> |
| 332 | </AlertDialogHeader> |
| 333 | <AlertDialogFooter> |
| 334 | <AlertDialogClose render={<Button variant="outline" />}> |
| 335 | <T>Cancel</T> |
| 336 | </AlertDialogClose> |
| 337 | <Button disabled={disabled} onClick={onConfirm}> |
| 338 | <T>Use credit</T> |
| 339 | </Button> |
| 340 | </AlertDialogFooter> |
| 341 | </AlertDialogPopup> |
| 342 | </AlertDialog> |
| 343 | ); |
| 344 | } |
| 345 | |
| 346 | export function ResetCredits({ |
| 347 | environmentId, |
| 348 | input, |
| 349 | credits, |
| 350 | now, |
| 351 | }: { |
| 352 | readonly environmentId: EnvironmentId; |
| 353 | readonly input: ProviderConsumeResetCreditInput; |
| 354 | readonly credits: ServerProviderResetCredits; |
| 355 | readonly now: number; |
| 356 | }) { |
| 357 | const { canManageProviders, choice, confirming, setConfirming, confirm, busy, status, redeem } = |
| 358 | useResetCredit(environmentId); |
| 359 | const gt = useGT(); |
| 360 | const m = useMessages(); |
| 361 | if (credits.availableCount === 0 && status === null) return null; |
| 362 | return ( |
| 363 | <div className="flex flex-col gap-1 text-xs text-muted-foreground"> |
| 364 | {resetCreditChoices(credits, input, now, false, m).map((choice) => ( |
| 365 | <div key={choice.key} className="flex flex-wrap items-center gap-x-3 gap-y-1"> |
| 366 | <span className="tabular-nums">{choice.summary}</span> |
| 367 | {choice.availableCount > 0 ? ( |
| 368 | <Button |
| 369 | size="xs" |
| 370 | variant="outline" |
| 371 | disabled={busy || !canManageProviders} |
| 372 | onClick={() => confirm(choice)} |
| 373 | > |
| 374 | {busy ? gt("Using…") : choice.actionLabel} |
| 375 | </Button> |
| 376 | ) : null} |
| 377 | </div> |
| 378 | ))} |
| 379 | {status ? <span className="text-foreground">{status}</span> : null} |
| 380 | <ResetCreditDialog |
| 381 | open={confirming} |
| 382 | onOpenChange={setConfirming} |
| 383 | choice={choice} |
| 384 | onConfirm={() => void redeem()} |
| 385 | disabled={!canManageProviders} |
| 386 | /> |
| 387 | </div> |
| 388 | ); |
| 389 | } |
| 390 | |
| 391 | /** Advance now only on explicit refresh to avoid page repaints from ticking. */ |
| 392 | export function UsageLimitsSection({ |
| 393 | selectedEnvironmentIds, |
| 394 | hiddenProviders, |
| 395 | now, |
| 396 | }: { |
| 397 | readonly selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null; |
| 398 | readonly hiddenProviders: ReadonlySet<UsageProviderKind>; |
| 399 | readonly now: number; |
| 400 | }) { |
| 401 | const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom); |
| 402 | const hiddenDrivers = new Set<ServerProvider["driver"]>( |
| 403 | [...hiddenProviders].map((provider) => PROVIDER_PRESENTATION[provider].driverKind), |
| 404 | ); |
| 405 | const isVisible = (driver: ServerProvider["driver"]) => !hiddenDrivers.has(driver); |
| 406 | const selected = new Map( |
| 407 | [...presentations].flatMap(([id, presentation]) => { |
| 408 | if (selectedEnvironmentIds !== null && !selectedEnvironmentIds.has(id)) return []; |
| 409 | const config = presentation.serverConfig; |
| 410 | if (hiddenDrivers.size === 0 || config === null) return [[id, presentation] as const]; |
| 411 | return [ |
| 412 | [ |
| 413 | id, |
| 414 | { |
| 415 | ...presentation, |
| 416 | serverConfig: { |
| 417 | ...config, |
| 418 | providers: config.providers.filter((provider) => isVisible(provider.driver)), |
| 419 | usageLimitSources: config.usageLimitSources?.flatMap((source) => { |
| 420 | const accounts = source.accounts.filter((account) => isVisible(account.driver)); |
| 421 | return accounts.length === 0 && source.accounts.length > 0 |
| 422 | ? [] |
| 423 | : [{ ...source, accounts }]; |
| 424 | }), |
| 425 | }, |
| 426 | }, |
| 427 | ] as const, |
| 428 | ]; |
| 429 | }), |
| 430 | ); |
| 431 | return <UsageLimitsPooled presentations={selected} now={now} />; |
| 432 | } |