The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 00:45 UTC
feat(claude): Fable resets are offered and redeemed apart from weekly resets (#34106)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 10, 2026 at 15:47 UTC
9e1f81c78894270c7e281c78402a69a1a97c4474
11 files changed
+285
-135
apps/mobile/src/features/usage/UsageLimitsSection.tsx
+38
-47
@@ -11,7 +11,8 @@ import {
11
type ServerProviderUsageWindow,
12
} from "@t3tools/contracts";
13
import {
14
- formatDuration,
14
+ type ResetCreditChoice,
15
+ resetCreditChoices,
16
formatResetsIn,
17
limitsNotice,
18
paceOf,
@@ -243,21 +244,11 @@ export function ResetCredits(props: {
244
const [status, setStatus] = useState<string | null>(null);
245
if (dense && credits.availableCount === 0 && status === null) return null;
246
246
- const expiresIn = credits.nextExpiresAt
247
- ? formatDuration(Date.parse(credits.nextExpiresAt) - now)
248
- : null;
249
- const summary =
250
- credits.availableCount === 0
251
- ? "No reset credits banked"
252
- : `${credits.availableCount} ${credits.availableCount === 1 ? "reset credit" : "reset credits"} banked${
253
- expiresIn ? ` · next expires in ${expiresIn}` : ""
254
- }`;
255
-
256
- const redeem = async () => {
247
+ const redeem = async (choice: ResetCreditChoice) => {
248
if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
249
setBusy(true);
250
setStatus(null);
260
- const result = await consume({ environmentId, input });
251
+ const result = await consume({ environmentId, input: choice.input });
252
setBusy(false);
253
if (result._tag === "Success") {
254
setStatus(result.value.warning ?? OUTCOME_TEXT[result.value.outcome]);
@@ -270,44 +261,44 @@ export function ResetCredits(props: {
261
);
262
};
263
273
- const confirm = () => {
264
+ const confirm = (choice: ResetCreditChoice) => {
265
if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
275
- Dialog.alert(
276
- "Use a reset credit?",
277
- "This redeems one credit on your account and clears the current rate-limit windows. It cannot be undone.",
278
- [
279
- { text: "Cancel", style: "cancel" },
280
- { text: "Use credit", onPress: () => void redeem() },
281
- ],
282
- );
266
+ Dialog.alert("Use a reset credit?", choice.confirmDescription, [
267
+ { text: "Cancel", style: "cancel" },
268
+ { text: "Use credit", onPress: () => void redeem(choice) },
269
+ ]);
270
};
271
272
return (
286
- <View className="flex-row flex-wrap items-center gap-x-3 gap-y-1">
287
- <Text className="text-xs tabular-nums text-foreground-tertiary">{summary}</Text>
288
- {credits.availableCount > 0 ? (
289
- <Pressable
290
- accessibilityRole="button"
291
- accessibilityState={{ disabled: busy || !canManageProviders }}
292
- disabled={busy || !canManageProviders}
293
- onPress={confirm}
294
- className={
295
- dense
296
- ? "rounded-full bg-subtle-strong px-2.5 py-1 disabled:opacity-[0.45]"
297
- : "min-h-[44px] justify-center rounded-full bg-subtle-strong px-3 py-1.5 disabled:opacity-[0.45]"
298
- }
299
- >
300
- <Text
301
- className={
302
- dense
303
- ? "text-xs font-t3-medium text-foreground"
304
- : "text-sm font-t3-medium text-foreground"
305
- }
306
- >
307
- {busy ? "Using…" : "Use reset"}
308
- </Text>
309
- </Pressable>
310
- ) : null}
273
+ <View className="gap-1">
274
+ {resetCreditChoices(credits, input, now).map((choice) => (
275
+ <View key={choice.key} className="flex-row flex-wrap items-center gap-x-3 gap-y-1">
276
+ <Text className="text-xs tabular-nums text-foreground-tertiary">{choice.summary}</Text>
277
+ {choice.availableCount > 0 ? (
278
+ <Pressable
279
+ accessibilityRole="button"
280
+ accessibilityState={{ disabled: busy || !canManageProviders }}
281
+ disabled={busy || !canManageProviders}
282
+ onPress={() => confirm(choice)}
283
+ className={
284
+ dense
285
+ ? "rounded-full bg-subtle-strong px-2.5 py-1 disabled:opacity-[0.45]"
286
+ : "min-h-[44px] justify-center rounded-full bg-subtle-strong px-3 py-1.5 disabled:opacity-[0.45]"
287
+ }
288
+ >
289
+ <Text
290
+ className={
291
+ dense
292
+ ? "text-xs font-t3-medium text-foreground"
293
+ : "text-sm font-t3-medium text-foreground"
294
+ }
295
+ >
296
+ {busy ? "Using…" : choice.actionLabel}
297
+ </Text>
298
+ </Pressable>
299
+ ) : null}
300
+ </View>
301
+ ))}
302
{!canManageProviders ? (
303
<Text className="text-xs text-foreground-tertiary">
304
This connection cannot manage provider accounts.
apps/server/src/provider/Drivers/ClaudeDriver.ts
+8
-2
@@ -309,9 +309,15 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.
309
const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = Effect.fn(
310
"ClaudeDriver.consumeResetCredit",
311
)(
312
- function* () {
312
+ function* (creditId) {
313
const current = yield* snapshot.getSnapshot;
314
- const grantId = current.usageLimits?.resetCredits?.nextCreditId;
314
+ const credits = current.usageLimits?.resetCredits;
315
+ const grantId =
316
+ creditId === undefined
317
+ ? credits?.nextCreditId
318
+ : credits?.options?.some((option) => option.creditId === creditId)
319
+ ? creditId
320
+ : undefined;
321
if (!grantId || !current.version) return "noCredit" as const;
322
const version = current.version;
323
return yield* resetCreditCoordinator.redeem(
apps/server/src/provider/ProviderInstanceRegistry.test.ts
+1
-1
@@ -664,7 +664,7 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
664
const before = yield* instance!.snapshot.refresh;
665
expect(before.usageLimits?.windows[0]?.usedPercent).toBe(100);
666
expect(before.usageLimits?.resetCredits?.nextCreditId).toBe("grant_a");
667
- const outcome = yield* instance!.consumeResetCredit!().pipe(Effect.result);
667
+ const outcome = yield* instance!.consumeResetCredit!(undefined).pipe(Effect.result);
668
return { outcome, after: yield* instance!.snapshot.getSnapshot };
669
}).pipe(
670
// macOS logins live in the Keychain, where resets are never read.
apps/server/src/provider/claudeResetCredits.test.ts
+43
-1
@@ -62,9 +62,51 @@ describe("claudeResetCreditsToContract", () => {
62
availableCount: 2,
63
nextCreditId: "grant_a",
64
nextExpiresAt: "2026-10-01T00:00:00.000Z",
65
+ options: [
66
+ expect.objectContaining({
67
+ creditId: "grant_a",
68
+ label: "Full reset",
69
+ availableCount: 2,
70
+ expiresAt: "2026-10-01T00:00:00.000Z",
71
+ }),
72
+ ],
73
});
74
});
75
76
+ it("offers each kind of reset by its own grant", () => {
77
+ const credits = ClaudeResetCredits.claudeResetCreditsToContract(
78
+ {
79
+ eligible: true,
80
+ next_grant_id: "weekly_a",
81
+ grants: [
82
+ grant({ id: "weekly_a", clears: ["seven_day"], ends_at: "2026-12-10T22:00:00Z" }),
83
+ grant({
84
+ id: "fable_a",
85
+ clears: ["seven_day_overage_included"],
86
+ gives_back_weekly: true,
87
+ ends_at: "2027-03-09T07:59:00Z",
88
+ }),
89
+ grant({ id: "fable_b", gives_back_weekly: true, type: "weekly" }),
90
+ grant({ id: "session_a", type: "session" }),
91
+ grant({ id: "spent", clears: ["seven_day"], resets_left: 0 }),
92
+ ],
93
+ },
94
+ NOW,
95
+ );
96
+ expect(
97
+ credits?.options?.map(({ creditId, label, availableCount }) => [
98
+ creditId,
99
+ label,
100
+ availableCount,
101
+ ]),
102
+ ).toEqual([
103
+ ["session_a", "5-hour reset", 1],
104
+ ["weekly_a", "Weekly reset", 1],
105
+ ["fable_a", "Fable reset", 2],
106
+ ]);
107
+ expect(credits).toMatchObject({ availableCount: 4, nextCreditId: "weekly_a" });
108
+ });
109
+
110
it("offers nothing to redeem without a usable next grant or an eligible account", () => {
111
expect(
112
ClaudeResetCredits.claudeResetCreditsToContract(
@@ -111,7 +153,7 @@ effectIt.layer(NodeServices.layer)("readClaudeResetCredits", (it) => {
153
Effect.provideService(HostProcess.Platform, "linux"),
154
Effect.provideService(HttpClient.HttpClient, client),
155
);
114
- expect(credits).toEqual({ availableCount: 1, nextCreditId: "grant_a" });
156
+ expect(credits).toMatchObject({ availableCount: 1, nextCreditId: "grant_a" });
157
}),
158
);
159
apps/server/src/provider/claudeResetCredits.ts
+58
-4
@@ -1,5 +1,6 @@
1
import type {
2
ProviderConsumeResetCreditOutcome,
3
+ ServerProviderResetCreditOption,
4
ServerProviderResetCredits,
5
} from "@t3tools/contracts";
6
import * as HostProcess from "@t3tools/shared/HostProcess";
@@ -31,6 +32,9 @@ const Grant = Schema.Struct({
32
ends_at: Schema.optional(Schema.NullOr(Schema.String)),
33
paused: Schema.optional(Schema.Boolean),
34
usable_now: Schema.optional(Schema.Boolean),
35
+ clears: Schema.optional(Schema.Array(Schema.Unknown)),
36
+ type: Schema.optional(Schema.Unknown),
37
+ gives_back_weekly: Schema.optional(Schema.Boolean),
38
});
39
const decodeGrant = Schema.decodeUnknownOption(Grant);
40
const CedarEmber = Schema.Struct({
@@ -95,6 +99,31 @@ const isFutureTimestamp = (value: string, nowMs: number) => {
99
);
100
};
101
102
+// Claude Code's own grouping: a grant that gives back weekly usage is a Fable reset, else its
103
+// declared type, else what it clears.
104
+const RESET_KINDS = {
105
+ session: { label: "5-hour reset", description: "Refills your 5-hour limit." },
106
+ weekly: { label: "Weekly reset", description: "Refills your weekly limit." },
107
+ fable: {
108
+ label: "Fable reset",
109
+ description:
110
+ "Refills your Fable allowance and gives back what Fable used on your weekly limit. It doesn't reset your whole week.",
111
+ },
112
+ full: { label: "Full reset", description: "Refills your 5-hour and weekly limits." },
113
+} as const;
114
+type ResetKind = keyof typeof RESET_KINDS;
115
+
116
+const grantKind = (grant: typeof Grant.Type): ResetKind => {
117
+ if (grant.gives_back_weekly) return "fable";
118
+ if (grant.type === "session" || grant.type === "weekly" || grant.type === "full") {
119
+ return grant.type;
120
+ }
121
+ const clears = grant.clears ?? [];
122
+ const session = clears.includes("five_hour");
123
+ const other = clears.some((limit) => limit !== "five_hour");
124
+ return session && !other ? "session" : other && !session ? "weekly" : "full";
125
+};
126
+
127
export function claudeResetCreditsToContract(
128
block: unknown,
129
nowMs: number,
@@ -110,13 +139,38 @@ export function claudeResetCreditsToContract(
139
(grant.ends_at == null || isFutureTimestamp(grant.ends_at, nowMs)),
140
);
141
const next = live.find((grant) => grant.id === parsed.value.next_grant_id);
113
- const nextExpiresAt = next?.ends_at ? DateTime.make(next.ends_at) : Option.none();
142
+ const expiresAt = (grant: typeof Grant.Type | undefined) => {
143
+ const at = grant?.ends_at ? DateTime.make(grant.ends_at) : Option.none();
144
+ return Option.isSome(at) ? DateTime.formatIso(at.value) : undefined;
145
+ };
146
+ const byKind = new Map<ResetKind, Array<typeof Grant.Type>>();
147
+ for (const grant of live) {
148
+ if (grant.resets_left === 0) continue;
149
+ const kind = grantKind(grant);
150
+ byKind.set(kind, [...(byKind.get(kind) ?? []), grant]);
151
+ }
152
+ const options = (Object.keys(RESET_KINDS) as Array<ResetKind>).flatMap(
153
+ (kind): Array<ServerProviderResetCreditOption> => {
154
+ const grants = byKind.get(kind);
155
+ const target = grants?.[0];
156
+ if (!grants || !target) return [];
157
+ const optionExpiresAt = expiresAt(target);
158
+ return [
159
+ {
160
+ creditId: target.id,
161
+ ...RESET_KINDS[kind],
162
+ availableCount: grants.reduce((sum, grant) => sum + grant.resets_left, 0),
163
+ ...(optionExpiresAt ? { expiresAt: optionExpiresAt } : {}),
164
+ },
165
+ ];
166
+ },
167
+ );
168
+ const nextExpiresAt = expiresAt(next);
169
return {
170
availableCount: next ? live.reduce((sum, grant) => sum + grant.resets_left, 0) : 0,
116
- ...(Option.isSome(nextExpiresAt)
117
- ? { nextExpiresAt: DateTime.formatIso(nextExpiresAt.value) }
118
- : {}),
171
+ ...(nextExpiresAt ? { nextExpiresAt } : {}),
172
...(next ? { nextCreditId: next.id } : {}),
173
+ ...(next ? { options } : {}),
174
};
175
}
176
apps/server/src/ws.ts
+1
-1
@@ -2649,7 +2649,7 @@ export const layerWsRpc = (
2649
detail: "This provider does not bank reset credits.",
2650
});
2651
}
2652
- const outcome = yield* instance.consumeResetCredit().pipe(
2652
+ const outcome = yield* instance.consumeResetCredit(input.creditId).pipe(
2653
Effect.mapError(
2654
(error) =>
2655
new ProviderSetupError({
apps/web/src/components/usage/UsageLimits.tsx
+36
-46
@@ -11,12 +11,13 @@ import {
11
import { useAtomValue } from "@effect/atom-react";
12
import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display";
13
import {
14
- formatDuration,
14
formatResetsIn,
15
type LimitPace,
16
paceOf,
17
paceRemainingPercent,
18
remainingPercent,
19
+ type ResetCreditChoice,
20
+ resetCreditChoices,
21
} from "@t3tools/shared/usageLimits";
22
import { GaugeIcon, TrendingDownIcon, TrendingUpIcon } from "lucide-react";
23
import { Fragment, useLayoutEffect, useState } from "react";
@@ -237,22 +238,21 @@ const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {
238
alreadyRedeemed: "That credit was already redeemed.",
239
};
240
240
-export function useResetCredit(
241
- environmentId: EnvironmentId,
242
- input: ProviderConsumeResetCreditInput,
243
-) {
241
+export function useResetCredit(environmentId: EnvironmentId) {
242
const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
243
const consume = useAtomCommand(serverEnvironment.consumeResetCredit, { reportFailure: false });
244
+ // Kept after close so the dialog's text survives its exit animation.
245
+ const [choice, setChoice] = useState<ResetCreditChoice | null>(null);
246
const [confirming, setConfirming] = useState(false);
247
const [busy, setBusy] = useState(false);
248
const [status, setStatus] = useState<string | null>(null);
249
250
const redeem = async () => {
251
setConfirming(false);
252
- if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
252
+ if (!choice || !readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
253
setBusy(true);
254
setStatus(null);
255
- const result = await consume({ environmentId, input });
255
+ const result = await consume({ environmentId, input: choice.input });
256
setBusy(false);
257
if (result._tag === "Success") {
258
setStatus(result.value.warning ?? OUTCOME_TEXT[result.value.outcome]);
@@ -265,7 +265,13 @@ export function useResetCredit(
265
);
266
};
267
268
- return { canManageProviders, confirming, setConfirming, busy, status, redeem };
268
+ const confirm = (next: ResetCreditChoice) => {
269
+ if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
270
+ setChoice(next);
271
+ setConfirming(true);
272
+ };
273
+
274
+ return { canManageProviders, choice, confirming, setConfirming, confirm, busy, status, redeem };
275
}
276
277
/** Require confirmation because redemption spends credits. Mount outside popovers, which stack above
@@ -273,11 +279,13 @@ export function useResetCredit(
279
export function ResetCreditDialog({
280
open,
281
onOpenChange,
282
+ choice,
283
onConfirm,
284
disabled = false,
285
}: {
286
readonly open: boolean;
287
readonly onOpenChange: (open: boolean) => void;
288
+ readonly choice: ResetCreditChoice | null;
289
readonly onConfirm: () => void;
290
readonly disabled?: boolean;
291
}) {
@@ -286,10 +294,7 @@ export function ResetCreditDialog({
294
<AlertDialogPopup>
295
<AlertDialogHeader>
296
<AlertDialogTitle>Use a reset credit?</AlertDialogTitle>
289
- <AlertDialogDescription>
290
- This redeems one credit on your account and clears the current rate-limit windows. It
291
- cannot be undone.
292
- </AlertDialogDescription>
297
+ <AlertDialogDescription>{choice?.confirmDescription}</AlertDialogDescription>
298
</AlertDialogHeader>
299
<AlertDialogFooter>
300
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
@@ -302,22 +307,6 @@ export function ResetCreditDialog({
307
);
308
}
309
305
-export function resetCreditsSummary(
306
- credits: ServerProviderResetCredits,
307
- now: number,
308
- compact = false,
309
-): string {
310
- const expiresIn = credits.nextExpiresAt
311
- ? formatDuration(Date.parse(credits.nextExpiresAt) - now)
312
- : null;
313
- if (credits.availableCount === 0) return "No reset credits banked";
314
- if (compact)
315
- return `${credits.availableCount} banked${expiresIn ? ` · expires in ${expiresIn}` : ""}`;
316
- return `${credits.availableCount} ${credits.availableCount === 1 ? "reset credit" : "reset credits"} banked${
317
- expiresIn ? ` · next expires in ${expiresIn}` : ""
318
- }`;
319
-}
320
-
310
export function ResetCredits({
311
environmentId,
312
input,
@@ -329,30 +318,31 @@ export function ResetCredits({
318
readonly credits: ServerProviderResetCredits;
319
readonly now: number;
320
}) {
332
- const { canManageProviders, confirming, setConfirming, busy, status, redeem } = useResetCredit(
333
- environmentId,
334
- input,
335
- );
321
+ const { canManageProviders, choice, confirming, setConfirming, confirm, busy, status, redeem } =
322
+ useResetCredit(environmentId);
323
if (credits.availableCount === 0 && status === null) return null;
324
return (
338
- <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
339
- <span className="tabular-nums">{resetCreditsSummary(credits, now)}</span>
340
- {credits.availableCount > 0 ? (
341
- <Button
342
- size="xs"
343
- variant="outline"
344
- disabled={busy || !canManageProviders}
345
- onClick={() => {
346
- if (readEnvironmentScope(environmentId, AuthProvidersManageScope)) setConfirming(true);
347
- }}
348
- >
349
- {busy ? "Using…" : "Use reset"}
350
- </Button>
351
- ) : null}
325
+ <div className="flex flex-col gap-1 text-xs text-muted-foreground">
326
+ {resetCreditChoices(credits, input, now).map((choice) => (
327
+ <div key={choice.key} className="flex flex-wrap items-center gap-x-3 gap-y-1">
328
+ <span className="tabular-nums">{choice.summary}</span>
329
+ {choice.availableCount > 0 ? (
330
+ <Button
331
+ size="xs"
332
+ variant="outline"
333
+ disabled={busy || !canManageProviders}
334
+ onClick={() => confirm(choice)}
335
+ >
336
+ {busy ? "Using…" : choice.actionLabel}
337
+ </Button>
338
+ ) : null}
339
+ </div>
340
+ ))}
341
{status ? <span className="text-foreground">{status}</span> : null}
342
<ResetCreditDialog
343
open={confirming}
344
onOpenChange={setConfirming}
345
+ choice={choice}
346
onConfirm={() => void redeem()}
347
disabled={!canManageProviders}
348
/>
apps/web/src/components/usage/UsageLimitsPooled.tsx
+30
-28
@@ -13,6 +13,8 @@ import {
13
type LimitPoolWindow,
14
paceRemainingPercent,
15
remainingPercent,
16
+ type ResetCreditChoice,
17
+ resetCreditChoices,
18
} from "@t3tools/shared/usageLimits";
19
import type { Popover as PopoverPrimitive } from "@base-ui/react/popover";
20
import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display";
@@ -39,14 +41,7 @@ import { Button } from "../ui/button";
41
import { OpenAI } from "../Icons";
42
import { Alert, AlertTitle } from "../ui/alert";
43
import { Popover, PopoverCreateHandle, PopoverPopup, PopoverTrigger } from "../ui/popover";
42
-import {
43
- PaceIcon,
44
- ResetCreditDialog,
45
- barColor,
46
- usePaceMark,
47
- resetCreditsSummary,
48
- useResetCredit,
49
-} from "./UsageLimits";
44
+import { PaceIcon, ResetCreditDialog, barColor, usePaceMark, useResetCredit } from "./UsageLimits";
45
46
function accountInitials(email: string): string {
47
const [local = "", domain = ""] = email.split("@");
@@ -146,7 +141,7 @@ function SegmentPopover({
141
readonly reset: LimitPoolWindow["resets"][number] | undefined;
142
readonly now: number;
143
readonly redeem: ReturnType<typeof useResetCredit> | null;
149
- readonly onRedeem: () => void;
144
+ readonly onRedeem: (choice: ResetCreditChoice) => void;
145
}) {
146
const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat);
147
const remaining = remainingPercent(window);
@@ -156,8 +151,10 @@ function SegmentPopover({
151
account.environments.length > 0
152
? account.environments.map((environment) => environment.label).join(", ")
153
: account.sourceLabel;
159
- const credits =
160
- redeem && account.limits.resetCredits?.availableCount ? account.limits.resetCredits : null;
154
+ const choices =
155
+ redeem && account.redeem && account.limits.resetCredits?.availableCount
156
+ ? resetCreditChoices(account.limits.resetCredits, account.redeem.input, now, true)
157
+ : [];
158
return (
159
<div className="flex w-72 max-w-[calc(100vw-3rem)] flex-col gap-2.5 text-xs">
160
<div className="flex min-w-0 flex-col gap-0.5">
@@ -196,20 +193,24 @@ function SegmentPopover({
193
<Row label="Restores">+{reset.restoresPercent}% of pool</Row>
194
) : null}
195
</div>
199
- {credits && redeem ? (
200
- <div className="border-t border-border/60 pt-2.5 text-muted-foreground">
201
- <span className="flex items-center gap-3">
202
- <span className="tabular-nums">{resetCreditsSummary(credits, now, true)}</span>
203
- <Button
204
- size="xs"
205
- variant="outline"
206
- disabled={redeem.busy || !redeem.canManageProviders}
207
- className="ms-auto"
208
- onClick={onRedeem}
209
- >
210
- {redeem.busy ? "Using…" : "Use reset"}
211
- </Button>
212
- </span>
196
+ {choices.length > 0 && redeem ? (
197
+ <div className="flex flex-col gap-1.5 border-t border-border/60 pt-2.5 text-muted-foreground">
198
+ {choices.map((choice) => (
199
+ <span key={choice.key} className="flex items-center gap-3">
200
+ <span className="tabular-nums">{choice.summary}</span>
201
+ {choice.availableCount > 0 ? (
202
+ <Button
203
+ size="xs"
204
+ variant="outline"
205
+ disabled={redeem.busy || !redeem.canManageProviders}
206
+ className="ms-auto"
207
+ onClick={() => onRedeem(choice)}
208
+ >
209
+ {redeem.busy ? "Using…" : choice.actionLabel}
210
+ </Button>
211
+ ) : null}
212
+ </span>
213
+ ))}
214
</div>
215
) : null}
216
</div>
@@ -264,9 +265,9 @@ function ActiveSegmentPopover({
265
<SegmentPopover
266
{...payload}
267
now={now}
267
- onRedeem={() => {
268
+ onRedeem={(choice) => {
269
handle.close();
269
- payload.redeem?.setConfirming(true);
270
+ payload.redeem?.confirm(choice);
271
}}
272
/>
273
</PopoverPopup>
@@ -303,13 +304,14 @@ function RedeemableSegment({
304
}: Omit<Parameters<typeof SegmentTriggers>[0], "redeem"> & {
305
readonly redeemAt: NonNullable<LimitAccount["redeem"]>;
306
}) {
306
- const redeem = useResetCredit(redeemAt.environmentId, redeemAt.input);
307
+ const redeem = useResetCredit(redeemAt.environmentId);
308
return (
309
<>
310
<SegmentTriggers redeem={redeem} {...props} />
311
<ResetCreditDialog
312
open={redeem.confirming}
313
onOpenChange={redeem.setConfirming}
314
+ choice={redeem.choice}
315
onConfirm={() => void redeem.redeem()}
316
disabled={!redeem.canManageProviders}
317
/>
packages/contracts/src/providerUsageLimits.ts
+16
-1
@@ -20,11 +20,23 @@ export const ServerProviderUsageWindow = Schema.Struct({
20
});
21
export type ServerProviderUsageWindow = typeof ServerProviderUsageWindow.Type;
22
23
+/** One kind of banked reset, such as Claude's weekly reset or its Fable-only reset. */
24
+export const ServerProviderResetCreditOption = Schema.Struct({
25
+ creditId: TrimmedNonEmptyString,
26
+ label: TrimmedNonEmptyString,
27
+ description: TrimmedNonEmptyString,
28
+ availableCount: NonNegativeInt,
29
+ expiresAt: Schema.optional(IsoDateTime),
30
+});
31
+export type ServerProviderResetCreditOption = typeof ServerProviderResetCreditOption.Type;
32
+
33
export const ServerProviderResetCredits = Schema.Struct({
34
availableCount: NonNegativeInt,
35
nextExpiresAt: Schema.optional(IsoDateTime),
36
/** Pins hub redemption to the displayed credit, including retries from another client. */
37
nextCreditId: Schema.optional(TrimmedNonEmptyString),
38
+ /** Present when resets differ in what they refill; redeem one by its `creditId`. */
39
+ options: Schema.optional(ForwardCompatibleArray(ServerProviderResetCreditOption)),
40
});
41
export type ServerProviderResetCredits = typeof ServerProviderResetCredits.Type;
42
@@ -87,7 +99,10 @@ export type UsageLimitSourceConsumeResetCreditInput =
99
typeof UsageLimitSourceConsumeResetCreditInput.Type;
100
101
export const ProviderConsumeResetCreditInput = Schema.Union([
90
- Schema.Struct({ instanceId: ProviderInstanceId }),
102
+ Schema.Struct({
103
+ instanceId: ProviderInstanceId,
104
+ creditId: Schema.optional(TrimmedNonEmptyString),
105
+ }),
106
UsageLimitSourceConsumeResetCreditInput,
107
]);
108
export type ProviderConsumeResetCreditInput = typeof ProviderConsumeResetCreditInput.Type;
packages/provider-core/src/server/driver.ts
+3
-4
@@ -45,10 +45,9 @@ export interface ProviderInstance {
45
) => Effect.Effect<ProviderWorkspaceSnapshot, ProviderDriverError>;
46
readonly refreshModels?: () => Effect.Effect<void, ProviderDriverError>;
47
readonly invalidateCaches?: Effect.Effect<void>;
48
- readonly consumeResetCredit?: () => Effect.Effect<
49
- ProviderConsumeResetCreditOutcome,
50
- ProviderDriverError
51
- >;
48
+ readonly consumeResetCredit?: (
49
+ creditId: string | undefined,
50
+ ) => Effect.Effect<ProviderConsumeResetCreditOutcome, ProviderDriverError>;
51
readonly orchestrationAdapter: ProviderAdapter.ProviderAdapterV2["Service"];
52
readonly textGeneration: ProviderTextGeneration;
53
readonly auth?: ProviderAuthController;
packages/shared/src/usageLimits.ts
+51
@@ -11,6 +11,7 @@ import {
11
isProviderAvailable,
12
PROVIDER_DISPLAY_NAMES,
13
type ServerProvider,
14
+ type ServerProviderResetCredits,
15
type ServerProviderUsageLimits,
16
type ServerProviderUsageWindow,
17
type UsageLimitSourceSnapshots,
@@ -675,6 +676,56 @@ export function formatDuration(ms: number): string {
676
return `${minutes}m`;
677
}
678
679
+/** One redeemable reset as clients offer it; `input` already names the chosen credit. */
680
+export interface ResetCreditChoice {
681
+ readonly key: string;
682
+ readonly summary: string;
683
+ readonly actionLabel: string;
684
+ readonly confirmDescription: string;
685
+ readonly availableCount: number;
686
+ readonly input: ProviderConsumeResetCreditInput;
687
+}
688
+
689
+export function resetCreditChoices(
690
+ credits: ServerProviderResetCredits,
691
+ input: ProviderConsumeResetCreditInput,
692
+ now: number,
693
+ compact = false,
694
+): ReadonlyArray<ResetCreditChoice> {
695
+ const expiresIn = (at: string | undefined) => (at ? formatDuration(Date.parse(at) - now) : null);
696
+ if (credits.options && "instanceId" in input) {
697
+ return credits.options.map((option) => {
698
+ const expires = expiresIn(option.expiresAt);
699
+ return {
700
+ key: option.creditId,
701
+ summary: `${option.label} · ${option.availableCount} left${expires ? ` · expires in ${expires}` : ""}`,
702
+ actionLabel: "Use",
703
+ confirmDescription: `${option.label}: ${option.description} This cannot be undone.`,
704
+ availableCount: option.availableCount,
705
+ input: { ...input, creditId: option.creditId },
706
+ };
707
+ });
708
+ }
709
+ const count = credits.availableCount;
710
+ const expires = expiresIn(credits.nextExpiresAt);
711
+ return [
712
+ {
713
+ key: "next",
714
+ summary:
715
+ count === 0
716
+ ? "No reset credits banked"
717
+ : compact
718
+ ? `${count} banked${expires ? ` · expires in ${expires}` : ""}`
719
+ : `${count} ${count === 1 ? "reset credit" : "reset credits"} banked${expires ? ` · next expires in ${expires}` : ""}`,
720
+ actionLabel: "Use reset",
721
+ confirmDescription:
722
+ "This redeems one credit on your account and clears the current rate-limit windows. It cannot be undone.",
723
+ availableCount: count,
724
+ input,
725
+ },
726
+ ];
727
+}
728
+
729
export function formatResetsIn(window: ServerProviderUsageWindow, now: number): string | null {
730
const resetsAt = resetMillis(window);
731
if (resetsAt === null) return null;