The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display"; |
| 2 | import { |
| 3 | collectLimitAccounts, |
| 4 | collectLimitPools, |
| 5 | remainingPercent, |
| 6 | type LimitAccount, |
| 7 | type LimitPoolWindow, |
| 8 | type LimitPresentations, |
| 9 | } from "@t3tools/shared/usageLimits"; |
| 10 | import { msg } from "gt-react-native"; |
| 11 | |
| 12 | import { m, type MessageResolver } from "../i18n/messages"; |
| 13 | |
| 14 | import { providerColors } from "../features/usage/providerColors"; |
| 15 | import type { WidgetTheme } from "./widgetTheme"; |
| 16 | |
| 17 | /** |
| 18 | * Copy for the widget, which runs without the app's catalogs. `{name}` tokens are filled in by the |
| 19 | * widget; `moreInApp` is keyed by count. |
| 20 | */ |
| 21 | export interface SubscriptionUsageText { |
| 22 | refresh: string; |
| 23 | noSessionLimit: string; |
| 24 | noWeeklyLimit: string; |
| 25 | subscriptionRemaining: string; |
| 26 | percentLeft: string; |
| 27 | windowPercentLeft: string; |
| 28 | left: string; |
| 29 | notApplicable: string; |
| 30 | openApp: string; |
| 31 | noLimits: string; |
| 32 | asOf: string; |
| 33 | tapToConnect: string; |
| 34 | providerAccessibility: string; |
| 35 | windowAccessibility: string; |
| 36 | moreInApp: Record<string, string>; |
| 37 | } |
| 38 | |
| 39 | export interface WidgetLimitAccount { |
| 40 | name: string; |
| 41 | color?: string; |
| 42 | /** Absent when this account does not report the window. */ |
| 43 | remaining?: number; |
| 44 | refill?: number; |
| 45 | resetsAt?: number; |
| 46 | reset?: string; |
| 47 | durationMs?: number; |
| 48 | } |
| 49 | |
| 50 | export interface SubscriptionUsageSnapshot { |
| 51 | theme?: WidgetTheme; |
| 52 | url?: string; |
| 53 | text?: SubscriptionUsageText; |
| 54 | checkedAt: number; |
| 55 | providers: Array<{ |
| 56 | name: string; |
| 57 | colors?: { light: string; dark: string }; |
| 58 | detail: string; |
| 59 | windows: Array<{ |
| 60 | kind?: string; |
| 61 | label: string; |
| 62 | remaining: number; |
| 63 | reset: string; |
| 64 | accounts?: WidgetLimitAccount[]; |
| 65 | }>; |
| 66 | expiresAt: number; |
| 67 | totalWindows: number; |
| 68 | }>; |
| 69 | } |
| 70 | |
| 71 | // Snapshots expire after 15 minutes; suspended refresh requires a separate authenticated transport. |
| 72 | const SNAPSHOT_MAX_AGE = 15 * 60_000; |
| 73 | export const WIDGET_REFRESH_INTERVAL = 5 * 60_000; |
| 74 | |
| 75 | export function createWidgetRefresher<Id>(refresh: (id: Id) => Promise<unknown>) { |
| 76 | const attempted = new Map<Id, number>(); |
| 77 | const pending = new Set<Id>(); |
| 78 | return async (connected: readonly Id[], now: number) => { |
| 79 | await Promise.allSettled( |
| 80 | connected.map(async (id) => { |
| 81 | if (pending.has(id) || now - (attempted.get(id) ?? -Infinity) < WIDGET_REFRESH_INTERVAL) |
| 82 | return; |
| 83 | attempted.set(id, now); |
| 84 | pending.add(id); |
| 85 | try { |
| 86 | await refresh(id); |
| 87 | } finally { |
| 88 | pending.delete(id); |
| 89 | } |
| 90 | }), |
| 91 | ); |
| 92 | }; |
| 93 | } |
| 94 | |
| 95 | // Widget snapshots must not persist account emails. |
| 96 | function accountName(account: LimitAccount, resolve: MessageResolver) { |
| 97 | if (account.displayName && !account.displayName.includes("@")) return account.displayName; |
| 98 | const email = account.email ?? account.displayName; |
| 99 | if (!email?.includes("@")) |
| 100 | return resolve(msg("Account", { $context: "an unnamed provider account" })); |
| 101 | const [local = "", domain = ""] = email.split("@"); |
| 102 | return `${local[0] ?? ""}${domain[0] ?? ""}`.toUpperCase(); |
| 103 | } |
| 104 | |
| 105 | function clockLabel(at: number, from: number) { |
| 106 | const time = { hour: "numeric", minute: "2-digit" } as const; |
| 107 | if (new Date(at).toDateString() === new Date(from).toDateString()) |
| 108 | return new Date(at).toLocaleTimeString(undefined, time); |
| 109 | return new Date(at).toLocaleString( |
| 110 | undefined, |
| 111 | at - from < 6 * 86_400_000 ? { weekday: "short", ...time } : { month: "short", day: "numeric" }, |
| 112 | ); |
| 113 | } |
| 114 | |
| 115 | function widgetAccounts(window: LimitPoolWindow, resolve: MessageResolver): WidgetLimitAccount[] { |
| 116 | const seen = new Map<string, number>(); |
| 117 | return window.columns.map((column) => { |
| 118 | // Redacted initials can collide, and the widget keys segments by name. |
| 119 | const base = accountName(column.account, resolve); |
| 120 | const count = (seen.get(base) ?? 0) + 1; |
| 121 | seen.set(base, count); |
| 122 | const color = normalizeProviderAccentColor(column.account.accentColor); |
| 123 | // expo-widgets cannot convert an explicit undefined into a Kotlin value. |
| 124 | const account = { name: count > 1 ? `${base}${count}` : base, ...(color && { color }) }; |
| 125 | if (column.window === null) return account; |
| 126 | const checkedAt = Date.parse(column.account.limits.checkedAt); |
| 127 | const resetsAt = column.window.resetsAt ? Date.parse(column.window.resetsAt) : NaN; |
| 128 | // A reset at or before the observation already happened. |
| 129 | const reset = resetsAt > checkedAt; |
| 130 | return { |
| 131 | ...account, |
| 132 | remaining: remainingPercent(column.window), |
| 133 | refill: reset ? column.refillPercent : 0, |
| 134 | ...(reset && { |
| 135 | resetsAt, |
| 136 | reset: clockLabel(resetsAt, checkedAt), |
| 137 | }), |
| 138 | ...(column.window.windowDurationMins && { |
| 139 | durationMs: column.window.windowDurationMins * 60_000, |
| 140 | }), |
| 141 | }; |
| 142 | }); |
| 143 | } |
| 144 | |
| 145 | // A reset at or before its account's observation already happened, so it cannot expire the snapshot. |
| 146 | const isUpcoming = (reset: LimitPoolWindow["resets"][number]) => |
| 147 | reset.at > Date.parse(reset.member.account.limits.checkedAt); |
| 148 | |
| 149 | const resetTime = (at: number) => |
| 150 | new Date(at).toLocaleString(undefined, { |
| 151 | month: "short", |
| 152 | day: "numeric", |
| 153 | hour: "numeric", |
| 154 | minute: "2-digit", |
| 155 | }); |
| 156 | |
| 157 | function subscriptionUsageText( |
| 158 | resolve: MessageResolver, |
| 159 | maxHiddenWindows: number, |
| 160 | ): SubscriptionUsageText { |
| 161 | return { |
| 162 | refresh: resolve(msg("Open {app} to refresh", { app: "T3" })), |
| 163 | noSessionLimit: resolve(msg("No session limit reported")), |
| 164 | noWeeklyLimit: resolve(msg("No weekly limit reported")), |
| 165 | subscriptionRemaining: resolve(msg("Subscription remaining")), |
| 166 | percentLeft: resolve(msg("{remaining}% left", { remaining: "{remaining}" })), |
| 167 | windowPercentLeft: resolve( |
| 168 | msg("{window} · {remaining}% left", { window: "{window}", remaining: "{remaining}" }), |
| 169 | ), |
| 170 | left: resolve(msg("left", { $context: "follows a bold percentage, as in 40% left" })), |
| 171 | notApplicable: resolve(msg("N/A", { $context: "no usage limit for the chosen period" })), |
| 172 | openApp: resolve(msg("Open {app}", { app: "T3" })), |
| 173 | noLimits: resolve(msg("No subscription limits available.")), |
| 174 | asOf: resolve(msg("As of {time}", { time: "{time}" })), |
| 175 | tapToConnect: resolve(msg("Tap to connect in {app}", { app: "T3" })), |
| 176 | providerAccessibility: resolve( |
| 177 | // oxlint-disable-next-line t3code/no-untranslated-copy -- placeholders the widget fills in |
| 178 | msg("{provider}. {detail}.", { provider: "{provider}", detail: "{detail}" }), |
| 179 | ), |
| 180 | windowAccessibility: resolve( |
| 181 | msg("{provider}, {window}, {remaining} percent remaining. {reset}. {detail}.", { |
| 182 | provider: "{provider}", |
| 183 | window: "{window}", |
| 184 | remaining: "{remaining}", |
| 185 | reset: "{reset}", |
| 186 | // oxlint-disable-next-line t3code/no-untranslated-copy -- placeholders the widget fills in |
| 187 | detail: "{detail}", |
| 188 | }), |
| 189 | ), |
| 190 | moreInApp: Object.fromEntries( |
| 191 | Array.from({ length: maxHiddenWindows }, (_, index) => [ |
| 192 | String(index + 1), |
| 193 | resolve( |
| 194 | msg("{count, plural, one {{count} more in {app}} other {{count} more in {app}}}", { |
| 195 | count: index + 1, |
| 196 | app: "T3", |
| 197 | }), |
| 198 | ), |
| 199 | ]), |
| 200 | ), |
| 201 | }; |
| 202 | } |
| 203 | |
| 204 | function subscriptionUsageProps( |
| 205 | accounts: readonly LimitAccount[], |
| 206 | now: number, |
| 207 | configuredDrivers: ReadonlySet<string>, |
| 208 | maxWindowsPerProvider: number, |
| 209 | resolve: MessageResolver, |
| 210 | ): SubscriptionUsageSnapshot { |
| 211 | const pools = collectLimitPools(accounts, now); |
| 212 | const checked = accounts |
| 213 | .filter((account) => account.driver === "codex" || account.driver === "claudeAgent") |
| 214 | .map((account) => Date.parse(account.limits.checkedAt)); |
| 215 | return { |
| 216 | checkedAt: checked.length > 0 && checked.every(Number.isFinite) ? Math.min(...checked) : 0, |
| 217 | providers: (["codex", "claudeAgent"] as const) |
| 218 | .filter( |
| 219 | (driver) => |
| 220 | configuredDrivers.has(driver) || accounts.some((account) => account.driver === driver), |
| 221 | ) |
| 222 | .map((driver) => { |
| 223 | const pool = pools.find((candidate) => candidate.driver === driver); |
| 224 | const name = driver === "codex" ? "Codex" : "Claude"; |
| 225 | const kind = driver === "codex" ? "codex" : "claude"; |
| 226 | const colors = { light: providerColors("light")[kind], dark: providerColors("dark")[kind] }; |
| 227 | if (!pool) |
| 228 | return { |
| 229 | name, |
| 230 | colors, |
| 231 | detail: resolve(msg("No limits available")), |
| 232 | windows: [], |
| 233 | expiresAt: 0, |
| 234 | totalWindows: 0, |
| 235 | }; |
| 236 | const checkedAt = Math.min(...pool.accounts.map((a) => Date.parse(a.limits.checkedAt))); |
| 237 | const expiresAt = Math.min( |
| 238 | checkedAt + SNAPSHOT_MAX_AGE, |
| 239 | ...pool.windows.flatMap((window) => |
| 240 | window.resets.filter(isUpcoming).map((reset) => reset.at), |
| 241 | ), |
| 242 | ); |
| 243 | const fresh = Number.isFinite(expiresAt) && expiresAt > now; |
| 244 | const sortedWindows = [...pool.windows].sort( |
| 245 | (a, b) => a.remainingPercent - b.remainingPercent, |
| 246 | ); |
| 247 | const selectedWindows = [ |
| 248 | ...new Set([ |
| 249 | sortedWindows.find((window) => window.kind === "session"), |
| 250 | sortedWindows.find((window) => window.kind === "weekly"), |
| 251 | ...sortedWindows, |
| 252 | ]), |
| 253 | ] |
| 254 | .filter((window) => window !== undefined) |
| 255 | .slice(0, maxWindowsPerProvider) |
| 256 | .sort((a, b) => a.remainingPercent - b.remainingPercent); |
| 257 | return { |
| 258 | name, |
| 259 | colors, |
| 260 | detail: !fresh |
| 261 | ? resolve(msg("Open {app} to refresh", { app: "T3" })) |
| 262 | : pool.accounts.length > 1 |
| 263 | ? resolve( |
| 264 | msg( |
| 265 | "{count, plural, one {{count} account · pooled} other {{count} accounts · pooled}}", |
| 266 | { |
| 267 | count: pool.accounts.length, |
| 268 | }, |
| 269 | ), |
| 270 | ) |
| 271 | : resolve(msg("Subscription remaining")), |
| 272 | expiresAt: fresh ? expiresAt : 0, |
| 273 | totalWindows: fresh ? pool.windows.length : 0, |
| 274 | windows: fresh |
| 275 | ? selectedWindows.map((window) => ({ |
| 276 | kind: window.kind, |
| 277 | label: window.label, |
| 278 | remaining: Math.round(window.remainingPercent), |
| 279 | reset: window.resets[0] |
| 280 | ? isUpcoming(window.resets[0]) |
| 281 | ? resolve(msg("Next reset {time}", { time: resetTime(window.resets[0].at) })) |
| 282 | : resolve(msg("Reset {time}", { time: resetTime(window.resets[0].at) })) |
| 283 | : resolve(msg("Reset time unavailable")), |
| 284 | accounts: widgetAccounts(window, resolve), |
| 285 | })) |
| 286 | : [], |
| 287 | }; |
| 288 | }), |
| 289 | }; |
| 290 | } |
| 291 | |
| 292 | export function buildSubscriptionUsageSnapshot( |
| 293 | presentations: LimitPresentations, |
| 294 | url: string, |
| 295 | maxWindowsPerProvider = 6, |
| 296 | resolve: MessageResolver = m, |
| 297 | ): SubscriptionUsageSnapshot { |
| 298 | const configuredDrivers = new Set( |
| 299 | [...presentations.values()].flatMap((presentation) => |
| 300 | (presentation.serverConfig?.providers ?? []) |
| 301 | // Servers report default-enabled drivers even when their CLI is missing. |
| 302 | .filter( |
| 303 | (provider) => |
| 304 | provider.enabled && |
| 305 | provider.installed && |
| 306 | provider.usageLimits?.unavailable?.reason !== "unsupported", |
| 307 | ) |
| 308 | .map((provider) => provider.driver), |
| 309 | ), |
| 310 | ); |
| 311 | const props = subscriptionUsageProps( |
| 312 | collectLimitAccounts(presentations), |
| 313 | 0, |
| 314 | configuredDrivers, |
| 315 | maxWindowsPerProvider, |
| 316 | resolve, |
| 317 | ); |
| 318 | return { |
| 319 | ...props, |
| 320 | url, |
| 321 | // The Android widget counts hidden rows across providers, a note row included. |
| 322 | text: subscriptionUsageText( |
| 323 | resolve, |
| 324 | props.providers.reduce((sum, provider) => sum + Math.max(1, provider.totalWindows), 0), |
| 325 | ), |
| 326 | }; |
| 327 | } |
| 328 | |
| 329 | export function subscriptionUsageTimeline(snapshot: SubscriptionUsageSnapshot, now: number) { |
| 330 | const deadlines = [...new Set(snapshot.providers.map((p) => p.expiresAt))] |
| 331 | .filter((deadline) => deadline > now) |
| 332 | .sort((a, b) => a - b); |
| 333 | return [now, ...deadlines].map((date) => ({ |
| 334 | date: new Date(date), |
| 335 | props: { |
| 336 | ...snapshot, |
| 337 | providers: snapshot.providers.map((provider) => |
| 338 | provider.windows.length > 0 && provider.expiresAt <= date |
| 339 | ? { |
| 340 | ...provider, |
| 341 | detail: snapshot.text?.refresh ?? m(msg("Open {app} to refresh", { app: "T3" })), |
| 342 | windows: [], |
| 343 | totalWindows: 0, |
| 344 | } |
| 345 | : provider, |
| 346 | ), |
| 347 | }, |
| 348 | })); |
| 349 | } |