diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 9d894e659..1f4d7189e 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -115,6 +115,7 @@ A signed-in account's model list exists only at its vendor (Cursor's `cursor-age - 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. [`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 .ghe.com`, or the login alone when it names one account. diff --git a/internal/provider/login_usage.go b/internal/provider/login_usage.go index ac2221839..ecd8c0a63 100644 --- a/internal/provider/login_usage.go +++ b/internal/provider/login_usage.go @@ -198,8 +198,8 @@ func loginReading(ctx context.Context, l Login) loginUsageEntry { } c.pending[key] = r ctx, _ = quotaReading(ctx) + asked := claudeAskGeneration.Load() go func() { - start := time.Now() // read for all who wait for it: no one's ctx cuts it short, but // it is bounded as the Usage page's refresh is rctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), subscriptionTimeout) @@ -211,7 +211,7 @@ func loginReading(ctx context.Context, l Login) loginUsageEntry { // (AskClaudeUsage), as SubscriptionUsage reads it: neither is kept if c.pending[key] == r { delete(c.pending, key) - if l.Agent != "claude" || claudeAsked.Load() <= start.UnixNano() { + if l.Agent != "claude" || claudeAskGeneration.Load() == asked { if c.m == nil { c.m = map[string]loginUsageEntry{} } diff --git a/internal/provider/quota_refresh.go b/internal/provider/quota_refresh.go index da55ef84b..413a834dd 100644 --- a/internal/provider/quota_refresh.go +++ b/internal/provider/quota_refresh.go @@ -104,7 +104,7 @@ func RefreshUsage(ctx context.Context, provider, user string) { ctx, seq := quotaReading(ctx) if provider == "claude" { // Claude Code's /usage, run when the user asks (claudeWindows) - claudeAsked.Store(time.Now().UnixNano()) + markClaudeUsageAsked() } var wg sync.WaitGroup wg.Add(3) diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index a23f70cd6..8ff1ec0e0 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -226,15 +226,15 @@ func SubscriptionUsage(ctx context.Context) []SubscriptionQuota { bg = Asked(bg) } readCtx, seq := quotaReading(bg) + asked := claudeAskGeneration.Load() go func() { - start := time.Now() out := fetchSubscriptionUsage(readCtx) noteDailyCredits(out, time.Now()) noteQuotaHistory(out, time.Now()) c.Lock() c.data = cacheCards(c.data, out, seq, false) c.at, c.pending = time.Now(), nil - if claudeAsked.Load() > start.UnixNano() { + if claudeAskGeneration.Load() != asked { c.at = time.Time{} // asked meanwhile: read again } c.Unlock() @@ -620,6 +620,7 @@ type claudeUsageEntry struct { ws []QuotaWindow heard time.Time // when Claude Code last told it, answering tried time.Time // when /usage was last run, answered or not + asked uint64 // the ask generation that run answered wait time.Duration // how long after tried it runs again unasked err error // what the last run said, when it failed whole bool // /usage was read: ws has every window the account has @@ -681,12 +682,28 @@ var claudeUsedSince = func(t time.Time) bool { // nanoseconds; zero: never). var claudeAsked atomic.Int64 +// claudeAskGeneration orders asks against readings, even when both happen +// in one wall-clock tick. tried and wait still schedule the next /usage. +var claudeAskGeneration atomic.Uint64 + +func markClaudeUsageAsked() { + // Serialize the ask with both caches' snapshots and publications: + // neither may observe the old generation, then publish after this ask. + // When both locks are needed, the subscription cache comes first. + subscriptionUsageCache.Lock() + loginUsageCache.Lock() + claudeAsked.Store(time.Now().UnixNano()) + claudeAskGeneration.Add(1) + loginUsageCache.Unlock() + subscriptionUsageCache.Unlock() +} + // AskClaudeUsage is the user asking to see Claude's usage — opening the // Usage page, refreshing it, `magpie quota` — so Claude Code's /usage is // run at once rather than when the next unasked reading is due // (claudeUsageWait); the next SubscriptionUsage waits for it. func AskClaudeUsage() { - claudeAsked.Store(time.Now().UnixNano()) + markClaudeUsageAsked() AskUsage() l := &loginUsageCache l.Lock() @@ -731,11 +748,11 @@ func claudeWindows(ctx context.Context, user string, active bool) ([]QuotaWindow key := strings.ToLower(user) c := &claudeUsage now := time.Now() - asked := claudeAsked.Load() + asked := claudeAskGeneration.Load() c.Lock() e, ok := c.m[key] c.Unlock() - due := e.tried.IsZero() || asked > e.tried.UnixNano() || + due := e.tried.IsZero() || claudeAsked.Load() != 0 && asked > e.asked || active && now.Sub(e.tried) >= e.wait && (e.heard.After(e.tried) || claudeUsedSince(e.tried)) // nor, with allowances read only when asked, one nobody asked for read := (active || savedRefresh(ctx, user)) && due && now.Sub(e.tried) >= claudeAskFloor && !holding(ctx) @@ -750,6 +767,7 @@ func claudeWindows(ctx context.Context, user string, active bool) ([]QuotaWindow c.m = map[string]claudeUsageEntry{} } e.tried, e.wait = now, claudeUsageWait() + e.asked = asked c.m[key] = e } c.Unlock() @@ -813,7 +831,7 @@ func claudeWindows(ctx context.Context, user string, active bool) ([]QuotaWindow if c.m == nil { c.m = map[string]claudeUsageEntry{} } - c.m[key] = claudeUsageEntry{at: now, ws: ws, heard: e.heard, tried: now, wait: e.wait, whole: true} + c.m[key] = claudeUsageEntry{at: now, ws: ws, heard: e.heard, tried: now, asked: asked, wait: e.wait, whole: true} c.Unlock() // as of now, as a kept reading is: /usage gives a reset to the minute // and can lag it, so a window it still counts full may have started