Commit Graph
14 Commits
Author SHA1 Message Date
yetone 82403f9f6d claude: /usage is read through -p, never the interactive mode, which opened idle accounts' 5-hour window (#5582)
Since v0.1.2635 (ccd746e03), when the interactive mode is on (the
default), magpie read the plan's allowance by starting the interactive
Claude Code in its helper and typing /usage there (claudeUsageTUI). The
interactive Claude Code 2.1.316 sends a model request as it starts,
before anything is typed. That is probeQuotaStatus: haiku, max_tokens 1,
content "quota". It sends it unless CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC
is set, and that variable also keeps /usage from loading. The request
counts, so on an account with no 5-hour window it started one. The
reporter's reads came at magpie's start and when a window ended, and
each opened a window with warm-up off. Their counterexample (11-01,
v0.1.2433, before ccd746e03) read /usage through -p and opened nothing.

Recorded (sandbox HOME and CLAUDE_CONFIG_DIR, a fake sign-in, the real
Claude Code 2.1.316 behind a recording proxy that answers everything
itself, so no account was spent):
- magpie's interactive args and env, in a pty. At start, before /usage
  was typed:
  POST api.anthropic.com /v1/messages?beta=true
  {"model":"claude-haiku-4-5-20251001","max_tokens":1,
   "messages":[{"role":"user","content":"quota"}],...}
  then GET /api/oauth/usage once /usage was typed.
- The same with CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1: no POST, but
  no /api/oauth/usage either, and the panel says "Failed to load usage
  data". This can't be the fix.
- `claude -p /usage` with claudeUsageArgs and claudeUsageEnv: no
  /v1/messages at all, only GET /api/oauth/usage (plus profile and
  bootstrap GETs). It printed "You are currently using your subscription
  to power your Claude Code usage" / "Current session: 13% used · resets
  Nov 7 at 4pm (Asia/Shanghai)" / "Current week (all models): 4% used ·
  ...". ccd746e03 said -p's /usage tells only the session's cost. In
  2.1.316's source that is only for a sign-in without a subscription or
  the user:profile scope, such as a setup-token, which provider never
  reads (errClaudeSetupToken), or an API key.

Fix: claudeUsage always runs `claude -p /usage`, with the interactive
mode on or off. claudeUsageTUI and claudeTUIUsageArgs are gone. This is
the one choke point (provider.UsageClaudeVia -> runClaudeUsage) for
every magpie read of Claude usage: the signed-in account's card,
saved accounts (readSavedClaudeUsage), the 8-day keep-alive, the
used-up switch's spare reads and refreshes. The other interactive
starts are the bridge's turns, the warm-up and the model test. Each one
sends a model request the user asked for, and each runs with
cleanClaudeEnv's CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1, so the
startup probe isn't added there. Not changed: claudetui still takes a
typed /usage, and magpie no longer sends it.

Docs: docs/subsystems/claude-subscription-bridge.md says why and
removes the wrong -p claim. The comments in claude_warmup.go, tui.go
and claude_usage_cli.go are updated to match.

Tests: TestClaudeUsageStartsNoInteractiveRun replaces
TestClaudeUsageTUIOn, TestClaudeUsageTUIWorksInMagpiesFolder and
TestClaudeUsageTUISaysItsDeadline. With the interactive mode on, it
checks that a read of the signed-in account and of a saved one starts
no helper, runs -p /usage, and leaves the traffic variable off. The
"usage" rows of TestClaudeOneOffTrustsMagpiesFolder and
TestClaudeOneOffFailureLogged are removed, since a /usage read is no
longer an interactive one-off run. Their "test" rows stay.

Run (mote, at this tree on origin/main 665b9aff1; after the rebase on 9e6687e3a, vet and claudetui plus gateway's ClaudeUsage|OneOff|Trust|TUI tests again: ok):
- gofmt -l internal/gateway internal/provider internal/claudetui: clean.
- go vet for darwin, and for linux and windows with -tags nogui:
  ./internal/gateway ./internal/provider ./internal/claudetui ok.
- On mote: go test -count=1 -timeout 45m ./internal/provider ./internal/claudetui: ok (114s, 110s);
  go test -run 'Claude|Usage|Warm|Trust|OneOff|TUI|Shim|Guard|Loop|Budget' ./internal/gateway: ok (89s).

Broken by hand: with HEAD's claude_warmup.go (its claudeTUIOn branch
back) and the new test, TestClaudeUsageStartsNoInteractiveRun went red:
"a /usage read started the interactive Claude Code: claude-tui-helper
.../claude -p --output-format stream-json --input-format stream-json ...".

