feat(usage): show and redeem free limit resets for cc accounts

Adds the free usage-limit reset (the desktop app's "Reset for free")
to the Quota Tracker for cc OAuth accounts, mirroring the existing
Codex reset-credit button.

- Reset button with remaining count on the card; tooltip shows use-by
  date and which limits get refilled.
- Expiry modal (clock button) listing each grant: label, resets left,
  refills (session / weekly), use-by date, time remaining, status.
- Confirm dialog before redeeming, since a reset is irreversible.
- Usage and reset calls send the CLI User-Agent required for cedar_ember.
- Usage cache is dropped after a redeem so the card shows the refilled limits.
This commit is contained in:
Reid Nguyen
2026-09-23 12:16:10 +07:00
parent 8403576095
commit e571a8b6da
6 changed files with 236 additions and 23 deletions

View File

@@ -3,7 +3,7 @@
*/
import { proxyAwareFetch } from "../../utils/proxyFetch.js";
import { ANTHROPIC_API_VERSION } from "../../providers/shared.js";
import { ANTHROPIC_API_VERSION, CLAUDE_CLI_VERSION } from "../../providers/shared.js";
import { U, parseResetTime } from "./shared.js";
// Claude API config (urls from registry, apiVersion is header logic kept here)
@@ -11,7 +11,11 @@ const CLAUDE_CONFIG = {
oauthUsageUrl: U("claude").oauthUrl,
usageUrl: U("claude").orgUrl,
settingsUrl: U("claude").settingsUrl,
profileUrl: U("claude").profileUrl,
resetUrl: U("claude").resetUrl,
apiVersion: ANTHROPIC_API_VERSION,
// Reset grants are gated by surface: only "(external, cli)" UA is eligible
userAgent: `claude-cli/${CLAUDE_CLI_VERSION} (external, cli)`,
};
// OAuth usage endpoint rate-limits (429); cool down per-token to stop hammering it.
@@ -64,12 +68,14 @@ async function fetchClaudeUsageRaw(accessToken, proxyOptions = null) {
}
// Primary: OAuth usage endpoint (Claude Code consumer OAuth tokens)
const oauthResponse = await proxyAwareFetch(CLAUDE_CONFIG.oauthUsageUrl, {
// cedar_ember=1 adds the "limit reset" grant block (same flag Claude Code sends)
const oauthResponse = await proxyAwareFetch(`${CLAUDE_CONFIG.oauthUsageUrl}?cedar_ember=1`, {
method: "GET",
headers: {
"Authorization": `Bearer ${accessToken}`,
"anthropic-beta": "oauth-2025-04-20",
"anthropic-version": CLAUDE_CONFIG.apiVersion,
"User-Agent": CLAUDE_CONFIG.userAgent,
},
}, proxyOptions);
@@ -129,6 +135,7 @@ async function fetchClaudeUsageRaw(accessToken, proxyOptions = null) {
return {
plan: "Claude Code",
extraUsage: data.extra_usage ?? null,
resetCredits: parseClaudeResetGrants(data.cedar_ember),
quotas,
};
}
@@ -146,6 +153,70 @@ async function fetchClaudeUsageRaw(accessToken, proxyOptions = null) {
}
}
// Free "limit reset" grants (Anthropic program id "cedar_ember").
// Shape: { eligible, next_grant_id, grants: [{ id, resets_left, ends_at, paused, clears }] }
export function parseClaudeResetGrants(block) {
if (!block?.eligible || !Array.isArray(block.grants)) return null;
const grants = block.grants.filter((g) => g?.id && !g.paused && Number(g.resets_left) > 0);
const next = grants.find((g) => g.id === block.next_grant_id) || grants[0] || null;
return {
availableCount: grants.reduce((sum, g) => sum + Number(g.resets_left), 0),
nextGrantId: next?.id || null,
expiresAt: next?.ends_at || null,
clears: next?.clears || [],
cooldownUntil: block.cooldown_until || null,
weeklyResetsAt: block.weekly_resets_at || null,
grants: block.grants.filter((g) => g?.id).map((g) => ({
id: g.id,
label: g.label || "",
resetsLeft: Number(g.resets_left) || 0,
resetsTotal: Number(g.resets_total) || 0,
startsAt: g.starts_at || null,
endsAt: g.ends_at || null,
clears: Array.isArray(g.clears) ? g.clears : [],
paused: g.paused === true,
usableNow: g.usable_now === true,
useRequiresLimit: g.use_requires_limit !== false,
})),
};
}
// Spend one reset grant: refills the limits listed in grant.clears. Irreversible.
export async function consumeClaudeResetGrant(accessToken, grantId, proxyOptions = null) {
if (!accessToken) throw new Error("No Claude access token available. Please re-authorize the connection.");
if (!/^[a-z0-9_-]{1,40}$/.test(grantId || "")) throw new Error("Invalid reset grant id.");
const headers = {
"Authorization": `Bearer ${accessToken}`,
"anthropic-beta": "oauth-2025-04-20",
"anthropic-version": CLAUDE_CONFIG.apiVersion,
"User-Agent": CLAUDE_CONFIG.userAgent,
"Content-Type": "application/json",
};
const profileRes = await proxyAwareFetch(CLAUDE_CONFIG.profileUrl, { method: "GET", headers }, proxyOptions);
const profile = await profileRes.json().catch(() => null);
const orgId = profile?.organization?.uuid;
if (!profileRes.ok || !orgId) throw new Error(`Cannot resolve Claude organization (${profileRes.status}).`);
const res = await proxyAwareFetch(CLAUDE_CONFIG.resetUrl.replace("{org_id}", orgId), {
method: "POST",
headers,
body: JSON.stringify({ program: "cedar_ember", grant_id: grantId, request_id: crypto.randomUUID() }),
}, proxyOptions);
const data = await res.json().catch(() => null);
usageCache.delete(accessToken); // next read must show refilled limits
return {
ok: res.ok && data?.result === "reset",
status: res.status,
result: data?.result || null,
reason: data?.reason || null,
resetsLeft: data?.resets_left ?? null,
message: data?.error?.message || null,
};
}
/**
* Legacy Claude usage for API key / org admin users
*/