claude usage: a /usage panel with no window is no window started, and a failure says why
koohoko5924 (Discord #help, v0.1.3057, macOS): a Claude Enterprise
account with a five-hour window only. A manual refresh took ~5s and
gave the card no window and the error "Claude Code's usage showed no
usage figures: ▐▛███▜▌ … magpie-claude-work…": Claude Code's banner,
not a reason.
Claude Code 2.1.316's Usage tab (gi) draws a window only once
Anthropic's answer has it non-null, and a window is null until the
request that starts it. An idle 5h-only account's panel loads with
the session's cost, maybe the plan's credit bar, and no window. The
helper told that panel's words, joined from the top of the screen, and
the card took them as a failure with the banner first.
- claudetui: a panel that loaded (tabs, Session/Total cost, nothing
loading, refreshing, stale or failed, no gateway Spend limit) with no
"Current session"/"Current week" is told as NoUsageWindow ("No usage
window has started"). The provider reads that as no window started:
no error, the unstarted 5h window as for any account.
- claudetui: the two rate-limit errors gi draws ("Claude is temporarily
limiting requests to the usage page (not your usage limit)…",
"Usage endpoint is rate limited until …") are failures to load, like
"Failed to load usage data": retried once, then told as an error with
the panel's own "Error: …" text, never the banner. A panel with no
window and no error is told from its tabs on, the session's cost
lines left out.
- provider: "(not your usage limit)" no longer reads as an account
refused (claudeDenied, at every place claudeUsageDenied judged a
reading: the CLI parse, codex_switch, quota_last, subscription_usage).
Counts ("Last 7d · 403 requests …") are taken out wherever they sit in
a line before that check, as the panel's words come on one line now.
A no-figures error keeps every line (600 runes), not the first clipped
at 120.
Tests are built from 2.1.316's own strings (ko/gi/hi in the bundled
cli.js), drawn on the helper's 200x50 grid row by row. Guessed: the
exact bytes of a real Enterprise panel (not captured; no such account
here) and the credit bar's layout.
Run (mote, at this tree): go test ./internal/claudetui ./internal/provider
-run 'Usage|Claude|Shim|Quota|Codex' ok; go vet for claudetui, provider,
gateway; GOOS=linux -tags nogui and GOOS=windows go vet; gofmt -l clean.
Broken by hand (each red, then restored):
- the NoUsageWindow case off: TestShimReadsUsageWithNoWindow red in all
three panels (told the panel's words as success);
- the provider's claudeNoWindow branch off: TestClaudeUsageNoWindowStarted
red ("showed no usage figures: No usage window has started");
- claudeDenied back to claudeUsageDenied: TestClaudeUsageWhyKept red
("read as an account refused");
- usageFailed back to "Failed to load usage data" and the whole screen as
the reason: TestShimToldWhyUsageFailed red in all three (the banner as
the reason; the rate-limit panels told as no window), TestUsageNoWindow
red.
Not tried: a real Claude Enterprise account; a real rate-limited panel.
This commit is contained in:
@@ -486,7 +486,21 @@ The provider keeps the account's last reading on that error
|
||||
(`claudeUsageUnknown`, as for Claude Code's own "temporarily
|
||||
unavailable"), and a panel with no figure otherwise is "Claude Code's
|
||||
/usage showed no usage figures: …", never "told no allowance", which is
|
||||
kept for an account Claude Code refuses (`claudeUsageDenied`).
|
||||
kept for an account Claude Code refuses (`claudeUsageDenied`, matched by
|
||||
`claudeDenied`, which drops "(not your usage limit)" and the request
|
||||
counts first). That error names the panel's own text from its tabs on,
|
||||
or its "Error: …" line (`usageWhy`, `usagePart`), never the banner and
|
||||
folder drawn above it. A panel drawn whole, with its Session tab and no
|
||||
error, loading or stale mark, that has no "Current session" or "Current
|
||||
week" is an account with no window started yet: Anthropic leaves a
|
||||
window out until the request that starts it. Its result is
|
||||
`NoUsageWindow`, and the card shows the five-hour window unused, with no
|
||||
error (`TestShimReadsUsageWithNoWindow`, `TestClaudeUsageNoWindowStarted`;
|
||||
koohoko5924 on Discord, a Claude Enterprise account, on panels built from
|
||||
2.1.316's strings, not captured). The Usage endpoint's own errors
|
||||
("temporarily limiting requests to the usage page", "rate limited
|
||||
until …") are failures as "Failed to load usage data" is
|
||||
(`TestShimToldWhyUsageFailed`).
|
||||
|
||||
These one-off interactive runs (`askClaudeTUI`, `claudeUsageTUI`) work in
|
||||
magpie's shared work folder (`oneOffDir`: `claudeWorkDir`, a fresh temp
|
||||
|
||||
@@ -826,12 +826,19 @@ func (s *shim) command(name string) error {
|
||||
// no figures, the panel still loading them or saying it
|
||||
// couldn't: unknown, not a plan with no allowance
|
||||
s.emit(map[string]any{"type": "result", "subtype": "error_during_execution", "is_error": true, "session_id": s.sid,
|
||||
"result": name + " couldn't load the plan's usage: " + strings.Join(strings.Fields(now), " ")})
|
||||
"result": name + " couldn't load the plan's usage: " + usageWhy(now)})
|
||||
return nil
|
||||
case !drawn:
|
||||
s.emit(map[string]any{"type": "result", "subtype": "error_during_execution", "is_error": true, "session_id": s.sid,
|
||||
"result": fmt.Sprintf("Claude Code hadn't drawn /usage's panel in %s: %s", commandWait, s.lastScreen())})
|
||||
return nil
|
||||
case !usageWindow.MatchString(text) && (usageNoWindow(now) || usageNoWindow(panel)):
|
||||
// the panel loaded, and none of the account's windows is
|
||||
// running: Anthropic leaves a window out until the request that
|
||||
// starts it. Told as the panel, its banner was read as the
|
||||
// account's error (koohoko5924, a Claude Enterprise account with
|
||||
// a five-hour window only, idle)
|
||||
text = NoUsageWindow
|
||||
}
|
||||
s.emit(map[string]any{"type": "result", "subtype": "success", "is_error": false, "session_id": s.sid,
|
||||
"local_command": "usage", "result": text})
|
||||
@@ -846,8 +853,75 @@ func usageDrawn(screen string) bool {
|
||||
return usagePanel.MatchString(t) && !usageLoading.MatchString(t)
|
||||
}
|
||||
|
||||
// /usage's panel once its figures failed to load (Claude Code 2.1.316)
|
||||
var usageFailed = regexp.MustCompile(`Failed to load usage data`)
|
||||
// /usage's panel once its figures failed to load, as Claude Code 2.1.316
|
||||
// says it: "Error: Failed to load usage data", and Anthropic turning the
|
||||
// usage page's requests away for a while ("Error: Claude is temporarily
|
||||
// limiting requests to the usage page (not your usage limit). Try again
|
||||
// in a moment.", "Error: Usage endpoint is rate limited until 12:11am."),
|
||||
// which were read as a panel with no window.
|
||||
var usageFailed = regexp.MustCompile(`Failed to load usage data|limiting requests to the usage page|Usage endpoint is rate limited`)
|
||||
|
||||
// NoUsageWindow is what the helper tells for a /usage panel that loaded
|
||||
// with none of the account's windows drawn: each is left out until the
|
||||
// request that starts it, so none has started.
|
||||
const NoUsageWindow = "No usage window has started"
|
||||
|
||||
// usageWindow is one of the account's windows as usageText tells it.
|
||||
var usageWindow = regexp.MustCompile(`(?m)^Current (?:session|week)\b`)
|
||||
|
||||
// usageNoWindow says whether screen is /usage's panel loaded, its figures
|
||||
// told, with none of the account's windows among them: the Usage tab's
|
||||
// "Session" and its "Total cost:" (Claude Code 2.1.316 draws them first), nothing loading,
|
||||
// refreshing or failed, no gateway's "Spend limit" in place of the plan's
|
||||
// windows, and no "Current session" or "Current week" drawn. What else it
|
||||
// draws is no window: the plan's credit ("Usage credits", "Claude Code and
|
||||
// Cowork credit") and what used the account ("What's contributing to your
|
||||
// usage?").
|
||||
func usageNoWindow(screen string) bool {
|
||||
t := strings.Join(strings.Fields(screen), " ")
|
||||
at := usagePanel.FindStringIndex(t)
|
||||
if at == nil || !usageDrawn(t) {
|
||||
return false
|
||||
}
|
||||
t = t[at[0]:]
|
||||
return usageSession.MatchString(t) && !usageFailed.MatchString(t) && !usageRefreshing.MatchString(t) &&
|
||||
!usageStale.MatchString(t) && !strings.Contains(t, "Spend limit") && !usageCurrent.MatchString(t)
|
||||
}
|
||||
|
||||
var (
|
||||
usageSession = regexp.MustCompile(`\bSession\b|\bTotal cost:`)
|
||||
usageCurrent = regexp.MustCompile(`\bCurrent (?:session|week)\b`)
|
||||
// the panel's "Error: …", however many rows it wraps to, up to the
|
||||
// keys it draws under it ("r to retry · Esc to cancel")
|
||||
usageError = regexp.MustCompile(`\bError: .*?(?: r to retry\b|$)`)
|
||||
)
|
||||
|
||||
// usagePart is the words of /usage's panel in t (its fields joined) that
|
||||
// can say why it told no window: from its tabs on, not Claude Code's
|
||||
// banner above them, and without the session's cost the Usage tab draws
|
||||
// first ("Total cost: $0.0000 … Usage: 0 input, 0 output, 0 cache read, 0
|
||||
// cache write"), whose counts ("403 lines added") read as an HTTP status.
|
||||
// t whole when no tabs are drawn.
|
||||
func usagePart(t string) string {
|
||||
at := usagePanel.FindStringIndex(t)
|
||||
if at == nil {
|
||||
return t
|
||||
}
|
||||
return strings.Join(strings.Fields(usageCost.ReplaceAllString(t[at[0]:], "")), " ")
|
||||
}
|
||||
|
||||
var usageCost = regexp.MustCompile(`\bTotal cost:.*?\bcache write\b`)
|
||||
|
||||
// usageWhy is why /usage's panel told no figures, as it says it: its
|
||||
// "Error: …" whole, else what it drew from its tabs on, not Claude Code's
|
||||
// banner above them, which said nothing of why (koohoko5924).
|
||||
func usageWhy(screen string) string {
|
||||
t := usagePart(strings.Join(strings.Fields(screen), " "))
|
||||
if m := usageError.FindString(t); m != "" {
|
||||
return strings.TrimSuffix(m, " r to retry")
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
// /usage's panel drawing the figures Claude Code saved on an earlier read
|
||||
// (cachedUsageUtilization, up to an hour old) while it asks for today's
|
||||
@@ -901,7 +975,7 @@ func usageText(screen string) string {
|
||||
lines = append(lines, "You are currently using your overages to power your Claude Code usage.")
|
||||
}
|
||||
if len(lines) == 0 {
|
||||
return t
|
||||
return usagePart(t)
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
@@ -966,6 +966,105 @@ func TestShimReadsUsageBelowTheTwentyFourthRow(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// usagePanel200 is /usage's panel as Claude Code 2.1.316 draws it in the
|
||||
// helper's 200 by 50 terminal, from its Usage tab (ko: the tabs, the
|
||||
// session's cost, then what gi draws for the plan), a row at a time
|
||||
// (CR, ESC[nB). The words are 2.1.316's own; the Enterprise panels below
|
||||
// weren't captured from a real account, and are built from them.
|
||||
func usagePanel200(t *testing.T, rows ...string) string {
|
||||
t.Helper()
|
||||
var b strings.Builder
|
||||
b.WriteString("\x1b[H\r\x1b[20B Settings Status Config Usage Stats\x1b[K")
|
||||
for _, r := range append([]string{"", " Session", "", " Total cost: $0.0000", " Total duration (API): 0s",
|
||||
" Total duration (wall): 10s", " Total code changes: 0 lines added, 0 lines removed",
|
||||
" Usage: 0 input, 0 output, 0 cache read, 0 cache write", ""}, rows...) {
|
||||
b.WriteString("\r\x1b[1B " + r + "\x1b[K")
|
||||
}
|
||||
b.WriteString("\x1b[50;1H")
|
||||
panel := filepath.Join(t.TempDir(), "usage-200x50.bin")
|
||||
if err := os.WriteFile(panel, []byte(b.String()), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return panel
|
||||
}
|
||||
|
||||
// A Claude Enterprise account with a five-hour window only, idle: its
|
||||
// panel draws no window, Anthropic leaving each out until the request that
|
||||
// starts it, at most the plan's credit. It was told as the panel's words,
|
||||
// and Claude Code's banner above them was the card's error ("Claude Code's
|
||||
// usage showed no usage figures: …magpie-claude-work…", koohoko5924,
|
||||
// v0.1.3057). It is told as no window started.
|
||||
func TestShimReadsUsageWithNoWindow(t *testing.T) {
|
||||
for name, rows := range map[string][]string{
|
||||
"none": {" Esc to cancel"},
|
||||
"credit": {" Usage credits", " ████▌" + strings.Repeat(" ", 46) + "12% used", " Resets Dec 1 (Asia/Shanghai)", "", " Esc to cancel"},
|
||||
"what's contributing": {" What's contributing to your usage?", " Approximate · sessions on this machine only", "", " Esc to cancel"},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
out := runShim(t, []string{"FAKE_USAGE=" + usagePanel200(t, rows...), "FAKE_USAGE_BANNER=0"},
|
||||
append([]string{fakePath(t)}, pArgs...), []string{`raw:{"type":"command","command":"/usage"}`}, 2)
|
||||
if r := out[1]; r["type"] != "result" || r["is_error"] != false || r["result"] != NoUsageWindow {
|
||||
t.Fatalf("told %v", r)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Anthropic turning the usage page's requests away for a while is a
|
||||
// failure to load, told with the panel's own words, retried once: read as
|
||||
// a panel with no window, its reason was lost. The banner above the panel
|
||||
// is never the reason (koohoko5924).
|
||||
func TestShimToldWhyUsageFailed(t *testing.T) {
|
||||
for _, why := range []string{
|
||||
"Failed to load usage data",
|
||||
"Claude is temporarily limiting requests to the usage page (not your usage limit). Try again in a moment.",
|
||||
"Usage endpoint is rate limited until 12:11am.",
|
||||
} {
|
||||
t.Run(why, func(t *testing.T) {
|
||||
failed := usagePanel200(t, " Error: "+why, "", " r to retry · Esc to cancel")
|
||||
out := runShim(t, []string{"FAKE_USAGE=" + failed, "FAKE_USAGE_FIRST=" + failed, "FAKE_USAGE_THEN=retry-fails", "FAKE_USAGE_BANNER=0"},
|
||||
append([]string{fakePath(t)}, pArgs...), []string{`raw:{"type":"command","command":"/usage"}`}, 2)
|
||||
want := "/usage couldn't load the plan's usage: Error: " + why
|
||||
if r := out[1]; r["type"] != "result" || r["is_error"] != true || r["result"] != want {
|
||||
t.Fatalf("told %v, want %q", r, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUsageWhy(t *testing.T) {
|
||||
banner := "▐▛███▜▌ Claude Code v2.1.316 ▘▘ ▝▝ /private/var/folders/3d/x/T/magpie-claude-work-501 ──── ❯ /usage ──── "
|
||||
for screen, want := range map[string]string{
|
||||
banner + "Settings Status Config Usage Stats Session Total cost: $0.0000 Usage: 0 input, 0 output, 0 cache read, 0 cache write Error: Failed to load usage data r to retry · Esc to cancel": "Error: Failed to load usage data",
|
||||
banner + "Settings Status Config Usage Stats Session Total cost: $1.20 Total code changes: 403 lines added, 2 lines removed Usage: 9 input, 0 output, 0 cache read, 0 cache write Loading usage data…": "Settings Status Config Usage Stats Session Loading usage data…",
|
||||
"no panel at all": "no panel at all",
|
||||
} {
|
||||
if got := usageWhy(screen); got != want {
|
||||
t.Errorf("usageWhy(%q) = %q, want %q", screen, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUsageNoWindow(t *testing.T) {
|
||||
tab := "Settings Status Config Usage Stats Session Total cost: $0.0000 Usage: 0 input, 0 output, 0 cache read, 0 cache write "
|
||||
for screen, want := range map[string]bool{
|
||||
tab + "Esc to cancel": true,
|
||||
tab + "Usage credits ██ 12% used Resets Dec 1 Esc to cancel": true,
|
||||
tab + "Current session ██ 12% used Resets 7pm Esc to cancel": false,
|
||||
tab + "Current week (all models) █ 3% used Esc to cancel": false,
|
||||
tab + "Loading usage data…": false,
|
||||
tab + "Error: Usage endpoint is rate limited until 12:11am. r to retry": false,
|
||||
tab + "Refreshing…": false,
|
||||
tab + "Spend limit $50 Esc to cancel": false,
|
||||
"Settings Usage /usage is only available for subscription plans.": false,
|
||||
"▐▛███▜▌ Claude Code v2.1.316 /private/var/folders/3d/x/T/magpie-claude-work-501": false,
|
||||
} {
|
||||
if got := usageNoWindow(screen); got != want {
|
||||
t.Errorf("usageNoWindow(%q) = %v, want %v", screen, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Claude Code draws its banner again before /usage's panel, and a slow
|
||||
// /usage leaves it still for seconds. It is waited past, never told as the
|
||||
// panel: read as one, the banner was an allowance's error (ikunbots on X,
|
||||
|
||||
@@ -82,13 +82,25 @@ var errClaudeCannotRun = errors.New("Claude Code can't be run from here")
|
||||
// rate limit. It is not a temporary failure to read the usage endpoint.
|
||||
var claudeUsageDenied = regexp.MustCompile(`(?i)\b(401|403)\b|not (logged|signed) in|signed out|sign-in (has )?expired|unauthorized|forbidden|authentication (failed|required)|invalid (access )?token|(session|usage) limit|hit your limit`)
|
||||
|
||||
// claudeDenied says s tells an account error (claudeUsageDenied). Claude
|
||||
// Code's "(not your usage limit)", which it says of Anthropic turning the
|
||||
// usage page's requests away for a while ("Claude is temporarily limiting
|
||||
// requests to the usage page (not your usage limit)"), tells none: read as
|
||||
// one, a /usage that couldn't load had the account refused.
|
||||
func claudeDenied(s string) bool {
|
||||
return claudeUsageDenied.MatchString(claudeNotYourLimit.ReplaceAllString(s, ""))
|
||||
}
|
||||
|
||||
var claudeNotYourLimit = regexp.MustCompile(`(?i)\(not your usage limit\)`)
|
||||
|
||||
// claudeUsageCounts is /usage's closing line of the account's local
|
||||
// activity ("Last 7d · 403 requests · 388 sessions"): counts, not the
|
||||
// HTTP statuses a count of 401 or 403 reads as (SCIYYDy, #4995). Read
|
||||
// whole, the line is no account error; read with more words, as "Last
|
||||
// 7d · 403 requests · 388 sessions · HTTP 403 Forbidden", it is. Any span
|
||||
// and a count with thousands separators ("1,403 requests") are counts too.
|
||||
var claudeUsageCounts = regexp.MustCompile(`^Last [0-9]+[a-z]+ · [0-9][0-9,]* requests? · [0-9][0-9,]* sessions?$`)
|
||||
// activity ("Last 7d · 403 requests · 388 sessions"), with the " · "
|
||||
// before it wherever it sits in a line: counts, not the HTTP statuses a
|
||||
// count of 401 or 403 reads as (SCIYYDy, #4995). Taken out, what is left
|
||||
// of the line is read: "Last 7d · 403 requests · 388 sessions · HTTP 403
|
||||
// Forbidden" is an account error. Any span and a count with thousands
|
||||
// separators ("1,403 requests") are counts too.
|
||||
var claudeUsageCounts = regexp.MustCompile(`(?: · )?Last [0-9]+[a-z]+ · [0-9][0-9,]* requests? · [0-9][0-9,]* sessions?`)
|
||||
|
||||
// claudeOverages is /usage's line for an account past its plan's limits
|
||||
// and billed for what it uses ("You are currently using your overages to
|
||||
@@ -124,10 +136,10 @@ func parseClaudeUsage(text string, now time.Time) ([]QuotaWindow, error) {
|
||||
lines := strings.Split(text, "\n")
|
||||
// Account errors take precedence over notices (and partial readings).
|
||||
for _, line := range lines {
|
||||
if claudeUsageCounts.MatchString(strings.TrimSpace(line)) {
|
||||
continue
|
||||
}
|
||||
if claudeUsageDenied.MatchString(line) {
|
||||
// the counts are no HTTP status, wherever the line has them: the
|
||||
// interactive panel's words come joined on one line
|
||||
// (claudetui.usagePart)
|
||||
if claudeDenied(claudeUsageCounts.ReplaceAllString(line, "")) {
|
||||
return out, errors.New("Claude Code's /usage told no allowance: " + clipLine(strings.TrimSpace(line)))
|
||||
}
|
||||
}
|
||||
@@ -169,24 +181,40 @@ func parseClaudeUsage(text string, now time.Time) ([]QuotaWindow, error) {
|
||||
out = append(out, claudeOveragesWindow(out))
|
||||
}
|
||||
if len(out) == 0 {
|
||||
if text == claudeNoWindow {
|
||||
// the interactive panel loaded with none of the account's
|
||||
// windows: none has started (claudeWithUnstarted)
|
||||
return out, nil
|
||||
}
|
||||
if text == "" || slices.ContainsFunc(lines, func(line string) bool {
|
||||
return strings.TrimSuffix(strings.TrimSpace(line), ".") == "You are currently using your subscription to power your Claude Code usage"
|
||||
}) {
|
||||
return out, errClaudeUsageUnavailable
|
||||
}
|
||||
// a panel with no figure says nothing of the account's allowance:
|
||||
// unknown, its words told
|
||||
first, _, _ := strings.Cut(text, "\n")
|
||||
if claudeUsageCounts.MatchString(strings.TrimSpace(first)) {
|
||||
// its counts, told in the error, would read as a 401 or 403
|
||||
// where the error is matched again (claudeUsageDenied)
|
||||
// unknown, its words told whole, not the first line clipped, which
|
||||
// left out why (koohoko5924); its counts, told in the error, would
|
||||
// read as a 401 or 403 where the error is matched again
|
||||
// (claudeUsageDenied)
|
||||
var said []string
|
||||
for _, line := range lines {
|
||||
line = strings.TrimSpace(claudeUsageCounts.ReplaceAllString(line, ""))
|
||||
if line != "" {
|
||||
said = append(said, line)
|
||||
}
|
||||
}
|
||||
if len(said) == 0 {
|
||||
return out, errors.New("Claude Code's /usage showed no usage figures")
|
||||
}
|
||||
return out, errors.New("Claude Code's /usage showed no usage figures: " + clipLine(first))
|
||||
return out, errors.New("Claude Code's /usage showed no usage figures: " + clipReason(strings.Join(said, " · ")))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// claudeNoWindow is the helper's word for an interactive /usage panel that
|
||||
// loaded with no window drawn (claudetui.NoUsageWindow).
|
||||
const claudeNoWindow = "No usage window has started"
|
||||
|
||||
func clipLine(s string) string {
|
||||
if r := []rune(s); len(r) > 120 {
|
||||
return string(r[:120]) + "…"
|
||||
@@ -194,6 +222,14 @@ func clipLine(s string) string {
|
||||
return s
|
||||
}
|
||||
|
||||
// clipReason is a failure's words, kept long enough to say why.
|
||||
func clipReason(s string) string {
|
||||
if r := []rune(s); len(r) > 600 {
|
||||
return string(r[:600]) + "…"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// claudeResetTime reads "Oct 1 at 3:30pm (Asia/Shanghai)", "Oct 9, 2:59pm
|
||||
// (UTC)" (Claude Code 2.1.285 on) or "3pm (Asia/Shanghai)", in the zone
|
||||
// named, else local time. It ends a window span long, so it is never further
|
||||
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/claudetui"
|
||||
)
|
||||
|
||||
const subscriptionNotice = "You are currently using your subscription to power your Claude Code usage"
|
||||
@@ -351,3 +353,52 @@ func TestClaudeUsageWithoutFiguresIsUnknown(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// An interactive /usage panel with none of the account's windows (a Claude
|
||||
// Enterprise account with a five-hour window only, idle) is an account
|
||||
// whose windows haven't started, never a failure: it was told as the
|
||||
// panel's words, and the card showed Claude Code's banner as its error
|
||||
// and no window (koohoko5924, v0.1.3057).
|
||||
func TestClaudeUsageNoWindowStarted(t *testing.T) {
|
||||
if claudeNoWindow != claudetui.NoUsageWindow {
|
||||
t.Fatalf("the helper says %q, the card reads %q", claudetui.NoUsageWindow, claudeNoWindow)
|
||||
}
|
||||
_, card := claudeUsageCards(t, claudeNoWindow, nil)
|
||||
q := card()
|
||||
if q.Error != "" || len(q.Windows) != 1 || q.Windows[0].Name != "5 hours" || q.Windows[0].Used != 0 || q.Windows[0].ResetsAt != nil {
|
||||
t.Fatalf("no window started read as %+v", q)
|
||||
}
|
||||
}
|
||||
|
||||
// A panel that couldn't load its figures is told with its whole reason,
|
||||
// and Anthropic turning the usage page away for a while, "(not your usage
|
||||
// limit)", is no account refused: read as "usage limit", it was.
|
||||
func TestClaudeUsageWhyKept(t *testing.T) {
|
||||
now := time.Now()
|
||||
why := "Settings Status Config Usage Stats Session What's contributing to your usage? Approximate · sessions on this machine only · Last 7d · 403 requests · 388 sessions · Esc to cancel"
|
||||
_, err := parseClaudeUsage(why, now)
|
||||
want := "Claude Code's /usage showed no usage figures: Settings Status Config Usage Stats Session What's contributing to your usage? Approximate · sessions on this machine only · Esc to cancel"
|
||||
if err == nil || err.Error() != want {
|
||||
t.Fatalf("told %v, want %q", err, want)
|
||||
}
|
||||
if claudeDenied(err.Error()) {
|
||||
t.Fatalf("%q read as an account refused", err)
|
||||
}
|
||||
limited := "Claude Code: /usage couldn't load the plan's usage: Error: Claude is temporarily limiting requests to the usage page (not your usage limit). Try again in a moment."
|
||||
if claudeDenied(limited) {
|
||||
t.Fatalf("%q read as an account refused", limited)
|
||||
}
|
||||
if !claudeDenied("You've hit your session limit · resets 7pm") || !claudeDenied("Error: 401 unauthorized") {
|
||||
t.Fatal("an account refused isn't read as one")
|
||||
}
|
||||
at := time.Now().Add(-10 * time.Minute).Truncate(time.Second)
|
||||
reset := time.Now().Add(time.Hour).Truncate(time.Second)
|
||||
snapshot := lastQuota{At: at, Q: SubscriptionQuota{Provider: "claude", Plan: "pro", Windows: []QuotaWindow{
|
||||
{Name: "5 hours", Used: 40, ResetsAt: &reset},
|
||||
}}}
|
||||
_, card := claudeUsageCards(t, "", &snapshot)
|
||||
UsageClaudeVia(func(context.Context, string) (string, error) { return "", errors.New(limited) })
|
||||
if q := card(); q.Error != "" || q.AsOf == nil || !q.AsOf.Equal(at) || len(q.Windows) != 1 || q.Windows[0].Used != 40 {
|
||||
t.Fatalf("the usage page turned away should keep this account's reading: %+v", q)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -465,7 +465,7 @@ func NextInOrder(ctx context.Context, agent string) (to string, over bool, err e
|
||||
// by: never read (a /usage not run), or a read that failed for a reason
|
||||
// not the account's own. Its /usage is then run (readSpare).
|
||||
func unreadSpare(q SubscriptionQuota) bool {
|
||||
return q.Error != "" && (readDeferred(q.Error) || !claudeUsageDenied.MatchString(q.Error))
|
||||
return q.Error != "" && (readDeferred(q.Error) || !claudeDenied(q.Error))
|
||||
}
|
||||
|
||||
// readSpare is the reading of the saved Claude account l, its /usage run
|
||||
|
||||
@@ -97,7 +97,7 @@ func keepLast(q SubscriptionQuota, user string) SubscriptionQuota {
|
||||
}
|
||||
return q
|
||||
}
|
||||
if q.Provider == "claude" && claudeUsageDenied.MatchString(q.Error) {
|
||||
if q.Provider == "claude" && claudeDenied(q.Error) {
|
||||
return q
|
||||
}
|
||||
claudeUnavailable := q.Provider == "claude" && claudeUsageUnknown.MatchString(q.Error)
|
||||
|
||||
@@ -905,7 +905,7 @@ func claudeWindows(ctx context.Context, user string, active bool) ([]QuotaWindow
|
||||
heard := e.ws != nil && now.Sub(e.heard) < claudeHeard
|
||||
if !read {
|
||||
switch {
|
||||
case ok && e.err != nil && !(heard && !claudeUsageDenied.MatchString(e.err.Error())):
|
||||
case ok && e.err != nil && !(heard && !claudeDenied(e.err.Error())):
|
||||
return []QuotaWindow{}, e.err
|
||||
case ok && e.ws != nil:
|
||||
return e.windows(now), nil
|
||||
@@ -949,7 +949,7 @@ func claudeWindows(ctx context.Context, user string, active bool) ([]QuotaWindow
|
||||
if f, ok := c.m[key]; ok {
|
||||
// A failed read cannot establish that an account refusal cleared.
|
||||
// A successful reading or a new header clears it instead.
|
||||
if f.err != nil && claudeUsageDenied.MatchString(f.err.Error()) && !claudeUsageDenied.MatchString(err.Error()) {
|
||||
if f.err != nil && claudeDenied(f.err.Error()) && !claudeDenied(err.Error()) {
|
||||
err = f.err
|
||||
}
|
||||
if f.tried.Equal(now) {
|
||||
@@ -959,7 +959,7 @@ func claudeWindows(ctx context.Context, user string, active bool) ([]QuotaWindow
|
||||
e = f // headers received while /usage ran are newer than e
|
||||
}
|
||||
c.Unlock()
|
||||
if e.ws != nil && time.Since(e.heard) < claudeHeard && !claudeUsageDenied.MatchString(err.Error()) {
|
||||
if e.ws != nil && time.Since(e.heard) < claudeHeard && !claudeDenied(err.Error()) {
|
||||
return e.windows(time.Now()), nil // a fresh header stands unless the account was refused
|
||||
}
|
||||
return ws, err
|
||||
|
||||
Reference in New Issue
Block a user