From 81cb7ea4f2cb3ee0f880210e91b2ee9f29333454 Mon Sep 17 00:00:00 2001 From: Danathar <6772335+Danathar@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:03:22 -0500 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20gauge:=20show=20Claude=20usage=20cr?= =?UTF-8?q?edits=20(on/off,=20spent=20of=20monthly=20cap)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Claude prober's /api/oauth/usage response carries Claude's extra usage (usage credits) next to the plan windows: a `spend` object (enabled, used and limit in minor units with an exponent) and an `extra_usage` object (the same in cents, plus spend_limit_reached). The reading now keeps it as Headroom.ExtraUsage, tri-state throughout (nil = Claude did not say, never 0 or off), preferring spend and falling back to extra_usage. Both are decoded apart from the limits, so an odd shape there never fails the reading. PaidCreditsAvailable follows the enabled flag. /api/providers/headroom serializes it as extra_usage, and the Overview gauge shows one line under the Claude dials: "Usage credits: on · $0.00 of $350.00 used this month", "off", or "limit reached" in amber; hidden when unknown. Display only. The endpoint reports no purchased balance (spend.balance is null) and no banked limit resets, so those are left out. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1 Signed-off-by: Danathar <6772335+Danathar@users.noreply.github.com> --- .../added-claude-usage-credits-gauge.md | 1 + .../api-reference/cost-tokens-telemetry.md | 2 +- src/docs/dashboard.md | 8 + src/pkg/dashboard/static-src/css/overview.css | 2 + .../static-src/js/subscription-gauge.js | 31 ++++ src/pkg/dashboard/static/index.html | 33 ++++ src/pkg/dashboard/subscription_gauge.test.js | 37 +++++ .../subscription_gauge_overview_test.go | 7 + src/pkg/rotation/rotation.go | 133 ++++++++++++++- .../rotation_claude_extra_usage_test.go | 156 ++++++++++++++++++ src/pkg/rotation/testdata/README.md | 8 + .../claude_oauth_usage_extra_usage.json | 38 +++++ 12 files changed, 451 insertions(+), 5 deletions(-) create mode 100644 changelog.d/added-claude-usage-credits-gauge.md create mode 100644 src/pkg/rotation/rotation_claude_extra_usage_test.go create mode 100644 src/pkg/rotation/testdata/claude_oauth_usage_extra_usage.json diff --git a/changelog.d/added-claude-usage-credits-gauge.md b/changelog.d/added-claude-usage-credits-gauge.md new file mode 100644 index 0000000000..09d8ccd804 --- /dev/null +++ b/changelog.d/added-claude-usage-credits-gauge.md @@ -0,0 +1 @@ +- The Overview usage gauge shows Claude's usage credits (extra usage) under the Claude dials when Claude reports them: on or off, and how much of the monthly cap is spent, for example "Usage credits: on · $0.00 of $350.00 used this month", with "limit reached" in amber once the cap is spent. The line is hidden when Claude does not report it, and it is display only. `/api/providers/headroom` carries the same reading as `extra_usage`. Claude's usage endpoint does not report a purchased credit balance or banked limit resets, so those are not shown. diff --git a/src/docs/api-reference/cost-tokens-telemetry.md b/src/docs/api-reference/cost-tokens-telemetry.md index ccd9e48f90..21555d1f69 100644 --- a/src/docs/api-reference/cost-tokens-telemetry.md +++ b/src/docs/api-reference/cost-tokens-telemetry.md @@ -16,5 +16,5 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/cost/history` | Dashboard auth/session | Cost History | `pkg/dashboard/api.go:151` | | `GET` | `/api/trend/history` | Dashboard auth/session | Trend History | `pkg/dashboard/api.go:154` | | `GET` | `/api/timeseries` | Dashboard auth/session | Time Series | `pkg/dashboard/api.go:156` | -| `GET` | `/api/providers/headroom` | Owner only | Last stored per-provider usage readings (`providers[]` with `limits[]`, `captured_at`, `stale`, `probe_error_cause`, and `plan_type` when a provider reports one), from provider rotation or the default publish-only reading, plus `used_by`: per provider, the enabled agents whose backend spends its plan; serving it never triggers a new measurement. Feeds the Overview usage gauge and the rotation settings table | `pkg/dashboard/api.go:65` | +| `GET` | `/api/providers/headroom` | Owner only | Last stored per-provider usage readings (`providers[]` with `limits[]`, `captured_at`, `stale`, `probe_error_cause`, `plan_type` when a provider reports one, and for Claude `extra_usage` when reported: `enabled`, `used_minor`, `limit_minor`, `exponent`, `currency`, `spend_limit_reached`, each left out when unknown), from provider rotation or the default publish-only reading, plus `used_by`: per provider, the enabled agents whose backend spends its plan; serving it never triggers a new measurement. Feeds the Overview usage gauge and the rotation settings table | `pkg/dashboard/api.go:65` | | `GET` | `/api/budget/history` | Dashboard auth/session | Budget History | `pkg/dashboard/api.go:153` | diff --git a/src/docs/dashboard.md b/src/docs/dashboard.md index c4eedd90dd..ccc2278dff 100644 --- a/src/docs/dashboard.md +++ b/src/docs/dashboard.md @@ -166,6 +166,14 @@ with the percentage left and when it resets: - **Claude**: the weekly limit, plus a 5-hour or model-specific weekly limit when the plan has one. A model-specific limit is named after its model the way Claude Code's `/usage` names it, for example "Weekly (Fable)". + Under the dials, one line shows Claude's usage credits (extra usage, which + keeps the account working past a plan limit) when Claude reports them: + "Usage credits: on · $0.00 of $350.00 used this month", "off", or "limit + reached" in amber once the monthly cap is spent. The line is hidden when + Claude does not report them. It is display only: the hive never turns + credits on or spends them. Claude's usage endpoint does not report a + purchased credit balance or banked limit resets, so the gauge cannot show + those; claude.ai's Settings › Usage page does. - **Copilot**: the monthly premium-request quota ("Premium requests"), as Copilot itself reports it, resetting at the start of each month. diff --git a/src/pkg/dashboard/static-src/css/overview.css b/src/pkg/dashboard/static-src/css/overview.css index 4c6721350a..1c45353d7a 100644 --- a/src/pkg/dashboard/static-src/css/overview.css +++ b/src/pkg/dashboard/static-src/css/overview.css @@ -183,6 +183,8 @@ .overview-usage-gauge__provider { font-weight: var(--fw-semibold); } .overview-usage-gauge__users { font-size: var(--fs-sm); color: var(--text-muted); overflow-wrap: anywhere; } .overview-usage-gauge__spend { font-size: var(--fs-base); font-weight: 600; } + .overview-usage-gauge__credits { font-size: var(--fs-sm); color: var(--text-muted); } + .overview-usage-gauge__credits[data-status="warn"] { color: var(--status-warn); font-weight: 600; } .overview-usage-gauge__dials { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: var(--sp-4); } .overview-usage-gauge__dial { display: flex; flex-direction: column; align-items: center; gap: var(--sp-1); text-align: center; } .overview-usage-gauge__label { font-weight: var(--fw-semibold); } diff --git a/src/pkg/dashboard/static-src/js/subscription-gauge.js b/src/pkg/dashboard/static-src/js/subscription-gauge.js index 6edc7cd26b..14d12af8ec 100644 --- a/src/pkg/dashboard/static-src/js/subscription-gauge.js +++ b/src/pkg/dashboard/static-src/js/subscription-gauge.js @@ -55,6 +55,31 @@ }; // Paid credit pools and prepaid balances are not plan limits. const NOT_LIMITS = ['credits', 'balance']; + // Claude's extra usage (usage credits past the plan limits) as one + // line: on/off and spent of the monthly cap. null hides the line: the + // provider did not say, which is never shown as 0 or off. Display + // only; the dashboard never turns credits on or spends them. + const creditsFor = (x) => { + if (!x || typeof x !== 'object' || Array.isArray(x)) return null; + const enabled = typeof x.enabled === 'boolean' ? x.enabled : null; + const reached = x.spend_limit_reached === true; + const exp = Number.isInteger(x.exponent) && x.exponent >= 0 && x.exponent <= 6 ? x.exponent : 2; + const amount = (v) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v / Math.pow(10, exp) : null); + const used = amount(x.used_minor); + const cap = amount(x.limit_minor); + const currency = String(x.currency || '').toUpperCase(); + const money = (n) => (currency === 'USD' || currency === '' ? '$' + n.toFixed(exp) : n.toFixed(exp) + ' ' + currency); + const parts = []; + if (reached) parts.push('limit reached'); + else if (enabled !== null) parts.push(enabled ? 'on' : 'off'); + if (enabled !== false) { + if (used !== null && cap !== null) parts.push(money(used) + ' of ' + money(cap) + ' used this month'); + else if (cap !== null) parts.push(money(cap) + ' monthly cap'); + else if (used !== null) parts.push(money(used) + ' used this month'); + } + if (!parts.length) return null; + return { text: 'Usage credits: ' + parts.join(' · '), status: reached ? 'warn' : 'ok', enabled: enabled, limitReached: reached, used: used, cap: cap, currency: currency }; + }; // listed: the provider is in used_by, so agents spend it and a missing // or failed reading is worth saying. Unlisted (a server without // used_by) keeps the Claude-only rule: hidden when Claude is not used. @@ -127,6 +152,7 @@ ageMs: ageMs, outOfDate: !!reading.stale || (ageMs !== null && ageMs > OUT_OF_DATE_MS), planName: String(reading.plan_type || ''), + credits: creditsFor(reading.extra_usage), accountNote: 'Reflects the ' + name + ' account this hive is signed in with.', }); }; @@ -339,6 +365,11 @@ grid.appendChild(cell); }); box.appendChild(grid); + if (row.credits) { + const credits = el('div', 'overview-usage-gauge__credits', row.credits.text); + credits.setAttribute('data-status', row.credits.status); + box.appendChild(credits); + } } parts.push(box); }); diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index f69b920f56..12bff2c8fb 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -3863,6 +3863,8 @@ .overview-usage-gauge__provider { font-weight: var(--fw-semibold); } .overview-usage-gauge__users { font-size: var(--fs-sm); color: var(--text-muted); overflow-wrap: anywhere; } .overview-usage-gauge__spend { font-size: var(--fs-base); font-weight: 600; } + .overview-usage-gauge__credits { font-size: var(--fs-sm); color: var(--text-muted); } + .overview-usage-gauge__credits[data-status="warn"] { color: var(--status-warn); font-weight: 600; } .overview-usage-gauge__dials { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: var(--sp-4); } .overview-usage-gauge__dial { display: flex; flex-direction: column; align-items: center; gap: var(--sp-1); text-align: center; } .overview-usage-gauge__label { font-weight: var(--fw-semibold); } @@ -57747,6 +57749,31 @@ }; // Paid credit pools and prepaid balances are not plan limits. const NOT_LIMITS = ['credits', 'balance']; + // Claude's extra usage (usage credits past the plan limits) as one + // line: on/off and spent of the monthly cap. null hides the line: the + // provider did not say, which is never shown as 0 or off. Display + // only; the dashboard never turns credits on or spends them. + const creditsFor = (x) => { + if (!x || typeof x !== 'object' || Array.isArray(x)) return null; + const enabled = typeof x.enabled === 'boolean' ? x.enabled : null; + const reached = x.spend_limit_reached === true; + const exp = Number.isInteger(x.exponent) && x.exponent >= 0 && x.exponent <= 6 ? x.exponent : 2; + const amount = (v) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v / Math.pow(10, exp) : null); + const used = amount(x.used_minor); + const cap = amount(x.limit_minor); + const currency = String(x.currency || '').toUpperCase(); + const money = (n) => (currency === 'USD' || currency === '' ? '$' + n.toFixed(exp) : n.toFixed(exp) + ' ' + currency); + const parts = []; + if (reached) parts.push('limit reached'); + else if (enabled !== null) parts.push(enabled ? 'on' : 'off'); + if (enabled !== false) { + if (used !== null && cap !== null) parts.push(money(used) + ' of ' + money(cap) + ' used this month'); + else if (cap !== null) parts.push(money(cap) + ' monthly cap'); + else if (used !== null) parts.push(money(used) + ' used this month'); + } + if (!parts.length) return null; + return { text: 'Usage credits: ' + parts.join(' · '), status: reached ? 'warn' : 'ok', enabled: enabled, limitReached: reached, used: used, cap: cap, currency: currency }; + }; // listed: the provider is in used_by, so agents spend it and a missing // or failed reading is worth saying. Unlisted (a server without // used_by) keeps the Claude-only rule: hidden when Claude is not used. @@ -57819,6 +57846,7 @@ ageMs: ageMs, outOfDate: !!reading.stale || (ageMs !== null && ageMs > OUT_OF_DATE_MS), planName: String(reading.plan_type || ''), + credits: creditsFor(reading.extra_usage), accountNote: 'Reflects the ' + name + ' account this hive is signed in with.', }); }; @@ -58031,6 +58059,11 @@ grid.appendChild(cell); }); box.appendChild(grid); + if (row.credits) { + const credits = el('div', 'overview-usage-gauge__credits', row.credits.text); + credits.setAttribute('data-status', row.credits.status); + box.appendChild(credits); + } } parts.push(box); }); diff --git a/src/pkg/dashboard/subscription_gauge.test.js b/src/pkg/dashboard/subscription_gauge.test.js index 430056f337..f3b07e714f 100644 --- a/src/pkg/dashboard/subscription_gauge.test.js +++ b/src/pkg/dashboard/subscription_gauge.test.js @@ -234,3 +234,40 @@ test('a one-provider hive reads exactly as before at the top level', () => { assert.deepEqual(plain(m.dials.map(d => d.label)), ['Weekly', 'Weekly (Fable)']); assert.equal(m.accountNote, 'Reflects the Claude account this hive is signed in with.'); }); + +// Claude's extra usage, shaped like the live /api/oauth/usage reading the +// prober serializes (2026-11-19): on, $0.00 of a $350.00 monthly cap. +const EXTRA_ON = { enabled: true, used_minor: 0, limit_minor: 35000, exponent: 2, currency: 'USD', spend_limit_reached: false }; + +test('extra usage on shows spent of the monthly cap', () => { + const m = model(resp({ limits: [limit('weekly_all', 'weekly', 54, 10080)], extra_usage: EXTRA_ON }), NOW); + assert.equal(m.credits.text, 'Usage credits: on · $0.00 of $350.00 used this month'); + assert.equal(m.credits.status, 'ok'); + assert.equal(m.rows[0].credits.text, m.credits.text); +}); + +test('extra usage off says off and no amounts', () => { + const m = model(resp({ limits: [limit('weekly_all', 'weekly', 54, 10080)], extra_usage: { enabled: false, exponent: 2 } }), NOW); + assert.equal(m.credits.text, 'Usage credits: off'); +}); + +test('spend limit reached is a warning', () => { + const m = model(resp({ limits: [limit('weekly_all', 'weekly', 54, 10080)], extra_usage: Object.assign({}, EXTRA_ON, { used_minor: 35000, spend_limit_reached: true }) }), NOW); + assert.equal(m.credits.text, 'Usage credits: limit reached · $350.00 of $350.00 used this month'); + assert.equal(m.credits.status, 'warn'); +}); + +test('no extra usage reported hides the line (never shown as 0 or off)', () => { + for (const extra of [undefined, null, {}, { exponent: 2 }, 'on', []]) { + const r = { limits: [limit('weekly_all', 'weekly', 54, 10080)] }; + if (extra !== undefined) r.extra_usage = extra; + const m = model(resp(r), NOW); + assert.equal(m.state, 'reading'); + assert.equal(m.credits, null, JSON.stringify(extra)); + } +}); + +test('amounts follow the stated exponent and currency', () => { + const m = model(resp({ limits: [limit('weekly_all', 'weekly', 54, 10080)], extra_usage: { enabled: true, used_minor: 1234, limit_minor: 50000, exponent: 2, currency: 'EUR' } }), NOW); + assert.equal(m.credits.text, 'Usage credits: on · 12.34 EUR of 500.00 EUR used this month'); +}); diff --git a/src/pkg/dashboard/subscription_gauge_overview_test.go b/src/pkg/dashboard/subscription_gauge_overview_test.go index 1355c92d44..0dac03b813 100644 --- a/src/pkg/dashboard/subscription_gauge_overview_test.go +++ b/src/pkg/dashboard/subscription_gauge_overview_test.go @@ -65,6 +65,13 @@ func TestSubscriptionGaugeOverviewWiring(t *testing.T) { if strings.Contains(overview, "innerHTML") { t.Fatalf("Overview gauge must build its DOM without innerHTML:\n%s", overview) } + // Claude's usage-credits line renders under the dials only when the + // model built one, and is a display: the gauge has no credits control. + for _, want := range []string{"if (row.credits)", "'overview-usage-gauge__credits', row.credits.text", "credits.setAttribute('data-status', row.credits.status)"} { + if !strings.Contains(overview, want) { + t.Fatalf("renderSubscriptionGaugeOverview missing %q:\n%s", want, overview) + } + } dial := jsFunc(t, html, "subscriptionGaugeDialSvg") if !strings.Contains(dial, "createElementNS") || strings.Contains(dial, "innerHTML") { t.Fatalf("fuel dial must be built with createElementNS, not innerHTML:\n%s", dial) diff --git a/src/pkg/rotation/rotation.go b/src/pkg/rotation/rotation.go index 8d8c1c235d..13d01d5012 100644 --- a/src/pkg/rotation/rotation.go +++ b/src/pkg/rotation/rotation.go @@ -12,6 +12,7 @@ import ( "fmt" "io" "log/slog" + "math" "net/http" "os" "os/exec" @@ -110,7 +111,11 @@ type Headroom struct { // did not say". nil must never be read as recovery (#6833), so consumers // that need a definite answer treat it as unknown. OrdinaryUsageAllowed *bool `json:"ordinary_usage_allowed,omitempty"` - ProbeErr error `json:"-"` // non-nil = measurement failed (NOT treated as exhausted) + // ExtraUsage is Claude's "extra usage" (usage credits that keep the + // account working past its plan limits), read-only. nil means the + // provider did not report it. + ExtraUsage *ExtraUsage `json:"extra_usage,omitempty"` + ProbeErr error `json:"-"` // non-nil = measurement failed (NOT treated as exhausted) // ProbeErrCause categorizes ProbeErr so a dead adapter — one that parses // nothing a real payload contains and would report `unknown` forever on a // correctly configured host (kubestellar/hive#6986) — stays DISTINGUISHABLE @@ -257,7 +262,8 @@ func sanitizeProbeError(msg string) string { // MarshalJSON includes the probe error text alongside the exported fields. // PlanType is emitted only when a probe reported one, so readings without a -// plan (Claude's today) serialize exactly as before. +// plan (Claude's today) serialize exactly as before; ExtraUsage likewise only +// when the provider reported it. func (h Headroom) MarshalJSON() ([]byte, error) { type alias struct { Provider string `json:"provider"` @@ -271,6 +277,7 @@ func (h Headroom) MarshalJSON() ([]byte, error) { Error string `json:"error,omitempty"` ProbeErrCause string `json:"probe_error_cause,omitempty"` PlanType string `json:"plan_type,omitempty"` + ExtraUsage *ExtraUsage `json:"extra_usage,omitempty"` } return json.Marshal(alias{ Provider: h.Provider, @@ -284,6 +291,7 @@ func (h Headroom) MarshalJSON() ([]byte, error) { Error: h.ProbeError(), ProbeErrCause: string(h.ProbeErrCause), PlanType: h.PlanType, + ExtraUsage: h.ExtraUsage, }) } @@ -388,6 +396,114 @@ type claudeUsageResponse struct { ResetsAt *time.Time `json:"resets_at"` Scope *claudeUsageScope `json:"scope"` } `json:"limits"` + // Spend and ExtraUsage stay raw here and are decoded on their own + // (claudeExtraUsage), so an unexpected shape there can never fail the + // limits reading. + Spend json.RawMessage `json:"spend"` + ExtraUsage json.RawMessage `json:"extra_usage"` +} + +// ExtraUsage is what /api/oauth/usage says about Claude's extra usage: whether +// it is on, and how much of its monthly cap is spent, in minor currency units +// (UsedMinor / 10^Exponent is the amount). Every pointer is tri-state: nil +// means the provider did not say and must never be shown as 0 or off. The +// response carries no purchased credit balance (spend.balance is null) and no +// banked limit resets, so neither is read here. +type ExtraUsage struct { + Enabled *bool `json:"enabled,omitempty"` + UsedMinor *int64 `json:"used_minor,omitempty"` + LimitMinor *int64 `json:"limit_minor,omitempty"` + Exponent int `json:"exponent"` + Currency string `json:"currency,omitempty"` + SpendLimitReached *bool `json:"spend_limit_reached,omitempty"` +} + +// claudeMoney is the endpoint's money shape: {"amount_minor": 35000, +// "currency": "USD", "exponent": 2}. +type claudeMoney struct { + AmountMinor *float64 `json:"amount_minor"` + Currency string `json:"currency"` + Exponent *int `json:"exponent"` +} + +// claudeSpend is the response's `spend` object, as far as the gauge reads it. +type claudeSpend struct { + Used *claudeMoney `json:"used"` + Limit *claudeMoney `json:"limit"` + Enabled *bool `json:"enabled"` +} + +// claudeExtra is the response's `extra_usage` object; its amounts are in +// cents (decimal_places says so). +type claudeExtra struct { + IsEnabled *bool `json:"is_enabled"` + MonthlyLimit *float64 `json:"monthly_limit"` + UsedCredits *float64 `json:"used_credits"` + Currency string `json:"currency"` + DecimalPlaces *int `json:"decimal_places"` + SpendLimitReached *bool `json:"spend_limit_reached"` +} + +// claudeExtraUsage reads the extra-usage state from the response's `spend` +// object (minor units plus exponent), falling back to the `extra_usage` +// object (amounts in cents, decimal_places) for what spend does not carry. A +// missing, null or malformed object contributes nothing; nil when neither +// says anything. +func claudeExtraUsage(spendRaw, extraRaw json.RawMessage) *ExtraUsage { + var spend claudeSpend + if len(spendRaw) == 0 || json.Unmarshal(spendRaw, &spend) != nil { + spend = claudeSpend{} + } + var extra claudeExtra + if len(extraRaw) == 0 || json.Unmarshal(extraRaw, &extra) != nil { + extra = claudeExtra{} + } + minor := func(v *float64) *int64 { + if v == nil || math.IsNaN(*v) || math.IsInf(*v, 0) || *v < 0 { + return nil + } + n := int64(math.Round(*v)) + return &n + } + validExp := func(e *int) bool { return e != nil && *e >= 0 && *e <= 6 } + eu := &ExtraUsage{Exponent: 2, Enabled: spend.Enabled, SpendLimitReached: extra.SpendLimitReached} + for _, m := range []*claudeMoney{spend.Limit, spend.Used} { + if m == nil { + continue + } + if validExp(m.Exponent) { + eu.Exponent = *m.Exponent + } + if eu.Currency == "" { + eu.Currency = strings.TrimSpace(m.Currency) + } + } + if spend.Used != nil { + eu.UsedMinor = minor(spend.Used.AmountMinor) + } + if spend.Limit != nil { + eu.LimitMinor = minor(spend.Limit.AmountMinor) + } + if eu.Enabled == nil { + eu.Enabled = extra.IsEnabled + } + // extra_usage's amounts are used only when spend gave neither, so the two + // are never mixed under different exponents. + if eu.UsedMinor == nil && eu.LimitMinor == nil && (extra.UsedCredits != nil || extra.MonthlyLimit != nil) { + eu.Exponent = 2 + if validExp(extra.DecimalPlaces) { + eu.Exponent = *extra.DecimalPlaces + } + eu.UsedMinor = minor(extra.UsedCredits) + eu.LimitMinor = minor(extra.MonthlyLimit) + } + if eu.Currency == "" { + eu.Currency = strings.TrimSpace(extra.Currency) + } + if eu.Enabled == nil && eu.UsedMinor == nil && eu.LimitMinor == nil && eu.SpendLimitReached == nil { + return nil + } + return eu } // claudeUsageScope names the model a weekly_scoped window counts, e.g. @@ -560,13 +676,22 @@ func claudeHeadroom(provider string, thresholdPct int, body []byte) (Headroom, e if len(limits) == 0 { return Headroom{}, withCause(ProbeCauseUnrecognizedSchema, errors.New("claude usage: no limit window carried a percent (unrecognized schema)")) } - return Headroom{ + extra := claudeExtraUsage(parsed.Spend, parsed.ExtraUsage) + h := Headroom{ Provider: provider, Available: used < thresholdPct, PctRemaining: fullPct - used, ResetAt: resetAt, Limits: limits, - }, nil + ExtraUsage: extra, + } + if extra != nil && extra.Enabled != nil { + // Display only: whether usage credits would cover a plan limit. + // Nothing here turns them on or spends them. + enabled := *extra.Enabled + h.PaidCreditsAvailable = &enabled + } + return h, nil } func normalizeLimitKind(kind string) string { diff --git a/src/pkg/rotation/rotation_claude_extra_usage_test.go b/src/pkg/rotation/rotation_claude_extra_usage_test.go new file mode 100644 index 0000000000..aea942c6da --- /dev/null +++ b/src/pkg/rotation/rotation_claude_extra_usage_test.go @@ -0,0 +1,156 @@ +package rotation + +import ( + "context" + "encoding/json" + "net/http" + "os" + "path/filepath" + "strings" + "testing" +) + +// claudeLimitsJSON is one plan window, so each case below parses as a valid +// reading and only its extra-usage part varies. +const claudeLimitsJSON = `"limits":[{"kind":"weekly_all","percent":46,"resets_at":"2026-11-23T07:00:00Z","scope":null}]` + +func claudeExtraUsageReading(t *testing.T, extra string) Headroom { + t.Helper() + body := "{" + claudeLimitsJSON + if extra != "" { + body += "," + extra + } + h, err := claudeHeadroom("anthropic", 80, []byte(body+"}")) + if err != nil { + t.Fatalf("claudeHeadroom: %v", err) + } + if len(h.Limits) != 1 { + t.Fatalf("extra usage must not disturb the plan windows: Limits=%+v", h.Limits) + } + return h +} + +// The fixture is shaped like a live /api/oauth/usage response (2026-11-19): +// extra usage on, $0.00 of a $350.00 monthly cap spent, no balance. +func TestClaudeExtraUsageFromLiveShapedFixture(t *testing.T) { + raw, err := os.ReadFile(filepath.Join("testdata", "claude_oauth_usage_extra_usage.json")) + if err != nil { + t.Fatal(err) + } + srv := claudeUsageServer(t, http.StatusOK, string(raw)) + h := ClaudeProber{ThresholdPct: 80, BaseURL: srv.URL, CredentialsPath: claudeCredsFile(t, "test-token")}.Probe(context.Background()) + if h.ProbeErr != nil { + t.Fatalf("ProbeErr = %v", h.ProbeErr) + } + if len(h.Limits) != 2 || h.PctRemaining != 54 { + t.Fatalf("plan windows changed: PctRemaining=%d Limits=%+v", h.PctRemaining, h.Limits) + } + eu := h.ExtraUsage + if eu == nil { + t.Fatal("ExtraUsage = nil, want the spend reading") + } + if eu.Enabled == nil || !*eu.Enabled { + t.Errorf("Enabled = %v, want true", eu.Enabled) + } + if eu.UsedMinor == nil || *eu.UsedMinor != 0 { + t.Errorf("UsedMinor = %v, want 0 (stated, not unknown)", eu.UsedMinor) + } + if eu.LimitMinor == nil || *eu.LimitMinor != 35000 { + t.Errorf("LimitMinor = %v, want 35000", eu.LimitMinor) + } + if eu.Exponent != 2 || eu.Currency != "USD" { + t.Errorf("Exponent/Currency = %d/%q, want 2/USD", eu.Exponent, eu.Currency) + } + if eu.SpendLimitReached == nil || *eu.SpendLimitReached { + t.Errorf("SpendLimitReached = %v, want false", eu.SpendLimitReached) + } + if h.PaidCreditsAvailable == nil || !*h.PaidCreditsAvailable { + t.Errorf("PaidCreditsAvailable = %v, want true from the enabled flag", h.PaidCreditsAvailable) + } + out, err := json.Marshal(h) + if err != nil { + t.Fatal(err) + } + want := `"extra_usage":{"enabled":true,"used_minor":0,"limit_minor":35000,"exponent":2,"currency":"USD","spend_limit_reached":false}` + if !strings.Contains(string(out), want) { + t.Errorf("headroom JSON missing %s:\n%s", want, out) + } +} + +func TestClaudeExtraUsageDisabled(t *testing.T) { + h := claudeExtraUsageReading(t, `"spend":{"enabled":false,"used":null,"limit":null},"extra_usage":{"is_enabled":false,"monthly_limit":null,"used_credits":null}`) + if h.ExtraUsage == nil || h.ExtraUsage.Enabled == nil || *h.ExtraUsage.Enabled { + t.Fatalf("ExtraUsage = %+v, want enabled=false", h.ExtraUsage) + } + if h.ExtraUsage.UsedMinor != nil || h.ExtraUsage.LimitMinor != nil { + t.Errorf("null amounts must stay nil, got used=%v limit=%v", h.ExtraUsage.UsedMinor, h.ExtraUsage.LimitMinor) + } + if h.PaidCreditsAvailable == nil || *h.PaidCreditsAvailable { + t.Errorf("PaidCreditsAvailable = %v, want false", h.PaidCreditsAvailable) + } +} + +func TestClaudeExtraUsageLimitReached(t *testing.T) { + h := claudeExtraUsageReading(t, `"spend":{"enabled":true,"used":{"amount_minor":35000,"currency":"USD","exponent":2},"limit":{"amount_minor":35000,"currency":"USD","exponent":2}},"extra_usage":{"is_enabled":true,"spend_limit_reached":true}`) + eu := h.ExtraUsage + if eu == nil || eu.SpendLimitReached == nil || !*eu.SpendLimitReached { + t.Fatalf("ExtraUsage = %+v, want spend_limit_reached=true", eu) + } + if *eu.UsedMinor != 35000 || *eu.LimitMinor != 35000 { + t.Errorf("used/limit = %d/%d, want 35000/35000", *eu.UsedMinor, *eu.LimitMinor) + } +} + +// A response without spend or extra_usage (the older schema, and the +// original fixture) leaves every extra-usage field unknown: nil, never 0/off. +func TestClaudeExtraUsageAbsentStaysNil(t *testing.T) { + for name, extra := range map[string]string{ + "absent": "", + "null": `"spend":null,"extra_usage":null`, + "empty": `"spend":{},"extra_usage":{}`, + "all nulls": `"spend":{"enabled":null,"used":null,"limit":null},"extra_usage":{"is_enabled":null,"monthly_limit":null,"used_credits":null,"spend_limit_reached":null}`, + "wrong types": `"spend":"on","extra_usage":["x"]`, + } { + t.Run(name, func(t *testing.T) { + h := claudeExtraUsageReading(t, extra) + if h.ExtraUsage != nil { + t.Errorf("ExtraUsage = %+v, want nil", h.ExtraUsage) + } + if h.PaidCreditsAvailable != nil { + t.Errorf("PaidCreditsAvailable = %v, want nil", *h.PaidCreditsAvailable) + } + out, _ := json.Marshal(h) + if strings.Contains(string(out), "extra_usage") { + t.Errorf("headroom JSON names extra_usage with nothing reported:\n%s", out) + } + }) + } + raw, err := os.ReadFile(filepath.Join("testdata", "claude_oauth_usage.json")) + if err != nil { + t.Fatal(err) + } + h, err := claudeHeadroom("anthropic", 80, raw) + if err != nil || h.ExtraUsage != nil { + t.Fatalf("old-schema fixture: err=%v ExtraUsage=%+v, want nil", err, h.ExtraUsage) + } +} + +// Without spend, the amounts come from extra_usage (cents, decimal_places). +// A malformed spend object is ignored rather than failing the reading. +func TestClaudeExtraUsageFallsBackToExtraUsageObject(t *testing.T) { + for name, spend := range map[string]string{ + "no spend": "", + "malformed spend": `"spend":{"used":"lots"},`, + } { + t.Run(name, func(t *testing.T) { + h := claudeExtraUsageReading(t, spend+`"extra_usage":{"is_enabled":true,"monthly_limit":35000,"used_credits":1234.0,"currency":"USD","decimal_places":2,"spend_limit_reached":false}`) + eu := h.ExtraUsage + if eu == nil || eu.Enabled == nil || !*eu.Enabled { + t.Fatalf("ExtraUsage = %+v, want enabled", eu) + } + if eu.UsedMinor == nil || *eu.UsedMinor != 1234 || eu.LimitMinor == nil || *eu.LimitMinor != 35000 || eu.Exponent != 2 || eu.Currency != "USD" { + t.Errorf("ExtraUsage = %+v, want 1234 of 35000 cents USD", eu) + } + }) + } +} diff --git a/src/pkg/rotation/testdata/README.md b/src/pkg/rotation/testdata/README.md index 60ec306a3e..0d5d19cc34 100644 --- a/src/pkg/rotation/testdata/README.md +++ b/src/pkg/rotation/testdata/README.md @@ -56,6 +56,14 @@ available it should replace this file. The adapter's behaviour on an unrecognized schema (an empty/percent-less `limits` array) is pinned separately by `TestClaudeHeadroomRejectsUnrecognizedSchema`. +`claude_oauth_usage_extra_usage.json` is shaped like a live response from the +same endpoint (shape captured from a live response 2026-11-19, read-only; +identifiers dropped, and the many feature keys that came back null are left +out). Next to `limits` it carries the `extra_usage` and `spend` objects the +prober reads for Claude's extra usage (usage credits): enabled, $0.00 used of a +$350.00 monthly cap, in minor units with an exponent. `spend.balance` was null +and no field reported banked limit resets, so neither is read. + # Agy usage fixture `agy_usage.json` is a **real recorded payload** of diff --git a/src/pkg/rotation/testdata/claude_oauth_usage_extra_usage.json b/src/pkg/rotation/testdata/claude_oauth_usage_extra_usage.json new file mode 100644 index 0000000000..036276a9dd --- /dev/null +++ b/src/pkg/rotation/testdata/claude_oauth_usage_extra_usage.json @@ -0,0 +1,38 @@ +{ + "five_hour": null, + "seven_day": {"utilization": 46.0, "resets_at": "2026-11-23T07:00:00.786379+00:00"}, + "limits": [ + {"kind": "weekly_all", "group": "weekly", "percent": 46, "severity": "normal", "resets_at": "2026-11-23T07:00:00.786379+00:00", "scope": null, "is_active": true}, + {"kind": "weekly_scoped", "group": "weekly", "percent": 0, "severity": "normal", "resets_at": "2026-11-23T07:00:00+00:00", "scope": {"model": {"id": null, "display_name": "Fable"}, "surface": null}, "is_active": false} + ], + "extra_usage": { + "is_enabled": true, + "monthly_limit": 35000, + "used_credits": 0.0, + "utilization": null, + "currency": "USD", + "decimal_places": 2, + "disabled_reason": null, + "user_disabled": false, + "spend_limit_reached": false, + "credits_ever_enabled": true, + "daily": null, + "weekly": null + }, + "spend": { + "used": {"amount_minor": 0, "currency": "USD", "exponent": 2}, + "limit": {"amount_minor": 35000, "currency": "USD", "exponent": 2}, + "percent": 0, + "severity": "normal", + "enabled": true, + "disabled_reason": null, + "cap": {"money": null, "credits": {"amount_minor": 35000, "exponent": 2}}, + "balance": null, + "auto_reload": null, + "disclaimer": "Usage credits cover you when you hit your plan limits. [Learn more](https://support.claude.com/articles/12429409)", + "can_purchase_credits": false, + "can_toggle": false + }, + "promo_credits": null, + "member_dashboard_available": false +}