usage: the top refresh reads saved Claude accounts again (#5380)
The tray panel's Allowances refresh said "Allowances refreshed" but a
saved, non-active Claude account kept its old reading: claudeWindows runs
Claude Code's /usage for a saved account only under savedRefresh, which
only that account's own card refresh sets.
Now a refresh of every allowance by hand asks usage/quotas?asked=1&all=1
(AskEveryClaudeUsage). It marks its ask generation in claudeEveryAsked,
and for claudeEveryFor (2 minutes) each saved account not read since is
read as its card's refresh would, under the same due check, the
30-second per-account floor and the same running holds. Opening the
Usage page or the Allowances tab (?asked=1 alone), the timed refresh and
every background read are unchanged, so nothing polls more. Callers:
the panel's top refresh (refreshPage "allowances"), the Usage page's
refresh and sidebar reload (refreshUsage -> loadQuotas("all")),
Routing's Read allowances, and the TUI's r. loadQuotas no longer lets a
lesser load on its way (an opening's asked read) swallow a Refresh.
Siblings: saved Codex accounts are already read anew on every asked
whole read (loginReading over HTTP after AskUsage clears the cache), so
Codex is unaffected. PlanQuotas and KeyBalances keep their 1-minute cache
on an asked read; left as is. The core scripts' budget is not raised:
the ~140 bytes are paid for by two loadQuotas/quotasOpened comments cut.
Run (mote, at 807341cdc on origin/main 5666cb049; rebased onto
505534992 after, which touches only internal/plugin and internal/proc;
the core script budget rechecked at the pushed head, 193 bytes under):
- go test ./internal/provider/ ./internal/gui/ ./internal/tui/ ok
(TestMainWindowCorners/macOS_26_SDK red on mote's macOS 27, #3949;
green when run with the -run set at the pushed head)
- go vet the three packages; GOOS=linux go vet -tags nogui and
GOOS=windows go vet of them ok; go vet provider+tui in WSL ok; gofmt -l
clean
- GUI, Chromium and WebKit, en+zh: refresh-page, claude-usage-asked,
usage-refresh, routing-read-allowances, allowance-open-read,
quota-refresh-order, usage-refresh-flight all pass. A wider set of 119
files (quota*, panel-quota*, usage-*, allowance*, routing-read/account,
menu-*, tray-*, i18n-keys) has reds in 6 files, identical at the parent
commit and filed: i18n-keys #5332, menu-input-scroll #3402,
tray-cell-click #5215, usage-agents-hide #3414, usage-fold #3415,
usage-ledger #5048.
- New TestRefreshEveryReadsSavedClaude: an opening's ask runs nothing
for saved accounts; a top refresh reads each anew; an unasked read and
a plain asked read after it don't; rapid refreshes keep the floor; the
every-ask lapses after claudeEveryFor.
Broken by hand: dropping "|| every" from claudeWindows' read turns
TestRefreshEveryReadsSavedClaude red ("top refresh read no allowance of
saved max@x.com"); the panel's refreshPage back on loadQuotas(true)
turns refresh-page's panel subtests red in both engines.
Not tried: a real saved Claude account's /usage run from the real tray
panel (the test fakes Claude Code's /usage per account directory); the
full GUI suite; the de/ja/zh-TW GUI runs (no string changed).
This commit is contained in:
@@ -596,7 +596,7 @@ covers it in both engines, every language and a narrow window.
|
||||
- Usage › Overview's Agents, Models, Accounts and Gateway keys lists each fold under their heading (#2378): the heading is a `.fold` button with its chevron, as on the Gateway page, and the click doesn't move the page (`backToReader`). What is folded is kept per viewer in localStorage `magpie.usageFolded` (`mountUsageFolds`, `showUsageFolds`). The totals leave the cache out, as before, unless the tokens tile's label, a pop-up button (`usageTokensPick`, the app menu), is set to *With cache*: then the tile, the chart and every row's count and share add cache read and written (`usageTokens`), and the tile says the cache's count; kept in localStorage `magpie.usageWithCache`. The Sessions tab counts by the same pick (#2591): its tokens tile carries the same label pop-up and says the cache's count, and the list's rows, the projects and models bars and pickers, the day chart (whose day and week buckets carry the cache's counts), the calendar and the top sessions read `usageTokens` too, the top list ranked again by the count shown (`sessTokens`, `sessSums`, `renderSessChart`, `renderSessTop`); a pick made on that tab refreshes the tab, not the Overview. The per-session median and p90 stay counted in and out (`Stats.Overview`). The Requests tab's total already counts every token (`allTokens`). A token line in parts (the Requests strip's Tokens card, the Overview's and the Sessions tab's tokens tiles) wraps between its counts and keeps each whole (`usageParts`, `.parts`); only a count wider than its card on its own is cut. See `usage-overview-fold.test.cjs` and `sessions-cache-tokens.test.cjs`.
|
||||
- A request's details in the Usage ledger say its tokens at every width (#1839, `ledDetail`): "{i} in · {o} out · {r} cache read · {w} cache creation", 0 said as 0, with how much was written for 5 minutes and for an hour when it says so. A failure that spent nothing has no Tokens row. See `ledger-cache-tokens.test.cjs` and `usage-ledger-detail.test.cjs`.
|
||||
- The requests magpie makes by itself (a routing classifier's, a web search's, an image description's) are told apart from the agents' on the Usage page (#1839): magpie's row among the agents and its rows in the ledger carry a "magpie's own" mark (`ownBadge`), an account's, key's or model's row adds "{n} by magpie itself" from the summary's `own`, and an account's card says how many of the period's requests were magpie's own (`ownLine`, drawn again once the summary comes after the allowances). See `own-requests.test.cjs` and `TestSummaryCountsMagpiesOwnCallsApart`.
|
||||
- Opening the allowances is asking to see them (#1588, `quotasOpened` in `app.js`): the Usage page from the nav or its Overview tab picked, the window brought back to the front on the Overview, the tray panel's Allowances tab picked or the panel brought up on it, and a menu bar cell clicked each load `usage/quotas?asked=1`, as Refresh now does. An asked read makes the backend read every account again (`AskClaudeUsage`), so an opening within 30s (`QUOTAS_OPEN_GAP`) of the last asked read sends an ordinary read instead, which joins one on its way; Refresh now always asks. A panel page loaded while it is put away (hidden, or without focus) doesn't ask. The timed refresh is unchanged and never asks. See `allowance-open-read.test.cjs`.
|
||||
- Opening the allowances is asking to see them (#1588, `quotasOpened` in `app.js`): the Usage page from the nav or its Overview tab picked, the window brought back to the front on the Overview, the tray panel's Allowances tab picked or the panel brought up on it, and a menu bar cell clicked each load `usage/quotas?asked=1`, as Refresh now does. An asked read makes the backend read every account again (`AskClaudeUsage`), so an opening within 30s (`QUOTAS_OPEN_GAP`) of the last asked read sends an ordinary read instead, which joins one on its way; Refresh now always asks, with `&all=1` (`loadQuotas("all")`, `AskEveryClaudeUsage`), so saved Claude accounts are read again too, as their cards' refresh reads them (#5380); an opening's asked read on its way doesn't take its place. A panel page loaded while it is put away (hidden, or without focus) doesn't ask. The timed refresh is unchanged and never asks. See `allowance-open-read.test.cjs`.
|
||||
- The menu bar can show magpie's own totals beside the allowances (#1984): `usage:today` and `usage:7d` in `settings.TrayUsages`, offered after the cards in the same picker. `trayUsageCards` sums them with `usage.QueryPage(p, Filter{}, 0, 1).Sum` (the Requests tab's and the panel's cached ledger sum, gateway and session-file calls together) and asks no vendor when only totals are picked; `trayTotalCard` makes every token (in, out and cache, as `allTokens`), marked `Σ` so it doesn't read as the input, over the cost in Settings' currency, `+` when some calls had no price, the cost row left out when none had one. The Mac draws them as plain cells, the bird beside them saying whose. A click opens the Requests tab at the period (`quotaView`, `?tab=requests&period=`) or the panel's Usage tab (`panelUseFocus`). No 3-day total: the Usage page has no such window. See `TestTrayTotals` and `tray-totals.test.cjs`. Settings › *Menu bar cost* (`settings.TrayNoCost`, on by default, on every OS, per computer through `KeepOwn`) turned off leaves the money out (BussanQ on Discord): `trayMoney` drops the total's cost and its count of unpriced calls before `trayTotalCard` and the no-card tooltip `trayIdleTip` see it, so the cards, their tooltip and the idle tooltip say the tokens and requests alone. A relay's or subscription's balance card is money itself and stays. See `TestTrayNoCost` and `tray-cost.test.cjs`.
|
||||
- The tray's icon is the bird alone where the bar's other icons are glyphs: the Mac's menu bar takes `tray.png` as a template image, and a Linux bar (StatusNotifierItem `IconPixmap`) gets the same silhouette in one colour on transparency (`trayIconFor`, `linuxTrayIcon` in [`trayglyph.go`](../../internal/gui/trayglyph.go)), so a bar that tints its icons by their alpha tints the bird, not a tile (ylorn on Discord). A bar that doesn't tint shows it light, or dark when the portal's `org.freedesktop.appearance` `color-scheme` prefers light (`traySchemeLight`), and it is drawn again when that changes (`watchTrayScheme`). No `IconName` is set: a host that found a `-symbolic` name and drew it untinted would show a black bird on a dark bar, with no pixmap to fall back on. Windows' tray keeps the app's coloured icon, unless a card is in the menu bar: Windows' notification area shows no text beside an icon, so the icon itself is the first card's figure (Benjaminliang_1 on X; `trayIconFigure`, `trayNumberIcon` in [`traynumber.go`](../../internal/gui/traynumber.go)). It is the first row of the first card whose first row is a percentage, used or left as Allowance display has it, through *Menu bar windows*' pick, its digits alone, drawn in Segoe UI Semibold (Go's bold where the font can't be read) at `SM_CXSMICON`, white on a dark taskbar and near black on a light one, as tall as fits with a pixel above and below, centred by its ink, and three digits narrowed into the square. A balance or magpie's totals are skipped for the next card; with none the icon is the bird. It is drawn again when the figure, the icon size or the taskbar's theme changes (`SystemThemeChanged` wakes the loop); the tooltip still says every card. Settings › *Tray icon number* (`settings.TrayNoNumber`, Windows' alone, on by default) keeps the bird when off. One icon is set for the current theme, not a light and a dark one: Wails' Windows tray shares one handle between them. Linux keeps its label and tooltip; the Mac its cells. See `TestTrayIconFigure`, `TestTrayNumberIcon` and `tray-windows.test.cjs`. With no cards in the menu bar the tooltip is magpie over today's total (`trayIdleTip`: every token, split into input, output and cache as the today card's tooltip is, then the cost and the requests), brought up to date with the cards' refresh; the tray's menu stays Open, the version and Quit. Wails sets the tooltip only on Windows: on Linux `setTrayTip` sets the StatusNotifierItem's `ToolTip` and sends `NewToolTip` ([`traytip_linux.go`](../../internal/gui/traytip_linux.go)), and on the Mac it is the status item's button's `toolTip` (`trayTipNative` in [`trayimage_darwin.go`](../../internal/gui/trayimage_darwin.go); NextCommit on Discord: no hover there showed anything). See `TestTrayIconPerOS`, `TestTrayIdleTip` and `TestMacTrayTipIsSet`. Every tooltip, the idle one, magpie's totals' and each card's (its use or what is left, the pace, when it resets, "as of …"), is in magpie's language, as the tray menu is: `watchTrayUsage` passes `trayLang(settings.Lang, systemLang)` to `trayCardsView`, `trayUsageCards` and `trayIdleTip`, whose words are in `trayWords` beside the menu's, and a change of language in Settings refreshes it at once (`onTrayUsage`). A window's name and an error are the card's own (yi_time on Discord: English on a Windows magpie set to Chinese; `TestTrayTooltipFollowsMagpiesLanguage`).
|
||||
- A window's Pace is a number on its card's reset line (fflake33 on Discord): the share used less the share of the window gone by, in points, "Pace +12%" over an even pace and "−8%" under it, turned with the meter when it shows what is left, amber while more is used than an even pace would have (`quotaPace`, `paceLine`). The window's start is the gateway's, `startsAt` from `provider.WithWindowStarts` (its reset less its span, `QuotaWindow.Bounds`); a window whose span isn't known, with no limit, or a past cycle has none. Settings › *Menu bar pace* (`settings.TrayPace`, off by default, hidden on Windows, whose tray shows no text but the first card's figure as its icon) puts the same number beside each figure in the menu bar and in its tooltip (`trayPace`, `QuotaWindow.Pace`). See `TestWindowPace`, `TestTrayUsagePace` and `quota-pace.test.cjs`.
|
||||
|
||||
@@ -309,7 +309,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. That lock is this process's only, so each run also holds a lock file of its own beside the account's directory (`markClaudeRun`, `<dir>.run-<pid>-<n>.lock`), and the switch waits on every one there first (`waitClaudeRuns`, up to `claudeRunWait`, 90s, then `errClaudeRunning` with the sign-in left as it was): before, `magpie accounts switch` didn't wait for the app's run (#4532; `TestClaudeSwitchWaitsForAnotherMagpiesRun`, `TestClaudeSwitchRunHeldAndLeft`). A file whose run ended without removing it is free and taken out. After the switch, the gateway lets go of the account's idle runs, and a run in a turn then ends as the turn does rather than waiting for the next (`handedOver`, `subscriptionRun.handed`, `TestClaudeHandOverEndsTheAccountsBusyRuns`). 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.
|
||||
- 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), or when every allowance is refreshed by hand (#5380): the tray panel's and the Usage page's top refresh, Routing's Read allowances and the TUI's `r` ask `usage/quotas?asked=1&all=1` (`AskEveryClaudeUsage`), which marks its generation in `claudeEveryAsked`, and for `claudeEveryFor` (2 minutes) each saved account not read since is read as its card's refresh would, under the same due check and 30-second floor (`TestRefreshEveryReadsSavedClaude`). 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 or the Allowances tab opened, `magpie quota` and `magpie accounts` ask every card without `all` 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. That lock is this process's only, so each run also holds a lock file of its own beside the account's directory (`markClaudeRun`, `<dir>.run-<pid>-<n>.lock`), and the switch waits on every one there first (`waitClaudeRuns`, up to `claudeRunWait`, 90s, then `errClaudeRunning` with the sign-in left as it was): before, `magpie accounts switch` didn't wait for the app's run (#4532; `TestClaudeSwitchWaitsForAnotherMagpiesRun`, `TestClaudeSwitchRunHeldAndLeft`). A file whose run ended without removing it is free and taken out. After the switch, the gateway lets go of the account's idle runs, and a run in a turn then ends as the turn does rather than waiting for the next (`handedOver`, `subscriptionRun.handed`, `TestClaudeHandOverEndsTheAccountsBusyRuns`). 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).
|
||||
|
||||
+11
-13
@@ -15737,21 +15737,18 @@ if (mode === "panel") { const none = [], k = kept("panelQuotas", none); if (k !=
|
||||
let quotaHist = []; // each account's windows over time, for the curves (#651)
|
||||
// quotasOpened: the reader opened what shows the allowances (the Usage
|
||||
// page's Overview, the tray panel's Allowances tab, a menu bar cell, either
|
||||
// brought back to the front), which is asking to see them now (#1588,
|
||||
// qq666666qq), as Refresh now is: an asked read, the one that goes out
|
||||
// with allowances read only when asked (#1518). Each one asked makes the
|
||||
// backend read every account again, so opening within QUOTAS_OPEN_GAP of
|
||||
// the last asked read (switching tabs and back, the window's focus and
|
||||
// visibility both firing, focus-follows-mouse) asks nothing: it takes what
|
||||
// is kept, or the read on its way. Refresh now asks every time.
|
||||
// brought back to the front): an asked read (#1588, #1518), which reads
|
||||
// every account again, so opening within QUOTAS_OPEN_GAP of the last one
|
||||
// (tabs, focus and visibility both firing) asks nothing. Refresh always
|
||||
// asks, saved Claude accounts too ("all", #5380).
|
||||
const QUOTAS_OPEN_GAP = 30e3;
|
||||
let quotasAskedAt = -Infinity;
|
||||
function quotasOpened() {
|
||||
return loadQuotas(performance.now() - quotasAskedAt >= QUOTAS_OPEN_GAP);
|
||||
}
|
||||
|
||||
// An asked load is never swallowed by one already on its way that wasn't:
|
||||
// it goes after it.
|
||||
// A load is never swallowed by a lesser one on its way (asked over none,
|
||||
// "all" over both): it goes after it.
|
||||
// An answer said to be read while the accounts' usage is being read again
|
||||
// (X-Magpie-Reading) can be the stale copy that read replaces: it is asked
|
||||
// for again, every 1.5s for half a minute at most, until the new one has
|
||||
@@ -15761,7 +15758,8 @@ let quotasLoading = null, quotasLater = 0, quotasTries = 0;
|
||||
let quotaRefreshVersion = 0;
|
||||
const quotaRefreshVersions = new Map();
|
||||
function loadQuotas(asked, again) {
|
||||
if (quotasLoading && (!asked || quotasLoading.asked)) return quotasLoading;
|
||||
const r = (a) => (a === "all" ? 2 : +!!a);
|
||||
if (quotasLoading && r(asked) <= r(quotasLoading.asked)) return quotasLoading;
|
||||
if (asked) { quotasAskedAt = performance.now(); quotaCycleHolds.clear(); }
|
||||
if (!again) quotasTries = 0;
|
||||
let reading = false, same = false, began;
|
||||
@@ -15771,7 +15769,7 @@ function loadQuotas(asked, again) {
|
||||
// the curves come on their own: the allowances now never wait for
|
||||
// them (a remote magpie's history can take seconds; #3192)
|
||||
loadQuotaHist();
|
||||
return api("usage/quotas" + (asked ? "?asked=1" : ""), undefined, (h) => { reading = h.get("X-Magpie-Reading") === "1"; });
|
||||
return api("usage/quotas" + (asked ? "?asked=1" + (asked === "all" ? "&all=1" : "") : ""), undefined, (h) => { reading = h.get("X-Magpie-Reading") === "1"; });
|
||||
})
|
||||
.then((q) => {
|
||||
// an answer that isn't a list of cards is a read that failed: what
|
||||
@@ -15791,7 +15789,7 @@ function loadQuotas(asked, again) {
|
||||
if (view === "usage") loadUpstream();
|
||||
if (reading && !quotasLater && ++quotasTries <= 20) quotasLater = setTimeout(() => { quotasLater = 0; loadQuotas(false, true); }, 1500);
|
||||
});
|
||||
p.asked = !!asked;
|
||||
p.asked = asked;
|
||||
quotasLoading = p;
|
||||
return p;
|
||||
}
|
||||
@@ -23389,7 +23387,7 @@ async function refreshPage(kind) {
|
||||
await magpie.call("usage", "reload");
|
||||
return t("Usage refreshed");
|
||||
case "allowances":
|
||||
await loadQuotas(true);
|
||||
await loadQuotas("all");
|
||||
return t("Allowances refreshed");
|
||||
case "requests":
|
||||
await loadPanelUse();
|
||||
|
||||
@@ -210,7 +210,7 @@ function routingPage(part) {
|
||||
if (actRead.classList.contains("busy")) return;
|
||||
actRead.classList.add("busy");
|
||||
actRead.setAttribute("aria-busy", "true");
|
||||
try { await loadQuotas(true); } finally {
|
||||
try { await loadQuotas("all"); } finally {
|
||||
actRead.classList.remove("busy");
|
||||
actRead.removeAttribute("aria-busy");
|
||||
steady(() => renderActs(listed()));
|
||||
|
||||
@@ -4180,7 +4180,7 @@ function refreshUsage(now = false) {
|
||||
// the reader asking reads the allowances afresh, a Claude account's by
|
||||
// running Claude Code's own /usage (the backend runs it at most once in 30s)
|
||||
let q = null;
|
||||
if (want) { quotasAsked = performance.now(); q = loadQuotas(true); }
|
||||
if (want) { quotasAsked = performance.now(); q = loadQuotas("all"); }
|
||||
else if (usage && performance.now() - quotasAsked > 60e3) { quotasAsked = performance.now(); loadQuotas(); }
|
||||
if (usage) {
|
||||
const p = period, read = ++usageRead;
|
||||
|
||||
@@ -7,7 +7,10 @@
|
||||
// window coming back to the front within 30s of that (#1588,
|
||||
// allowance-open-read.test.cjs) and the timed reload load it without; an
|
||||
// asked load isn't swallowed by an unasked one already on its way, it goes
|
||||
// after it. Chromium and WebKit; no backend, the API is faked here.
|
||||
// after it. Refresh's is every account's (&all=1, #5380): a saved Claude
|
||||
// account's /usage is run too; opening's isn't, and an opening's asked
|
||||
// load on its way doesn't swallow it. Chromium and WebKit; no backend, the
|
||||
// API is faked here.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
@@ -152,7 +155,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const asks = [], hold = { on: false };
|
||||
await page.route("**/*", serve(asks, hold));
|
||||
const asked = () => asks.filter((s) => s === "?asked=1").length;
|
||||
const asked = () => asks.filter((s) => s.startsWith("?asked=1")).length;
|
||||
const every = () => asks.filter((s) => s === "?asked=1&all=1").length;
|
||||
const settle = async (n) => { for (let i = 0; i < 100 && asks.length < n; i++) await page.waitForTimeout(20); await page.waitForTimeout(150); };
|
||||
|
||||
// opening the page asks
|
||||
@@ -160,6 +164,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await page.locator("#usageReload").waitFor();
|
||||
await settle(1);
|
||||
assert.equal(asked(), 1, `opening Usage asks once: ${JSON.stringify(asks)}`);
|
||||
assert.equal(every(), 0, `opening Usage reads no saved account: ${JSON.stringify(asks)}`);
|
||||
|
||||
// the window coming back to the front at once reads what is kept, asking nothing
|
||||
let n = asks.length;
|
||||
@@ -176,6 +181,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await page.locator("#usageReload").click();
|
||||
await settle(asks.length + 1);
|
||||
assert.equal(asked(), 2, `Refresh asks: ${JSON.stringify(asks)}`);
|
||||
assert.equal(every(), 1, `Refresh reads every account: ${JSON.stringify(asks)}`);
|
||||
|
||||
// an unasked load on its way doesn't swallow Refresh: it goes after it
|
||||
hold.on = true;
|
||||
@@ -186,7 +192,18 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
hold.on = false;
|
||||
hold.release();
|
||||
await settle(n + 2);
|
||||
assert.deepEqual(asks.slice(n), ["", "?asked=1"], "Refresh went after the load on its way");
|
||||
assert.deepEqual(asks.slice(n), ["", "?asked=1&all=1"], "Refresh went after the load on its way");
|
||||
// nor does an opening's asked load on its way swallow it
|
||||
hold.on = true;
|
||||
hold.release = null;
|
||||
n = asks.length;
|
||||
await page.evaluate(() => { loadQuotas(true); });
|
||||
for (let i = 0; i < 100 && !hold.release; i++) await page.waitForTimeout(20);
|
||||
await page.locator("#usageReload").click();
|
||||
hold.on = false;
|
||||
hold.release();
|
||||
await settle(n + 2);
|
||||
assert.deepEqual(asks.slice(n), ["?asked=1", "?asked=1&all=1"], "Refresh went after the opening's ask on its way");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -19,12 +19,14 @@ const words = {
|
||||
en: {
|
||||
agents: "Look for agents on this computer again: one just installed or removed, or its settings changed",
|
||||
usage: "Read the usage again now",
|
||||
allowances: "Read the allowances again now",
|
||||
models: "Refresh model lists (models.dev and every vendor)",
|
||||
nav: { usage: "Usage", providers: "Providers" },
|
||||
},
|
||||
zh: {
|
||||
agents: "重新检测本机的 Agent:刚安装或卸载的,或在别处改过配置的",
|
||||
usage: "立即重新读取用量",
|
||||
allowances: "立即重新读取额度",
|
||||
models: "刷新模型列表(models.dev 与各供应商)",
|
||||
nav: { usage: "用量", providers: "供应商" },
|
||||
},
|
||||
@@ -55,7 +57,7 @@ function server(lang, ctl) {
|
||||
if (url.pathname === "/api/agents/install") return json(ctl.installs);
|
||||
if (url.pathname === "/api/agents/cli") return json({ agents: {}, pending: false });
|
||||
if (url.pathname === "/api/update") return json({ state: "latest", current: "0.1.400" });
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname === "/api/usage/quotas") return json(ctl.quotas || []);
|
||||
if (url.pathname === "/api/usage/quotas/history") return json([]);
|
||||
if (url.pathname === "/api/usage") return json({ totals: {}, days: [], providers: [], models: [], agents: [] });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
@@ -110,9 +112,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await page.locator(`#nav [data-view="usage"]`).click();
|
||||
assert.equal(await sync.getAttribute("title"), words[lang].usage);
|
||||
await page.waitForTimeout(300);
|
||||
const asked = count(ctl, /\/api\/usage\/quotas\?asked=1/);
|
||||
const asked = count(ctl, /\/api\/usage\/quotas\?asked=1&all=1$/);
|
||||
await click(page, sync);
|
||||
assert.equal(count(ctl, /\/api\/usage\/quotas\?asked=1/), asked + 1, "the allowances read afresh");
|
||||
// every account's, a saved Claude account's too (#5380)
|
||||
assert.equal(count(ctl, /\/api\/usage\/quotas\?asked=1&all=1$/), asked + 1, "the allowances read afresh, every account");
|
||||
assert.equal(count(ctl, /\/api\/sync$/), 0);
|
||||
|
||||
// Providers: refreshes the model lists
|
||||
@@ -142,6 +145,20 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await page.locator('.row.agent[data-id="claude"]').waitFor();
|
||||
assert.equal(count(ctl, /^POST \/api\/agents\/rescan$/), 1);
|
||||
assert.equal(count(ctl, /\/api\/sync$|\/api\/update\/check/), 0);
|
||||
// Allowances: every account read again, a saved Claude account's
|
||||
// too, as its card's refresh reads it (#5380); opening the tab
|
||||
// asks without
|
||||
await page.locator("#sync:not(.spin)").waitFor();
|
||||
ctl.quotas = [{ provider: "claude", name: "Claude", user: "a@x.com", windows: [{ label: "5h", used: 9, limit: 100 }] }];
|
||||
await page.evaluate(() => loadQuotas());
|
||||
await page.locator('#ptabs [data-ptab="usage"]').click();
|
||||
await page.waitForFunction(() => document.body.dataset.ptab === "usage");
|
||||
await page.waitForTimeout(300);
|
||||
assert.equal(count(ctl, /\/api\/usage\/quotas\?.*all=1/), 0, "opening the tab reads every account: " + ctl.calls.join(" "));
|
||||
assert.equal(await sync.getAttribute("title"), words[lang].allowances);
|
||||
await click(page, sync);
|
||||
await page.locator("#sync:not(.spin)").waitFor();
|
||||
assert.equal(count(ctl, /\/api\/usage\/quotas\?asked=1&all=1$/), 1, "the top refresh reads every account");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -38,7 +38,8 @@ function serve(lang, order, asks, held) {
|
||||
}
|
||||
if (url.pathname === "/api/usage/quotas") {
|
||||
const asked = url.searchParams.get("asked") === "1";
|
||||
asks.push(asked);
|
||||
// the button's read is of every account, a saved Claude one's too (#5380)
|
||||
asks.push(asked && url.searchParams.get("all") === "1" ? "all" : asked);
|
||||
if (!asked) return json(card(40));
|
||||
await held; // the vendor takes its time
|
||||
return json(card(70));
|
||||
@@ -110,7 +111,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
const box = await b.boundingBox();
|
||||
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
|
||||
await page.waitForFunction(() => document.querySelector("#rtReadAllowances").classList.contains("busy"));
|
||||
assert.equal(asks.filter(Boolean).length, 1, "one asked read");
|
||||
assert.deepEqual(asks.filter(Boolean), ["all"], "one asked read, of every account");
|
||||
// a second click while it turns asks nothing more
|
||||
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
|
||||
release();
|
||||
|
||||
@@ -32,7 +32,7 @@ function server(lang, calls) {
|
||||
calls.overview++;
|
||||
return json({ calls: 1, errors: 0, input: 100, output: 10, cache_read: 0, cache_write: 0, reasoning: 0, unpriced: 0, cost: 0.01 + calls.overview * 0.001, bucket: "day", series: [{ label: "Mon", input: 100, output: 10, calls: 1, cost: 0.01 }], agents: [{ name: "Codex", calls: 1, cost: 0.01 }], models: [{ name: "gpt-6-sol", calls: 1, cost: 0.01 }], path: "~/.config/magpie/usage.jsonl" });
|
||||
}
|
||||
if (url.pathname === "/api/usage/quotas") { calls.quotas++; if (url.search === "?asked=1") calls.asked++; return json([]); }
|
||||
if (url.pathname === "/api/usage/quotas") { calls.quotas++; if (url.searchParams.get("asked") === "1") calls.asked++; if (url.searchParams.get("all") === "1") calls.all++; return json([]); }
|
||||
if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] });
|
||||
if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
@@ -54,7 +54,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const w = L[lang];
|
||||
const errors = [], calls = { requests: 0, overview: 0, quotas: 0, asked: 0 };
|
||||
const errors = [], calls = { requests: 0, overview: 0, quotas: 0, asked: 0, all: 0 };
|
||||
const context = await browser.newContext({ viewport: { width: 1180, height: 700 }, reducedMotion: "reduce" });
|
||||
const open = async () => {
|
||||
const p = await context.newPage();
|
||||
@@ -112,7 +112,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
// on Overview it reads the summary, and the allowances are read now too
|
||||
await p.locator(":is(#usageTab .opt, .nav-s):visible").nth(0).click();
|
||||
await p.locator("#stats .kpi:not(.loading-kpi)").first().waitFor();
|
||||
const o = calls.overview, q = calls.quotas, a = calls.asked;
|
||||
const o = calls.overview, q = calls.quotas, a = calls.asked, every = calls.all;
|
||||
await p.locator("#usageReload").click();
|
||||
await p.waitForTimeout(200);
|
||||
assert(calls.overview > o, "the summary again");
|
||||
@@ -120,6 +120,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
// it is the allowances' Refresh too (#486): asked, as that one was, and
|
||||
// there is no second Refresh beside them
|
||||
assert(calls.asked > a, "the allowances asked for, a Claude account's by its /usage");
|
||||
// every account's, a saved Claude account's too (#5380)
|
||||
assert(calls.all > every, "every account's allowance asked for");
|
||||
assert.equal(await p.locator("#quotaRefresh").count(), 0, "one refresh on the page");
|
||||
const tip = await p.locator("#usageReload").getAttribute("title");
|
||||
assert(tip.startsWith(w.now) && tip.includes("/usage"), tip);
|
||||
|
||||
+10
-2
@@ -255,10 +255,18 @@ func usageRoutes(mux *http.ServeMux, w Windows) {
|
||||
// own /usage is run at once (provider.AskClaudeUsage).
|
||||
// Only then are they read while the user has allowances read only
|
||||
// when asked (#1518).
|
||||
// &all=1 is the user's Refresh of every allowance by hand (the tray
|
||||
// panel's, the Usage page's, routing's): each saved Claude account's
|
||||
// /usage is run too, as its card's refresh runs it (#5380); opening
|
||||
// the page asks without it.
|
||||
mux.HandleFunc("GET /api/usage/quotas", func(rw http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
if r.URL.Query().Get("asked") != "" {
|
||||
provider.AskClaudeUsage()
|
||||
if q := r.URL.Query(); q.Get("asked") != "" {
|
||||
if q.Get("all") != "" {
|
||||
provider.AskEveryClaudeUsage()
|
||||
} else {
|
||||
provider.AskClaudeUsage()
|
||||
}
|
||||
ctx = provider.Asked(ctx)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 12*time.Second)
|
||||
|
||||
@@ -91,6 +91,118 @@ func TestRefreshSavedClaudeUsage(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The tray panel's top refresh of the allowances, and the Usage page's
|
||||
// Refresh (AskEveryClaudeUsage, &all=1), read every saved Claude account
|
||||
// anew, as each card's refresh does (#5380: the panel said "Allowances
|
||||
// refreshed" while each saved account kept a reading half an hour old).
|
||||
// Opening the page and an unasked read still start no saved account's
|
||||
// Claude Code, and the 30-second floor holds.
|
||||
func TestRefreshEveryReadsSavedClaude(t *testing.T) {
|
||||
claudeThree(t)
|
||||
var text atomic.Value
|
||||
text.Store("Current session: 9% used\nCurrent week (all models): 97% used")
|
||||
runs := fakeClaudeUsage(t, &text, nil)
|
||||
var mu sync.Mutex
|
||||
ran := map[string]int{}
|
||||
UsageClaudeVia(func(_ context.Context, dir string) (string, error) {
|
||||
runs.Add(1)
|
||||
mu.Lock()
|
||||
ran[dir]++
|
||||
mu.Unlock()
|
||||
return text.Load().(string), nil
|
||||
})
|
||||
runsIn := func(user string) int {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return ran[claudeAccountDir(user)]
|
||||
}
|
||||
var saved []string
|
||||
for _, l := range Logins("claude") {
|
||||
if !l.Active {
|
||||
saved = append(saved, l.User)
|
||||
}
|
||||
}
|
||||
if len(saved) != 2 {
|
||||
t.Fatalf("saved accounts: %v", saved)
|
||||
}
|
||||
age := func(user string) {
|
||||
claudeUsage.Lock()
|
||||
e := claudeUsage.m[strings.ToLower(user)]
|
||||
e.tried = e.tried.Add(-time.Hour)
|
||||
claudeUsage.m[strings.ToLower(user)] = e
|
||||
claudeUsage.Unlock()
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
// the page opened: asked, but no saved account's Claude Code
|
||||
AskClaudeUsage()
|
||||
LoginUsage(Asked(ctx), "claude")
|
||||
for _, user := range saved {
|
||||
if n := runsIn(user); n != 0 {
|
||||
t.Fatalf("opening ran saved %s %d times", user, n)
|
||||
}
|
||||
}
|
||||
|
||||
// the top refresh: every saved account read, each once, in its own
|
||||
// directory
|
||||
AskEveryClaudeUsage()
|
||||
got := LoginUsage(Asked(ctx), "claude")
|
||||
for _, user := range saved {
|
||||
q := got[user]
|
||||
if q.Error != "" || len(q.Windows) != 2 || q.Windows[0].Used != 9 || q.Windows[1].Used != 97 || q.ReadAt == nil {
|
||||
t.Fatalf("top refresh read no allowance of saved %s: %+v", user, q)
|
||||
}
|
||||
if n := runsIn(user); n != 1 {
|
||||
t.Fatalf("top refresh ran saved %s %d times, want once", user, n)
|
||||
}
|
||||
}
|
||||
|
||||
// Claude Code used meanwhile; past the floor, nobody asking, and the
|
||||
// page opened again: the readings stand
|
||||
text.Store("Current session: 36% used\nCurrent week (all models): 100% used")
|
||||
for _, user := range saved {
|
||||
age(user)
|
||||
}
|
||||
for _, user := range saved {
|
||||
if ws, err := claudeWindows(ctx, user, false); err != nil || len(ws) != 2 || ws[0].Used != 9 || runsIn(user) != 1 {
|
||||
t.Fatalf("unasked read ran saved %s: %v %+v", user, err, ws)
|
||||
}
|
||||
}
|
||||
AskClaudeUsage()
|
||||
for _, user := range saved {
|
||||
if q := LoginUsage(Asked(ctx), "claude")[user]; q.Windows[0].Used != 9 || runsIn(user) != 1 {
|
||||
t.Fatalf("opening again ran saved %s: %+v", user, q)
|
||||
}
|
||||
}
|
||||
|
||||
// the top refresh again reads the new figures
|
||||
AskEveryClaudeUsage()
|
||||
got = LoginUsage(Asked(ctx), "claude")
|
||||
for _, user := range saved {
|
||||
if q := got[user]; q.Error != "" || q.Windows[0].Used != 36 || q.Windows[1].Used != 100 || runsIn(user) != 2 {
|
||||
t.Fatalf("second top refresh kept an old reading of %s: %+v, %d runs", user, q, runsIn(user))
|
||||
}
|
||||
}
|
||||
|
||||
// rapid clicks keep to the per-account floor: one account past it is
|
||||
// read, the other not
|
||||
age(saved[0])
|
||||
AskEveryClaudeUsage()
|
||||
LoginUsage(Asked(ctx), "claude")
|
||||
if runsIn(saved[0]) != 3 || runsIn(saved[1]) != 2 {
|
||||
t.Fatalf("rapid top refresh: %s ran %d, %s ran %d; want 3 and 2", saved[0], runsIn(saved[0]), saved[1], runsIn(saved[1]))
|
||||
}
|
||||
|
||||
// an ask the floor put off isn't run by a read long after it
|
||||
AskEveryClaudeUsage() // saved[1] is inside its floor: not read
|
||||
LoginUsage(Asked(ctx), "claude")
|
||||
claudeEveryAt.Store(time.Now().Add(-claudeEveryFor - time.Second).UnixNano())
|
||||
age(saved[1])
|
||||
if _, err := claudeWindows(ctx, saved[1], false); err != nil || runsIn(saved[1]) != 2 {
|
||||
t.Fatalf("a timed read ran saved %s for a refresh long gone: %v, %d runs", saved[1], err, runsIn(saved[1]))
|
||||
}
|
||||
}
|
||||
|
||||
// Claude Code run in a saved account's directory refreshes the sign-in it
|
||||
// keeps there when it is due, spending the old refresh token. magpie keeps
|
||||
// the new one at once, and doesn't hand the account to Claude Code itself
|
||||
|
||||
@@ -37,10 +37,14 @@ func fakeClaudeUsage(t *testing.T, out *atomic.Value, fail *atomic.Bool) *atomic
|
||||
claudeUsageWait = func() time.Duration { return usageTestWait }
|
||||
claudeUsedSince = func(time.Time) bool { return true }
|
||||
claudeAsked.Store(0)
|
||||
// no refresh of every allowance (AskEveryClaudeUsage) left from
|
||||
// another test
|
||||
claudeEveryAsked.Store(0)
|
||||
claudeUsage.Lock()
|
||||
claudeUsage.m = nil
|
||||
claudeUsage.Unlock()
|
||||
t.Cleanup(func() {
|
||||
claudeEveryAsked.Store(0)
|
||||
UsageClaudeVia(old)
|
||||
claudeBase, claudeUsageWait, claudeUsedSince = oldBase, oldWait, oldUsed
|
||||
claudeAsked.Store(oldAsked)
|
||||
|
||||
@@ -761,14 +761,35 @@ var claudeAsked atomic.Int64
|
||||
// in one wall-clock tick. tried and wait still schedule the next /usage.
|
||||
var claudeAskGeneration atomic.Uint64
|
||||
|
||||
func markClaudeUsageAsked() {
|
||||
// claudeEveryAsked is the ask generation of the user's last refresh of
|
||||
// every allowance at once (AskEveryClaudeUsage): a saved account read
|
||||
// before it (claudeUsageEntry.asked) is read again, as its card's refresh
|
||||
// would read it (#5380), by a read that starts within claudeEveryFor of
|
||||
// the ask (claudeEveryAt): one the 30-second floor put off isn't run by a
|
||||
// timed read long after.
|
||||
var (
|
||||
claudeEveryAsked atomic.Uint64
|
||||
claudeEveryAt atomic.Int64
|
||||
)
|
||||
|
||||
const claudeEveryFor = 2 * time.Minute
|
||||
|
||||
func markClaudeUsageAsked() { markClaudeAsk(false) }
|
||||
|
||||
// markClaudeAsk is an ask of Claude's usage; every, the user's refresh of
|
||||
// every allowance, whose saved accounts are read too.
|
||||
func markClaudeAsk(every bool) {
|
||||
// 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)
|
||||
at := time.Now().UnixNano()
|
||||
claudeAsked.Store(at)
|
||||
if g := claudeAskGeneration.Add(1); every {
|
||||
claudeEveryAt.Store(at)
|
||||
claudeEveryAsked.Store(g)
|
||||
}
|
||||
loginUsageCache.Unlock()
|
||||
subscriptionUsageCache.Unlock()
|
||||
}
|
||||
@@ -777,8 +798,21 @@ func markClaudeUsageAsked() {
|
||||
// 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() {
|
||||
markClaudeUsageAsked()
|
||||
func AskClaudeUsage() { askClaudeUsage(false) }
|
||||
|
||||
// AskEveryClaudeUsage is the user refreshing every allowance by hand: the
|
||||
// tray panel's or the Usage page's Refresh, routing's read of the
|
||||
// allowances, the TUI's r (#5380: the panel said "Allowances refreshed"
|
||||
// while each saved Claude account kept its old reading, which only its
|
||||
// own card's refresh read again). As AskClaudeUsage, and each saved
|
||||
// Claude account's /usage is run too, as its card's refresh runs it, the
|
||||
// 30-second floor and all. Opening the page, its timer and `magpie
|
||||
// quota` ask with AskClaudeUsage, which starts no saved account's Claude
|
||||
// Code (savedRefresh).
|
||||
func AskEveryClaudeUsage() { askClaudeUsage(true) }
|
||||
|
||||
func askClaudeUsage(every bool) {
|
||||
markClaudeAsk(every)
|
||||
AskUsage()
|
||||
l := &loginUsageCache
|
||||
l.Lock()
|
||||
@@ -815,11 +849,12 @@ func AskUsage() {
|
||||
// (active) is read when the user asked since it last was, when the last
|
||||
// reading's claudeUsageWait (claudeNearOutWait near out) is up and Claude
|
||||
// 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), or
|
||||
// when the keep-alive runs Claude Code on it (keepingAlive), by
|
||||
// Claude Code run in the account's own config directory
|
||||
// since. A saved account is read only when its card is refreshed
|
||||
// (savedRefresh) or every allowance was refreshed by hand since it was
|
||||
// read (AskEveryClaudeUsage), or when 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.
|
||||
// magpie itself never asks Anthropic.
|
||||
@@ -848,7 +883,10 @@ func claudeWindows(ctx context.Context, user string, active bool) ([]QuotaWindow
|
||||
if active {
|
||||
alive = nil
|
||||
}
|
||||
read := ((active || savedRefresh(ctx, user)) && due || spare || alive != nil) && (now.Sub(e.tried) >= claudeAskFloor || alive != nil) && !holding(ctx)
|
||||
// every allowance refreshed by hand since this saved account's last
|
||||
// read (AskEveryClaudeUsage), as its own card's refresh would
|
||||
every := !active && claudeEveryAsked.Load() > e.asked && now.Sub(time.Unix(0, claudeEveryAt.Load())) < claudeEveryFor
|
||||
read := ((active || savedRefresh(ctx, user) || every) && 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
|
||||
@@ -946,7 +984,8 @@ var (
|
||||
)
|
||||
|
||||
// savedRefresh says ctx is the refresh of the card of the saved Claude
|
||||
// account user, the one ask that runs Claude Code for a saved account. The
|
||||
// account user, one ask that runs Claude Code for a saved account; the
|
||||
// other is the user's refresh of every allowance (AskEveryClaudeUsage). The
|
||||
// Usage page opened, its timer, `magpie quota` and routing keep to what
|
||||
// was read: a run in every saved account's directory for each of them
|
||||
// would start Claude Code once per account.
|
||||
|
||||
@@ -383,6 +383,10 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
m.flash, m.flashOK = "reloaded", true
|
||||
if m.page == pageUsage {
|
||||
m.quotas = nil
|
||||
// every account read again, a saved Claude
|
||||
// account's /usage run too, as the app's
|
||||
// Refresh does (#5380)
|
||||
provider.AskEveryClaudeUsage()
|
||||
return m, m.loadQuotas(true)
|
||||
}
|
||||
return m, nil
|
||||
|
||||
Reference in New Issue
Block a user