provider: the Claude keep-alive keeps off accounts, its reading, and its turn (#4532)

stringke read b48881f50 and 42c49e74d and left three notes on #4532
(issuecomment-6540015427). All three hold against the code:

1. Only accounts that were on were kept alive (claudeKeptAlive needed
   l.On). An account switched off as a reserve is still a sign-in the
   user kept for later, and Codex's keep-alive already renews saved
   ChatGPT sign-ins on or off. A run of Claude Code's /usage every eight
   days costs one local run and asks Anthropic nothing magpie doesn't
   already ask, so off accounts are kept too. Setup-token and signed-out
   accounts still aren't. The keep-alive never switches an account on.

2. The run's /usage reading was dropped (`_, err :=
   readSavedClaudeUsage`). The run now goes through the account's
   reading, the way a card's refresh reads a saved account:
   renewClaude forgets the account's minute-cached reading and calls
   loginReading with a keepingAlive ctx (asked, so nothing is held).
   claudeWindows runs Claude Code for it as for savedRefresh, past the
   30-second floor (the keep-alive is an hour apart at most), and keeps
   it in claudeUsage. loginReading keeps it beside the account and on
   disk (keepReading), and the new keepCardRead puts it on the account's
   card in the Usage cache with its history and the menu bar told, the
   way refreshCards does. A card the Usage page doesn't have isn't added.
   The run's own error comes back through the ctx, not the kept reading,
   so a failure is still told apart from a reading kept from before. This
   path doesn't bump the global ask generation, so Claude Code's own
   account isn't read again because of it.

3. A failed run held the hourly slot: still due, and with one renewal a
   look, the accounts after it never had theirs. A renewal that fails, for
   Claude and for Codex (the same loop had the same gap), now waits
   keepAliveRetry (6 hours, in memory) before the hourly look tries it
   again, and doesn't take the look's turn meanwhile. `magpie accounts
   refresh` (every 0) still tries it at once. A success clears it.

The help text, refreshAccounts' comment and providers-accounts.md say so.

Run on mote at 82b45888a plus this change: go test -timeout 45m
-count=1 ./internal/provider/... ./internal/cli/... ok; go test -race
-count=10 -run 'TestRenewLogins|WeeklyOnly|TestClaudeUsage'
./internal/provider ok; gofmt -l clean; GOOS=linux go vet -tags nogui,
GOOS=windows go vet and go vet of ./internal/provider/...
./internal/cli/... clean.

Broken by hand, each on mote:
- l.On put back in claudeKeptAlive: TestRenewLoginsKeepsSavedClaudeSignedIn
  ("renewed what wasn't due" with team@ missing), TestRenewLoginsKeepsClaudeReading,
  TestRenewLoginsFailedWaitsItsTurn and TestRenewLoginsLeavesClaudeSetupToken
  fail.
- renewClaude back to `_, err := readSavedClaudeUsage(...)`:
  TestRenewLoginsKeepsClaudeReading fails ("the account's reading: false").
- renewWaiting taken out of the loop: TestRenewLoginsFailedWaitsItsTurn
  fails at look 2 (the failed account took the turn again).

Not tried: real accounts and real Claude Code (fake runner, sandbox
HOME). The back-off is in memory, so a restarted magpie tries a failed
account on its first look. Codex's back-off is covered only through the
shared loop; there's no Codex-specific test for it.
This commit is contained in:
yetone
2026-10-31 14:40:03 +08:00
parent 82b45888ac
commit fbb1b36d1f
7 changed files with 409 additions and 53 deletions
+1 -1
View File
@@ -253,7 +253,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.
- Each refresh token has exactly one holder. Vendors rotate tokens on refresh, so two copies of one token would sign each other out. `savedTokenMu` stops two requests refreshing one saved account at once.
- A Claude subscription account is used only for Claude Code, through the genuine Claude Code binary (see [Claude subscription bridge](claude-subscription-bridge.md)).
- Claude usage asks are ordered by `claudeAskGeneration`, not wall-clock timestamps. `AskClaudeUsage` and a Claude card's `RefreshUsage` advance it while holding the subscription cache then the login cache lock (`markClaudeUsageAsked`). Each cache captures it under its own lock before launching a read and checks it under that lock when publishing: a newer ask prevents `LoginUsage` from keeping the older reading and leaves `SubscriptionUsage` due to read again. Each `claudeWindows` entry records the generation its run answered. The timestamp's zero sentinel, `tried`/`wait`, the 30-second floor, idle behavior and saved-account scope remain unchanged. [`login_usage.go`](../../internal/provider/login_usage.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go).
- A saved Claude account's allowance is read only when its own card is refreshed (#1630; `savedRefresh`: `RefreshUsage` for that account, so `cardRefresh.wants` it and the read is asked). The real Claude Code runs `/usage` with `CLAUDE_CONFIG_DIR` set to the account's `claudeSavedDir` (`readSavedClaudeUsage`, through the gateway's `claudeUsage`), so magpie never calls Anthropic with the token itself and the account Claude Code is signed in to is not switched. The Usage page opened, `magpie quota` and `magpie accounts` ask every card and so start no saved account's Claude Code: they keep its last reading, or `errClaudeSaved` before one. Background reads keep the last reading, and the 30-second per-account floor holds for repeated refreshes. Claude Code may refresh the account's token in that directory while it runs (its own lock file keeps two Claude Codes in one directory from refreshing at once). So `inSavedClaudeDir` holds `claudeDirRun(user)` for reading while it runs, which `switchSavedLogin` takes for writing first, and after the run `syncSavedClaude` copies a rotated sign-in back into `logins.json` under `savedTokenMu` and `loginsMu`. A saved account's warm-up runs the same way, and so does the keep-alive (#4532): every eight days (`keepAliveEvery`, as for a ChatGPT sign-in, since how long Anthropic keeps an idle Claude refresh token isn't known), one account a look shared with Codex's, `RenewLogins` runs that `/usage` once for each saved Claude account that is on, has a sign-in rather than a setup-token and isn't signed out (`claudeKeptAlive`, `renewClaude`), so Claude Code refreshes the sign-in if it is due and `syncSavedClaude` keeps it. The run marks `Renewed`, refreshed or not. A refusal is kept as a request's is (`NoteClaudeSignInFailure`, or the emptied sign-in `syncClaudeDir` reads), so the account's row says to sign in again. Its reading isn't kept as the card's (`TestRenewLoginsKeepsSavedClaudeSignedIn`). [`claude_usage_saved_test.go`](../../internal/provider/claude_usage_saved_test.go) covers the refresh, the other accounts left alone, the floor, background reads, a switch waiting for the run and the rotated sign-in kept; `TestClaudeUsageRunsInSavedAccountDirectory` checks the directory the command runs in.
- A saved Claude account's allowance is read only when its own card is refreshed (#1630; `savedRefresh`: `RefreshUsage` for that account, so `cardRefresh.wants` it and the read is asked). The real Claude Code runs `/usage` with `CLAUDE_CONFIG_DIR` set to the account's `claudeSavedDir` (`readSavedClaudeUsage`, through the gateway's `claudeUsage`), so magpie never calls Anthropic with the token itself and the account Claude Code is signed in to is not switched. The Usage page opened, `magpie quota` and `magpie accounts` ask every card and so start no saved account's Claude Code: they keep its last reading, or `errClaudeSaved` before one. Background reads keep the last reading, and the 30-second per-account floor holds for repeated refreshes. Claude Code may refresh the account's token in that directory while it runs (its own lock file keeps two Claude Codes in one directory from refreshing at once). So `inSavedClaudeDir` holds `claudeDirRun(user)` for reading while it runs, which `switchSavedLogin` takes for writing first, and after the run `syncSavedClaude` copies a rotated sign-in back into `logins.json` under `savedTokenMu` and `loginsMu`. A saved account's warm-up runs the same way, and so does the keep-alive (#4532): every eight days (`keepAliveEvery`, as for a ChatGPT sign-in, since how long Anthropic keeps an idle Claude refresh token isn't known), one account a look shared with Codex's, `RenewLogins` runs that `/usage` once for each saved Claude account, on or off (one off is a sign-in kept for later, as a ChatGPT one is), that has a sign-in rather than a setup-token and isn't signed out (`claudeKeptAlive`, `renewClaude`), so Claude Code refreshes the sign-in if it is due and `syncSavedClaude` keeps it. The run goes through the account's reading as a card refresh's does (`keepingAlive` has `claudeWindows` run it, past the 30-second floor; `loginReading` keeps it beside the account and on disk, `keepCardRead` on its card when the Usage page has one), so under switch-only it is the reading a saved account gets. The run marks `Renewed`, refreshed or not. A refusal is kept as a request's is (`NoteClaudeSignInFailure`, or the emptied sign-in `syncClaudeDir` reads), so the account's row says to sign in again. A renewal that fails, of either agent, waits `keepAliveRetry` (6 hours, `renewWaiting`) before the hourly look tries it again, so it doesn't take every look's one turn from the accounts after it; `magpie accounts refresh` tries it at once (`TestRenewLoginsKeepsSavedClaudeSignedIn`, `TestRenewLoginsKeepsClaudeReading`, `TestRenewLoginsFailedWaitsItsTurn`). [`claude_usage_saved_test.go`](../../internal/provider/claude_usage_saved_test.go) covers the refresh, the other accounts left alone, the floor, background reads, a switch waiting for the run and the rotated sign-in kept; `TestClaudeUsageRunsInSavedAccountDirectory` checks the directory the command runs in.
- Claude Code's `/usage` prints a reset with no year when it falls this year ("Oct 9, 2:59pm (UTC)"), or, in older versions, as a time alone ("3pm"). `claudeResetTime` reads it as the end of its window, so never further ahead than the window's length (5 hours for the session, 7 days for a week) and `claudeResetSlack`: a date is in the first of last year, this year and next that is less than a day past and no further ahead, a time alone the next one no further ahead. Where none is, as for a reading days old, it is the latest one already past, so the window reads as renewed rather than full for a year. Where the clocks go back and show a time twice, the reading not yet past is taken. A week's time alone read just after its reset still reads as tomorrow's.
- A Copilot account is known by its GitHub login and host (`CopilotAccountName`, #1220): `mona` on github.com, `mona@acme.ghe.com` on an enterprise's GHE.com. That name is its `logins.json` user, its row in every list, its usage card and its per-account routing settings, and it is what `SwitchLogin`, `SetLoginOn` and `ForgetLogin` take, so one login on two hosts is two accounts, neither written over by the other nor dropped as the editors' own. One saved before on an enterprise's host under its login alone is read under its name with the host (`copilotSavedName`), keeping its id; the editors' own remembered so is renamed in place, still hidden if it was (`copilotRenamed`). Either rename takes the account's per-account settings in `providers.json` (proxy, models, cap, concurrency) from the bare login to the new name before the new name is written to `logins.json` (`renameSettled`): a setting the new name has already stays, and while `providers.json` can't be read or written the account stays saved under its old name, its settings with it. `magpie accounts switch|forget copilot` takes the full name, the login with `--host <name>.ghe.com`, or the login alone when it names one account.
- A Codex account is known by its email, with the plan for a workspace seat (`codexUser`), and a second seat of one email in another workspace by that name with its workspace after it (`codexName`): `me@example.com · Team · ws-two`. The account Codex is signed in to goes by the name it is saved under (`codexLiveName`) everywhere: its provider's `Account.User` (`codexAccount`), `liveLogin`, and its session identity (`SessionIdentities`). Its allowance, rests and sticks (`restKey`), cap, proxy, model list, a gateway key's account list (`LoginID`) and the Routing page all go by that name, so two seats of one email are never read as one (#1424).
+1 -1
View File
@@ -690,7 +690,7 @@ func openURLInBrowser(url string) {
}
// refreshAccounts: `magpie accounts refresh` renews the sign-in of every
// saved ChatGPT account, and every saved Claude account that is on (Claude
// saved ChatGPT account, and every saved Claude account, on or off (Claude
// Code's /usage run in its own directory), the agent isn't signed in to
// now — what the gateway does every eight days, for a magpie that isn't
// left running (cron, launchd). A sign-in the vendor refuses is marked as
+1 -1
View File
@@ -97,7 +97,7 @@ const usage = `magpie — one place to pick every agent's model
magpie accounts discovery [on|off] read agents' sign-ins (default on; MAGPIE_NO_ACCOUNTS=1 disables too)
magpie accounts import <codex|claude|antigravity|factory> <file>... [--yes] bring in accounts from other tools' files (Codex's auth.json, Cockpit Tools, CLIProxyAPI, Sub2API); the tool a ChatGPT or Claude file came from is signed out of it
magpie accounts switch <agent> <email> sign the agent in to another of them
magpie accounts refresh renew the saved ChatGPT sign-ins, and the Claude ones that are on, now (the gateway does it every 8 days)
magpie accounts refresh renew the saved ChatGPT and Claude sign-ins now (the gateway does it every 8 days)
magpie accounts checkin WorkBuddy's daily check-in (签到) for each WorkBuddy account, now (Settings can do it daily)
magpie accounts project <gemini|antigravity> <email> <project> the Google Cloud project a Google account's requests go to
magpie accounts alias <agent> <email> [<name>|--clear] a name of your own for an account, shown on its card, in the menu bar and in magpie quota
+128 -15
View File
@@ -10,17 +10,20 @@ package provider
// account an hour, never all of them at once. The account the agent is signed in to is the
// agent's own to refresh, and is left to it.
//
// A saved Claude account that is on goes the same way, but is never
// A saved Claude account goes the same way, on or off, but is never
// refreshed by magpie, nor is Anthropic asked anything with its sign-in
// (9bf6d4352): Claude Code refreshes it whenever it runs on it
// (claude_dirs.go), so the keep-alive runs Claude Code's /usage once in the
// account's own config directory, as its card's refresh does, and keeps
// what Claude Code made of the sign-in (syncSavedClaude). One switched on
// what Claude Code made of the sign-in (syncSavedClaude) and the reading
// (its card's, as a refresh keeps it). One switched on
// to stand behind Claude Code's own but not needed for weeks
// (switch-only) otherwise had nothing run on it, and was found signed out
// only when the switch reached it (#4532). How long Anthropic keeps an idle
// Claude refresh token isn't known, so it is run as often as a ChatGPT
// one is renewed, every eight days.
// one is renewed, every eight days. One switched off is kept too, as a
// ChatGPT one is: it is a sign-in the user kept for later, and found
// signed out when turned on again it was no reserve (#4532).
import (
"context"
@@ -28,6 +31,7 @@ import (
"errors"
"log"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/settings"
@@ -45,6 +49,45 @@ const keepAliveEvery = 8 * 24 * time.Hour
// instead of being renewed side by side for good.
const keepAliveAtOnce = 1
// keepAliveRetry is how long a saved sign-in whose renewal failed is left
// before the keep-alive tries it again. Left due, it took the one renewal
// of every hourly look, and the accounts after it never had theirs
// (#4532): they go first meanwhile.
const keepAliveRetry = 6 * time.Hour
// renewFailed is when each saved sign-in's renewal last failed
// (agent/user), for keepAliveRetry; one that went through is taken out.
var renewFailed struct {
sync.Mutex
m map[string]time.Time
}
func renewKey(agent, user string) string { return agent + "/" + strings.ToLower(user) }
// renewWaiting says the renewal of agent's user failed less than
// keepAliveRetry before now.
func renewWaiting(agent, user string, now time.Time) bool {
renewFailed.Lock()
defer renewFailed.Unlock()
t, ok := renewFailed.m[renewKey(agent, user)]
return ok && now.Sub(t) < keepAliveRetry
}
// noteRenewal keeps whether r failed, for renewWaiting.
func noteRenewal(r Renewal) {
renewFailed.Lock()
defer renewFailed.Unlock()
k := renewKey(r.Agent, r.User)
if r.Err == "" {
delete(renewFailed.m, k)
return
}
if renewFailed.m == nil {
renewFailed.m = map[string]time.Time{}
}
renewFailed.m[k] = time.Now()
}
// Renewal is what came of renewing one saved account.
type Renewal struct {
Agent string `json:"agent"`
@@ -56,16 +99,17 @@ type Renewal struct {
Lapsed bool `json:"lapsed,omitempty"`
}
// RenewLogins renews the saved ChatGPT sign-ins, and the saved Claude
// sign-ins that are on, not in the agent's hands that have gone every or
// longer without it; every 0 renews all of them.
// RenewLogins renews the saved ChatGPT and Claude sign-ins not in the
// agent's hands that have gone every or longer without it; every 0 renews
// all of them, one that failed lately too.
func RenewLogins(ctx context.Context, every time.Duration) []Renewal {
return renewLogins(ctx, every, 0)
}
// renewLogins is RenewLogins renewing at most atOnce of the due sign-ins
// (0: all of them); a due one past that is left for the next look and
// reported as not renewed.
// reported as not renewed, as is one whose renewal failed less than
// keepAliveRetry ago, which doesn't take the look's turn.
func renewLogins(ctx context.Context, every time.Duration, atOnce int) []Renewal {
if settings.AccountDiscoveryOff() {
return nil
@@ -87,13 +131,15 @@ func renewLogins(ctx context.Context, every time.Duration, atOnce int) []Renewal
continue
}
r := Renewal{Agent: l.Agent, User: l.User}
if every > 0 && !renewalDue(l, every, time.Now()) || atOnce > 0 && tried >= atOnce {
if every > 0 && (!renewalDue(l, every, time.Now()) || renewWaiting(l.Agent, l.User, time.Now())) || atOnce > 0 && tried >= atOnce {
out = append(out, r)
continue
}
tried++
if l.Agent == "claude" {
out = append(out, renewClaude(ctx, r))
r = renewClaude(ctx, r)
noteRenewal(r)
out = append(out, r)
continue
}
why := ctx
@@ -107,29 +153,96 @@ func renewLogins(ctx context.Context, every time.Duration, atOnce int) []Renewal
} else {
r.Renewed = true
}
noteRenewal(r)
out = append(out, r)
}
return out
}
// claudeKeptAlive says the saved Claude login l is one the keep-alive
// runs Claude Code on: switched on, with a sign-in Claude Code refreshes
// (a setup-token has none, and lasts a year), and not signed out already,
// which its row says.
// runs Claude Code on: one with a sign-in Claude Code refreshes (a
// setup-token has none, and lasts a year), and not signed out already,
// which its row says. Switched off or not: off, it is still a sign-in
// kept for when it is turned on.
func claudeKeptAlive(l savedLogin) bool {
return l.Agent == "claude" && l.On && claudeSetupToken(l.Auth) == "" && claudeSignedOut(l) == ""
return l.Agent == "claude" && claudeSetupToken(l.Auth) == "" && claudeSignedOut(l) == ""
}
// keepAliveRun is the keep-alive's run of Claude Code's /usage for one
// saved account (renewClaude), as the reading it goes through tells it:
// whether it ran, and how it failed.
type keepAliveRun struct {
user string
mu sync.Mutex
ran bool
err error
}
type keepAliveRunKey struct{}
// keepingAlive is ctx for the keep-alive's reading of the saved Claude
// account user: claudeWindows runs Claude Code for it, as for a refresh
// of its card, and tells run what came of it.
func keepingAlive(ctx context.Context, user string) (context.Context, *keepAliveRun) {
run := &keepAliveRun{user: user}
return context.WithValue(ctx, keepAliveRunKey{}, run), run
}
// keepAliveOf is the keep-alive's run ctx reads user for, or nil.
func keepAliveOf(ctx context.Context, user string) *keepAliveRun {
run, _ := ctx.Value(keepAliveRunKey{}).(*keepAliveRun)
if run == nil || !strings.EqualFold(run.user, user) {
return nil
}
return run
}
func (k *keepAliveRun) done(err error) {
k.mu.Lock()
defer k.mu.Unlock()
k.ran, k.err = true, err
}
func (k *keepAliveRun) result() (bool, error) {
k.mu.Lock()
defer k.mu.Unlock()
return k.ran, k.err
}
// errKeepAliveNotRun is a keep-alive whose reading ran no Claude Code:
// another reading of the account was running, or had just run.
var errKeepAliveNotRun = errors.New("Claude Code wasn't run: the account was being read already")
// renewClaude has Claude Code keep the saved Claude account r.User signed
// in: its /usage run once in the account's config directory, where Claude
// Code refreshes the sign-in when it is due, and what it made of it kept in
// logins.json. A run that went through is the account's renewal, refreshed
// logins.json. The run is the account's reading, read and kept as its
// card's refresh reads it (loginReading, keepCardRead): under switch-only
// it is the one a saved account has. A run that went through is the account's renewal, refreshed
// or not (a sign-in Claude Code needn't refresh yet is a live one); one
// whose sign-in Claude Code was refused is marked as needing a new one, on
// the account's row, as a request's refusal is (NoteClaudeSignInFailure).
func renewClaude(ctx context.Context, r Renewal) Renewal {
version := ClaudeLoginVersion(r.User)
_, err := readSavedClaudeUsage(ctx, r.User)
l := Login{Agent: "claude", User: r.User}
for _, x := range Logins("claude") {
if !x.Active && strings.EqualFold(x.User, r.User) {
l = x
}
}
// asked for, as a card's refresh is: nothing of it is held back
ctx, run := keepingAlive(Asked(ctx), r.User)
ctx, seq := quotaReading(ctx)
forgetLoginReading(l)
face := accountCard("claude")
q := loginReading(ctx, l).read
q.Name, q.Icon, q.User = face.name, face.icon, l.User
ran, err := run.result()
if ran {
keepCardRead(q, seq)
} else {
err = errKeepAliveNotRun
}
if err != nil {
NoteClaudeSignInFailure(r.User, version, err.Error())
}
+244 -33
View File
@@ -12,14 +12,15 @@ import (
"time"
)
// #4532: a saved Claude account switched on but not needed for weeks
// (switch-only) had nothing run on it, and its refresh token sat idle
// until it was found signed out. The keep-alive has Claude Code itself
// run on it, in its own config directory, and keeps what Claude Code made
// of the sign-in; magpie asks Anthropic nothing (fakeClaudeUsage fails a
// test that does).
// #4532: a saved Claude account not needed for weeks (switch-only, or
// switched off as a reserve) had nothing run on it, and its refresh token
// sat idle until it was found signed out. The keep-alive has Claude Code
// itself run on each, in its own config directory, and keeps what Claude
// Code made of the sign-in; magpie asks Anthropic nothing (fakeClaudeUsage
// fails a test that does).
func TestRenewLoginsKeepsSavedClaudeSignedIn(t *testing.T) {
claudeThree(t) // team@ and max@ saved, Claude Code on pro@
keepAliveClean(t)
var text atomic.Value
text.Store("Current week (all models): 1% used · resets Nov 6 at 11am (Asia/Dubai)")
fakeClaudeUsage(t, &text, nil)
@@ -38,7 +39,7 @@ func TestRenewLoginsKeepsSavedClaudeSignedIn(t *testing.T) {
if rotate.Load() {
// as Claude Code refreshes a sign-in that is due
writeFile(t, filepath.Join(dir, ".credentials.json"), map[string]any{"claudeAiOauth": map[string]any{
"accessToken": "tok-max-2", "refreshToken": "r-max-2",
"accessToken": "tok-2", "refreshToken": "r2-" + dir,
"expiresAt": time.Now().Add(8 * time.Hour).UnixMilli(), "subscriptionType": "max"}})
}
return text.Load().(string), nil
@@ -48,12 +49,16 @@ func TestRenewLoginsKeepsSavedClaudeSignedIn(t *testing.T) {
defer mu.Unlock()
out := slices.Clone(dirs)
dirs = nil
slices.Sort(out)
return out
}
max, team := "max@x.com", "team@x.com · Acme"
// max@ on behind Claude Code's own; team@ left off, kept for later
if err := SetLoginOn("claude", max, true); err != nil {
t.Fatal(err)
}
both := []string{claudeAccountDir(max), claudeAccountDir(team)}
slices.Sort(both)
saved := func(user string) savedLogin {
for _, l := range readLogins() {
if l.Agent == "claude" && l.User == user {
@@ -63,32 +68,49 @@ func TestRenewLoginsKeepsSavedClaudeSignedIn(t *testing.T) {
t.Fatalf("%s isn't saved", user)
return savedLogin{}
}
of := func(rs []Renewal) map[string]Renewal {
m := map[string]Renewal{}
for _, r := range rs {
m[r.User] = r
}
if len(m) != len(rs) {
t.Fatalf("an account twice: %+v", rs)
}
return m
}
ctx := context.Background()
// seen in Claude Code's hands a moment ago: not due, nothing run
if rs := RenewLogins(ctx, keepAliveEvery); len(rs) != 1 || rs[0].User != max || rs[0].Renewed || len(runs()) != 0 {
if rs := of(RenewLogins(ctx, keepAliveEvery)); len(rs) != 2 || rs[max].Renewed || rs[team].Renewed || len(runs()) != 0 {
t.Fatalf("renewed what wasn't due: %+v", rs)
}
// due: Claude Code runs once, in max@'s own directory; team@, off,
// and pro@, Claude Code's own, are left alone
// due: Claude Code runs once in each saved account's own directory,
// the one switched off too; pro@, Claude Code's own, is left alone
rotate.Store(true)
rs := RenewLogins(ctx, 0)
if len(rs) != 1 || rs[0].Agent != "claude" || rs[0].User != max || !rs[0].Renewed || rs[0].Err != "" || rs[0].Lapsed {
t.Fatalf("renew: %+v", rs)
rs := of(RenewLogins(ctx, 0))
for _, u := range []string{max, team} {
if r := rs[u]; r.Agent != "claude" || !r.Renewed || r.Err != "" || r.Lapsed {
t.Fatalf("renew %s: %+v", u, rs)
}
}
if got := runs(); len(got) != 1 || got[0] != claudeAccountDir(max) {
t.Fatalf("Claude Code ran in %q, want only %q", got, claudeAccountDir(max))
if len(rs) != 2 {
t.Fatalf("renewed: %+v", rs)
}
l := saved(max)
if c, _ := parseClaudeCredentials(l.Auth); c.OAuth.RefreshToken != "r-max-2" {
t.Fatalf("the sign-in Claude Code refreshed isn't kept: %+v", c.OAuth)
if got := runs(); !slices.Equal(got, both) {
t.Fatalf("Claude Code ran in %q, want %q", got, both)
}
if time.Since(l.Renewed) > time.Minute || renewalDue(l, keepAliveEvery, time.Now()) || !renewalDue(l, keepAliveEvery, time.Now().Add(keepAliveEvery+time.Hour)) {
t.Fatalf("renewed at %v", l.Renewed)
for _, u := range []string{max, team} {
l := saved(u)
if c, _ := parseClaudeCredentials(l.Auth); c.OAuth.RefreshToken != "r2-"+claudeAccountDir(u) {
t.Fatalf("the sign-in Claude Code refreshed for %s isn't kept: %+v", u, c.OAuth)
}
if time.Since(l.Renewed) > time.Minute || renewalDue(l, keepAliveEvery, time.Now()) || !renewalDue(l, keepAliveEvery, time.Now().Add(keepAliveEvery+time.Hour)) {
t.Fatalf("%s renewed at %v", u, l.Renewed)
}
}
if c, _ := parseClaudeCredentials(saved(team).Auth); c.OAuth.RefreshToken != "r-team@x.com" {
t.Fatalf("team@, switched off, changed: %+v", c.OAuth)
if saved(team).On {
t.Fatal("the keep-alive switched team@ on")
}
if c, _ := parseClaudeCredentials(saved("pro@x.com").Auth); c.OAuth.RefreshToken != "r-pro@x.com" {
t.Fatalf("Claude Code's own account changed: %+v", c.OAuth)
@@ -97,16 +119,16 @@ func TestRenewLoginsKeepsSavedClaudeSignedIn(t *testing.T) {
// a sign-in Claude Code needn't refresh yet: the run is the renewal,
// so the account isn't run again every hour
rotate.Store(false)
if rs := RenewLogins(ctx, 0); !rs[0].Renewed || len(runs()) != 1 {
if rs := of(RenewLogins(ctx, 0)); !rs[max].Renewed || !rs[team].Renewed || len(runs()) != 2 {
t.Fatalf("a live sign-in: %+v", rs)
}
if rs := RenewLogins(ctx, keepAliveEvery); rs[0].Renewed || len(runs()) != 0 {
if rs := of(RenewLogins(ctx, keepAliveEvery)); rs[max].Renewed || rs[team].Renewed || len(runs()) != 0 {
t.Fatalf("run again within its eight days: %+v", rs)
}
// no answer: it may yet renew, so nothing is marked
fail.Store("Claude Code: network is unreachable")
if rs := RenewLogins(ctx, 0); rs[0].Err == "" || rs[0].Lapsed || rs[0].Renewed || saved(max).Lapsed != "" {
if rs := of(RenewLogins(ctx, 0)); rs[max].Err == "" || rs[max].Lapsed || rs[max].Renewed || saved(max).Lapsed != "" {
t.Fatalf("a network failure lapsed it: %+v", rs)
}
runs()
@@ -114,12 +136,12 @@ func TestRenewLoginsKeepsSavedClaudeSignedIn(t *testing.T) {
// refused: the account's row says to sign in again, as a request's
// refusal does, and the keep-alive runs nothing on it after
fail.Store("Claude Code: OAuth session expired and could not be refreshed. Please run /login.")
rs = RenewLogins(ctx, 0)
if len(rs) != 1 || !rs[0].Lapsed || rs[0].Renewed || !strings.Contains(rs[0].Err, "sign in again") {
rs = of(RenewLogins(ctx, 0))
if r := rs[max]; !r.Lapsed || r.Renewed || !strings.Contains(r.Err, "sign in again") {
t.Fatalf("refused: %+v", rs)
}
for _, lg := range Logins("claude") {
if (lg.User == max) != (lg.Lapsed != "") {
if (lg.User == max || lg.User == team) != (lg.Lapsed != "") {
t.Fatalf("lapsed: %+v", lg)
}
}
@@ -129,10 +151,190 @@ func TestRenewLoginsKeepsSavedClaudeSignedIn(t *testing.T) {
}
}
// keepAliveClean has the test start, and leave, with no renewal on record
// as failed (renewWaiting) and no reading kept from another test.
func keepAliveClean(t *testing.T) {
t.Helper()
clean := func() {
renewFailed.Lock()
renewFailed.m = nil
renewFailed.Unlock()
loginUsageCache.Lock()
loginUsageCache.m = nil
loginUsageCache.Unlock()
subscriptionUsageCache.Lock()
subscriptionUsageCache.data = nil
subscriptionUsageCache.Unlock()
lastQuotas.Lock()
lastQuotas.m, lastQuotas.loaded = nil, false
lastQuotas.Unlock()
}
clean()
t.Cleanup(clean)
}
// #4532: under switch-only the keep-alive's run is the one reading a saved
// account gets, so it is kept as the account's reading, as a refresh of
// its card keeps one: beside the account, on its card, and on disk.
func TestRenewLoginsKeepsClaudeReading(t *testing.T) {
claudeThree(t)
keepAliveClean(t)
var text atomic.Value
text.Store(claudeWeeklyOnly)
fakeClaudeUsage(t, &text, nil)
runs := atomic.Int32{}
UsageClaudeVia(func(_ context.Context, dir string) (string, error) {
runs.Add(1)
return strings.Replace(claudeWeeklyOnly, "(all models): 1%", "(all models): 37%", 1), nil
})
max := "max@x.com"
var l Login
for _, x := range Logins("claude") {
if x.User == max {
l = x
}
}
// the Usage page has read max@'s card before, with nothing then
subscriptionUsageCache.Lock()
subscriptionUsageCache.data = []SubscriptionQuota{{Provider: "claude", User: max, Name: "Claude Code", Windows: []QuotaWindow{}, Error: errClaudeSaved.Error()}}
subscriptionUsageCache.Unlock()
rs := RenewLogins(context.Background(), 0)
if runs.Load() != 2 {
t.Fatalf("%d runs: %+v", runs.Load(), rs)
}
used := func(ws []QuotaWindow) float64 {
for _, w := range ws {
if w.Name == "7 days" {
return w.Used
}
}
return -1
}
// beside the account (LoginUsage, the switch, warm-up)
e, ok := loginReadingKnown(l)
if !ok || used(e.read.Windows) != 37 || e.read.Error != "" || e.read.ReadAt == nil {
t.Fatalf("the account's reading: %v %+v", ok, e.read)
}
// as Claude Code told it, for the next look that reads none
if at := claudeReadAt(max); at == nil || time.Since(*at) > time.Minute {
t.Fatalf("read at %v", at)
}
// on its card
subscriptionUsageCache.Lock()
cards := slices.Clone(subscriptionUsageCache.data)
subscriptionUsageCache.Unlock()
if len(cards) != 1 || used(cards[0].Windows) != 37 || cards[0].Error != "" || cards[0].User != max {
t.Fatalf("the card: %+v", cards)
}
// and on disk, dated, for a magpie started after
lastQuotas.Lock()
lastQuotas.m, lastQuotas.loaded = nil, false
lastQuotas.Unlock()
q := keepLast(SubscriptionQuota{Provider: "claude", Windows: []QuotaWindow{}, Error: errClaudeSaved.Error()}, max)
if used(q.Windows) != 37 {
t.Fatalf("kept on disk: %+v", q)
}
}
// #4532: a renewal that fails before anything is refreshed (the network,
// a proxy, Claude Code not runnable) left the account due, and with one
// renewal a look it took every look: the accounts after it never had
// theirs. One that failed waits keepAliveRetry, the others going first.
func TestRenewLoginsFailedWaitsItsTurn(t *testing.T) {
claudeThree(t)
keepAliveClean(t)
var text atomic.Value
text.Store("Current week (all models): 1% used")
fakeClaudeUsage(t, &text, nil)
max, team := "max@x.com", "team@x.com · Acme"
// both due: last seen and renewed a month ago
loginsMu.Lock()
ls := readLogins()
order := []string{}
for i := range ls {
if ls[i].Agent == "claude" && (ls[i].User == max || ls[i].User == team) {
ls[i].Seen, ls[i].Renewed = time.Now().Add(-30*24*time.Hour), time.Now().Add(-30*24*time.Hour)
order = append(order, ls[i].User)
}
}
if err := writeLogins(ls); err != nil {
t.Fatal(err)
}
loginsMu.Unlock()
if len(order) != 2 {
t.Fatalf("saved: %v", order)
}
first, second := order[0], order[1]
var mu sync.Mutex
var ran []string
UsageClaudeVia(func(_ context.Context, dir string) (string, error) {
mu.Lock()
defer mu.Unlock()
ran = append(ran, dir)
if dir == claudeAccountDir(first) {
return "", errors.New("Claude Code: connect ECONNREFUSED 127.0.0.1:7890")
}
return text.Load().(string), nil
})
took := func() []string {
mu.Lock()
defer mu.Unlock()
out := ran
ran = nil
return out
}
look := func() map[string]Renewal {
m := map[string]Renewal{}
for _, r := range renewLogins(context.Background(), keepAliveEvery, keepAliveAtOnce) {
m[r.User] = r
}
return m
}
// the first look: the first account's turn, and it fails
if rs := look(); rs[first].Err == "" || rs[first].Lapsed || rs[second].Renewed {
t.Fatalf("look 1: %+v", rs)
}
if got := took(); !slices.Equal(got, []string{claudeAccountDir(first)}) {
t.Fatalf("look 1 ran %q", got)
}
// the next: the second's turn, not the failed one's again
if rs := look(); !rs[second].Renewed {
t.Fatalf("look 2: %+v", rs)
}
if got := took(); !slices.Equal(got, []string{claudeAccountDir(second)}) {
t.Fatalf("look 2 ran %q", got)
}
// the one after: nothing due but the failed one, which waits
if rs := look(); rs[first].Renewed || rs[first].Err != "" || len(took()) != 0 {
t.Fatalf("look 3: %+v", rs)
}
// past keepAliveRetry it is tried again
renewFailed.Lock()
for k, at := range renewFailed.m {
renewFailed.m[k] = at.Add(-keepAliveRetry - time.Minute)
}
renewFailed.Unlock()
if rs := look(); rs[first].Err == "" {
t.Fatalf("look 4: %+v", rs)
}
if got := took(); !slices.Equal(got, []string{claudeAccountDir(first)}) {
t.Fatalf("look 4 ran %q", got)
}
// `magpie accounts refresh` tries it at once, waiting or not
if rs := RenewLogins(context.Background(), 0); len(rs) != 2 {
t.Fatalf("refresh: %+v", rs)
}
if got := took(); !slices.Contains(got, claudeAccountDir(first)) {
t.Fatalf("refresh ran %q", got)
}
}
// Claude Code empties the sign-in in its directory when Anthropic refuses
// its refresh, and says no more of it: that too is the account signed out.
func TestRenewLoginsClaudeEmptiedSignIn(t *testing.T) {
claudeThree(t)
keepAliveClean(t)
var text atomic.Value
text.Store("Current week (all models): 1% used")
fakeClaudeUsage(t, &text, nil)
@@ -146,7 +348,16 @@ func TestRenewLoginsClaudeEmptiedSignIn(t *testing.T) {
t.Fatal(err)
}
rs := RenewLogins(context.Background(), 0)
if len(rs) != 1 || !rs[0].Lapsed || rs[0].Renewed {
n := 0
for _, r := range rs {
if r.User == max {
n++
if !r.Lapsed || r.Renewed {
t.Fatalf("emptied: %+v", rs)
}
}
}
if n != 1 {
t.Fatalf("emptied: %+v", rs)
}
for _, lg := range Logins("claude") {
@@ -156,16 +367,16 @@ func TestRenewLoginsClaudeEmptiedSignIn(t *testing.T) {
}
}
// A Claude account added by setup-token has no refresh token to keep, and
// one switched off isn't run on: only the accounts on are.
// A Claude account added by setup-token has no refresh token to keep;
// one signed in, on or off, has.
func TestRenewLoginsLeavesClaudeSetupToken(t *testing.T) {
l := savedLogin{Agent: "claude", User: "ci@x.com", On: true, Auth: []byte(`{"setupToken":"sk-ant-oat01-x"}`)}
if claudeKeptAlive(l) {
t.Fatal("a setup-token account is kept alive")
}
signedIn := []byte(`{"claudeAiOauth":{"accessToken":"a","refreshToken":"r"}}`)
if claudeKeptAlive(savedLogin{Agent: "claude", User: "x", Auth: signedIn}) {
t.Fatal("an account switched off is kept alive")
if !claudeKeptAlive(savedLogin{Agent: "claude", User: "x", Auth: signedIn}) {
t.Fatal("an account switched off isn't kept alive")
}
if !claudeKeptAlive(savedLogin{Agent: "claude", User: "x", On: true, Auth: signedIn}) {
t.Fatal("an account switched on isn't kept alive")
+22
View File
@@ -164,6 +164,28 @@ func refreshCards(ctx context.Context, provider, user string) (subs, plans, bala
return subs, plans, balances
}
// keepCardRead keeps q, an account's card read outside a refresh of it
// (the keep-alive's run, renewClaude), as refreshCards keeps a card read
// again: in place of the card, newer reads standing, with its history,
// and the menu bar told. A card the Usage page doesn't have (hidden, or
// nothing read yet) isn't added.
func keepCardRead(q SubscriptionQuota, seq uint64) {
out := []SubscriptionQuota{q}
c := &subscriptionUsageCache
c.Lock()
has := slices.ContainsFunc(c.data, func(k SubscriptionQuota) bool {
return k.Provider == q.Provider && strings.EqualFold(k.User, q.User)
})
if has {
c.data = cacheCards(c.data, out, seq, true)
}
c.Unlock()
if has {
noteQuotaHistory(out, time.Now())
toldUsage()
}
}
// cacheCards commits a batch without overwriting cards read by a newer
// batch. A whole-page read still replaces the other cards (and drops ones
// no longer present); a partial read keeps the rest as they were.
+12 -2
View File
@@ -788,7 +788,8 @@ func AskUsage() {
// Code was used since, or when Claude Code was refused for its limit
// since. A saved
// account is read only when its card is refreshed (savedRefresh), or when
// the switch off a spent account has no reading of it (spareRead), by
// the switch off a spent account has no reading of it (spareRead), or
// when the keep-alive runs Claude Code on it (keepingAlive), by
// Claude Code run in the account's own config directory
// (readSavedClaudeUsage), Claude Code's own sign-in left as it is (#1630).
// Any other time it is what was kept.
@@ -812,7 +813,13 @@ func claudeWindows(ctx context.Context, user string, active bool) ([]QuotaWindow
// keeps failing, never every look
spare := !active && spareRead(ctx) && e.ws == nil && (e.tried.IsZero() || now.Sub(e.tried) >= e.wait)
// nor, with allowances read only when asked, one nobody asked for
read := ((active || savedRefresh(ctx, user)) && due || spare) && now.Sub(e.tried) >= claudeAskFloor && !holding(ctx)
// and the keep-alive's run on a saved account (renewClaude), an hour
// apart at the most, whose run is the renewal: not put off by the floor
alive := keepAliveOf(ctx, user)
if active {
alive = nil
}
read := ((active || savedRefresh(ctx, user)) && due || spare || alive != nil) && (now.Sub(e.tried) >= claudeAskFloor || alive != nil) && !holding(ctx)
c.Lock()
// one reading an ask or a wait, its first caller's; the others keep
// to it
@@ -863,6 +870,9 @@ func claudeWindows(ctx context.Context, user string, active bool) ([]QuotaWindow
ws, err = readClaudeUsage(ctx, "")
} else {
ws, err = readSavedClaudeUsage(ctx, user)
if alive != nil {
alive.done(err)
}
}
if active && ClaudeCodeMovedOff(user) {
return kept()