Files
magpie/internal/provider/claude_warmup.go
T
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

84 lines
3.1 KiB
Go

package provider
// Starting a Claude account's next window as soon as the last one resets,
// as codex_warmup.go does a ChatGPT account's: a Claude window, the 5-hour
// one and the weekly one, starts at the account's first request after it
// resets. The request goes through Claude Code itself, as the gateway's
// Claude Subscription does, so it is Claude Code's own; the gateway, which
// runs Claude Code, says how.
import (
"context"
"fmt"
"path/filepath"
"slices"
"strings"
"time"
"github.com/yetone/magpie/internal/settings"
)
func claudeWarmPath() string { return filepath.Join(filepath.Dir(Path()), "claude-warmup.json") }
// claudeWarmUsage is each Claude account's windows, the cached reads the
// Usage page shares; an account whose sign-in lapsed is left out.
func claudeWarmUsage(ctx context.Context) map[string]SubscriptionQuota {
u := LoginUsage(ctx, "claude")
for _, l := range Logins("claude") {
if l.Lapsed != "" {
delete(u, l.User)
}
}
return u
}
// warmClaudeLogin is a warm-up's send for the Claude accounts: send asks
// Claude Code, with configDir the config directory of a saved account
// (claude_dirs.go), "" for the one Claude Code is signed in to.
func warmClaudeLogin(send func(ctx context.Context, configDir string) error) func(context.Context, string) error {
return func(ctx context.Context, user string) error {
// the account's own proxy, which send's Claude Code runs with too
ctx = ViaLogin(ctx, "claude", user)
ls := Logins("claude")
i := slices.IndexFunc(ls, func(l Login) bool { return strings.EqualFold(l.User, user) })
if i < 0 {
return fmt.Errorf("no Claude account %q", user)
}
if !ls[i].Active {
return inSavedClaudeDir(ls[i].User, func(dir string) error { return send(ctx, dir) })
}
return send(ctx, "")
}
}
// claudeWindowsExpected is the windows every Claude account has: Anthropic
// leaves them out (null) for an account never used.
var claudeWindowsExpected = []QuotaWindow{{Name: "5 hours", Span: 5 * time.Hour}, {Name: "7 days", Span: 7 * 24 * time.Hour}}
// claudeWarmedNow has what the Claude account user has left read again,
// not taken from the last few minutes' read: the window a warm-up started
// has its reset known, and routing ranks the account by it at once.
func claudeWarmedNow(user string) {
key := strings.ToLower(user)
c := &claudeUsage
c.Lock()
if e, ok := c.m[key]; ok {
e.at = time.Time{}
c.m[key] = e
}
c.Unlock()
StaleAllowance("claude", user)
}
// ClaudeWarmed is when magpie last started a window of each Claude account,
// by user as kept (lower-cased).
func ClaudeWarmed() map[string]time.Time { return codexWarmedIn(claudeWarmPath()) }
// KeepClaudeWindowsWarm starts the Claude accounts' windows as they reset,
// while settings say to, each with one request send makes.
func KeepClaudeWindowsWarm(ctx context.Context, send func(ctx context.Context, configDir string) error) {
w := codexWarmer{path: claudeWarmPath(), now: time.Now, usage: claudeWarmUsage, send: warmClaudeLogin(send),
expect: claudeWindowsExpected, warmed: claudeWarmedNow}
keepWarm(ctx, "claude", w, func() (string, []string) { s := settings.Load(); return s.ClaudeWarmup, s.ClaudeWarmAts })
}