From a06872dec825114cdc8cae74faffeef1d250c068 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 9 Nov 2026 19:20:34 +0800 Subject: [PATCH] caps: a wallet window's spend is counted, so a cap holds it (#5770) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A window that tells only what is left (QuotaWindow.Balance: AStudio 0.2.0's 通用积分 and 星火积分, SuperMagic's points) read 0% used until it was empty, so an account cap never tripped on it. 9won capped an AStudio account at 4 and it spent over 1,000 credits past it. magpie now counts what such a wallet spends (wallet_spend.go). Each plugin reading's balance is set against the one before: a fall is spent, a rise (top-up, daily grant) is not. The count runs over the window's own period when it tells a reset, else the local day: a wallet never renews, and a cap reached for good would switch the account off with no time it comes back; the ask was "N a day". Spend before a period's first reading, or across a gap between periods, is unknown and not counted; spentSince says when counting began. The counts are kept in wallet-spend.json beside providers.json, so a restart doesn't lose them. Every wallet window carries spent and spentSince. On an account with a usage cap (WindowCaps.Holds) it also reads as amount spent of limit (spent plus what is left), and used that share. A cap by share then holds it in routing (allowanceOf takes the fields as they are) and on the GUI row (capHeldOf reads used). So does 40cbdaa7e's amount cap, which skipped a window with no total: 9won's "at most 300 a day" on a wallet now holds (magpie provider account-cap ... --window 通用积分 --amount 300). An uncapped wallet is unchanged: balance alone, routed by Allowance.Left. A cap just set is judged from the next reading. holdsBounds leaves wallets out: there is no whole to reckon "holds" from. Tests, each red on the old code (broken by hand where they compile): - TestPluginWalletCapHolds: real plugin host, fake plugin, wallet 10,000 -> 9,500 on an account capped at 4. Used 5, CapHeld set, the uncapped account untouched. Red with the plugin_usage.go hook removed (Used 0, Spent nil). - TestWalletSpendCounted: falls counted, top-ups not, a restart reads the count back, the next local day and a told reset start over (UTC+8 fixed zone), failed and share readings left alone. - TestWalletCapHolds: account cap 4, the window's own cap 4, and an amount cap of 700 (not held at 650 spent, held at 750). - TestWindowHoldsLeavesAWalletOut: red without the holdsBounds change (a wallet reckoned a 500-token whole). Run on mote at this tree on f8186c691. Rebased under it after: 7000b23b8 (GUI files only) and 36ddd5761 (internal/sessions only) (lockf ~/suite.lock mote-run): - go test ./internal/provider -run 'Wallet|Cap|Amount' -count=1: ok - go test ./internal/usage -run TestWindowHolds -count=1: ok - gofmt -l .: clean - go vet ./... for darwin and windows, and for linux with -tags nogui: ok Pushed and tagged at once, per the owner's rule. The full go test ./... -timeout 45m runs after the push and any red gets filed. Not changed: the GUI. A wallet meter still shows "{n} left". A capped one shows "At its cap" from used. The meter's Amount... item still needs a total and a unit, so an uncapped wallet doesn't offer it yet (follow-up). A Text window (a balance that isn't a number) still can't be capped by share. Reported-by: 9won (Discord) --- docs/subsystems/providers-accounts.md | 1 + internal/provider/plugin_usage.go | 3 +- internal/provider/subscription_usage.go | 10 +- internal/provider/wallet_spend.go | 141 +++++++++++++++++++ internal/provider/wallet_spend_test.go | 178 ++++++++++++++++++++++++ internal/usage/window_holds.go | 4 +- internal/usage/window_holds_test.go | 22 +++ 7 files changed, 356 insertions(+), 3 deletions(-) create mode 100644 internal/provider/wallet_spend.go create mode 100644 internal/provider/wallet_spend_test.go diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index d3364fe62..befdefd60 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -376,6 +376,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`. - The Vertex AI preset's `HeaderHints` are Google's Priority PayGo and Flex PayGo headers, `X-Vertex-AI-LLM-Request-Type` and `X-Vertex-AI-LLM-Shared-Request-Type`: the editor offers to add them, the values are the user's, and they go as `Headers` do. Priority PayGo couldn't be confirmed: on the project it was tried on, Vertex AI answered with `trafficType` `ON_DEMAND`. - An account's weight under `weight` routing is kept per account too (`AccountWeights`, by the account in lower case, 2–1000; one not in it weighs 1, and nothing sets one from the plan), as a key's is (`KeyAccount.Weight`), so a Max and a Pro account can share requests by how much more one allows (rubbzha on X). `SetAccountWeight` (GUI `provider/accountweight`, the chip beside each account in use in the editor while the routing is By weight; `magpie provider account-weight [account [n|default]]`) sets it, `moveAccountSettings` carries it through a Copilot rename, and `withPicks` puts it on the accounts `All` gives, so the gateway's `keyWeight` reads it with no file read (`Provider.AccountWeight`). - A usage cap is kept per account (`AccountCaps`, 1–99) and, beside it, per window (`AccountWindowCaps`, by the account and the window's `capId`, its name in lower case: `WindowCapID`). A window's own share wins over the account's; 100 is no cap on that window. `CapsOf` gives both (`WindowCaps`), `CapHeld` and `capReached` judge each window by its own, and `SetWindowCap` (GUI `provider/windowcap`, `magpie provider account-cap --window `) sets one; `SetWindowCaps` sets several at once, as the GUI's meter for a family of models (Antigravity's Gemini 3.1 Pro, High and Low) posts its models' windows in `windows`. An Antigravity pool's own windows ("Gemini · 7 days") are set aside for routing but capped (`WithCapped`, `capId` the pool's name and its own, as `LineName`): `allowanceOf` hangs each on its members' windows (`Limit.pool`), and `CapHeld` and `NearCap` count them through `capLimits`, so a cap on one holds that pool's models only (pluviophile714 on Discord, `TestPoolWindowCapHeld`). A window counted in a unit with its total (`QuotaWindow.Amount`, `Limit`, `Unit`: WorkBuddy's credits, a plan's requests) can instead be capped at a fixed amount of that unit (`AccountWindowAmounts`, by account and `capId`; 9won_25273 on Discord). `SetWindowAmount` (GUI `provider/windowcap` with `amount` in place of `cap`, the meter's menu's Amount…, typed in place) sets it, 0 lifts it; a window has a share of its own or an amount, never both, and setting one clears the other. `limitShare` makes the amount a share of the window's total for marks and `NearCap`, while `CapHeld` and `capReached` hold the account once the count reaches the amount (`past`); `CapHold` and the trace carry `Amount`, `Count` and `Unit`, and `cappedError` says "has used 300 credits … past its cap of 300". A reading with no total leaves the amount aside and the account's share applies. Every cap reads the vendor's own count of the window, so what the account spent outside magpie (the vendor's app, another machine) counts toward it as the vendor reports it, from the next reading on; magpie can only hold back its own requests (`TestWindowAmountCapHeld`, `TestSetWindowAmount`, `window-cap.test.cjs`). A config without window caps reads as before. How a pool ends at its caps is kept with the provider (plugins#349): `CapStop` answers 429 rather than going on to the fallbacks once every account in use is at its cap, and `CapCareful` reads usage again near a cap and holds an account whose usage can't be told (both off by default; within 5 points of its cap an account takes one turn at a time whatever they say, [gateway routing](gateway-routing.md); `SetCapStop`, `SetCapCareful`, GUI `provider/capstop` and `provider/capcareful`, ticks under the account list once an account has a cap). `UsageRead` says when an account's usage was last read well and whether the last try failed (a failed try keeps the good reading's time), and `ReadUsageNow` reads it again. `magpie provider pool [--accounts a,b,…] [--cap percent|off] [--stop on|off] [--careful on|off]` shows and sets the whole pool in one command: which accounts are on and in what order, each one's cap, and both settings, and names the accounts in use with no cap. +- A wallet's window, one that tells only what is left (`QuotaWindow.Balance`, no share and no total: AStudio's 通用积分 and 星火积分, SuperMagic's points), has its spend counted by magpie ([`wallet_spend.go`](../../internal/provider/wallet_spend.go), #5770, 9won on Discord: an account capped at 4 spent over 1,000 credits past it, since the wallet read 0% used until it was empty). Each reading a plugin's usage gives (`pluginLoginQuota` → `withWalletSpend`) is set against the one before: a fall is spent, a rise (a top-up, a daily grant) is not. The count runs over the window's own period when it tells a reset, else the local day, and starts at 0 at the period's first reading; what was spent before it, or between one period's last reading and the next's first, isn't known and isn't counted. Each window carries it as `spent` and `spentSince`. On an account with a usage cap (`WindowCaps.Holds`) the window reads as `amount` spent of `limit`, what the period had (spent plus what is left), and `used` that share, so a cap by share holds it in routing and on the GUI's row as it holds any window; without a cap the window is its balance alone, and routing goes by that (`Allowance.Left`). A cap set is judged from the next reading on. The counts are kept in `wallet-spend.json` beside providers.json, by provider, account and window, a period over for a week dropped; one that can't be read starts each count again. `holdsBounds` leaves a wallet out of a window's holds (no whole). `TestWalletSpendCounted`, `TestWalletCapHolds`, `TestPluginWalletCapHolds`. - A key's spend cap (`KeySpendCaps`, by the key's fingerprint, [`key_spend.go`](../../internal/provider/key_spend.go); sparkling_lemur_62868 on Discord: a team's OpenAI key whose granted credits other services spend from too) is how much magpie may spend on an API key, in USD, per calendar day or month in local time, or in all since it was set (`Since`, kept while the cap stays one in all, its amount changed or not). What counts is what the Usage page prices magpie's own calls on the key at (`usage.KeySpent`: records whose `ProviderKeyID` is the key, not turned away, not reported by an app; the log is read once and each new call added by `Append`, read again after 5 minutes), not the vendor's bill: a model with no known price counts nothing, and requests under way when it is reached still finish, so the key can go a little past it. At or past the cap the gateway passes the key over ([gateway routing](gateway-routing.md)). Only a key has one: `SetKeySpendCap` refuses a subscription, an amount not above 0 or over `MaxSpendCap` (1,000,000) and a period it doesn't know. `ReplaceKey` carries it to the new value. Set from the key's row in the editor (a pill: "$7.50 of $20.00 today", the app's menu, then the amount typed in place, drawn by `keyspend.js`, which app.js imports when it draws a key's row; GUI `provider/keyspendcap`, `key-spend-cap.test.cjs`) or `magpie provider spend-cap [key [usd [day|month|total]|off]]`, which also lists each key's spend. `TestKeySpendCapSet`, `TestSpendCapWindow`, `TestParseSpendCap`, `TestKeySpentCountsTheKeysCalls`, `TestSpendCapCmd`. - A key's balance typed by hand (`KeyOwnBalances`, by the key's fingerprint: `{usd | cny, at, refill, expirings}`, [`key_balance_own.go`](../../internal/provider/key_balance_own.go); tenacious_eagle on Discord) is for a key whose vendor tells no balance magpie can read (`TakesOwnBalance`: an API key with no balance source, not Cline's or OpenCode Zen's, not on a plan's windows). The user types what the vendor's page says is left; the key's card on the Usage page and the tray then shows it less what the Usage page prices magpie's own calls on the key at since then (`usage.KeySpent` from `at`, through the `provider.KeySpent` hook usage sets), as `≈$12.50` with `Estimate` (`set`, `at`, `spent`) and below nothing as `≈$-2.00`. Typing it again counts from then. It is an estimate, not a reading: it is kept out of the balance history (no trend or runs-out), is never shared, and routing reads nothing from it; a low-balance alert reads its number. A balance the vendor tells always wins: with a Balance URL or a source magpie knows the card is the vendor's, and a relay whose query is looked for shows the typed one only when none is found (`errNoBalance`); the typed value stays saved as the user left it. `SetKeyOwnBalance` (GUI `provider/keyownbalance`, a pill in the key's row, "≈$12.50 left" or "Set balance", drawn by `keybalance.js` while `takesOwnBalance` and no balance was found; `magpie provider key-balance [key [usd|¥cny|off] [--refill …]]`) refuses a subscription, an amount outside 0 to `MaxOwnBalance` (1,000,000) in either currency, and any currency but USD and CNY; nil takes it off, `ReplaceKey` carries it to the new value, and saving the editor keeps it. It may be typed in yuan (`cny`, "¥100", or a bare number with ¥ CNY picked in the currency button beside the field, which starts at the balance's own currency, else Settings' one; picking keeps the number typed and posts nothing until the field is left or Enter is pressed, so a balance's currency changes without clearing it or going to Settings, tenacious_eagle on Discord): what is spent is counted in USD and turned into yuan at `fx.Known()`, the rate `internal/fx` last fetched (cached 12h in `fxrate.json`, fetched again in the background, never on the request path); `fx.Known` never hands out `fx.Fallback`, so with no rate fetched yet and something spent the left is unknown (`left` null, the card's `Error` says why) rather than a guess. It may refill (`refill`: `{every: month, day: 1–31}`, a day past the month's end meaning its last, or `{every: week, day: 1 Monday–7 Sunday}`), at midnight in the user's local time: nothing is stored on a refill; the spend is counted from the last refill boundary after `at` (`From`), and `Next` is the next one. Typing the amount again keeps the refill. `SetKeyBalanceRefill` (GUI `provider/keybalancerefill`, the pill's menu: Refills each month…, Refills each week…, Never refills; CLI `--refill monthly[:day]|weekly[:mon…sun]|off`) refuses a key with no balance. Part of it may expire, in grants (`expirings`: a list of `{amount, until, at}`, up to `MaxExpiring` (20), each amount in the balance's currency, `until` the last day it counts as 2006-01-02, `at` when it was typed; tenacious_eagle_96548 on Discord: money that stays and promotional credit twice, one good until tomorrow and one the day after). Grants are spent first, as DeepSeek spends its granted balance before the money topped up, and of them the one that ends soonest first (`spendGrants`): the spend is taken piece by piece over the times between `From`, now, and each grant's `at` and end (midnight after `until`, local time), each piece going to the live grant that ends first, and only what grants took after `From` is off the rest, so a refill or typing the balance again doesn't count it twice. `left` is the whole balance, the grants' remainders included; from a grant's end its remainder counts no more (`expired`, the latest such end), and unspent credit is simply gone. A grant whose end is at or before `From` is dropped on the next write (`liveGrants`). `AddKeyExpiring` (GUI `provider/keyexpiring` `{expiring: {amount, until}}`), `RemoveKeyExpiring` (`{expiring: {at, until}, remove: true}`, matched by `at`, else by `until` and the amount when given; nothing matched is an error) and `ClearKeyExpiring` (`{expiring: null}`) edit them. The pill's menu has Add credit that expires…, which opens one small form (`.abal-form`, the app's popover, no native control but the date field) with the amount, in the balance's currency, and the last day, a month ahead to begin with: Add or Enter saves, Escape or a click outside leaves it, an amount in the other currency or a day gone by is refused with the form kept; then a Remove {amount} for each grant with when it goes beside it, and No credit that expires with two or more, or one that expired. The CLI takes `--expiring amount@yyyy-mm-dd` and `--expiring-remove [amount@]yyyy-mm-dd`, each as often as wanted and applied in order after the balance, every value read before anything is written; `--expiring off` takes every grant off. Each refuses a key with no balance typed (type the rest first, 0 when all of it expires), an amount not above 0 or past `MaxOwnBalance`, and a date that isn't one. A v0.1.3305 balance's one `expiring` object is read as the first grant (`UnmarshalJSON`) and saved as `expirings` on the next write; a magpie before this reads `expirings` as no grant, so going back loses them from the estimate, not from the file until it writes. Typing the balance again keeps the grants in the same currency and drops them in the other, where its amount would mean another sum. A balance saved before has none and is counted as it was. The estimate's `expiring`, one per grant soonest first (`set`, `at`, `until`, `left`, `ends`), is the pill's "≈$60.00 left · $5.00 expires tomorrow · $20.00 expires in 30 days" (wrapping at a grant on a narrow row), and the card's `BalanceSplit` a line each with `expires`, which the Usage page and the panel label "Expires in 30 days" (`expiresIn` in app.js), amber from a week; the TUI and CLI quota say "$20.00 until Dec 31" (`SplitWords`). Each key with one gets `balance` in `/api/providers`' `keyList` (`set`, `at`, `spent`, `currency`, `rate`, `left`, `from`, `refill`, `next`, `expiring`, `expired`). `TestTypedBalanceExpires`, `TestTypedBalanceSavedBeforeExpiring`, `TestTypedBalanceGrantsSoonestFirst`, `TestTypedBalanceGrantsEdited`, `TestTypedBalanceOneGrantMigrated`, `TestExpiringParsed`, `TestExpiringDayParsed`, `TestKeyBalanceCmd`, `key-balance-expiring.test.cjs`, `TestKnownIsNeverAGuess`, `TestTypedBalanceInYuan`, `TestTypedBalanceRefills`, `TestRefillDays`, `TestTypedBalanceCountsDown`, `TestToldBalanceWinsOverTyped`, `TestOwnBalanceParsed`, `TestKeyOwnBalanceRoutes`, `key-own-balance.test.cjs`. - A window whose reset time has passed has started again, whatever share it was read at (`resetPassed`). That holds for a reading kept from before (`AsOf`) and for a fresh one: Claude Code's `/usage` gives a reset to the minute and can lag it, so a run just after a reset can still say 100% with that reset. `claudeWindows` hands such a window back empty on every path, and `usedPast`, `usedUp`, `BackAt` and `capReached` leave it out when they judge an account spent, for Codex, Claude Code and `magpie quota wait` alike. A card can still show a kept reading as it was read (`reported`, for a Claude card while `/usage` is unavailable); that changes what it shows, never which account is used. A reset `/usage` gives as a time alone ("resets 3pm") can be read as its next one, a day on (`claudeResetTime`), and is then not seen as passed here. diff --git a/internal/provider/plugin_usage.go b/internal/provider/plugin_usage.go index eb51b521e..d686124ae 100644 --- a/internal/provider/plugin_usage.go +++ b/internal/provider/plugin_usage.go @@ -124,7 +124,8 @@ func pluginLoginQuota(ctx context.Context, l Login) SubscriptionQuota { notePluginLapseSince(pp, key, http.StatusOK, began) } keepPluginPlan(pp, key, u.Plan) - return quotaOfPlugin(q, u) + // a wallet's spend counted, for a cap to hold it (#5770) + return withWalletSpend(quotaOfPlugin(q, u), l.User, time.Now()) } // quotaOfPlugin fills q with what the plugin told. diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index 3b9571eb2..695ccaa31 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -58,8 +58,16 @@ type QuotaWindow struct { // (SuperMagic's points, #3950). Used is then no reading (0); the GUI // says the figure left, and routing knows the account by it and puts // the one with the most left first among a provider's accounts in the - // same unit (Allowance.Left). nil when not told. + // same unit (Allowance.Left). nil when not told. On an account with a + // usage cap, Amount of Limit and Used are what the wallet spent in the + // cap's period instead (wallet_spend.go, #5770), for the cap to hold. Balance *float64 `json:"balance,omitempty"` + // Spent is, on a wallet's window (Balance), how much of it magpie saw + // go since SpentSince, the first reading of the period a cap counts it + // over: the window's own until its reset, else the local day + // (wallet_spend.go). nil when not counted. + Spent *float64 `json:"spent,omitempty"` + SpentSince *time.Time `json:"spentSince,omitempty"` // Family is the model family a per-model window belongs to (Antigravity's // "Gemini 3.1 Pro (High)" is Gemini's), for the GUI to show one figure a // family, the tightest; each window is still here, and routing reads diff --git a/internal/provider/wallet_spend.go b/internal/provider/wallet_spend.go new file mode 100644 index 000000000..e2e96b73d --- /dev/null +++ b/internal/provider/wallet_spend.go @@ -0,0 +1,141 @@ +package provider + +// A wallet's window (QuotaWindow.Balance: AStudio's 通用积分 and 星火积分, +// SuperMagic's points) tells only what is left: no total, no share used. +// A usage cap had nothing to hold it at. It read 0% used until the wallet +// was empty, so a cap by share never tripped and one by amount, which +// needs the window's total, left it aside; an account capped at 4 spent +// over 1,000 credits past it (#5770, 9won_25273 on Discord). +// +// So magpie counts what such a wallet spends itself. Each reading's +// balance is set against the one before: a fall is spent, a rise (a +// top-up, a daily grant) is not. The count runs over a period, the +// window's own when it tells a reset, else the local day (a wallet never +// renews, and a cap that, once reached, held the account for good would +// turn it off with nothing to say when it comes back; the ask was a +// daily one). A period's count starts at 0 at its first reading. What +// went before that reading, or between the last reading of one period +// and the first of the next, isn't known and isn't counted. +// +// On an account with a usage cap, the window then reads as Amount spent +// of Limit, what the period had (spent plus what is left), and Used that +// share: a cap by share or by amount holds it as it holds any window, in +// routing (allowanceOf takes them as they are) and on the GUI's row. +// Without a cap the window keeps its balance alone, as before, and +// routing goes by that (Allowance.Left). +// +// The counts are kept in wallet-spend.json beside providers.json, by +// provider, account and window, so a restart doesn't start a period's +// count again. + +import ( + "encoding/json" + "os" + "path/filepath" + "sync" + "time" +) + +// walletSpend is one wallet window's count for its period. +type walletSpend struct { + Ends time.Time `json:"ends"` // when the period ends + Since time.Time `json:"since"` // its first reading + Spent float64 `json:"spent"` + Last float64 `json:"last"` // the balance last read +} + +var walletSpends struct { + sync.Mutex + m map[string]walletSpend + path string // the file m was read from: another HOME reads its own +} + +func walletSpendPath() string { return filepath.Join(filepath.Dir(Path()), "wallet-spend.json") } + +// walletPeriodEnd is when the period a reading of w at now starts ends: +// the window's reset when it tells one, else the next local midnight. +func walletPeriodEnd(w QuotaWindow, now time.Time) time.Time { + switch { + case w.ResetsAt != nil && w.ResetsAt.After(now): + return *w.ResetsAt + case w.ResetSecs > 0: + return now.Add(time.Duration(w.ResetSecs) * time.Second) + } + y, m, d := now.Date() + return time.Date(y, m, d+1, 0, 0, 0, 0, now.Location()) +} + +// noteWalletSpend counts the reading of wallet window w at now under key +// and is its period's count. +func noteWalletSpend(key string, w QuotaWindow, now time.Time) walletSpend { + b := *w.Balance + path := walletSpendPath() + c := &walletSpends + c.Lock() + defer c.Unlock() + if c.path != path { + c.path, c.m = path, nil + if raw, err := os.ReadFile(path); err == nil { + // one that can't be read starts each count again from now, + // which each window's SpentSince says + json.Unmarshal(raw, &c.m) + } + } + s, ok := c.m[key] + switch { + case !ok || !now.Before(s.Ends) || now.Before(s.Since): + s = walletSpend{Ends: walletPeriodEnd(w, now), Since: now, Last: b} + case b < s.Last: + s.Spent += s.Last - b + s.Last = b + case b > s.Last: + s.Last = b // topped up: nothing spent + default: + return s + } + if c.m == nil { + c.m = map[string]walletSpend{} + } + c.m[key] = s + for k, e := range c.m { + if now.Sub(e.Ends) > 7*24*time.Hour { + delete(c.m, k) // a wallet not read for a week + } + } + if raw, err := json.Marshal(c.m); err == nil { + os.MkdirAll(filepath.Dir(path), 0o700) + writeFileAtomic(path, raw) + } + return s +} + +// withWalletSpend is a fresh reading q of account user with each wallet +// window's spend counted (Spent, SpentSince) and, on an account with a +// usage cap, read as that much used of what its period had. q's windows +// are its own, changed in place. +func withWalletSpend(q SubscriptionQuota, user string, now time.Time) SubscriptionQuota { + if q.Error != "" || q.Provider == "" || user == "" { + return q + } + var caps *WindowCaps + for i := range q.Windows { + w := &q.Windows[i] + if w.Balance == nil || w.Text { + continue + } + s := noteWalletSpend(q.Provider+"/"+accountKey(user)+"/"+WindowCapID(w.Name), *w, now) + spent, since := s.Spent, s.Since + w.Spent, w.SpentSince = &spent, &since + if caps == nil { + c := AccountCapsOf(q.Provider, user) + caps = &c + } + of := spent + max(*w.Balance, 0) + if !caps.Holds() || of <= 0 { + continue + } + w.Amount, w.Limit = spent, of + w.Used = max(w.Used, spent/of*100) + } + return q +} diff --git a/internal/provider/wallet_spend_test.go b/internal/provider/wallet_spend_test.go new file mode 100644 index 000000000..87d023887 --- /dev/null +++ b/internal/provider/wallet_spend_test.go @@ -0,0 +1,178 @@ +package provider + +import ( + "context" + "fmt" + "os" + "path/filepath" + "testing" + "time" +) + +// wallet is a reading of a balance-only window (AStudio's 通用积分): what +// is left, nothing else. +func wallet(left float64, ws ...QuotaWindow) SubscriptionQuota { + b := left + return SubscriptionQuota{Provider: "codex", Windows: append([]QuotaWindow{{Name: "通用积分", Balance: &b}}, ws...)} +} + +// A wallet's falls are counted as spent, its rises (a top-up) are not, +// and the count starts again with the next local day or the window's own +// reset (#5770). +func TestWalletSpendCounted(t *testing.T) { + signIn(t) + zone := time.FixedZone("UTC+8", 8*3600) + t0 := time.Date(2026, 11, 9, 10, 0, 0, 0, zone) + read := func(left float64, at time.Time) QuotaWindow { + return withWalletSpend(wallet(left), "me@example.com", at).Windows[0] + } + for i, c := range []struct { + left, spent float64 + }{{1000, 0}, {900, 100}, {950, 100}, {800, 250}, {800, 250}} { + w := read(c.left, t0.Add(time.Duration(i)*time.Minute)) + if w.Spent == nil || *w.Spent != c.spent || w.SpentSince == nil || !w.SpentSince.Equal(t0) { + t.Fatalf("reading %d (%v left): spent %v since %v, want %v since %v", i, c.left, w.Spent, w.SpentSince, c.spent, t0) + } + // no cap: the window reads as it did, its balance alone + if w.Used != 0 || w.Amount != 0 || w.Limit != 0 { + t.Fatalf("an uncapped wallet read as used: %+v", w) + } + } + // a restart reads the count back + walletSpends.Lock() + walletSpends.path = "" + walletSpends.Unlock() + if w := read(700, t0.Add(time.Hour)); *w.Spent != 350 { + t.Fatalf("after a restart: spent %v", *w.Spent) + } + // the next local day starts again from its first reading + day := time.Date(2026, 11, 10, 0, 0, 1, 0, zone) + if w := read(600, day); *w.Spent != 0 || !w.SpentSince.Equal(day) { + t.Fatalf("next day: spent %v since %v", *w.Spent, w.SpentSince) + } + // a window telling its reset: its period, not the day + reset := day.Add(2 * time.Hour) + ws := func(left float64, at time.Time) QuotaWindow { + q := wallet(0) + b := left + q.Windows = []QuotaWindow{{Name: "星火积分", Balance: &b, ResetsAt: &reset}} + return withWalletSpend(q, "me@example.com", at).Windows[0] + } + ws(50, day) + if w := ws(40, day.Add(time.Hour)); *w.Spent != 10 { + t.Fatalf("before its reset: %v", *w.Spent) + } + if w := ws(45, reset.Add(time.Minute)); *w.Spent != 0 { + t.Fatalf("after its reset: %v", *w.Spent) + } + // a window with a share of its own, a failed reading: left alone + q := withWalletSpend(SubscriptionQuota{Provider: "codex", Windows: []QuotaWindow{{Name: "Weekly", Used: 30}}}, "me@example.com", t0) + if q.Windows[0].Spent != nil { + t.Fatal("a window with no balance counted") + } + q = wallet(10) + q.Error = "sign in again" + if q = withWalletSpend(q, "me@example.com", t0); q.Windows[0].Spent != nil { + t.Fatal("a failed reading counted") + } +} + +// #5770: 9won capped an AStudio account at 4 and it spent over 1,000 +// credits past it, since a wallet read 0% used until it was empty. A +// capped account's wallet reads as what it spent of what its period had, +// and the cap holds it. +func TestWalletCapHolds(t *testing.T) { + signIn(t) + now := time.Now() + if err := SetAccountCap("codex", "me@example.com", 4); err != nil { + t.Fatal(err) + } + caps := AccountCapsOf("codex", "me@example.com") + read := func(left float64, at time.Time) QuotaWindow { + return withWalletSpend(wallet(left), "me@example.com", at).Windows[0] + } + w := read(10000, now) + if h := allowanceOf([]QuotaWindow{w}, now).CapHeld("any", caps, now); h != nil { + t.Fatalf("held before spending: %+v", h) + } + w = read(9700, now.Add(time.Minute)) // 300 of 10,000: 3% + if w.Amount != 300 || w.Limit != 10000 || w.Used != 3 { + t.Fatalf("300 spent read as %+v", w) + } + if h := allowanceOf([]QuotaWindow{w}, now).CapHeld("any", caps, now); h != nil { + t.Fatalf("held at 3%% of 4%%: %+v", h) + } + w = read(9500, now.Add(2*time.Minute)) // 500: 5% + h := allowanceOf([]QuotaWindow{w}, now).CapHeld("any", caps, now) + if h == nil || h.Used < 4 || h.Cap != 4 { + t.Fatalf("500 of 10,000 spent, cap 4: held %+v (window %+v)", h, w) + } + // a window's own cap holds it as well + if err := SetAccountCap("codex", "me@example.com", 0); err != nil { + t.Fatal(err) + } + if err := SetWindowCap("codex", "me@example.com", "通用积分", 4); err != nil { + t.Fatal(err) + } + caps = AccountCapsOf("codex", "me@example.com") + w = read(9400, now.Add(3*time.Minute)) + if h := allowanceOf([]QuotaWindow{w}, now).CapHeld("any", caps, now); h == nil { + t.Fatalf("the wallet's own cap 4 not held at %+v", w) + } + // 9won's own ask: at most 700 credits of the wallet a day, an amount + if err := SetWindowCap("codex", "me@example.com", "通用积分", 0); err != nil { + t.Fatal(err) + } + if err := SetWindowAmount("codex", "me@example.com", []string{"通用积分"}, 700); err != nil { + t.Fatal(err) + } + caps = AccountCapsOf("codex", "me@example.com") + w = read(9350, now.Add(4*time.Minute)) // 650 spent + if h := allowanceOf([]QuotaWindow{w}, now).CapHeld("any", caps, now); h != nil { + t.Fatalf("held at 650 of an amount cap of 700: %+v (window %+v)", h, w) + } + w = read(9250, now.Add(5*time.Minute)) // 750 spent + if h := allowanceOf([]QuotaWindow{w}, now).CapHeld("any", caps, now); h == nil { + t.Fatalf("750 spent, amount cap 700, not held (window %+v)", w) + } +} + +// Through the plugin host, as 9won's AStudio account went: a wallet window +// on an account capped at 4, read again after it spent 5% of what it had, +// reads as 5 used, and the cap holds the account. +func TestPluginWalletCapHolds(t *testing.T) { + windows := filepath.Join(t.TempDir(), "windows.json") + put := func(left int) { + t.Helper() + raw := fmt.Sprintf(`{"a@fake": [{"name": "通用积分", "balance": %d}], "full@fake": [{"name": "通用积分", "balance": %d}]}`, left, left) + if err := os.WriteFile(windows, []byte(raw), 0o600); err != nil { + t.Fatal(err) + } + } + put(10000) + q := fakePluginUsage(t, windows)["a@fake"] + if len(q.Windows) != 1 || q.Windows[0].Balance == nil || q.Provider == "" { + t.Fatalf("the wallet: %+v", q) + } + if err := SetAccountCap(q.Provider, "a@fake", 4); err != nil { + t.Fatal(err) + } + put(9500) + StaleAllowance("plugin:fakeco", "a@fake") + StaleAllowance("plugin:fakeco", "full@fake") + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + u := LoginUsage(ctx, "plugin:fakeco") + now := time.Now() + w := u["a@fake"].Windows[0] + if w.Used != 5 || w.Amount != 500 || w.Limit != 10000 { + t.Fatalf("500 of 10,000 spent read as %+v", w) + } + if h := allowanceOf(u["a@fake"].Windows, now).CapHeld("any", AccountCapsOf(q.Provider, "a@fake"), now); h == nil { + t.Fatal("the cap of 4 didn't hold an account 5% spent") + } + // full@fake has no cap: its wallet reads as its balance alone + if f := u["full@fake"].Windows[0]; f.Used != 0 || f.Spent == nil || *f.Spent != 500 { + t.Fatalf("the uncapped account: %+v", f) + } +} diff --git a/internal/usage/window_holds.go b/internal/usage/window_holds.go index 1e9ed363b..5294f6270 100644 --- a/internal/usage/window_holds.go +++ b/internal/usage/window_holds.go @@ -74,7 +74,9 @@ func holdsBounds(q provider.SubscriptionQuota, w provider.QuotaWindow, at time.T // Discord); the models' own windows drawing on it, and a pool whose // models aren't known, aren't. pool := w.PoolWindow() && len(provider.PoolMembers(q.Windows, w)) > 0 - if w.Unlimited || w.Aside && !pool || w.Family != "" || w.Pool != "" && !pool || math.IsNaN(w.Used) { + // a wallet (Balance) has no whole: its Used, on a capped account, is + // what it spent in the cap's period (provider's wallet_spend.go) + if w.Unlimited || w.Aside && !pool || w.Family != "" || w.Pool != "" && !pool || w.Balance != nil || math.IsNaN(w.Used) { return time.Time{}, time.Time{}, "-" } if w.Used < provider.HoldsFloor { diff --git a/internal/usage/window_holds_test.go b/internal/usage/window_holds_test.go index 3f2700b3d..7e2a518d9 100644 --- a/internal/usage/window_holds_test.go +++ b/internal/usage/window_holds_test.go @@ -548,3 +548,25 @@ func TestHoldsPriceTheModelTheReplyNamed(t *testing.T) { t.Fatalf("5 hours: %+v, a priced reply left the dollar whole out", h) } } + +// A wallet's window (#5770) tells what is left and no whole; on a capped +// account its Used is what magpie counted it spending in the cap's +// period, and nothing is reckoned from that as the window's whole. +func TestWindowHoldsLeavesAWalletOut(t *testing.T) { + now := time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC) + reset := now.Add(12 * time.Hour) + left := 9500.0 + qs := []provider.SubscriptionQuota{{Provider: "astudio", User: "9won@example.com", Windows: []provider.QuotaWindow{ + {Name: "通用积分", Balance: &left, Used: 40, Amount: 500, Limit: 10000, ResetsAt: &reset, Span: 24 * time.Hour}}}} + recs := []Record{{Time: now.Add(-time.Hour), Provider: "astudio", ProviderAccount: "9won@example.com", Model: "claude-opus-4-7", Input: 100, Output: 100, Status: 200}} + read := func(fn func(Record)) { + for _, r := range recs { + fn(r) + } + } + priceOf := func(Record) *catalog.Price { return nil } + got := windowHolds(qs, now, now.Add(-30*24*time.Hour), priceOf, provider.Renames{}, nil, nil, read) + if w := got[0].Windows[0]; w.Holds != nil || w.HoldsWhy != "" { + t.Fatalf("a wallet reckoned a whole: %+v, why %q", w.Holds, w.HoldsWhy) + } +}