diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index 48f7a3de8..bfcf2a5f7 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -761,6 +761,28 @@ 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. +The text draws the session and the weeks from the endpoint's `five_hour` +and `seven_day` fields, and from `limits[]` only the rows of kind +`weekly_scoped` with a model. The same `usage_report.rate_limits.limits` +carries every row as the server sent it (`kind` `session`, `weekly_all` +or `weekly_scoped`, `percent` 0-100, `resets_at` ISO 8601). When the text +drew no window, `claudeExtraUsage` adds each such row as /usage's own +line (the reset as written, which `claudeResetTime` reads), and an empty +`limits` (the server reported no meters) as +`provider.ClaudeNoLimitsLine`, read as a text row "5-hour and weekly +limits: None on this plan". `limits: null`, or `rate_limits: null` (the +fetch failed, or the token lacks the profile scope), adds nothing, and +the subscription line alone still reads as "temporarily unavailable" +(`errClaudeUsageUnavailable`), unless what Claude Code saved of the +account's organization (`.claude.json` `oauthAccount`) names a seat it +holds no rate limits for: `seatTier` `enterprise_usage_based` or +`billingType` `usage_based` (Claude Code's `vmr` and `fD`, +`claudeUsageBased`). A Claude Enterprise seat read as "temporarily +unavailable" before (@andy_chen1997 on X). Built from Claude Code +2.1.328's schema and handling; no Enterprise account was tried +(`TestClaudeUsageRows`, `TestClaudeEnterpriseUsage`, +`TestClaudeUsageBasedSeat`). + 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 diff --git a/internal/gateway/claude_warmup.go b/internal/gateway/claude_warmup.go index deb9318b9..4d6b0640e 100644 --- a/internal/gateway/claude_warmup.go +++ b/internal/gateway/claude_warmup.go @@ -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 + claudeExtraUsage(out.Bytes()), nil + return res.Result + claudeExtraUsage(out.Bytes(), res.Result), nil } msg := strings.TrimSpace(stderr.String()) if msg == "" { @@ -236,14 +236,29 @@ 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 { +// claudeExtraUsage is what the gateway adds under -p /usage's text from +// the usage_report Claude Code's verbose json carries (Claude Code's own +// read of Anthropic's usage endpoint, so magpie asks Anthropic nothing): +// +// - the month's extra usage (usage credits), which the text has no +// figure for (provider.ClaudeExtraLine); +// - the server's usage rows (limits[]), as /usage's own lines, when the +// text drew none: the text draws the session and week from the +// endpoint's five_hour and seven_day, and an account whose meters come +// only as rows (a Claude Enterprise seat, @andy_chen1997 on X) read as +// "temporarily unavailable" while the report held its 5 hours; +// - provider.ClaudeNoLimitsLine when the server reported no meters at +// all (limits: [], Claude Code's "the server reported no meters"): a +// plan without 5-hour or weekly limits, never a passing failure. A +// null limits or rate_limits says nothing: a server that predates the +// rows, or a fetch that failed. +func claudeExtraUsage(out []byte, text string) string { var all []struct { Report *struct { Limits *struct { + // as written: a row of another shape costs its rows, + // never the extra usage beside them + Rows json.RawMessage `json:"limits"` Extra *struct { On bool `json:"is_enabled"` Limit *float64 `json:"monthly_limit"` @@ -257,22 +272,87 @@ func claudeExtraUsage(out []byte) string { return "" } for _, m := range all { - if m.Report == nil || m.Report.Limits == nil || m.Report.Limits.Extra == nil { + if m.Report == nil || m.Report.Limits == nil { continue } - x := m.Report.Limits.Extra - if !x.On || x.Limit == nil || *x.Limit <= 0 { - return "" + var add strings.Builder + var rows []claudeLimitRow + if json.Unmarshal(m.Report.Limits.Rows, &rows) == nil && rows != nil && !claudeTextHasWindow(text) { + for _, row := range rows { + if line := row.line(); line != "" { + add.WriteString("\n" + line) + } + } + if len(rows) == 0 { + add.WriteString("\n" + provider.ClaudeNoLimitsLine) + } } - used := 0.0 - if x.Used != nil { - used = *x.Used + if x := m.Report.Limits.Extra; x != nil && x.On && x.Limit != nil && *x.Limit > 0 { + used := 0.0 + if x.Used != nil { + used = *x.Used + } + add.WriteString("\n" + provider.ClaudeExtraLine(used, *x.Limit, x.Currency)) } - return "\n" + provider.ClaudeExtraLine(used, *x.Limit, x.Currency) + return add.String() } return "" } +// claudeLimitRow is one of the usage endpoint's limits[] rows as Claude +// Code's usage_report carries them (2.1.328's schema): kind is the +// server's meter ("session", "weekly_all", "weekly_scoped"), percent is +// 0-100 and resets_at ISO 8601. +type claudeLimitRow struct { + Kind string `json:"kind"` + Percent *float64 `json:"percent"` + ResetsAt *string `json:"resets_at"` + Scope *struct { + Model *struct { + Name string `json:"display_name"` + } `json:"model"` + } `json:"scope"` +} + +// line is the row as /usage's text would say it, "" for a row it draws +// none for: a meter of no known kind, one with no reading, or one scoped +// to a surface rather than a model (Claude Code's text leaves those out +// too). +func (r claudeLimitRow) line() string { + if r.Percent == nil { + return "" + } + var head string + switch r.Kind { + case "session": + head = "Current session" + case "weekly_all": + head = "Current week (all models)" + case "weekly_scoped": + if r.Scope == nil || r.Scope.Model == nil || strings.TrimSpace(r.Scope.Model.Name) == "" || strings.ContainsAny(r.Scope.Model.Name, "()") { + return "" + } + head = "Current week (" + strings.TrimSpace(r.Scope.Model.Name) + ")" + default: + return "" + } + line := head + ": " + strconv.FormatFloat(*r.Percent, 'f', -1, 64) + "% used" + if r.ResetsAt != nil && *r.ResetsAt != "" { + line += " · resets " + *r.ResetsAt + } + return line +} + +// claudeTextHasWindow says /usage's text drew a window of its own. +func claudeTextHasWindow(text string) bool { + for _, line := range strings.Split(text, "\n") { + if l := strings.TrimSpace(line); strings.HasPrefix(l, "Current session:") || strings.HasPrefix(l, "Current week") { + return true + } + } + return false +} + // 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 diff --git a/internal/gateway/claude_warmup_test.go b/internal/gateway/claude_warmup_test.go index 0cf3f8c0f..381c8b8bf 100644 --- a/internal/gateway/claude_warmup_test.go +++ b/internal/gateway/claude_warmup_test.go @@ -157,6 +157,41 @@ func TestClaudeUsageCredits(t *testing.T) { } } +// A Claude Enterprise seat's -p /usage printed only the subscription line +// (@andy_chen1997 on X): its meters came as the usage endpoint's rows +// (limits[]), which Claude Code's text doesn't draw. The read adds them as +// /usage's own lines; a report of no meters ([]) as the plan having none; +// a null one, a fetch that failed or a server before rows, adds nothing. +// The rows follow Claude Code 2.1.328's usage_report schema; no Enterprise +// account was at hand. +func TestClaudeUsageRows(t *testing.T) { + const sub = "You are currently using your subscription to power your Claude Code usage" + msgs := func(text, limits string) string { + return `[{"type":"system","subtype":"init"},{"type":"assistant","usage_report":{"rate_limits":` + limits + `}},{"type":"result","is_error":false,"result":"` + text + `"}]` + } + rows := `{"limits":[` + + `{"kind":"session","group":"session","percent":37.5,"resets_at":"2026-11-19T15:00:00.000Z","scope":null,"severity":"normal","is_active":true},` + + `{"kind":"weekly_scoped","group":"weekly","percent":4,"resets_at":null,"scope":{"model":{"display_name":"Fable"}}},` + + `{"kind":"weekly_scoped","group":"weekly","percent":9,"resets_at":null,"scope":{"surface":{"display_name":"Claude Design"}}},` + + `{"kind":"new_meter","group":"x","percent":50,"resets_at":null}` + + `],"extra_usage":null}` + for _, c := range []struct{ name, text, limits, want string }{ + {"rows", sub, rows, "\nCurrent session: 37.5% used · resets 2026-11-19T15:00:00.000Z\nCurrent week (Fable): 4% used"}, + {"text drew its own", "Current session: 13% used", rows, ""}, + {"no meters", sub, `{"limits":[],"extra_usage":null}`, "\n" + provider.ClaudeNoLimitsLine}, + {"no meters, credits", sub, `{"limits":[],"extra_usage":{"is_enabled":true,"monthly_limit":50000,"used_credits":100,"currency":"USD"}}`, "\n" + provider.ClaudeNoLimitsLine + "\nExtra usage: 1.00 / 500.00 USD spent"}, + {"a row of another shape", sub, `{"limits":[{"kind":"session","percent":"most"}],"extra_usage":{"is_enabled":true,"monthly_limit":50000,"used_credits":100,"currency":"USD"}}`, "\nExtra usage: 1.00 / 500.00 USD spent"}, + {"rows unknown", sub, `{"limits":null,"extra_usage":null}`, ""}, + {"fetch failed", sub, `null`, ""}, + } { + fakeWarmClaude(t, msgs(c.text, c.limits), 0) + got, err := claudeUsage(context.Background(), "") + if want := c.text + c.want; 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. diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 22d44bfab..abfdbad30 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2369,6 +2369,8 @@ const I18N = { "Stop using this account": "停用这个账号", "Use this account too": "同时启用这个账号", "No allowance reported": "暂无额度数据", + "5-hour and weekly limits": "5 小时和每周额度", + "None on this plan": "此套餐没有", "Switched off, so no allowance is read — switch it on and refresh": "已关闭,不读取额度 — 打开开关后再刷新", "No plan": "无订阅", "resets {in}": "{in}重置", @@ -7867,6 +7869,8 @@ const I18N = { "Stop using this account": "停用這個帳號", "Use this account too": "同時啟用這個帳號", "No allowance reported": "暫無額度資料", + "5-hour and weekly limits": "5 小時與每週額度", + "None on this plan": "此方案沒有", "Switched off, so no allowance is read — switch it on and refresh": "已關閉,不讀取額度 — 開啟開關後再重新整理", "No plan": "無訂閱", "resets {in}": "{in}重置", @@ -13334,6 +13338,8 @@ const I18N = { "Stop using this account": "このアカウントの使用を停止", "Use this account too": "このアカウントも使用", "No allowance reported": "利用枠の情報なし", + "5-hour and weekly limits": "5 時間と週間の利用枠", + "None on this plan": "このプランにはなし", "Switched off, so no allowance is read — switch it on and refresh": "オフのため利用枠を読みません — オンにして更新してください", "No plan": "プランなし", "resets {in}": "{in}にリセット", @@ -18844,6 +18850,8 @@ const I18N = { "Stop using this account": "Dieses Konto nicht mehr verwenden", "Use this account too": "Dieses Konto ebenfalls verwenden", "No allowance reported": "Kein Kontingent gemeldet", + "5-hour and weekly limits": "5-Stunden- und Wochenlimits", + "None on this plan": "Keine in diesem Tarif", "Switched off, so no allowance is read — switch it on and refresh": "Ausgeschaltet, das Kontingent wird nicht gelesen — einschalten und neu laden", "No plan": "Kein Tarif", "resets {in}": "Reset {in}", diff --git a/internal/gui/tests/claude-no-limits.test.cjs b/internal/gui/tests/claude-no-limits.test.cjs new file mode 100644 index 000000000..0b0dfe2e9 --- /dev/null +++ b/internal/gui/tests/claude-no-limits.test.cjs @@ -0,0 +1,89 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// @andy_chen1997 on X: a Claude Enterprise seat's card said "Allowance +// unavailable — hover for why", "Claude Code's /usage is temporarily +// unavailable". A seat whose plan has no 5-hour or weekly limits (Claude +// Code's usage report of no meters, or a usage-based seat) is now a text +// row that says so in the reader's language, not a failed read, beside its +// usage credits when it has them; a seat whose rows hold its 5 hours shows +// them. Every language, at 360 and 1000px, both engines. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const soon = (h) => new Date(Date.now() + h * 3600e3).toISOString(); +const none = { name: "5-hour and weekly limits", used: 0, text: true, aside: true, display: "None on this plan" }; +const card = (user, windows) => ({ provider: "claude", name: "Claude Code", plan: "enterprise", user, windows }); +const quotas = [ + card("a@corp.example", [none]), + card("b@corp.example", [none, { name: "Usage credits", used: 24, aside: true, extra: true, amount: 120, limit: 500, unit: "USD" }]), + card("c@corp.example", [{ name: "5 hours", used: 37.5, resetsAt: soon(2) }]), +]; +function serve(lang) { + const settings = { lang, theme: "light", currency: "usd", chineseUnits: false }; + const state = { agents: [], profiles: [], settings }; + return async (r) => { + const url = new URL(r.request().url()); + const json = (data) => r.fulfill({ json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/settings") return json(settings); + if (url.pathname === "/api/gateway/trace") return url.searchParams.get("wait") ? new Promise(() => {}) : json({ mine: true, now: new Date().toISOString(), seq: 0, totals: {}, routes: [] }); + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); + if (url.pathname === "/api/usage/quotas") return json(quotas); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await r.fulfill({ body: await fs.readFile(file), contentType }); } catch { await r.fulfill({ status: 404, body: "" }); } + }; +} + +const words = { + en: { name: "5-hour and weekly limits", none: "None on this plan", bad: "Allowance unavailable" }, + zh: { name: "5 小时和每周额度", none: "此套餐没有", bad: "暂时无法获取额度" }, + "zh-TW": { name: "5 小時與每週額度", none: "此方案沒有", bad: "暫時無法取得額度" }, + ja: { name: "5 時間と週間の利用枠", none: "このプランにはなし", bad: "利用枠を取得できません" }, + de: { name: "5-Stunden- und Wochenlimits", none: "Keine in diesem Tarif", bad: "Kontingent nicht verfügbar" }, +}; + +for (const [name, engine] of [["webkit", webkit], ["chromium", chromium]]) { + test(`${name}: a Claude plan with no 5-hour or weekly limits says so, not unavailable, in every language, at 360 and 1000px`, async () => { + const browser = await engine.launch(); + try { + for (const [lang, w] of Object.entries(words)) { + for (const width of [360, 1000]) { + const page = await (await browser.newContext({ viewport: { width, height: 1200 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + await page.goto("http://magpie.test/?view=usage"); + await page.locator(".subscription-card .quota").first().waitFor(); + await page.waitForFunction(() => document.body.textContent.includes("c@corp.example")); + const got = await page.evaluate(() => ({ + body: document.body.textContent.replace(/\s+/g, " "), + rows: [...document.querySelectorAll(".subscription-card .quota")].map((q) => q.textContent.replace(/\s+/g, " ").trim()), + pageScroll: document.documentElement.scrollWidth > document.documentElement.clientWidth + 1, + })); + const at = `${lang} ${width}px`; + const said = got.rows.filter((r) => r.includes(w.name) && r.includes(w.none)); + assert.equal(said.length, 2, `${at}: rows ${JSON.stringify(got.rows)}`); + assert.ok(!got.body.includes(w.bad), `${at}: a plan with no limits read as unavailable`); + assert.ok(!said.some((r) => /\d%/.test(r)), `${at}: no limits read as a share ${JSON.stringify(said)}`); + assert.ok(got.rows.some((r) => /24\s?%/.test(r)), `${at}: usage credits beside it ${JSON.stringify(got.rows)}`); + assert.ok(got.rows.some((r) => /37[.,]5\s?%/.test(r)), `${at}: the rows' 5 hours ${JSON.stringify(got.rows)}`); + assert.equal(got.pageScroll, false, `${at}: the page scrolls sideways`); + assert.deepEqual(errors, [], at); + await page.close(); + } + } + } finally { await browser.close(); } + }); +} diff --git a/internal/provider/claude_enterprise_usage_test.go b/internal/provider/claude_enterprise_usage_test.go new file mode 100644 index 000000000..6fc1a6c4b --- /dev/null +++ b/internal/provider/claude_enterprise_usage_test.go @@ -0,0 +1,90 @@ +package provider + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" + "time" +) + +// @andy_chen1997 on X signed a Claude Enterprise seat in, and the card +// said Claude Code's /usage was "temporarily unavailable": -p /usage +// printed only the subscription line. Claude Code 2.1.328 draws its text +// from the usage endpoint's five_hour and seven_day, while the rows it +// carries in usage_report (limits[]) can hold the seat's 5 hours alone; +// the gateway adds those as /usage's own lines, the reset as written +// (ISO 8601). No Enterprise account was at hand: the fixtures follow +// Claude Code's schema (GPi) and its handling (Y, S, xNr, vmr, fD). +func TestClaudeEnterpriseUsage(t *testing.T) { + now := time.Date(2026, 11, 19, 13, 0, 0, 0, time.UTC) + const sub = "You are currently using your subscription to power your Claude Code usage" + + // the rows' 5 hours + ws, err := parseClaudeUsage(sub+"\nCurrent session: 37.5% used · resets 2026-11-19T15:00:00.000Z", now) + if err != nil || len(ws) != 1 { + t.Fatalf("rows' session: %+v %v", ws, err) + } + if w := ws[0]; w.Name != "5 hours" || w.Used != 37.5 || w.ResetsAt == nil || !w.ResetsAt.Equal(now.Add(2*time.Hour)) { + t.Fatalf("rows' session window: %+v", w) + } + + // the server reported no meters: a plan without them, no error + for _, text := range []string{sub + "\n" + ClaudeNoLimitsLine, sub + "\n" + ClaudeNoLimitsLine + "\n" + ClaudeExtraLine(1200, 50000, "USD")} { + ws, err := parseClaudeUsage(text, now) + if err != nil || len(ws) == 0 { + t.Fatalf("no meters: %+v %v", ws, err) + } + if w := ws[0]; !w.Text || !w.Aside || w.Display != "None on this plan" { + t.Fatalf("no meters window: %+v", w) + } + if usedUp(SubscriptionQuota{Windows: ws}, now) || usedPast(SubscriptionQuota{Windows: ws}, 98, now) { + t.Fatal("a plan with no limits read as used up") + } + } + if ws, _ := parseClaudeUsage(sub+"\n"+ClaudeNoLimitsLine+"\n"+ClaudeExtraLine(1200, 50000, "USD"), now); len(ws) != 2 || ws[1].Name != "Usage credits" { + t.Fatalf("no meters with usage credits: %+v", ws) + } + + // the subscription line alone, the report saying nothing: unknown, + // as before + if _, err := parseClaudeUsage(sub, now); !errors.Is(err, errClaudeUsageUnavailable) { + t.Fatalf("subscription line alone: %v", err) + } +} + +// A usage-based seat (Claude Code's vmr and fD: no rate limits) whose +// /usage draws nothing is told as having no limits, from what Claude Code +// saved of its organization; any other account's stays unknown. +func TestClaudeUsageBasedSeat(t *testing.T) { + t.Cleanup(func() { UsageClaudeVia(nil) }) + UsageClaudeVia(func(context.Context, string) (string, error) { + return "You are currently using your subscription to power your Claude Code usage", nil + }) + for _, c := range []struct { + name, account string + none bool + }{ + {"usage-based enterprise seat", `{"seatTier":"enterprise_usage_based","emailAddress":"a@example.com"}`, true}, + {"billed by usage", `{"billingType":"usage_based"}`, true}, + {"standard enterprise seat", `{"seatTier":"enterprise_standard"}`, false}, + {"no seat", `{"emailAddress":"a@example.com"}`, false}, + {"no file", ``, false}, + } { + dir := t.TempDir() + if c.account != "" { + if err := os.WriteFile(filepath.Join(dir, ".claude.json"), []byte(`{"oauthAccount":`+c.account+`}`), 0o600); err != nil { + t.Fatal(err) + } + } + ws, err := readClaudeUsage(context.Background(), dir) + if c.none { + if err != nil || len(ws) != 1 || ws[0].Display != "None on this plan" { + t.Errorf("%s: %+v %v", c.name, ws, err) + } + } else if !errors.Is(err, errClaudeUsageUnavailable) { + t.Errorf("%s: %+v %v, want unavailable", c.name, ws, err) + } + } +} diff --git a/internal/provider/claude_usage_cli.go b/internal/provider/claude_usage_cli.go index bc176a840..ca50e5adf 100644 --- a/internal/provider/claude_usage_cli.go +++ b/internal/provider/claude_usage_cli.go @@ -6,9 +6,12 @@ package provider import ( "context" + "encoding/json" "errors" "fmt" "math" + "os" + "path/filepath" "regexp" "slices" "strconv" @@ -58,7 +61,55 @@ func readClaudeUsage(ctx context.Context, configDir string) ([]QuotaWindow, erro if err != nil { return []QuotaWindow{}, err } - return parseClaudeUsage(text, time.Now()) + ws, err := parseClaudeUsage(text, time.Now()) + if errors.Is(err, errClaudeUsageUnavailable) && claudeUsageBased(configDir) { + // a seat Claude Code itself holds no rate limits for: nothing to + // wait for + return []QuotaWindow{claudeNoLimitsWindow()}, nil + } + return ws, err +} + +// ClaudeNoLimitsLine is the line the gateway adds under /usage's text when +// Claude Code's usage_report has the server reporting no meters (limits: +// []): the plan has no 5-hour or weekly limits. Read as /usage's text +// alone (the subscription line, no window), it said "temporarily +// unavailable" (@andy_chen1997 on X, a Claude Enterprise seat). Its words +// say no "usage limit", which claudeUsageDenied reads as an account error. +const ClaudeNoLimitsLine = "Usage report: no meters on this plan" + +// claudeNoLimitsWindow is a plan without 5-hour or weekly limits: told as +// text, set aside, so routing holds nothing against it. +func claudeNoLimitsWindow() QuotaWindow { + return QuotaWindow{Name: "5-hour and weekly limits", Display: "None on this plan", Text: true, Aside: true} +} + +// claudeUsageBased says the account in configDir ("" the user's own) is a +// seat Claude Code holds no rate limits for, by what it saved of the +// account's organization (.claude.json's oauthAccount): a usage-based +// Claude Enterprise seat (seatTier "enterprise_usage_based", Claude +// Code's vmr) or an organization billed by usage (billingType +// "usage_based", its fD). Its /usage then never draws a window. A read +// that fails says no. +func claudeUsageBased(configDir string) bool { + path := claudeProfilePath() + if configDir != "" { + path = filepath.Join(configDir, ".claude.json") + } + b, err := os.ReadFile(path) + if err != nil { + return false + } + var p struct { + Account *struct { + SeatTier string `json:"seatTier"` + BillingType string `json:"billingType"` + } `json:"oauthAccount"` + } + if json.Unmarshal(b, &p) != nil || p.Account == nil { + return false + } + return p.Account.SeatTier == "enterprise_usage_based" || p.Account.BillingType == "usage_based" } // "Current session: 13% used · resets Oct 1 at 3:30pm (Asia/Shanghai)", @@ -222,6 +273,13 @@ func parseClaudeUsage(text string, now time.Time) ([]QuotaWindow, error) { out = append(out, claudeOveragesWindow(out)) } if len(out) == 0 { + if slices.ContainsFunc(lines, func(line string) bool { return strings.TrimSpace(line) == ClaudeNoLimitsLine }) { + out = append(out, claudeNoLimitsWindow()) + if w, ok := claudeExtraWindow(lines); ok { + out = append(out, w) + } + return out, nil + } if text == claudeNoWindow { // the interactive panel loaded with none of the account's // windows: none has started (claudeWithUnstarted) @@ -290,6 +348,10 @@ func claudeResetTime(s string, now time.Time, span time.Duration) (time.Time, bo if s == "" { return time.Time{}, false } + // a usage_report row's resets_at, which the gateway adds as written + if t, err := time.Parse(time.RFC3339Nano, s); err == nil { + return t, true + } loc := time.Local if i := strings.LastIndex(s, "("); i >= 0 && strings.HasSuffix(s, ")") { if l, err := time.LoadLocation(s[i+1 : len(s)-1]); err == nil {