Open History to see the last commit
1import type {
2 ProviderConsumeResetCreditInput,
3 ServerProviderResetCredits,
4 ServerProviderUsageLimits,
5 ServerProviderUsageWindow,
6} from "@t3tools/contracts";
7import { mFallback, msg } from "gt-i18n";
8import type { MFunctionType } from "gt-i18n/types";
9
10import {
11 collectExternalUsageLinks as collectExternalUsageLinksWith,
12 cursorUsageWindowDetails as cursorUsageWindowDetailsBase,
13 type LimitPool,
14 type LimitPresentations,
15 providersWithLimits,
16 type ResetCreditChoice,
17 resetCountdown,
18 unshownFailedHubAccounts,
19} from "./usageLimits.ts";
20
21const MINUTE = 60_000;
22const HOUR = 60 * MINUTE;
23const DAY = 24 * HOUR;
24
25const CURSOR_USAGE_WINDOW_COPY: Readonly<
26 Record<string, { readonly label: string; readonly description: string }>
27> = {
28 totalPercentUsed: {
29 label: msg("Overall", { $context: "usage limit covering the whole plan" }),
30 description: msg("All usage on your plan this billing cycle."),
31 },
32 autoPercentUsed: {
33 label: msg("Cursor Models"),
34 description: msg("Grok, Composer, and Auto use this allowance."),
35 },
36 apiPercentUsed: {
37 label: msg("Other Models"),
38 description: msg("Usage allowance for third-party models such as Claude, GPT, and Gemini."),
39 },
40};
41
42/** @public */
43export function cursorUsageWindowDetails(
44 id: string,
45 pool: LimitPool,
46 resolve: MFunctionType = mFallback,
47) {
48 const details = cursorUsageWindowDetailsBase(id, pool);
49 const copy = CURSOR_USAGE_WINDOW_COPY[id];
50 if (!details || !copy) return details;
51 return {
52 ...details,
53 label: details.label === null ? null : resolve(copy.label),
54 description: details.description === undefined ? undefined : resolve(copy.description),
55 };
56}
57
58/** @public */
59export function collectExternalUsageLinks(
60 presentations: LimitPresentations,
61 resolve: MFunctionType = mFallback,
62) {
63 return collectExternalUsageLinksWith(presentations, (provider, environment) =>
64 resolve(msg("{provider} on {environment}", { provider, environment })),
65 );
66}
67
68/** @public */
69export function limitsNotice(
70 limits: ServerProviderUsageLimits,
71 resolve: MFunctionType = mFallback,
72): string | null {
73 if (limits.unavailable?.reason === "unsupported") {
74 return limits.unavailable.message ?? resolve(msg("This account has no subscription limits."));
75 }
76 if (limits.unavailable?.reason === "probeFailed") {
77 return limits.unavailable.message ?? resolve(msg("Could not read limits."));
78 }
79 return limits.windows.length === 0 ? resolve(msg("No limits reported.")) : null;
80}
81
82/** @public */
83export function collectLimitNotices(
84 presentations: LimitPresentations,
85 resolve: MFunctionType = mFallback,
86): readonly string[] {
87 const label = (environmentLabel: string, subject: string) =>
88 presentations.size > 1 ? `${environmentLabel} · ${subject}` : subject;
89 const notices = new Set<string>();
90 // A failed hub read needs no notice when another report already shows the account's row.
91 const failedAccounts = unshownFailedHubAccounts(presentations);
92 for (const presentation of presentations.values()) {
93 const environmentLabel = presentation.entry.target.label;
94 for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {
95 const limits = provider.usageLimits;
96 // A bare unsupported means the account has no limits; an external usage link shows its message.
97 if (
98 limits?.unavailable?.reason === "unsupported" &&
99 (!limits.unavailable.message || limits.externalUsage)
100 ) {
101 continue;
102 }
103 const notice = limits ? limitsNotice(limits, resolve) : null;
104 const name = provider.displayName?.trim() || String(provider.driver);
105 if (notice) notices.add(`${label(environmentLabel, name)}: ${notice}`);
106 }
107 for (const source of presentation.serverConfig?.usageLimitSources ?? []) {
108 if (source.error) {
109 notices.add(`${label(environmentLabel, source.label)}: ${source.error}`);
110 } else if (source.accounts.length === 0) {
111 notices.add(
112 resolve(
113 msg("{source}: No accounts reported.", {
114 source: label(environmentLabel, source.label),
115 }),
116 ),
117 );
118 }
119 for (const account of source.accounts) {
120 const name = failedAccounts.get(account);
121 if (name === undefined) continue;
122 const notice = limitsNotice(account.usageLimits, resolve);
123 notices.add(`${label(environmentLabel, source.label)} · ${name}: ${notice}`);
124 }
125 }
126 }
127 return [...notices];
128}
129
130/** @public */
131export function formatDuration(ms: number, resolve: MFunctionType = mFallback): string {
132 const remaining = Math.max(0, ms);
133 const days = Math.floor(remaining / DAY);
134 const hours = Math.floor((remaining % DAY) / HOUR);
135 const minutes = Math.floor((remaining % HOUR) / MINUTE);
136 if (days > 0) return resolve(msg("{days}d {hours}h", { days, hours }));
137 if (hours > 0) return resolve(msg("{hours}h {minutes}m", { hours, minutes }));
138 return resolve(msg("{minutes}m", { minutes }));
139}
140
141/** @public */
142export function resetCreditChoices(
143 credits: ServerProviderResetCredits,
144 input: ProviderConsumeResetCreditInput,
145 now: number,
146 compact = false,
147 resolve: MFunctionType = mFallback,
148): ReadonlyArray<ResetCreditChoice> {
149 const expiresIn = (at: string | undefined) =>
150 at ? formatDuration(Date.parse(at) - now, resolve) : null;
151 if (credits.options && "instanceId" in input) {
152 return credits.options.map((option) => {
153 const expires = expiresIn(option.expiresAt);
154 const values = { label: option.label, count: option.availableCount };
155 return {
156 key: option.creditId,
157 summary: expires
158 ? resolve(msg("{label} · {count} left · expires in {expires}", { ...values, expires }))
159 : resolve(msg("{label} · {count} left", values)),
160 actionLabel: resolve(msg("Use", { $context: "button that redeems a reset credit" })),
161 confirmDescription: resolve(
162 msg("{label}: {description} This cannot be undone.", {
163 label: option.label,
164 description: option.description,
165 }),
166 ),
167 availableCount: option.availableCount,
168 input: { ...input, creditId: option.creditId },
169 };
170 });
171 }
172 const count = credits.availableCount;
173 const expires = expiresIn(credits.nextExpiresAt);
174 return [
175 {
176 key: "next",
177 summary:
178 count === 0
179 ? resolve(msg("No reset credits banked"))
180 : compact
181 ? expires
182 ? resolve(msg("{count} banked · expires in {expires}", { count, expires }))
183 : resolve(msg("{count} banked", { count }))
184 : expires
185 ? resolve(
186 msg(
187 "{count, plural, one {{count} reset credit banked · next expires in {expires}} other {{count} reset credits banked · next expires in {expires}}}",
188 { count, expires },
189 ),
190 )
191 : resolve(
192 msg(
193 "{count, plural, one {{count} reset credit banked} other {{count} reset credits banked}}",
194 { count },
195 ),
196 ),
197 actionLabel: resolve(msg("Use reset")),
198 confirmDescription: resolve(
199 msg(
200 "This redeems one credit on your account and clears the current rate-limit windows. It cannot be undone.",
201 ),
202 ),
203 availableCount: count,
204 input,
205 },
206 ];
207}
208
209/**
210 * `full` reads "resets in 2h 5m", `in` reads "in 2h 5m", `refill` reads "↻ 2h 5m".
211 * @public
212 */
213export function formatResetsIn(
214 window: ServerProviderUsageWindow,
215 now: number,
216 resolve: MFunctionType = mFallback,
217 style: "full" | "in" | "refill" = "full",
218): string | null {
219 const countdown = resetCountdown(window, now);
220 if (countdown === null) return null;
221 if (countdown.kind === "now") return resolve(msg("resets now"));
222 if (countdown.kind === "momentarily") return resolve(msg("Resets momentarily"));
223 const duration = formatDuration(countdown.ms, resolve);
224 if (style === "in") {
225 return resolve(
226 msg("in {duration}", { duration, $context: "time until a usage window resets" }),
227 );
228 }
229 if (style === "refill") return resolve(msg("↻ {duration}", { duration }));
230 return resolve(msg("resets in {duration}", { duration }));
231}