caps: a wallet window's spend is counted, so a cap holds it (#5770)
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 onf8186c691. Rebased under it after:7000b23b8(GUI files only) and36ddd5761(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)
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user