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 (
111 (source.kind === "http" ? (source.quotaAccounts?.length ?? 0) : source.accounts.length) ===
112 0
113 ) {
114 notices.add(
115 resolve(
116 msg("{source}: No accounts reported.", {
117 source: label(environmentLabel, source.label),
118 }),
119 ),
120 );
121 }
122 for (const account of source.accounts) {
123 const name = failedAccounts.get(account);
124 if (name === undefined) continue;
125 const notice = limitsNotice(account.usageLimits, resolve);
126 notices.add(`${label(environmentLabel, source.label)} · ${name}: ${notice}`);
127 }
128 }
129 }
130 return [...notices];
131}
132
133/** @public */
134export function formatDuration(ms: number, resolve: MFunctionType = mFallback): string {
135 const remaining = Math.max(0, ms);
136 const days = Math.floor(remaining / DAY);
137 const hours = Math.floor((remaining % DAY) / HOUR);
138 const minutes = Math.floor((remaining % HOUR) / MINUTE);
139 if (days > 0) return resolve(msg("{days}d {hours}h", { days, hours }));
140 if (hours > 0) return resolve(msg("{hours}h {minutes}m", { hours, minutes }));
141 return resolve(msg("{minutes}m", { minutes }));
142}
143
144/** @public */
145export function resetCreditChoices(
146 credits: ServerProviderResetCredits,
147 input: ProviderConsumeResetCreditInput,
148 now: number,
149 compact = false,
150 resolve: MFunctionType = mFallback,
151): ReadonlyArray<ResetCreditChoice> {
152 const expiresIn = (at: string | undefined) =>
153 at ? formatDuration(Date.parse(at) - now, resolve) : null;
154 if (credits.options && "instanceId" in input) {
155 return credits.options.map((option) => {
156 const expires = expiresIn(option.expiresAt);
157 const values = { label: option.label, count: option.availableCount };
158 return {
159 key: option.creditId,
160 summary: expires
161 ? resolve(msg("{label} · {count} left · expires in {expires}", { ...values, expires }))
162 : resolve(msg("{label} · {count} left", values)),
163 actionLabel: resolve(msg("Use", { $context: "button that redeems a reset credit" })),
164 confirmDescription: resolve(
165 msg("{label}: {description} This cannot be undone.", {
166 label: option.label,
167 description: option.description,
168 }),
169 ),
170 availableCount: option.availableCount,
171 input: { ...input, creditId: option.creditId },
172 };
173 });
174 }
175 const count = credits.availableCount;
176 const expires = expiresIn(credits.nextExpiresAt);
177 return [
178 {
179 key: "next",
180 summary:
181 count === 0
182 ? resolve(msg("No reset credits banked"))
183 : compact
184 ? expires
185 ? resolve(msg("{count} banked · expires in {expires}", { count, expires }))
186 : resolve(msg("{count} banked", { count }))
187 : expires
188 ? resolve(
189 msg(
190 "{count, plural, one {{count} reset credit banked · next expires in {expires}} other {{count} reset credits banked · next expires in {expires}}}",
191 { count, expires },
192 ),
193 )
194 : resolve(
195 msg(
196 "{count, plural, one {{count} reset credit banked} other {{count} reset credits banked}}",
197 { count },
198 ),
199 ),
200 actionLabel: resolve(msg("Use reset")),
201 confirmDescription: resolve(
202 msg(
203 "This redeems one credit on your account and clears the current rate-limit windows. It cannot be undone.",
204 ),
205 ),
206 availableCount: count,
207 input,
208 },
209 ];
210}
211
212/**
213 * `full` reads "resets in 2h 5m", `in` reads "in 2h 5m", `refill` reads "↻ 2h 5m".
214 * @public
215 */
216export function formatResetsIn(
217 window: ServerProviderUsageWindow,
218 now: number,
219 resolve: MFunctionType = mFallback,
220 style: "full" | "in" | "refill" = "full",
221): string | null {
222 const countdown = resetCountdown(window, now);
223 if (countdown === null) return null;
224 if (countdown.kind === "now") return resolve(msg("resets now"));
225 if (countdown.kind === "momentarily") return resolve(msg("Resets momentarily"));
226 const duration = formatDuration(countdown.ms, resolve);
227 if (style === "in") {
228 return resolve(
229 msg("in {duration}", { duration, $context: "time until a usage window resets" }),
230 );
231 }
232 if (style === "refill") return resolve(msg("↻ {duration}", { duration }));
233 return resolve(msg("resets in {duration}", { duration }));
234}