Open History to see the last commit
1import {
2 collectLimitAccounts,
3 collectLimitPools,
4 type LimitAccount,
5 type LimitPresentations,
6} from "@t3tools/shared/usageLimits";
7
8export interface SubscriptionUsageSnapshot {
9 url?: string;
10 checkedAt: number;
11 providers: Array<{
12 name: string;
13 detail: string;
14 windows: Array<{ kind?: string; label: string; remaining: number; reset: string }>;
15 expiresAt: number;
16 totalWindows: number;
17 }>;
18}
19
20// Snapshots expire after 15 minutes; background refresh needs a
21// separate authenticated transport while the mobile app is suspended.
22const SNAPSHOT_MAX_AGE = 15 * 60_000;
23export const WIDGET_REFRESH_INTERVAL = 5 * 60_000;
24
25/** Bound probes across config updates, reconnects, and foreground transitions. */
26export function createWidgetRefresher<Id>(refresh: (id: Id) => Promise<unknown>) {
27 const attempted = new Map<Id, number>();
28 const pending = new Set<Id>();
29 return async (connected: readonly Id[], now: number) => {
30 await Promise.allSettled(
31 connected.map(async (id) => {
32 if (pending.has(id) || now - (attempted.get(id) ?? -Infinity) < WIDGET_REFRESH_INTERVAL)
33 return;
34 attempted.set(id, now);
35 pending.add(id);
36 try {
37 await refresh(id);
38 } finally {
39 pending.delete(id);
40 }
41 }),
42 );
43 };
44}
45
46function subscriptionUsageProps(
47 accounts: readonly LimitAccount[],
48 now: number,
49): SubscriptionUsageSnapshot {
50 const pools = collectLimitPools(accounts, now);
51 const checked = accounts
52 .filter((account) => account.driver === "codex" || account.driver === "claudeAgent")
53 .map((account) => Date.parse(account.limits.checkedAt));
54 return {
55 checkedAt: checked.length > 0 && checked.every(Number.isFinite) ? Math.min(...checked) : 0,
56 providers: (["codex", "claudeAgent"] as const).map((driver) => {
57 const pool = pools.find((candidate) => candidate.driver === driver);
58 const name = driver === "codex" ? "Codex" : "Claude";
59 if (!pool)
60 return { name, detail: "No limits available", windows: [], expiresAt: 0, totalWindows: 0 };
61 const checkedAt = Math.min(...pool.accounts.map((a) => Date.parse(a.limits.checkedAt)));
62 const expiresAt = Math.min(
63 checkedAt + SNAPSHOT_MAX_AGE,
64 ...pool.windows.flatMap((window) => window.resets.map((reset) => reset.at)),
65 );
66 const fresh = Number.isFinite(expiresAt) && expiresAt > now;
67 const sortedWindows = [...pool.windows].sort(
68 (a, b) => a.remainingPercent - b.remainingPercent,
69 );
70 // Keep a session and weekly limit when scoped limits fill the storage budget.
71 const selectedWindows = [
72 ...new Set([
73 sortedWindows.find((window) => window.kind === "session"),
74 sortedWindows.find((window) => window.kind === "weekly"),
75 ...sortedWindows,
76 ]),
77 ]
78 .filter((window) => window !== undefined)
79 .slice(0, 6)
80 .sort((a, b) => a.remainingPercent - b.remainingPercent);
81 return {
82 name,
83 detail: !fresh
84 ? "Open T3 to refresh"
85 : pool.accounts.length > 1
86 ? `${pool.accounts.length} accounts · pooled`
87 : "Subscription remaining",
88 expiresAt: fresh ? expiresAt : 0,
89 totalWindows: fresh ? pool.windows.length : 0,
90 windows: fresh
91 ? selectedWindows.map((window) => ({
92 kind: window.kind,
93 label: window.label,
94 remaining: Math.round(window.remainingPercent),
95 reset: window.resets[0]
96 ? `Next reset ${new Date(window.resets[0].at).toLocaleString(undefined, {
97 month: "short",
98 day: "numeric",
99 hour: "numeric",
100 minute: "2-digit",
101 })}`
102 : "Reset time unavailable",
103 }))
104 : [],
105 };
106 }),
107 };
108}
109
110/** Deduplicate accounts before pooling, and only publish display data to the OS. */
111export function buildSubscriptionUsageSnapshot(
112 presentations: LimitPresentations,
113 url: string,
114): SubscriptionUsageSnapshot {
115 // Freshness is evaluated at publication/render time, not on unrelated config emissions.
116 return { ...subscriptionUsageProps(collectLimitAccounts(presentations), 0), url };
117}
118
119export function subscriptionUsageTimeline(snapshot: SubscriptionUsageSnapshot, now: number) {
120 const deadlines = [...new Set(snapshot.providers.map((p) => p.expiresAt))]
121 .filter((deadline) => deadline > now)
122 .sort((a, b) => a - b);
123 return [now, ...deadlines].map((date) => ({
124 date: new Date(date),
125 props: {
126 ...snapshot,
127 providers: snapshot.providers.map((provider) =>
128 provider.windows.length > 0 && provider.expiresAt <= date
129 ? { ...provider, detail: "Open T3 to refresh", windows: [], totalWindows: 0 }
130 : provider,
131 ),
132 },
133 }));
134}