Not tried: a real account's -p /usage on this build. The windows output
above comes from the recorder's fake usage reply, and the reporter's
v0.1.2433 readings came from -p. Not tried: an Enterprise account whose
usage reply leaves the windows out. -p then prints only the
subscription line, which reads as "temporarily unavailable" and keeps
the last reading, where the interactive panel had said no window has
started. Not run on Windows or in WSL. The -p read there is the same code
(claudeUsage); the interactive read had run on Windows too.
Not run: the full ./... suite (mote's suite.lock had four full runs
queued).
2026-11-07 11:52:30 +08:00
yetone 77031d5817 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.
2026-11-06 06:30:23 +08:00
yetoneandggbdpq 59907fd554 claude: a /usage count of 401 or 403 is a count, not a denial (SCIYYDy, #4995)
SCIYYDy's Claude account closed /usage with the machine's own activity,
"Last 7d · 403 requests · 388 sessions", and magpie read the count of 403
as the HTTP status. parseClaudeUsage scans every line for
claudeUsageDenied before it reads the windows (account errors come first,
#4532), and the bare \b(401|403)\b in that regex cannot tell a statistic
from a status. So a whole reading with valid session and week windows came
back "told no allowance" and the card kept none. A count of 401 denies as
much.

The scan now skips a line that reads, whole, as one of /usage's count
lines ("Last <span> · N requests · N sessions", the numbers with or without
thousands commas, so "1,403 requests" is a count too). A line that says
more ("… · HTTP 403 Forbidden") is no count line, and a real 401
Unauthorized, 403 Forbidden or authentication failure still denies the
account, on its own line and beside the windows; the #4532 precedence
holds.

Sibling (review): a count line with no windows around it fell to the "no
usage figures" error, which quoted the panel's first line, so the error
text held "403". That error is matched with claudeUsageDenied again in
subscription_usage.go, quota_last.go and codex_switch.go, where it would
read as a denial after all. A counts-only panel now gets an error that does
not quote it, and the test asserts the error does not match
claudeUsageDenied.

Run on mote (macOS arm64, go1.26.8) at the pushed head, sandbox HOME:
go test -tags nogui -count=1 ./internal/provider/ ok (116s).
Broken by hand: without the count-line skip, the counts case is red ("told
no allowance: Last 7d · 403 requests"); with the patch's narrower regex
(no commas), the "1,403 requests" case is red.
Not tried: a real Claude account whose /usage shows 401 or 403 requests;
Windows and Linux.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-06 05:53:49 +08:00
yetone 3a74cd92e8 claude: /usage waits for its figures, and a read without them is unknown
Seagull fries (haioushutiao, Discord #help; magpie 0.1.2704, Claude Code
2.1.316, Windows 11, Claude Pro): the Claude card said 暂时无法获取额度,
"Claude Code's /usage told no allowance: ❯ /usage ─── Settin s Status
Config Usage …". Reproduced with a real Claude Code 2.1.316 under
Windows' pseudo console in a sandbox: /usage's panel is drawn first with
"Loading usage data…" while Claude Code asks Anthropic for the figures
(5s timeout, retried only on a 401), and the helper took 3s of a still
screen as the panel drawn whole. On a slow answer it told the panel's
frame as the result, and parseClaudeUsage called any text with no window
"told no allowance". A failed load ("Error: Failed to load usage data",
"r to retry") went the same way.

claudetui:
- screen.go: a small terminal grid (CUP/CUU..CHA/VPA, EL, ED, ECH, CR/LF
  with scrolling, OSC/DCS skipped, an escape or UTF-8 character cut
  between reads kept), 200x50 on Windows as the pseudo console is made,
  80x24 elsewhere. The pseudo console sends only the cells that changed,
  skipping a cell that holds the same letter ("Settin\x1b[1Cs"), so the
  stream read split words and kept a redrawn digit beside the old one.
  While /usage is read, each look of the screen with a window is kept
  (panel), and usageText reads that before the stream.
- command(), built on b4073c06a's wait for the panel (ikunbots; its
  usageDrawn and "hadn't drawn" error kept, now also judged on the grid,
  since the pseudo console's split "Settin s" never matched its tabs):
  "Loading usage data" on screen is waited out (to
  commandWait, s.doing "was still loading /usage's figures" for the
  deadline message); "Failed to load usage data" gets one "r"; a panel
  still with no figure and loading or failed on screen is an
  error_during_execution result, "/usage couldn't load the plan's usage:
  <screen>".
- the fake draws the panel a frame at a time (fakeFrames), as Claude Code
  does: with one write, the pseudo console passed on only the last
  frame, which no longer shows the windows. TestShimReadsUsage now passes
  on Windows (#4820, the fake's side; a real panel with figures was not
  seen on Windows, see below).

provider:
- parseClaudeUsage: a panel with no figure is "Claude Code's /usage
  showed no usage figures: …", not "told no allowance" (kept for
  claudeUsageDenied's refusals).
- claudeUsageUnknown: Claude Code's "temporarily unavailable" and the
  helper's "couldn't load the plan's usage" keep the account's reported
  reading (quota_last), as the first did alone before. Other no-figure
  text is still shown as an error (TestClaudeHeaderSurvivesUnclassified-
  UsageFailure, TestClaudeUsageReadingAloneDoesNotHideUnclassifiedFailure
  hold that).

Fixtures are the reporter's case as the pseudo console passed it on for
the real 2.1.316 (a temporary dump of the helper's screen bytes, sandbox config,
proxy that never answers / refuses): testdata/usage-loading-win-2.1.316.bin
and usage-failed-win-2.1.316.bin.

Run at the pushed head:
- mote: go test ./internal/claudetui ./internal/provider ok; go test
  -run 'Claude|Usage|TUI' ./internal/gateway ok; GOOS=darwin/linux/
  windows go vet ./internal/claudetui ./internal/provider ok; gofmt -l
  clean.
- xiaomi-gpu (win-run): go test ./internal/claudetui: all pass except
  TestShimFirstMessageWaitsForTools, red on Windows at main (#4810).
- xiaomi-gpu, real Claude Code 2.1.316 (npm), sandbox CLAUDE_CONFIG_DIR
  with a fake token, magpie.exe built from this tree, helper run as the
  gateway runs it: a proxy that never answers gives is_error "/usage
  couldn't load the plan's usage: … Settings Status … Loading usage data…"
  after the 20s wait (was a success with the chrome); a refused proxy
  shows "Failed to load usage data", "r" is pressed, and the same error
  comes back in 6.6s. "Settings" is whole now.

Broken by hand (before the rebase onto b4073c06a; the merged loop is
re-checked below):
- old tui.go: TestShimWaitsForUsageFigures slow, retried and failed again
  all red, each telling the reporter's chrome as success.
- the "r" not written: TestShimWaitsForUsageFigures/retried red.
- old parse message: TestClaudeUsageWithoutFiguresIsUnknown red ("told
  no allowance"); old quota_last check: its couldn't-load cases red.
- after the rebase, on the merged loop: the "r" not written,
  TestShimWaitsForUsageFigures/retried red; the old "anything still 3s"
  in place of usageDrawn on the grid, TestShimWaitsPastTheBanner red.

Not tried: a real account (the box has none of the owner's), so a real
2.1.316 panel with figures was never seen through the pseudo console;
whether Claude Code's frames that show the windows reach the pseudo
console's output before it renders the next one is shown only by the
fake. Not taken: asking Anthropic's /api/oauth/usage, which the owner
ruled out (9bf6d4352).
2026-11-03 05:16:40 +08:00
yetone 822f526a63 claude: /usage's "Sonnet only" week is the Sonnet week (#4532)
Claude Code 2.1.316 names it "Current week (Sonnet only)", and
claudeScopeModel made that the model word "sonnet-only", which no model
id holds: the Sonnet week used up stopped no Sonnet request in routing,
and it was a row apart from the "7 days · Sonnet" its seven_day_sonnet
header keeps (StringKe's audit, item 4, second half). A trailing " only"
is now dropped from the scope, so it reads "7 days · Sonnet", counts
sonnet, and the header replaces it in place; the GUI's existing
translation of the name applies too.

Not changed (item 4, first half): a model's own week still doesn't move
Claude Code's sign-in; usedPast counts windows that hold every model.
Moving the sign-in for one model's limit is a design question left on
#4532.

Run (mote, -tags nogui):
- TestClaudeUsageSonnetOnly: red on the old claude_usage_cli.go
  (Model sonnet-only, name "Sonnet only"), green now.
- go test ./internal/provider -run 'Claude|Allowance|Routing' ok.
- go vet darwin/linux/windows; gofmt clean.

Not tried: a real Sonnet-limited account.
2026-11-01 15:19:06 +08:00
yetone 7b6b7492a9 claude: an account on overages is read with its windows and switched off (#4532)
Claude Code's /usage line "You are currently using your overages to
power your Claude Code usage…" was in claudeUsageDenied, so the whole
reading became an error: the card lost its windows, and NextLogin, which
stays on an account it can't read, left Claude Code billing overages
while other accounts had room (StringKe's audit, item 3).

Now the line is no error. The windows under it are read as usual, and a
Text row "Extra usage" with Used 100 is added (claudeOveragesWindow), so
usedPast/roomLeft count the account spent and the switch moves off it.
The row ends when the last used-up window renews (the time Claude Code
says it switches back), else at the next reading. Routing skips Text
rows, so the gateway's own account choice is unchanged. The GUI says the
row "In use" in the reader's language (quotaText; a plugin's text row
keeps its display as it came). The overages case is out of
TestClaudeUsageFailureDoesNotHideAccountErrors: it was the bug.

Run (mote):
- TestClaudeUsageOverages, TestClaudeSwitchOffOverages: red on the old
  claude_usage_cli.go (an error; switched to ""), red with the row's Used
  set to 0 by hand, green now.
- go test -tags nogui ./internal/provider -run
  'Claude|Usage|NextLogin|Next|Switch' ok.
- GUI: claude-overages (new, 5 languages, chromium + webkit) red 8 of 10
  on the old app.js (en passes there), green now; with quota-text-row,
  quota-name-translated, i18n-keys, usage-no-reading: 40 pass.
- go vet darwin/linux/windows; gofmt clean.

Not tried: a real account on overages; the text is Claude Code
2.1.316's string table, and the windows under it are what StringKe
describes.
2026-11-01 15:16:00 +08:00
yetoneandhhh2210 957aa79aa3 provider, gateway: refreshing a saved Claude account's card reads its allowance through Claude Code, without switching to it (#1630, hhh2210)
A saved (not signed-in) Claude account's Usage card read nothing on
Refresh: claudeWindows only ever ran /usage for the account Claude Code
itself is signed in to, so the button did nothing for the rest.

Now the card's own refresh (RefreshUsage for that account, savedRefresh)
runs the real Claude Code's /usage with CLAUDE_CONFIG_DIR set to the
account's claudeSavedDir (readSavedClaudeUsage). magpie still never calls
Anthropic with the token itself, and Claude Code's own account is not
switched. The 30-second per-account floor holds, background reads keep
the last reading, and asks for every card (the Usage page opened, magpie
quota, magpie accounts) start no Claude Code per saved account: they keep
the last reading, or the "not read yet: refresh this account's card"
note.

Claude Code may refresh the account's token in that directory while it
runs, spending the old refresh token. So:
- inSavedClaudeDir holds a per-account RWMutex (claudeDirRun) for the run,
  and switchSavedLogin takes it for writing first, so a switch never hands
  Claude Code a copy the run has just spent;
- syncSavedClaude copies a rotated sign-in from the directory back into
  logins.json right after the run, under savedTokenMu and loginsMu.
Two Claude Codes in one directory are kept from refreshing at once by
Claude Code's own lock file (2.1.296's refresh lock in its config dir).
A saved account's warm-up, which already ran in that directory, now goes
through inSavedClaudeDir too.

The plumbing (configDir through UsageClaudeVia, readClaudeUsage and the
gateway's claudeUsage, and TestClaudeUsageRunsInSavedAccountDirectory)
is from hhh2210's patch 043ee7d7, reviewed line by line. Its gate (any
explicit read reads every saved account) was narrowed to the card's own
refresh, and the lock and sync back are new.

Run: go test -tags nogui ./internal/provider ./internal/gateway . (sandbox
HOME, fake claude via UsageClaudeVia, no real token), gofmt -l, GOOS=linux
and GOOS=windows go vet on the three packages. Broken by hand, each red:
saved never read (all three new tests), any ask reads saved
(TestRefreshSavedClaudeUsage), switch not held and no sync back
(TestSavedClaudeUsageKeepsRotatedSignIn / SavesRotatedSignIn), run in ""
instead of the account's directory. Not tried with a real Claude Code
binary against a real saved account.

Co-authored-by: hhh2210 <hzy2210@gmail.com>
2026-10-11 23:37:34 +08:00
yetone 570b8fdb2a provider: swapping LoginUsage's or Claude /usage's stand-in waits for the readings still running through the old one (data race in CI run 37942751214)
Cause: TestClaudeAccountBackOnceItsWindowRenews (a2c39053) failed the
ubuntu race shard of run 37942751214. Its Cleanup's LoginUsageVia(nil)
wrote the package-level stand-in while a reading Allowances had started
(routing.go:419) was still reading it in loginUsageAt. Allowances reads
in the background on purpose and returns without waiting (only the very
first ask waits, and not for long), so a reading can outlast the caller,
and the test. The window: Allowances deletes c.loading before it tells
the renewed hooks, so the test's next poll can start another reading
just as the rest it waits on is lifted; the test ends with that reading
in flight. In production the stand-in is never set, so there is no
production race; the goroutine outliving its caller is the design (it is
bounded by its 30 s context).

Change: the stand-in is held for reading while it runs, and
LoginUsageVia takes it for writing, so it returns once no reading is
running through the one it replaces and none starts through it after.
That fixes every test that swaps it (gateway claude_renewed and
allowance_stale, provider routing, allowance_renewed,
codex_reset_deadline, window_renewed), not only the one that failed.
UsageClaudeVia's claudeCLIUsage is the same shape (tests swap it, and
Allowances' background reading of a Claude account reaches it through
readClaudeUsage), so it gets the same treatment; claude_usage_test's
restore goes through UsageClaudeVia. ProbeClaudeVia is left: a Claude
account test calls it synchronously, nothing reads it in the background.

Tests: login_usage_via_test.go holds a call through each stand-in and
checks the swap waits for it.

Run:
- Red before: with a 30 ms delay injected into loginUsageAt and before
  Allowances tells the renewed hooks (not committed),
  go test -race -count=20 -run TestClaudeAccountBackOnceItsWindowRenews
  ./internal/gateway/ printed 7 "WARNING: DATA RACE", the write at
  login_usage.go:43 from the test's Cleanup and the read at
  login_usage.go:63 from Allowances.func1, as on CI. Same injection with
  this change: ok, no race. (-race -count=50 without the injection
  passed on the old code too; the window is too narrow on this Mac.)
- The new tests with the swap made unsynchronised again: both FAIL
  "swapped while a call was still running through the stand-in it
  replaced"; with the change: PASS, -race -count=5.
- gofmt -l: nothing. go vet (darwin) ./internal/provider ./internal/gateway
  ./internal/gui; GOOS=linux and GOOS=windows go vet -tags nogui on the
  same: clean.
- Under a temp HOME with pinned caches: go test -tags nogui
  ./internal/provider ./internal/gateway ok; go test -race
  ./internal/provider ok; go test -race -count=20 -run
  '^(TestClaudeAccountBackOnceItsWindowRenews|TestAllowance.*)$'
  ./internal/gateway ok.
- go test -race -tags nogui ./internal/gateway (whole package, temp HOME):
  ok in 635 s, no race.
2026-10-09 23:07:44 +08:00
forever dfde3acafc provider, gateway: a Claude /usage reset with no year is read within its window, so a reading a few days old no longer benches an account for a year (#1212)
* provider: a Claude reset read in the hour the clocks repeat, or the night they skip it, is the coming one, and a Dec 31 with no year read just after New Year is last year's

claudeResetTime turns /usage's reset text into the ResetsAt of the
"5 hours" and "7 days" windows, which smart routing orders accounts by and
rests a full account until.

- Where the clocks go back and read a time twice, time.Date gives either
  instant: the first west of UTC, the second east of it. Each reading is
  now considered (nextReading), and the one not yet past is taken.
  Before, at 2026-11-01 01:20 EST (the second 01:20), "Nov 1, 1:30am
  (America/New_York)" was 01:30 EDT, 50 minutes past, so a full window
  read as renewed; "1:30am" was 24h10m away instead of 10m. In Berlin at
  02:20 CEST on 2026-10-25, "2:30am" was 02:30 CET, 1h10m away instead of
  10m (Sydney and Lord Howe alike).
- A date with no year is in the first of last year, this year and next
  that is less than a day past, as the doc comment already said. Before,
  only this year and next were tried, so at 2027-01-01 00:00:05
  "Dec 31, 11:59pm" was 2027-12-31, 8760h away, and a 7-day window that
  had just renewed read as renewing in a year.
- A time alone the clocks skip today is the next day that has it,
  rebuilt from the clock read rather than from the normalized time.
  Before, the evening after New York skipped 02:00-02:59, "2:30am" was
  tomorrow's 1:30am; at 23:31 before Santiago skips midnight, "12:30am"
  was 23:30 that night, a minute past, instead of 00:30 the day after
  tomorrow.

What Claude Code prints, from the /usage formatter in the 2.1.290 binary:
every line of `claude -p /usage` carries a date, with the year only when
it isn't this one, so the New Year case needs /usage run just before
midnight and parsed after, and the repeated hour shows in the dated form.
Whether "at" or a comma joins date and time follows the platform's ICU,
and both are parsed. A time alone is the older form, which the TUI still
prints for the session within a day.

No other parser in internal/provider fills in a missing date or year:
zhipuTime and mimoTime read full dates in UTC+8, and the rest read
RFC3339 or Unix times.

Verified:
- TestClaudeResetTimeAroundClockChanges and TestClaudeResetTimeAtNewYear
  are new. With upstream's claudeResetTime put back, 15 rows fail, e.g.
  `"Nov 1, 1:30am (America/New_York)" at 2026-11-01 01:20:00 -0500 EST:
  2026-11-01 01:30:00 -0400 EDT true (in -50m0s)` and `"Dec 31, 11:59pm
  (America/New_York)" at 2027-01-01 00:00:05 -0500 EST: 2027-12-31
  23:59:00 -0500 EST true (in 8759h58m55s)`; the 16 controls pass. With
  the change, all pass, as does TestParseClaudeUsage, also with
  -race -count=20.
- An oracle that lists every instant a zone shows a clock at was swept
  over 518 zones, every transition 2025-2030, 85M calls: no deviation in
  anything Claude Code can print. What remains is Feb 29 in a non-leap
  year and dated times the clocks skip, both unchanged from upstream.
- Under a temporary HOME with GOPATH, GOMODCACHE and GOCACHE pinned:
  go vet ./..., go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build, go test -tags nogui ./... all pass.
- Not run: claude -p /usage on a real account across a clock change or
  New Year.

* provider: a Claude reset further ahead than its window can reach is the one already past, so a /usage reading days old no longer rests an account for a year

claudeResetTime now gets the window's length (5 hours for "Current
session", 7 days for "Current week ...") and never reads a reset further
ahead than that plus claudeResetSlack (2h, for this machine's clock being
behind Anthropic's; Claude Code prints the reset from Anthropic's instant
with seconds dropped, so never later).

- A date with no year is in the first of last year, this year and next
  that is less than a day past and within the window. Before, it was the
  first less than a day past: read on Oct 5, a week's "Oct 1, 3pm" was
  2027-10-01, 8667h away, and routing (candidate.full, Allowance.Full)
  rested a full account that long. Now it is 2026-10-01.
- Where no year fits, the latest year where it is already past is taken,
  rather than dropping ResetsAt. The date read fine, and the window's
  length rules out every later year, so the reset has passed and the
  window has renewed, which is what elapsed() does with a past reset.
  Dropping it would keep a 100% window with no time to clear it: Pooled
  counts a full model window with no reset as out, so Opus on the account
  stayed refused until the next read, and the card showed 100% with no
  reset.
- A 5-hour window's date 6 days ahead ("Oct 11, 3pm" on Oct 5) is likewise
  last year's and reads as renewed; a week's keeps Oct 11.
- A time alone (the older form) is the next one within the window, else
  the latest day where it is already past: at noon, "11am" is today's for
  the session (was tomorrow's, 23h on) and tomorrow's for the week.
- A fresh /usage read now goes through elapsed() as a kept one does, so a
  reset it gives as past reads as renewed at once. Before, only the next
  look did, and the switch (NextLogin's usedPast) and quota alerts saw the
  fresh 100%.
- Dates with a year are unchanged.

Tests: TestClaudeResetTimeWithinItsWindow covers the cases above, the
inclusive bound (exactly span+slack is kept, a minute more is not, for a
date and a time alone), a week across New York's fall-back, and
claudeWindows' fresh and kept reads of a 4-day-old reset (Used 0, no
reset, Full zero). The DST rows and the other New Year rows pass
unchanged, at the week's length. Changed existing rows, each of which
asserted a reset further ahead than any window reaches: TestParseClaudeUsage's
"Current week (Opus) ... Jan 2 at 2pm" read Oct 1 (now 2026-01-02), the
#631 "Jan 2, 9:05am (UTC)" row (2026-01-02), and the New Year "Dec 30,
11pm" read Jan 1 01:00, 26h past (2026-12-30, not 2027-12-30). The #631
format rows are read on Oct 3 instead of Oct 1, so "Oct 9, 2:59pm" stays
within its week. Fixtures that gave a 5-hour session a reset the next day
(soon(1) at 3:30pm in claude_usage, claude_seats, claude_usage_switched;
claude_made_first in gateway; "Jul 20 at 10am" at midnight in
claude_scoped) now give one 3 hours on, as /usage would.

Fails without: with the bound removed and fresh reads not through
elapsed, TestClaudeResetTimeWithinItsWindow fails ("Oct 1, 3pm (UTC)" for
168h at 2026-10-05: 2027-10-01 15:00 (in 8667h), want 2026-10-01 15:00;
"Oct 11, 3pm (UTC)" for 5h: 2026-10-11 (in 147h), want 2025-10-11;
"read true: held until 2027-10-03 15:00"), as do TestParseClaudeUsage and
TestClaudeResetTimeAtNewYear on the changed rows. With the bound but
fresh reads not through elapsed, it fails with "read true: 5 hours
Used:100 ResetsAt:<4 days ago>".

Verified, under a temp HOME with GOPATH, GOMODCACHE and GOCACHE pinned:
go vet ./..., go build, GOOS=linux go build -tags nogui, GOOS=windows go
build, go test -tags nogui ./... (all pass), and go test -race -count=20
-run 'TestClaudeResetTime|TestParseClaudeUsage' ./internal/provider.
Not run: claude /usage on a real account read days late. Unchanged: a
week's time alone read minutes after its reset still reads as tomorrow's
(at most a day).

* gateway: a subscription account that fails with a window full rests until it renews, but no more than 8 days, so a reset time read a year off no longer benches it for that year

restAfter's default branch (a failure that isn't credit, quota, a rate
limit or verification: a 502, a sign-in error) rests a subscription
account until its fullest window renews, by c.full(now). That time is
the vendor's reading, not the failure's: Claude Code's /usage text, read
by claudeResetTime, takes a date with no year for next year when it reads
it wrong, and the account then sat out ~365 days until the user noticed
and lifted it by hand. The failQuota branch of the same function already
holds every rest, window included, to longestQuota (a week's window and a
day over); the window rest here now takes the same bound:
min(t.Sub(now), longestQuota). A window renewing within 8 days rests
exactly as before.

Why longestQuota and not the full window's own Span: Allowance.Full
returns only the renewal time, so the call site doesn't know which window
was full or how long it runs; Span is zero where a reading doesn't say
(plugin windows may not); and a failure that isn't about quota must not
sit out longer than one that is, which the quota branch already caps at
8 days. Bounding by Span would only shorten a misread 5-hour window from
8 days to 5 hours, and would have to change the quota branch with it, so
it is left for a change of its own.

Siblings: restAfterMarked is the only place that stores a rest
(restingUntil). Its other branches are bounded already: failQuota by
longestQuota (resets in the body, the noted header, the window and
Retry-After alike), failRate by longestWait and longestRateRest, credit
and verify by constants; a key never takes the default branch's window
rest (c.p.Account != nil). Every other use of a window's reset (capHeld,
Allowance.Full/Renewal/Restarts/Pace in weighing, the sink condition) is
computed again from the latest reading on each request and stores
nothing. Not changed here: cappedError's soonest renewal still becomes
the agent's Retry-After uncapped, and a stored window rest isn't lifted
when a later reading corrects the time (only OnRenewed or a manual
Unrest does), so a bad reading can still bench an account for up to 8
days. Claude's parsing is fixed in the commit before this one, and a
Claude account's window rest is lifted by a renewed reading in #1200.

docs/subsystems/gateway-routing.md says so in the runtime path; its
gateway test list already takes the new test by its TestRouting prefix.

Verified under a temporary HOME with GOPATH, GOMODCACHE and GOCACHE
pinned: go vet ./..., go build, GOOS=linux go build -tags nogui and
GOOS=windows go build pass. TestRoutingHoldsAWindowRestToLongestQuota (new): a
Claude account whose window is full with ResetsAt a year out, failing
502, rests at most longestQuota; a control renewing in 3h rests 3h.
Without the change it fails: "window read a year off: rests
8759h59m59.999682292s by window (other), want at most 192h0m0s". It
passes with -race -count=20, with TestOrderedKeepsAnAccountAt98 and
TestQuotaRestsUntilItsReset. The routing reference's gateway test set
passes.

go test -tags nogui ./... ran with the machine at a load average of
~125 on 12 cores, and three packages failed there, none on this path:
internal/davsync timed out at 10m (it passes alone in 353s);
TestSetAnswersWhileDevinAndProvidersHang fails on e95852e3 too (4 of 20
with -race); TestQuietStreamsKeptAliveEveryProtocol/chat_mid-reply (a
keepalive written before the reply already passed) failed 6, then 1,
then 0 of 20 here with -race and 0 of 60 on e95852e3. Its provider is a
key that answers, so restAfter, the only code changed, never runs in it;
it is left for a change of its own, not called a flake.
2026-10-08 06:20:03 +08:00
yetone 5ca143bff3 provider: Claude usage reads the reset times Claude Code 2.1.285 on prints, "Oct 9, 2:59pm (UTC)" with a comma where "at" was (#631) — claudeResetTime took only "Oct 9 at 2:59pm", so the weekly windows lost their reset time. It now takes "Jan 2, 3:04pm", "Jan 2, 3pm" and the same with a year; TestParseClaudeUsage covers them (fails without the change). go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build and go test -tags nogui -count=1 ./... under a temp HOME pass. 2026-10-03 12:45:15 +08:00
SadWood 34538b0a4b Preserve fresh Claude headers and shorten tray cache labels (#548)
* Preserve fresh Claude headers and shorten tray cache labels

* Keep local permission errors separate from Claude account refusals
2026-10-02 18:31:27 +08:00
SadWood e0121f71b9 Preserve dated Claude usage when allowance is unavailable (#511)
* fix(provider): preserve dated Claude usage after unavailable reads

* fix: clarify cached Claude usage and preserve account return
2026-10-02 14:46:42 +08:00
yetone a2714f7506 claude: a Claude account's usage resets are read in the zone /usage names on Windows too, and the provider tests pass whole on Windows (goal: 插件订阅 provider 跟内置的所有逻辑都要一模一样, run on Windows and Linux) — Windows has no time zone database, so "resets Oct 1 at 3:30pm (Asia/Shanghai)" was read in the machine's own zone, hours off for anyone not in that zone; magpie now carries the database (time/tzdata). The provider tests set HOME but not USERPROFILE, which Windows takes the home from, so on Windows they read the test box's own agent sign-ins (Gemini models in a list, an extra provider, a Cursor version); every test home sets both now. Tests whose fake CLI is a shell script (Claude Code's auth status, codex --version, macOS's security) skip on Windows, as the fake devin did, and file mode bits go unchecked there. TestParseClaudeUsage fails on Windows without the change. On Windows and on Linux (WSL) the provider package passes whole, three times on Windows (15 failed before), the plugin package and the move/plugin/Grok/Devin/usage tests five times over on Linux. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass. 2026-10-01 13:51:24 +08:00
yetone 9bf6d43527 claude: magpie no longer asks Anthropic for a Claude account's usage, and adding a Claude account warns of a ban (the user: 不要伪造任何的 Claude 请求,能否通过 claude cli 获取 / 我害怕被封; 添加账号时要像其他的 Subscription Provider 一样显示风险提示) — the usage was read by magpie itself calling Anthropic's /api/oauth/usage with the account's token, on a timer, for every saved account, and Claude's usage-limit resets (cedar_ember) were listed, spent and auto-spent the same way. Now the usage is what Claude Code's own /usage prints (claude -p /usage, a command Claude Code answers itself without asking a model), run only when Usage is opened or Refresh pressed (GUI, magpie quota, accounts, TUI), for the account Claude Code is signed in to, at most once in 30s; a saved account shows only what Claude Code reported while using it, or the last reading kept. The Claude resets, Auto-use and their settings are gone (Codex's stay). Session jsonl files hold no usage figures, so they aren't read. Starting a Claude sign-in or import (GUI and CLI) first says Anthropic may suspend or ban the account and that it is at the user's own risk. TestClaudeWindowsAsked, TestParseClaudeUsage, TestClaudeUsageRunsClaudeCode, claude-usage-asked.test.cjs and claude-risk.test.cjs fail without the change. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass; routing-auto-reset, codex-auto-reset, quota-families, tray-usages, click-scroll, old-webkit, plugin-signin, usage-alert, usage-ledger pass. 2026-10-01 12:38:25 +08:00