Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

subscriptionUsageSnapshot.ts

355 lines12.4 KB

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