diff --git a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx index 41f350a11cb61..29a66d608752b 100644 --- a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx +++ b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx @@ -4,6 +4,7 @@ import { EnvironmentId } from "@t3tools/contracts"; import { providerClients } from "@t3tools/client-runtime/provider-clients"; import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display"; import { + bankedResetCreditCount, collectLimitAccounts, collectLimitPools, displayLimitWindows, @@ -247,7 +248,7 @@ function PoolWindowCard({ ); const { account, window } = member; const timeLeft = paceRemainingPercent(window, now); - const credits = account.limits.resetCredits?.availableCount ?? 0; + const credits = bankedResetCreditCount(account.limits.resetCredits); const resetsIn = resetLabels(window, now, m)?.compact; return ( { if (!window) return null; const segmentColor = normalizeProviderAccentColor(account.accentColor) ?? color; - const credits = account.limits.resetCredits?.availableCount ?? 0; + const credits = bankedResetCreditCount(account.limits.resetCredits); const reset = resetLabels(window, now, m); const resetsIn = reset?.full; return ( diff --git a/apps/mobile/src/features/usage/UsageLimitsSection.tsx b/apps/mobile/src/features/usage/UsageLimitsSection.tsx index 6721f3c2eac95..eaf527e0717f0 100644 --- a/apps/mobile/src/features/usage/UsageLimitsSection.tsx +++ b/apps/mobile/src/features/usage/UsageLimitsSection.tsx @@ -12,6 +12,7 @@ import { type ServerProviderUsageWindow, } from "@t3tools/contracts"; import { + bankedResetCreditCount, type ResetCreditChoice, paceOf, paceRemainingPercent, @@ -236,8 +237,7 @@ export function AccountLimits(props: { ); } -const OUTCOME_TEXT: Record = { - reset: msg("Reset applied. Your windows have cleared."), +const OUTCOME_TEXT: Record, string> = { nothingToReset: msg("Nothing to reset right now."), noCredit: msg("No reset credit left."), alreadyRedeemed: msg("That credit was already redeemed."), @@ -259,7 +259,7 @@ export function ResetCredits(props: { const [status, setStatus] = useState(null); const gt = useGT(); const m = useMessages(); - if (dense && credits.availableCount === 0 && status === null) return null; + if (dense && bankedResetCreditCount(credits) === 0 && status === null) return null; const redeem = async (choice: ResetCreditChoice) => { if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return; @@ -268,7 +268,13 @@ export function ResetCredits(props: { const result = await consume({ environmentId, input: choice.input }); setBusy(false); if (result._tag === "Success") { - setStatus(result.value.warning ?? resolveNow(OUTCOME_TEXT[result.value.outcome])); + setStatus( + result.value.warning ?? + (result.value.outcome === "reset" + ? choice.appliedText + : resolveNow(OUTCOME_TEXT[result.value.outcome])), + ); + return; } setStatus( @@ -291,7 +297,9 @@ export function ResetCredits(props: { {resetCreditChoices(credits, input, now, false, m).map((choice) => ( {choice.summary} - {choice.availableCount > 0 ? ( + {choice.unavailableReason ? ( + {choice.unavailableReason} + ) : choice.availableCount > 0 ? ( option.creditId === creditId) - ? creditId - : undefined; - if (!grantId || !current.version) return "noCredit" as const; + const target = ClaudeResetCredits.claudeRedeemTarget( + current.usageLimits?.resetCredits, + creditId, + ); + if ("outcome" in target) return target.outcome; + if (!current.version) return "noCredit" as const; + const { grantId } = target; const version = current.version; return yield* resetCreditCoordinator.redeem( configDir, diff --git a/apps/server/src/provider/claudeResetCredits.test.ts b/apps/server/src/provider/claudeResetCredits.test.ts index a3a1110d87d34..adb681a4549f7 100644 --- a/apps/server/src/provider/claudeResetCredits.test.ts +++ b/apps/server/src/provider/claudeResetCredits.test.ts @@ -37,6 +37,11 @@ const respond = (status: number, body: unknown) => ); const refuseRequests = HttpClient.make(() => Effect.die("must not send a request")); +const FULL = { + label: "Full reset", + description: "Refills your 5-hour and weekly limits.", +} as const; + describe("claudeResetCreditsToContract", () => { it("counts live grants and pins the next usable one", () => { expect( @@ -63,12 +68,20 @@ describe("claudeResetCreditsToContract", () => { nextCreditId: "grant_a", nextExpiresAt: "2026-10-01T00:00:00.000Z", options: [ - expect.objectContaining({ + { creditId: "grant_a", - label: "Full reset", + ...FULL, availableCount: 2, expiresAt: "2026-10-01T00:00:00.000Z", - }), + }, + ], + bankedOptions: [ + { + creditId: "grant_a", + ...FULL, + availableCount: 5, + expiresAt: "2026-10-01T00:00:00.000Z", + }, ], }); }); @@ -93,32 +106,171 @@ describe("claudeResetCreditsToContract", () => { }, NOW, ); + const rows = [ + ["session_a", "5-hour reset", 1], + ["weekly_a", "Weekly reset", 1], + ["fable_a", "Fable reset", 2], + ]; + for (const options of [credits?.options, credits?.bankedOptions]) { + expect( + options?.map(({ creditId, label, availableCount }) => [creditId, label, availableCount]), + ).toEqual(rows); + } + expect(credits).toMatchObject({ availableCount: 4, nextCreditId: "weekly_a" }); + }); + + it.each([ + [{}, {}, "Usable once you reach a limit it refills"], + [{ use_requires_limit: false }, {}, "Can't be used right now"], + [{}, { cooldown_until: "2026-09-22T12:01:00Z" }, "Try again in a minute"], + [{}, { cooldown_until: "2026-09-22T11:59:00Z" }, "Usable once you reach a limit it refills"], + [{ blocking: ["five_hour"] }, {}, "Can't be used while you're at your 5-hour limit"], + [ + { blocking: ["seven_day"], gives_back_weekly: true }, + {}, + "No Fable usage this week to give back", + ], + [ + { blocking: ["seven_day_cowork"] }, + {}, + "Can't be used while you're at a limit it doesn't refill", + ], + [ + { clears: ["five_hour"] }, + { at_limit: true, exhausted: ["seven_day"] }, + "Doesn't refill the limit you've reached", + ], + [{ unavailable_reason: "cooldown", blocking: ["five_hour"] }, {}, "Try again in a minute"], + [ + { unavailable_reason: "blocked_seven_day", gives_back_weekly: true }, + {}, + "No Fable usage this week to give back", + ], + ])( + "lists a banked reset that can't be used yet with why, and leaves it out of the older fields: %j %j", + (overrides, status, why) => { + const credits = ClaudeResetCredits.claudeResetCreditsToContract( + { + eligible: true, + next_grant_id: "grant_a", + grants: [grant({ usable_now: false, ...overrides })], + ...status, + }, + NOW, + ); + expect(credits).toEqual({ + availableCount: 0, + bankedOptions: [expect.objectContaining({ creditId: "grant_a", unavailableReason: why })], + }); + }, + ); + + it("keeps the older fields empty when Claude's next grant is waiting beside a usable one", () => { + const credits = ClaudeResetCredits.claudeResetCreditsToContract( + { + eligible: true, + next_grant_id: "full_a", + grants: [ + grant({ id: "full_a", type: "full", usable_now: false }), + grant({ id: "fable_wait", gives_back_weekly: true, usable_now: false }), + grant({ id: "fable_a", gives_back_weekly: true }), + ], + }, + NOW, + ); + expect(credits).toEqual({ availableCount: 0, bankedOptions: expect.any(Array) }); expect( - credits?.options?.map(({ creditId, label, availableCount }) => [ + credits?.bankedOptions?.map(({ creditId, availableCount, unavailableReason }) => [ creditId, - label, availableCount, + unavailableReason, ]), ).toEqual([ - ["session_a", "5-hour reset", 1], - ["weekly_a", "Weekly reset", 1], - ["fable_a", "Fable reset", 2], + ["fable_a", 2, undefined], + ["full_a", 1, "Usable once you reach a limit it refills"], ]); - expect(credits).toMatchObject({ availableCount: 4, nextCreditId: "weekly_a" }); }); - it("offers nothing to redeem without a usable next grant or an eligible account", () => { + it("keeps older clients' usable-only options when a waiting kind sits beside the next grant", () => { + const credits = ClaudeResetCredits.claudeResetCreditsToContract( + { + eligible: true, + next_grant_id: "fable_a", + grants: [ + grant({ id: "full_a", type: "full", usable_now: false }), + grant({ id: "fable_a", gives_back_weekly: true }), + ], + }, + NOW, + ); + expect(credits).toMatchObject({ availableCount: 1, nextCreditId: "fable_a" }); + expect(credits?.options?.map((option) => option.creditId)).toEqual(["fable_a"]); expect( - ClaudeResetCredits.claudeResetCreditsToContract( - { eligible: true, next_grant_id: "grant_a", grants: [grant({ usable_now: false })] }, - NOW, + credits?.bankedOptions?.map(({ creditId, unavailableReason }) => [ + creditId, + unavailableReason, + ]), + ).toEqual([ + ["fable_a", undefined], + ["full_a", "Usable once you reach a limit it refills"], + ]); + }); + + it("claims an eligible reset by id, even when Claude's next grant is waiting, and never a waiting one", () => { + const waitingNext = ClaudeResetCredits.claudeResetCreditsToContract( + { + eligible: true, + next_grant_id: "full_a", + grants: [ + grant({ id: "full_a", type: "full", usable_now: false }), + grant({ id: "fable_a", gives_back_weekly: true }), + ], + }, + NOW, + ); + expect( + [undefined, "fable_a", "full_a", "gone"].map((creditId) => + ClaudeResetCredits.claudeRedeemTarget(waitingNext, creditId), ), - ).toEqual({ availableCount: 0 }); + ).toEqual([ + { outcome: "noCredit" }, + { grantId: "fable_a" }, + { outcome: "nothingToReset" }, + { outcome: "noCredit" }, + ]); + const usableNext = ClaudeResetCredits.claudeResetCreditsToContract( + { + eligible: true, + next_grant_id: "fable_a", + grants: [ + grant({ id: "full_a", type: "full", usable_now: false }), + grant({ id: "fable_a", gives_back_weekly: true }), + ], + }, + NOW, + ); expect( - ClaudeResetCredits.claudeResetCreditsToContract({ eligible: true, grants: [grant({})] }, NOW), - ).toEqual({ - availableCount: 0, + [undefined, "fable_a", "full_a"].map((creditId) => + ClaudeResetCredits.claudeRedeemTarget(usableNext, creditId), + ), + ).toEqual([{ grantId: "fable_a" }, { grantId: "fable_a" }, { outcome: "nothingToReset" }]); + }); + + it("claims by an older server's options when there is no banked list", () => { + const olderServer = { + availableCount: 1, + nextCreditId: "fable_a", + options: [{ creditId: "fable_a", ...FULL, availableCount: 1 }], + }; + expect(ClaudeResetCredits.claudeRedeemTarget(olderServer, "fable_a")).toEqual({ + grantId: "fable_a", + }); + expect(ClaudeResetCredits.claudeRedeemTarget({ availableCount: 1 }, undefined)).toEqual({ + outcome: "noCredit", }); + }); + + it("offers nothing to redeem without an eligible account", () => { expect( ClaudeResetCredits.claudeResetCreditsToContract( { eligible: false, grants: [grant({})] }, diff --git a/apps/server/src/provider/claudeResetCredits.ts b/apps/server/src/provider/claudeResetCredits.ts index d2000804cf4f6..331a87441af57 100644 --- a/apps/server/src/provider/claudeResetCredits.ts +++ b/apps/server/src/provider/claudeResetCredits.ts @@ -35,15 +35,21 @@ const Grant = Schema.Struct({ ends_at: Schema.optional(Schema.NullOr(Schema.String)), paused: Schema.optional(Schema.Boolean), usable_now: Schema.optional(Schema.Boolean), + use_requires_limit: Schema.optional(Schema.Boolean), clears: Schema.optional(Schema.Array(Schema.Unknown)), + blocking: Schema.optional(Schema.Array(Schema.Unknown)), type: Schema.optional(Schema.Unknown), gives_back_weekly: Schema.optional(Schema.Boolean), + unavailable_reason: Schema.optional(Schema.Unknown), }); const decodeGrant = Schema.decodeUnknownOption(Grant); const CedarEmber = Schema.Struct({ eligible: Schema.Boolean, grants: Schema.optional(Schema.Array(Schema.Unknown)), next_grant_id: Schema.optional(Schema.NullOr(Schema.String)), + at_limit: Schema.optional(Schema.Unknown), + exhausted: Schema.optional(Schema.Unknown), + cooldown_until: Schema.optional(Schema.Unknown), }); const UsageResponse = Schema.Struct({ cedar_ember: Schema.optional(Schema.NullOr(Schema.Unknown)), @@ -127,53 +133,120 @@ const grantKind = (grant: typeof Grant.Type): ResetKind => { return session && !other ? "session" : other && !session ? "weekly" : "full"; }; +const WAITING_REASONS = { + cooldown: "Try again in a minute", + blocked_five_hour: "Can't be used while you're at your 5-hour limit", + blocked_seven_day: "Can't be used while you're at your weekly limit", + blocked_opus: "Can't be used while you're at your weekly Opus limit", + blocked_sonnet: "Can't be used while you're at your weekly Sonnet limit", + blocked_other: "Can't be used while you're at a limit it doesn't refill", + cannot_clear: "Doesn't refill the limit you've reached", + needs_limit: "Usable once you reach a limit it refills", + unavailable: "Can't be used right now", +} as const; +const BLOCKING_REASONS: Record = { + five_hour: "blocked_five_hour", + seven_day: "blocked_seven_day", + seven_day_opus: "blocked_opus", + seven_day_sonnet: "blocked_sonnet", +}; + +type WaitingReason = keyof typeof WAITING_REASONS; + +// Claude Code's own order: the server's stated reason, else a cooldown, what blocks the grant, +// a limit it can't clear, and last whether it needs a limit at all. +const waitingReasonKey = ( + grant: typeof Grant.Type, + status: typeof CedarEmber.Type, + nowMs: number, +): WaitingReason => { + const stated = grant.unavailable_reason; + if (typeof stated === "string" && Object.hasOwn(WAITING_REASONS, stated)) { + return stated as WaitingReason; + } + const cooldown = status.cooldown_until; + if (typeof cooldown === "string" && isFutureTimestamp(cooldown, nowMs)) return "cooldown"; + const blocking = grant.blocking ?? []; + for (const limit of blocking) { + const reason = + typeof limit === "string" && Object.hasOwn(BLOCKING_REASONS, limit) + ? BLOCKING_REASONS[limit] + : undefined; + if (reason) return reason; + } + if (blocking.length > 0) return "blocked_other"; + const exhausted = Array.isArray(status.exhausted) ? status.exhausted : []; + const clears = (limit: unknown) => + (grant.clears ?? []).includes(limit) || (limit === "seven_day" && grant.gives_back_weekly); + if (status.at_limit === true && !exhausted.some(clears)) return "cannot_clear"; + return grant.use_requires_limit === false ? "unavailable" : "needs_limit"; +}; + +const waitingReason = (grant: typeof Grant.Type, status: typeof CedarEmber.Type, nowMs: number) => { + const reason = waitingReasonKey(grant, status, nowMs); + return reason === "blocked_seven_day" && grant.gives_back_weekly + ? "No Fable usage this week to give back" + : WAITING_REASONS[reason]; +}; + +/** + * The legacy fields keep their usable-only meaning so older clients never offer Use on a waiting + * reset; `bankedOptions` lists every banked reset, and one Claude won't take right now says why. + */ export function claudeResetCreditsToContract( block: unknown, nowMs: number, ): ServerProviderResetCredits | undefined { const parsed = decodeCedarEmber(block); if (Option.isNone(parsed) || !parsed.value.eligible) return undefined; - const live = (parsed.value.grants ?? []) + const status = parsed.value; + const banked = (status.grants ?? []) .flatMap((raw) => Option.toArray(decodeGrant(raw))) .filter( (grant) => - !grant.paused && - grant.usable_now && - (grant.ends_at == null || isFutureTimestamp(grant.ends_at, nowMs)), + !grant.paused && (grant.ends_at == null || isFutureTimestamp(grant.ends_at, nowMs)), ); - const next = live.find((grant) => grant.id === parsed.value.next_grant_id); + const live = banked.filter((grant) => grant.usable_now); + const next = live.find((grant) => grant.id === status.next_grant_id); const expiresAt = (grant: typeof Grant.Type | undefined) => { const at = grant?.ends_at ? DateTime.make(grant.ends_at) : Option.none(); return Option.isSome(at) ? DateTime.formatIso(at.value) : undefined; }; - const byKind = new Map>(); - for (const grant of live) { - if (grant.resets_left === 0) continue; - const kind = grantKind(grant); - byKind.set(kind, [...(byKind.get(kind) ?? []), grant]); - } - const options = (Object.keys(RESET_KINDS) as Array).flatMap( - (kind): Array => { - const grants = byKind.get(kind); - const target = grants?.[0]; - if (!grants || !target) return []; - const optionExpiresAt = expiresAt(target); - return [ - { - creditId: target.id, - ...RESET_KINDS[kind], - availableCount: grants.reduce((sum, grant) => sum + grant.resets_left, 0), - ...(optionExpiresAt ? { expiresAt: optionExpiresAt } : {}), - }, - ]; - }, - ); + const kindOptions = (grants: ReadonlyArray) => { + const byKind = new Map>(); + for (const grant of grants) { + if (grant.resets_left === 0) continue; + const kind = grantKind(grant); + byKind.set(kind, [...(byKind.get(kind) ?? []), grant]); + } + return (Object.keys(RESET_KINDS) as Array).flatMap( + (kind): Array => { + const ofKind = byKind.get(kind); + const target = ofKind?.find((grant) => grant.usable_now) ?? ofKind?.[0]; + if (!ofKind || !target) return []; + const optionExpiresAt = expiresAt(target); + return [ + { + creditId: target.id, + ...RESET_KINDS[kind], + availableCount: ofKind.reduce((sum, grant) => sum + grant.resets_left, 0), + ...(optionExpiresAt ? { expiresAt: optionExpiresAt } : {}), + ...(target.usable_now + ? {} + : { unavailableReason: waitingReason(target, status, nowMs) }), + }, + ]; + }, + ); + }; + const bankedOptions = kindOptions(banked); const nextExpiresAt = expiresAt(next); return { availableCount: next ? live.reduce((sum, grant) => sum + grant.resets_left, 0) : 0, ...(nextExpiresAt ? { nextExpiresAt } : {}), ...(next ? { nextCreditId: next.id } : {}), - ...(next ? { options } : {}), + ...(next ? { options: kindOptions(live) } : {}), + ...(bankedOptions.length > 0 ? { bankedOptions } : {}), }; } @@ -249,6 +322,22 @@ export const claudeAccountConfigPath = Effect.fn("claudeAccountConfigPath")(func : path.join(yield* HostProcess.HomeDirectory, ".claude.json"); }); +/** The grant a redeem request names, or the answer when no claim should be sent for it. */ +export const claudeRedeemTarget = ( + credits: ServerProviderResetCredits | undefined, + creditId: string | undefined, +): { readonly grantId: string } | { readonly outcome: "noCredit" | "nothingToReset" } => { + if (creditId === undefined) { + return credits?.nextCreditId ? { grantId: credits.nextCreditId } : { outcome: "noCredit" }; + } + const option = (credits?.bankedOptions ?? credits?.options)?.find( + (candidate) => candidate.creditId === creditId, + ); + if (!option) return { outcome: "noCredit" }; + // A client reading an older snapshot can still ask for a reset that is now waiting. + return option.unavailableReason ? { outcome: "nothingToReset" } : { grantId: creditId }; +}; + const CLAIM_OUTCOMES = { reset: "reset", not_limited: "nothingToReset", diff --git a/apps/web/src/components/usage/UsageLimits.tsx b/apps/web/src/components/usage/UsageLimits.tsx index a36b220ee3efa..799324ef7dd28 100644 --- a/apps/web/src/components/usage/UsageLimits.tsx +++ b/apps/web/src/components/usage/UsageLimits.tsx @@ -11,6 +11,7 @@ import { import { useAtomValue } from "@effect/atom-react"; import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display"; import { + bankedResetCreditCount, type LimitPace, paceOf, paceRemainingPercent, @@ -262,8 +263,7 @@ export function LimitWindows({ ); } -const OUTCOME_TEXT: Record = { - reset: msg("Reset applied. Your windows have cleared."), +const OUTCOME_TEXT: Record, string> = { nothingToReset: msg("Nothing to reset right now."), noCredit: msg("No reset credit left."), alreadyRedeemed: msg("That credit was already redeemed."), @@ -287,7 +287,13 @@ export function useResetCredit(environmentId: EnvironmentId) { const result = await consume({ environmentId, input: choice.input }); setBusy(false); if (result._tag === "Success") { - setStatus(result.value.warning ?? m(OUTCOME_TEXT[result.value.outcome])); + setStatus( + result.value.warning ?? + (result.value.outcome === "reset" + ? choice.appliedText + : m(OUTCOME_TEXT[result.value.outcome])), + ); + return; } setStatus( @@ -358,13 +364,15 @@ export function ResetCredits({ useResetCredit(environmentId); const gt = useGT(); const m = useMessages(); - if (credits.availableCount === 0 && status === null) return null; + if (bankedResetCreditCount(credits) === 0 && status === null) return null; return (
{resetCreditChoices(credits, input, now, false, m).map((choice) => (
{choice.summary} - {choice.availableCount > 0 ? ( + {choice.unavailableReason ? ( + {choice.unavailableReason} + ) : choice.availableCount > 0 ? (