usage: Claude's card shows the extra-usage cap and its spend (Shinji_Zl on X)
Claude Code's `claude -p /usage` text omits extra usage, but with `--output-format json --verbose` a message carries usage_report.rate_limits.extra_usage (cap and spend in cents). The gateway adds it as a line; parseClaudeUsage reads it as an Aside "Usage credits" window (n / cap USD), so a spent cap never marks the account used up. magpie asks Anthropic nothing itself, and cannot make a request spend credits: Anthropic decides. The prepaid balance is a separate endpoint and is not shown. Run (wsl-run, linux): TestClaudeUsage*/TestClaudeOverage in provider and gateway, go vet linux/windows/darwin, i18n-keys, i18n-en-no-cjk and claude-overages GUI files (chromium + webkit). Broken by hand: Aside false -> TestClaudeUsageCredits red. Not tried: a real account with extra usage on (the owner's is off); full suite after the tag; Windows run.
This commit is contained in:
@@ -589,6 +589,17 @@ interactive, so its `/usage` asks the usage endpoint alone
|
||||
setup-token, which magpie never reads, or an API key) gets the session's
|
||||
cost instead. `TestClaudeUsageStartsNoInteractiveRun` holds it.
|
||||
|
||||
The text omits the extra-usage cap. The same run prints `--output-format
|
||||
json --verbose` (`claudeUsageArgs`), whose messages carry
|
||||
`usage_report.rate_limits.extra_usage` (cap and spend in cents);
|
||||
`claudeExtraUsage` turns an enabled one with a cap into one more line
|
||||
(`provider.ClaudeExtraLine`), read as the "Usage credits" window: an
|
||||
`Aside` row with the month's spend over the cap, which never marks the
|
||||
account used up. It is not the prepaid balance (a separate endpoint magpie
|
||||
does not call), and only Anthropic decides whether a request spends it
|
||||
(X, Shinji_Zl). Tried against fakes only; the owner's account has extra
|
||||
usage off.
|
||||
|
||||
A turn's run (`claudeRunEnv`) is not given
|
||||
`CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, which the one-off runs above
|
||||
keep (`cleanClaudeEnv`). With it, or `DISABLE_TELEMETRY` or
|
||||
|
||||
@@ -224,7 +224,7 @@ func claudeUsage(ctx context.Context, configDir string) (string, error) {
|
||||
if res.IsError {
|
||||
return "", errors.New("Claude Code: " + clip(res.Result))
|
||||
}
|
||||
return res.Result, nil
|
||||
return res.Result + claudeExtraUsage(out.Bytes()), nil
|
||||
}
|
||||
msg := strings.TrimSpace(stderr.String())
|
||||
if msg == "" {
|
||||
@@ -236,6 +236,43 @@ func claudeUsage(ctx context.Context, configDir string) (string, error) {
|
||||
return "", errors.New("Claude Code: " + clip(msg))
|
||||
}
|
||||
|
||||
// claudeExtraUsage is the line (provider.ClaudeExtraLine) for the extra
|
||||
// usage, Anthropic's usage credits, an account has on and a monthly cap
|
||||
// for, from the usage_report Claude Code's verbose json carries with its
|
||||
// /usage; "" when out has none, as from a Claude Code that sends none.
|
||||
func claudeExtraUsage(out []byte) string {
|
||||
var all []struct {
|
||||
Report *struct {
|
||||
Limits *struct {
|
||||
Extra *struct {
|
||||
On bool `json:"is_enabled"`
|
||||
Limit *float64 `json:"monthly_limit"`
|
||||
Used *float64 `json:"used_credits"`
|
||||
Currency string `json:"currency"`
|
||||
} `json:"extra_usage"`
|
||||
} `json:"rate_limits"`
|
||||
} `json:"usage_report"`
|
||||
}
|
||||
if json.Unmarshal(out, &all) != nil {
|
||||
return ""
|
||||
}
|
||||
for _, m := range all {
|
||||
if m.Report == nil || m.Report.Limits == nil || m.Report.Limits.Extra == nil {
|
||||
continue
|
||||
}
|
||||
x := m.Report.Limits.Extra
|
||||
if !x.On || x.Limit == nil || *x.Limit <= 0 {
|
||||
return ""
|
||||
}
|
||||
used := 0.0
|
||||
if x.Used != nil {
|
||||
used = *x.Used
|
||||
}
|
||||
return "\n" + provider.ClaudeExtraLine(used, *x.Limit, x.Currency)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// claudeUsageEnv is the environment a /usage read runs Claude Code in:
|
||||
// CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC makes /usage skip its request
|
||||
// and show only a reading another run left in the last hour, so it stays
|
||||
@@ -471,6 +508,9 @@ const disableDeepLinkSettings = `{"disableDeepLinkRegistration":"disable"}`
|
||||
|
||||
func claudeUsageArgs() []string {
|
||||
return []string{"-p", "/usage", "--output-format", "json",
|
||||
// verbose: the array of every message, whose usage_report holds
|
||||
// the extra usage (claudeExtraUsage); claudeResult reads it
|
||||
"--verbose",
|
||||
"--tools", "", "--strict-mcp-config", "--setting-sources", "", "--settings", disableDeepLinkSettings, "--no-session-persistence"}
|
||||
}
|
||||
|
||||
|
||||
@@ -127,6 +127,36 @@ func TestClaudeUsageRunsClaudeCode(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Claude Code's -p /usage prints no figure for extra usage (usage
|
||||
// credits), but its verbose json carries a usage_report with the month's cap
|
||||
// and spend (Shinji_Zl on X). The read adds them as a line for the card, and
|
||||
// adds none for an account with it off, no cap, or a Claude Code that sends
|
||||
// no report.
|
||||
func TestClaudeUsageCredits(t *testing.T) {
|
||||
text := "Current session: 13% used · resets 4pm (Asia/Shanghai)"
|
||||
msgs := func(extra string) string {
|
||||
report := ``
|
||||
if extra != "" {
|
||||
report = `,"usage_report":{"rate_limits":{"limits":null,"extra_usage":` + extra + `}}`
|
||||
}
|
||||
return `[{"type":"system","subtype":"init"},{"type":"assistant"` + report + `},{"type":"result","is_error":false,"result":"` + text + `"}]`
|
||||
}
|
||||
for _, c := range []struct{ name, extra, want string }{
|
||||
{"on", `{"is_enabled":true,"monthly_limit":50000,"used_credits":27140,"utilization":54,"currency":"USD"}`, "\nExtra usage: 271.40 / 500.00 USD spent"},
|
||||
{"unused", `{"is_enabled":true,"monthly_limit":2000,"used_credits":null,"utilization":null,"currency":"USD"}`, "\nExtra usage: 0.00 / 20.00 USD spent"},
|
||||
{"off", `{"is_enabled":false,"monthly_limit":null,"used_credits":null,"utilization":null,"currency":null}`, ""},
|
||||
{"no cap", `{"is_enabled":true,"monthly_limit":null,"used_credits":100,"utilization":null,"currency":"USD"}`, ""},
|
||||
{"no report", "", ""},
|
||||
} {
|
||||
fakeWarmClaude(t, msgs(c.extra), 0)
|
||||
got, err := claudeUsage(context.Background(), "")
|
||||
want := text + c.want
|
||||
if err != nil || got != want {
|
||||
t.Errorf("%s: usage %q %v, want %q", c.name, got, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// /usage runs without CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC, which keeps
|
||||
// Claude Code from asking for the usage, unless the user set it; telemetry,
|
||||
// error reporting and autoupdate stay off. The warm-up keeps it.
|
||||
|
||||
@@ -2318,6 +2318,7 @@ const I18N = {
|
||||
"Droid Core · 7 days": "Droid Core · 7 天",
|
||||
"Droid Core · 30 days": "Droid Core · 30 天",
|
||||
"Extra usage": "额外用量",
|
||||
"Usage credits": "额外用量额度",
|
||||
"Gift plans to claim in the ZCode app": "待在 ZCode 客户端领取的赠送额度",
|
||||
"ZCode gift plans (-Trial models) need ZCode's sign-in": "ZCode 赠送额度(-Trial 模型)需要 ZCode 登录",
|
||||
"ZCode gift plan not started yet": "尚未生效的 ZCode 赠送额度",
|
||||
@@ -7349,6 +7350,7 @@ const I18N = {
|
||||
"Droid Core · 7 days": "Droid Core · 7 天",
|
||||
"Droid Core · 30 days": "Droid Core · 30 天",
|
||||
"Extra usage": "額外用量",
|
||||
"Usage credits": "額外用量額度",
|
||||
"Gift plans to claim in the ZCode app": "待在 ZCode 用戶端領取的贈送額度",
|
||||
"ZCode gift plans (-Trial models) need ZCode's sign-in": "ZCode 贈送額度(-Trial 模型)需要 ZCode 登入",
|
||||
"ZCode gift plan not started yet": "尚未生效的 ZCode 贈送額度",
|
||||
@@ -12356,6 +12358,7 @@ const I18N = {
|
||||
"Droid Core · 7 days": "Droid Core · 7日",
|
||||
"Droid Core · 30 days": "Droid Core · 30日",
|
||||
"Extra usage": "追加使用量",
|
||||
"Usage credits": "追加使用量のクレジット",
|
||||
"Gift plans to claim in the ZCode app": "ZCode アプリで受け取れるギフト枠",
|
||||
"ZCode gift plans (-Trial models) need ZCode's sign-in": "ZCode のギフト枠(-Trial モデル)には ZCode でのサインインが必要",
|
||||
"ZCode gift plan not started yet": "開始前の ZCode ギフト枠",
|
||||
@@ -17394,6 +17397,7 @@ const I18N = {
|
||||
"Droid Core · 7 days": "Droid Core · 7 Tage",
|
||||
"Droid Core · 30 days": "Droid Core · 30 Tage",
|
||||
"Extra usage": "Zusätzliche Nutzung",
|
||||
"Usage credits": "Nutzungsguthaben",
|
||||
"Gift plans to claim in the ZCode app": "In der ZCode-App abzuholen",
|
||||
"ZCode gift plans (-Trial models) need ZCode's sign-in": "ZCode-Geschenkpläne (-Trial-Modelle) brauchen die ZCode-Anmeldung",
|
||||
"ZCode gift plan not started yet": "ZCode-Geschenkplan, noch nicht aktiv",
|
||||
|
||||
@@ -7,6 +7,8 @@ package provider
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
@@ -114,6 +116,43 @@ var claudeUsageCounts = lazyre.New(`(?: · )?Last [0-9]+[a-z]+ · [0-9][0-9,]* r
|
||||
// with other accounts that had room (StringKe, #4532).
|
||||
var claudeOverages = lazyre.New(`(?i)using your overages`)
|
||||
|
||||
// claudeExtraLineRE is the line the gateway adds under /usage's text for an
|
||||
// account with extra usage on ("usage credits"): Claude Code's -p /usage
|
||||
// prints no figure for it, but the usage_report it carries (verbose json)
|
||||
// has the month's cap and spend, which Claude Code read from Anthropic, so
|
||||
// magpie asks Anthropic nothing. "Extra usage: 271.40 / 500.00 USD spent".
|
||||
// ClaudeExtraLine writes it.
|
||||
var claudeExtraLineRE = lazyre.New(`^Extra usage: ([0-9.]+) / ([0-9.]+) ([A-Za-z]{3}) spent$`)
|
||||
|
||||
// ClaudeExtraLine is the line for spent and limit, in cents of currency.
|
||||
func ClaudeExtraLine(spent, limit float64, currency string) string {
|
||||
if currency == "" {
|
||||
currency = "USD"
|
||||
}
|
||||
return fmt.Sprintf("Extra usage: %.2f / %.2f %s spent", spent/100, limit/100, strings.ToUpper(currency))
|
||||
}
|
||||
|
||||
// claudeExtraWindow reads that line, when text has it: the month's spend of
|
||||
// the cap set aside (Aside), so a cap spent never stops the account the way
|
||||
// a plan window used up does: only Anthropic decides whether a request
|
||||
// spends it.
|
||||
func claudeExtraWindow(lines []string) (QuotaWindow, bool) {
|
||||
for _, line := range lines {
|
||||
m := claudeExtraLineRE.FindStringSubmatch(strings.TrimSpace(line))
|
||||
if m == nil {
|
||||
continue
|
||||
}
|
||||
spent, err1 := strconv.ParseFloat(m[1], 64)
|
||||
limit, err2 := strconv.ParseFloat(m[2], 64)
|
||||
if err1 != nil || err2 != nil || limit <= 0 {
|
||||
continue
|
||||
}
|
||||
return QuotaWindow{Name: "Usage credits", Used: math.Min(100, spent/limit*100), Aside: true,
|
||||
Amount: spent, Limit: limit, Unit: strings.ToUpper(m[3])}, true
|
||||
}
|
||||
return QuotaWindow{}, false
|
||||
}
|
||||
|
||||
// claudeOveragesWindow is the window an account on overages is read with,
|
||||
// beside ws: spent (usedPast, roomLeft), so the switch moves Claude Code
|
||||
// off it as off one whose window is used up, and told as its text. It
|
||||
@@ -210,6 +249,9 @@ func parseClaudeUsage(text string, now time.Time) ([]QuotaWindow, error) {
|
||||
}
|
||||
return out, errors.New("Claude Code's /usage showed no usage figures: " + clipReason(strings.Join(said, " · ")))
|
||||
}
|
||||
if w, ok := claudeExtraWindow(lines); ok {
|
||||
out = append(out, w)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Shinji_Zl on X asked for Claude's prepaid credits on its usage card, as
|
||||
// Codex's are. Claude Code's /usage prints none, but the usage_report it
|
||||
// carries has the month's spend of the extra-usage cap, which the gateway
|
||||
// adds as a line (ClaudeExtraLine). The card shows it set aside from the
|
||||
// plan's windows: a cap spent never marks the account used up, as Anthropic
|
||||
// alone decides what a request spends.
|
||||
func TestClaudeUsageCredits(t *testing.T) {
|
||||
now := time.Date(2026, 11, 11, 13, 0, 0, 0, time.UTC)
|
||||
base := "Current session: 10% used · resets 3pm (UTC)\nCurrent week (all models): 20% used · resets Nov 17 at 11am (UTC)\n"
|
||||
ws, err := parseClaudeUsage(base+"\n"+ClaudeExtraLine(27140, 50000, "USD"), now)
|
||||
if err != nil || len(ws) != 3 {
|
||||
t.Fatalf("windows %+v %v", ws, err)
|
||||
}
|
||||
x := ws[2]
|
||||
if x.Name != "Usage credits" || !x.Aside || x.Text || x.Amount != 271.4 || x.Limit != 500 || x.Unit != "USD" || x.Used < 54 || x.Used > 55 {
|
||||
t.Fatalf("credits row: %+v", x)
|
||||
}
|
||||
// spent to its cap, it is not the account spent
|
||||
ws, err = parseClaudeUsage(base+ClaudeExtraLine(50000, 50000, "usd"), now)
|
||||
if err != nil || len(ws) != 3 || ws[2].Used != 100 || ws[2].Unit != "USD" {
|
||||
t.Fatalf("spent cap: %+v %v", ws, err)
|
||||
}
|
||||
if usedUp(SubscriptionQuota{Windows: ws}, now) || usedPast(SubscriptionQuota{Windows: ws}, 98, now) {
|
||||
t.Fatal("a spent extra-usage cap read as the account used up")
|
||||
}
|
||||
// none said, none shown
|
||||
if ws, _ := parseClaudeUsage(base, now); len(ws) != 2 {
|
||||
t.Fatalf("windows without credits: %+v", ws)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user