The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import * as Dialog from "../../components/ui/Dialog"; |
| 3 | import { RegistryContext, useAtomMount, useAtomValue } from "@effect/atom-react"; |
| 4 | import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display"; |
| 5 | import { |
| 6 | AuthProvidersManageScope, |
| 7 | type EnvironmentId, |
| 8 | type ProviderConsumeResetCreditOutcome, |
| 9 | type ProviderConsumeResetCreditInput, |
| 10 | type ServerProvider, |
| 11 | type ServerProviderResetCredits, |
| 12 | type ServerProviderUsageWindow, |
| 13 | } from "@t3tools/contracts"; |
| 14 | import { |
| 15 | type ResetCreditChoice, |
| 16 | paceOf, |
| 17 | paceRemainingPercent, |
| 18 | remainingPercent, |
| 19 | resetCountdown, |
| 20 | } from "@t3tools/shared/usageLimits"; |
| 21 | import { formatDuration, limitsNotice, resetCreditChoices } from "@t3tools/shared/usageLimitsCopy"; |
| 22 | import { msg, T, useGT, useMessages, Var } from "gt-react-native"; |
| 23 | import { type ReactNode, useContext, useRef, useState } from "react"; |
| 24 | import { Atom } from "effect/reactivity"; |
| 25 | import { Pressable, View } from "react-native"; |
| 26 | import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; |
| 27 | |
| 28 | import { AppText as Text } from "../../components/ui/AppText"; |
| 29 | import { ProviderIcon } from "../../components/ProviderIcon"; |
| 30 | import { m as resolveNow, type MessageResolver } from "../../i18n/messages"; |
| 31 | import { environmentPresentations } from "../../state/presentation"; |
| 32 | import { serverEnvironment } from "../../state/server"; |
| 33 | import { readEnvironmentScope, useEnvironmentScope } from "../../state/session"; |
| 34 | import { useAtomCommand } from "../../state/use-atom-command"; |
| 35 | import { useNowMinuteMs } from "../../lib/clock"; |
| 36 | import { |
| 37 | environmentIdsKey, |
| 38 | limitsAutoRefreshSetAtom, |
| 39 | limitsRefreshFailuresAtom, |
| 40 | refreshEnvironmentLimits, |
| 41 | } from "./usageLimitsRefresh"; |
| 42 | import { usageProviderKind, useProviderColors } from "./usageProviders"; |
| 43 | |
| 44 | const PACE_LABEL = { |
| 45 | ahead: msg("ahead of pace"), |
| 46 | on: msg("on pace"), |
| 47 | under: msg("under pace"), |
| 48 | } as const; |
| 49 | |
| 50 | type Driver = ServerProvider["driver"]; |
| 51 | |
| 52 | function useBarColor(driver: Driver): string | null { |
| 53 | const colors = useProviderColors(); |
| 54 | const kind = usageProviderKind(driver); |
| 55 | return kind ? colors[kind] : null; |
| 56 | } |
| 57 | |
| 58 | function WindowRow(props: { |
| 59 | readonly window: ServerProviderUsageWindow; |
| 60 | readonly color: string | null; |
| 61 | readonly now: number; |
| 62 | }) { |
| 63 | const { window, now } = props; |
| 64 | const remaining = remainingPercent(window); |
| 65 | const timeLeft = paceRemainingPercent(window, now); |
| 66 | const pace = paceOf(window, now); |
| 67 | const m = useMessages(); |
| 68 | const resetsIn = resetLabels(window, now, m)?.full; |
| 69 | const [barWidth, setBarWidth] = useState(0); |
| 70 | const tickX = |
| 71 | timeLeft === null || barWidth < 6 |
| 72 | ? null |
| 73 | : Math.min(Math.max((barWidth * timeLeft) / 100, 3), barWidth - 3); |
| 74 | const bar = ( |
| 75 | <View |
| 76 | className="h-1.5 flex-row overflow-hidden rounded-full bg-subtle" |
| 77 | style={barWidth > 0 ? { width: barWidth } : undefined} |
| 78 | > |
| 79 | <View |
| 80 | className={ |
| 81 | remaining <= 10 |
| 82 | ? "h-full rounded-full bg-red-500" |
| 83 | : remaining <= 30 |
| 84 | ? "h-full rounded-full bg-amber-500" |
| 85 | : "h-full rounded-full bg-foreground" |
| 86 | } |
| 87 | style={[ |
| 88 | { flex: remaining }, |
| 89 | remaining > 30 && props.color ? { backgroundColor: props.color } : null, |
| 90 | ]} |
| 91 | /> |
| 92 | <View style={{ flex: 100 - remaining }} /> |
| 93 | </View> |
| 94 | ); |
| 95 | return ( |
| 96 | <View className="gap-1"> |
| 97 | <View className="flex-row items-baseline justify-between gap-3"> |
| 98 | <Text className="text-sm text-foreground">{window.label}</Text> |
| 99 | <Text className="text-sm font-t3-medium tabular-nums text-foreground"> |
| 100 | <T> |
| 101 | <Var>{remaining}</Var>% left |
| 102 | </T> |
| 103 | </Text> |
| 104 | </View> |
| 105 | <View |
| 106 | className="h-3 justify-center" |
| 107 | onLayout={(event) => setBarWidth(event.nativeEvent.layout.width)} |
| 108 | > |
| 109 | {tickX === null ? ( |
| 110 | bar |
| 111 | ) : ( |
| 112 | <View className="h-1.5"> |
| 113 | {/* Clip the same full-width bar so neither fill proportions nor corner radii change. */} |
| 114 | {( |
| 115 | [ |
| 116 | [0, tickX - 3], |
| 117 | [tickX + 3, barWidth], |
| 118 | ] as const |
| 119 | ).map(([start, end]) => ( |
| 120 | <View |
| 121 | key={start} |
| 122 | className="absolute top-0 bottom-0 overflow-hidden" |
| 123 | style={{ left: start, width: end - start }} |
| 124 | > |
| 125 | <View style={{ marginLeft: -start }}>{bar}</View> |
| 126 | </View> |
| 127 | ))} |
| 128 | </View> |
| 129 | )} |
| 130 | {tickX !== null ? ( |
| 131 | <View |
| 132 | className="absolute top-px bottom-px w-0.5 rounded-full bg-foreground" |
| 133 | style={{ left: tickX - 1 }} |
| 134 | /> |
| 135 | ) : null} |
| 136 | </View> |
| 137 | {pace || resetsIn ? ( |
| 138 | <View className="flex-row justify-between gap-3"> |
| 139 | <Text className="text-xs text-foreground-tertiary"> |
| 140 | {pace ? m(PACE_LABEL[pace]) : ""} |
| 141 | </Text> |
| 142 | <Text className="text-xs tabular-nums text-foreground-tertiary">{resetsIn ?? ""}</Text> |
| 143 | </View> |
| 144 | ) : null} |
| 145 | </View> |
| 146 | ); |
| 147 | } |
| 148 | |
| 149 | function AccountInstanceLabel({ value }: { readonly value: string }) { |
| 150 | const [revealed, setRevealed] = useState(false); |
| 151 | const gt = useGT(); |
| 152 | if (!value.includes("@")) { |
| 153 | return ( |
| 154 | <Text className="shrink text-xs text-foreground-tertiary" numberOfLines={1}> |
| 155 | · {value} |
| 156 | </Text> |
| 157 | ); |
| 158 | } |
| 159 | return ( |
| 160 | <Pressable |
| 161 | className="shrink active:opacity-60" |
| 162 | accessibilityRole="button" |
| 163 | accessibilityLabel={revealed ? gt("Hide account label") : gt("Reveal account label")} |
| 164 | onPress={() => setRevealed((current) => !current)} |
| 165 | > |
| 166 | <Text className="text-xs text-foreground-tertiary" numberOfLines={1}> |
| 167 | · {revealed ? value : "••••••@••••••"} |
| 168 | </Text> |
| 169 | </Pressable> |
| 170 | ); |
| 171 | } |
| 172 | |
| 173 | export function AccountLimits(props: { |
| 174 | readonly driver: Driver; |
| 175 | readonly accentColor?: string | undefined; |
| 176 | readonly label: string; |
| 177 | readonly instanceLabel: string; |
| 178 | readonly detail: string | undefined; |
| 179 | readonly limits: ServerProvider["usageLimits"]; |
| 180 | readonly now: number; |
| 181 | readonly first: boolean; |
| 182 | readonly dense?: boolean; |
| 183 | readonly trailing?: ReactNode; |
| 184 | readonly footer?: ReactNode; |
| 185 | }) { |
| 186 | const { limits, now, dense = false } = props; |
| 187 | const providerColor = useBarColor(props.driver); |
| 188 | const color = normalizeProviderAccentColor(props.accentColor) ?? providerColor; |
| 189 | const m = useMessages(); |
| 190 | if (!limits) return null; |
| 191 | const notice = limitsNotice(limits, m); |
| 192 | const externalUsage = limits.externalUsage; |
| 193 | const padding = dense ? "px-4 py-3" : "p-4"; |
| 194 | return ( |
| 195 | <View |
| 196 | className={ |
| 197 | props.first ? `gap-3 ${padding}` : `gap-3 border-t border-border-subtle ${padding}` |
| 198 | } |
| 199 | > |
| 200 | <View className="flex-row items-center gap-2"> |
| 201 | <ProviderIcon provider={props.driver} size={16} /> |
| 202 | <View className="min-w-0 flex-1 flex-row items-baseline gap-2"> |
| 203 | <Text className="text-base font-t3-medium text-foreground">{props.label}</Text> |
| 204 | {props.instanceLabel !== props.label ? ( |
| 205 | <AccountInstanceLabel key={props.instanceLabel} value={props.instanceLabel} /> |
| 206 | ) : null} |
| 207 | {props.detail ? ( |
| 208 | <Text className="shrink text-sm text-foreground-muted" numberOfLines={1}> |
| 209 | · {props.detail} |
| 210 | </Text> |
| 211 | ) : null} |
| 212 | </View> |
| 213 | {props.trailing} |
| 214 | </View> |
| 215 | {notice ? ( |
| 216 | <Text className="text-sm text-foreground-muted">{notice}</Text> |
| 217 | ) : ( |
| 218 | <View className="gap-3"> |
| 219 | {limits.windows.map((window) => ( |
| 220 | <WindowRow key={window.id} window={window} color={color} now={now} /> |
| 221 | ))} |
| 222 | </View> |
| 223 | )} |
| 224 | {externalUsage ? ( |
| 225 | <Pressable |
| 226 | accessibilityRole="link" |
| 227 | className="min-h-11 justify-center" |
| 228 | onPress={() => void tryOpenExternalUrl(externalUsage.url)} |
| 229 | > |
| 230 | <Text className="text-sm font-t3-medium text-primary"> |
| 231 | <T>Manage usage</T> |
| 232 | </Text> |
| 233 | </Pressable> |
| 234 | ) : null} |
| 235 | {props.footer} |
| 236 | </View> |
| 237 | ); |
| 238 | } |
| 239 | |
| 240 | const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = { |
| 241 | reset: msg("Reset applied. Your windows have cleared."), |
| 242 | nothingToReset: msg("Nothing to reset right now."), |
| 243 | noCredit: msg("No reset credit left."), |
| 244 | alreadyRedeemed: msg("That credit was already redeemed."), |
| 245 | }; |
| 246 | |
| 247 | export function ResetCredits(props: { |
| 248 | readonly environmentId: EnvironmentId; |
| 249 | readonly input: ProviderConsumeResetCreditInput; |
| 250 | readonly credits: ServerProviderResetCredits; |
| 251 | readonly now: number; |
| 252 | readonly dense?: boolean; |
| 253 | }) { |
| 254 | const { environmentId, input, credits, now, dense = false } = props; |
| 255 | const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope); |
| 256 | const consume = useAtomCommand(serverEnvironment.consumeResetCredit, { |
| 257 | reportFailure: false, |
| 258 | }); |
| 259 | const [busy, setBusy] = useState(false); |
| 260 | const [status, setStatus] = useState<string | null>(null); |
| 261 | const gt = useGT(); |
| 262 | const m = useMessages(); |
| 263 | if (dense && credits.availableCount === 0 && status === null) return null; |
| 264 | |
| 265 | const redeem = async (choice: ResetCreditChoice) => { |
| 266 | if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return; |
| 267 | setBusy(true); |
| 268 | setStatus(null); |
| 269 | const result = await consume({ environmentId, input: choice.input }); |
| 270 | setBusy(false); |
| 271 | if (result._tag === "Success") { |
| 272 | setStatus(result.value.warning ?? resolveNow(OUTCOME_TEXT[result.value.outcome])); |
| 273 | return; |
| 274 | } |
| 275 | setStatus( |
| 276 | "error" in result.cause && result.cause.error instanceof Error |
| 277 | ? (errorDisplayMessage(result.cause.error, resolveNow) ?? result.cause.error.message) |
| 278 | : resolveNow(msg("Could not use the reset credit.")), |
| 279 | ); |
| 280 | }; |
| 281 | |
| 282 | const confirm = (choice: ResetCreditChoice) => { |
| 283 | if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return; |
| 284 | Dialog.alert(resolveNow(msg("Use a reset credit?")), choice.confirmDescription, [ |
| 285 | { text: resolveNow(msg("Cancel")), style: "cancel" }, |
| 286 | { text: resolveNow(msg("Use credit")), onPress: () => void redeem(choice) }, |
| 287 | ]); |
| 288 | }; |
| 289 | |
| 290 | return ( |
| 291 | <View className="gap-1"> |
| 292 | {resetCreditChoices(credits, input, now, false, m).map((choice) => ( |
| 293 | <View key={choice.key} className="flex-row flex-wrap items-center gap-x-3 gap-y-1"> |
| 294 | <Text className="text-xs tabular-nums text-foreground-tertiary">{choice.summary}</Text> |
| 295 | {choice.availableCount > 0 ? ( |
| 296 | <Pressable |
| 297 | accessibilityRole="button" |
| 298 | accessibilityState={{ disabled: busy || !canManageProviders }} |
| 299 | disabled={busy || !canManageProviders} |
| 300 | onPress={() => confirm(choice)} |
| 301 | className={ |
| 302 | dense |
| 303 | ? "rounded-full bg-subtle-strong px-2.5 py-1 disabled:opacity-[0.45]" |
| 304 | : "min-h-[44px] justify-center rounded-full bg-subtle-strong px-3 py-1.5 disabled:opacity-[0.45]" |
| 305 | } |
| 306 | > |
| 307 | <Text |
| 308 | className={ |
| 309 | dense |
| 310 | ? "text-xs font-t3-medium text-foreground" |
| 311 | : "text-sm font-t3-medium text-foreground" |
| 312 | } |
| 313 | > |
| 314 | {busy |
| 315 | ? gt("Using…", { $context: "reset credit is being used" }) |
| 316 | : choice.actionLabel} |
| 317 | </Text> |
| 318 | </Pressable> |
| 319 | ) : null} |
| 320 | </View> |
| 321 | ))} |
| 322 | {!canManageProviders ? ( |
| 323 | <Text className="text-xs text-foreground-tertiary"> |
| 324 | <T>This connection cannot manage provider accounts.</T> |
| 325 | </Text> |
| 326 | ) : null} |
| 327 | {status ? <Text className="text-sm text-foreground">{status}</Text> : null} |
| 328 | </View> |
| 329 | ); |
| 330 | } |
| 331 | |
| 332 | const IDLE_ATOM = Atom.make(undefined); |
| 333 | |
| 334 | export function useRefreshLimits( |
| 335 | selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null = null, |
| 336 | active = false, |
| 337 | ) { |
| 338 | const registry = useContext(RegistryContext); |
| 339 | const presentations = useAtomValue(environmentPresentations.presentationsAtom); |
| 340 | const now = useNowMinuteMs(); |
| 341 | const [refreshing, setRefreshing] = useState(false); |
| 342 | const refreshingRef = useRef(false); |
| 343 | const selected = [...presentations].filter( |
| 344 | ([environmentId]) => |
| 345 | selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId), |
| 346 | ); |
| 347 | const connectedIds = selected |
| 348 | .filter(([, presentation]) => presentation.connection.phase === "connected") |
| 349 | .map(([environmentId]) => environmentId); |
| 350 | const connectedKey = environmentIdsKey(connectedIds); |
| 351 | useAtomMount(active && connectedKey !== "" ? limitsAutoRefreshSetAtom(connectedKey) : IDLE_ATOM); |
| 352 | const failedIds = new Set( |
| 353 | useAtomValue(limitsRefreshFailuresAtom(environmentIdsKey(selected.map(([id]) => id)))), |
| 354 | ); |
| 355 | const failedLabels = selected |
| 356 | .filter(([environmentId]) => failedIds.has(environmentId)) |
| 357 | .map(([, presentation]) => presentation.entry.target.label); |
| 358 | |
| 359 | const refresh = () => |
| 360 | Promise.all( |
| 361 | connectedIds.map((environmentId) => refreshEnvironmentLimits(registry, environmentId)), |
| 362 | ); |
| 363 | // Android RefreshControl needs a true-to-false cycle to stop, even with nothing to probe. |
| 364 | const refreshManually = async () => { |
| 365 | if (refreshingRef.current) return; |
| 366 | refreshingRef.current = true; |
| 367 | setRefreshing(true); |
| 368 | await refresh().finally(() => { |
| 369 | refreshingRef.current = false; |
| 370 | setRefreshing(false); |
| 371 | }); |
| 372 | }; |
| 373 | return { |
| 374 | now, |
| 375 | refreshing, |
| 376 | failedLabels, |
| 377 | refresh: refreshManually, |
| 378 | }; |
| 379 | } |
| 380 | |
| 381 | export function resetLabels( |
| 382 | window: ServerProviderUsageWindow, |
| 383 | now: number, |
| 384 | resolve: MessageResolver, |
| 385 | ): { readonly full: string; readonly compact: string } | null { |
| 386 | const countdown = resetCountdown(window, now); |
| 387 | if (countdown === null) return null; |
| 388 | if (countdown.kind === "now") { |
| 389 | const full = resolve(msg("resets now", { $context: "usage limit" })); |
| 390 | return { full, compact: full }; |
| 391 | } |
| 392 | if (countdown.kind === "momentarily") { |
| 393 | const momentarily = resolve(msg("Resets momentarily")); |
| 394 | return { full: momentarily, compact: momentarily }; |
| 395 | } |
| 396 | const duration = formatDuration(countdown.ms, resolve); |
| 397 | return { full: resolve(msg("resets in {duration}", { duration })), compact: duration }; |
| 398 | } |
| 399 | |
| 400 | export function refillLabel( |
| 401 | window: ServerProviderUsageWindow, |
| 402 | now: number, |
| 403 | percent: number, |
| 404 | resolve: MessageResolver, |
| 405 | ): string | null { |
| 406 | const countdown = resetCountdown(window, now); |
| 407 | if (countdown === null) return null; |
| 408 | if (countdown.kind === "now") { |
| 409 | return resolve(msg("↻ +{percent}% now", { percent, $context: "usage limit refill" })); |
| 410 | } |
| 411 | if (countdown.kind === "momentarily") { |
| 412 | return resolve(msg("↻ +{percent}% Resets momentarily", { percent })); |
| 413 | } |
| 414 | return resolve( |
| 415 | msg("↻ +{percent}% in {duration}", { |
| 416 | percent, |
| 417 | duration: formatDuration(countdown.ms, resolve), |
| 418 | $context: "usage limit refill", |
| 419 | }), |
| 420 | ); |
| 421 | } |