diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index db94c6616..dcb3c6b77 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -237,7 +237,8 @@ recorded as a prediction failure (`noPrediction`). - Antigravity's 429 for a model's quota used up writes how long until it is back as Go prints a duration: "You have exhausted your capacity on this model. Your quota will reset after 3h19m30s." (`quotaResetAfter`, read by `resetsAfter` beside Factory's "resets in …", held to `longestWritten`). The account (or, as `pooled` says, that model on it) rests that long (`resets`), and the agent's Retry-After says it when no account is left. Unread, it rested `quotaRest`, so the account first in order was asked again, and refused, every 15 minutes while the next ticked account had its quota (Dani Ariyanto on Discord, 10-24; `TestAntigravityQuotaRestsUntilItsReset`). Its other 429, "Resource has been exhausted (e.g. check quota).", names no time and rests `quotaRest` as before. - A ZCode plugin account's Start Plan trial entry (`-Trial`) that the plugin refuses before sending anything rests that entry alone (`zcodeTrialRefused`, `restID`), not the account: a 400 "ZCode has no active limited quota for GLM-5.3-Trial" when no live plan holds it any more (the trial ended), and a 429 "ZCode's limited quota for glm-5.3 is exhausted or temporarily unavailable" when its bucket is spent (the plugin names the bucket, the entry less `-Trial`). Read as `failQuota` by their words, both rested `zcode@…`, and the account's GLM Coding Plan models were paused with the trial (#3661, orion-nebula-dev; after skygunner's e04a1b994, which covered the 400). Only the plugin's exact words naming the model asked for count: another model named, a model without `-Trial`, the words on another status, the account's own quota or key, and the same words from another vendor still rest the account (`TestZCodeTrialRefusalRestsTheTrialAlone`). An expired trial still kept in a group is asked first and refused locally, as the guessed quota rest is asked again a minute on; the Routing page strikes it as skipped, which the gateway doesn't do for a member no account lists (#3805). - An account resting out of its window (a Claude account by the time Claude Code's refusal named, `resets`, or any by `window`) is back once magpie's reading of its windows (`provider.Allowances`) finds it full till sooner: the window used below `SpentShareOf`, or its reset passed, with no other window over the same models still full. The reading tells `provider.OnRenewed` as the account's `UsageAgent` and user, and `renewed` lifts that account's rests out of quota or by `window`; its rests for a rate limit, its credit, a verification or a failure stay, as a key's do, and so does every rest of other accounts still out of their windows. Planning reads every account candidate's allowance, ordered groups included, so this needs no step of its own in `restingOf`. -- Only an account is held at a usage cap (`capHeld`) or rested out of one model's pool (`pooled`); a key's windows order it and rest it, nothing more. +- Only an account is held at a usage cap (`capHeld`) or rested out of one model's pool (`pooled`); a key's windows order it and rest it, nothing more. A key is held only at its own spend cap (below). +- A key at its spend cap ([providers](providers-accounts.md), `provider.SpendCap`) is barred in `perKeyEvery` (`spendHeld`) with a `capHold` whose `spend` is set: it is passed over and the provider's other keys and its fallbacks take the request. Routing's row says what it spent of its cap (`Weighed.SpendCap`, `Spent`, `SpendPeriod`, `SpendSince`). With every candidate held, `cappedError` answers 429 naming each key, what it spent of its cap and when it is back (the next day or month, or not until a cap in all is raised), and the command that changes it, with `Retry-After` at the soonest; a cap in all gives none. A spend hold is not a usage cap: `capHeldOnly` leaves it out, so neither Stop at the caps (`CapStop`) nor Strict's `strictKeep` sends a request to a key past what it may spend. `TestKeySpendCapPassesTheKeyOver`. - A rest of one model alone (keyed by `restID`: a pool, a model not served, a paid model beside free ones) names that model in the trace (`Rest.Model`). The Routing page shows it on that model's rows only: the account's other models' rows on the stage, and the account's row under Accounts and keys, don't read as resting. The account's row names the models resting on a line of their own under what it has left, and its Try now lifts their rests. A kept request from before `Rest.Model` has the model on the end of `Rest.Key`, which the page reads the same (`restModel` in `plugins/routing/client.js`, #1960, `routing-model-rest.test.cjs`). - The Providers page shows a subscription account's rests in force on its row there too: `RestsUnder("@")` lists them, `providerJSON.accountRests` gives them by user in lower case (the account's own, and each model's, with `Rest.Model`, `Until`, `By` and the vendor's words, `Rest.Error`), and the row's line says which model, why and when it is back, the vendor's words beside it, with Try now lifting it by its key (`accountRestLines` in app.js). Before, only a key's rest showed there, and a WorkBuddy AI account whose model rested on a 429 "将在 … 重置" read as fine, its credits 82% left (maxleebeta on Discord; `TestRateLimitedModelListedUnderAccount`, `TestAccountRestsInProviderState`, `account-rest.test.cjs`). - A group member let go for no first content within the group's `FirstToken` (`hw.slow` in [`gateway.go`](../../internal/gateway/gateway.go), 504 "no first token in Ns", `failSlow`) doesn't rest the first time: a long prompt is slow to start anywhere. Slow again on the same account's model with no answer from it in between, and within `slowForget` (30 minutes) of its last slow start, that model rests on that account (`restSlow` in [`routing.go`](../../internal/gateway/routing.go), keyed by `restID`, `Rest.Model` set): a minute from the second time (`slowRests`), doubling each time after, up to the provider's rest cap (`RestCapOr(longestRetry)`), and never for a provider whose cap is off. Its answer clears the count (`servedCandidate`). A request its client cancelled counts nothing, as the cancel is read before `hw.slow`. Before it, each new request asked the stalled member first again and waited out the whole `FirstToken` (小八 on Discord: a WorkBuddy account's kimi-k3-1 and glm-5.3 stalled 58 times on the vendor's per-model token limit, 15 times in 17 minutes in one session). The same model on another account and another model on the same account are asked as before (`TestSlowStartsRestTheModelOnItsAccount`, `TestCanceledSlowStartRestsNothing`; the Routing page's story, `routing-went-on.test.cjs`). diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 7d3230e47..0672e7aea 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -334,6 +334,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 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; `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 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 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. - A restart to update can run two magpies for up to the old one's drain ([GUI shell](gui-shell.md#a-restart-to-update-hands-the-gateway-over)), each @@ -386,6 +387,8 @@ go test -tags nogui . -run TestAccountCapCmd go test -tags nogui ./internal/provider ./internal/gateway ./internal/cli -run 'TestSetAccountWeight|TestAccountWeight' node --test internal/gui/tests/account-weight.test.cjs node --test internal/gui/tests/account-cap.test.cjs internal/gui/tests/window-cap.test.cjs +go test -tags nogui ./internal/provider ./internal/usage ./internal/gateway ./internal/cli -run 'TestKeySpendCap|TestSpendCap|TestParseSpendCap|TestKeySpent' +node --test internal/gui/tests/key-spend-cap.test.cjs go test -tags nogui ./internal/provider -run 'TestRemoteMagpie' go test -tags nogui ./internal/provider -run 'TestVolc|TestQianfan|TestBedrock|TestMantleBase|TestAddCopy|TestBackupBalanceToken' go test -tags nogui ./internal/gui -run TestProviderSaveKeepsVolcengineSecret diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index 31a5c3734..22a6fb056 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -87,6 +87,10 @@ const providerUsage = `usage: magpie provider account-concurrency [account|key [n|off|default]] how many requests one account or key has out at once, over every model, routing group and agent: its own, off for none, default for the provider's + magpie provider spend-cap [key [usd [day|month|total]|off]] + how much an API key may spend, in USD as the Usage page prices its calls, + a day (the default), a month or in all from now: at it, routing takes the + key for used up and goes on to the other keys and the fallbacks magpie provider account-weight [account [n|default]] a subscription account's share of the requests with routing=weight: one weighing 3 takes three for each one weighing 1 takes (default 1) @@ -631,6 +635,8 @@ func providerCmd(args []string) error { return poolCmd(rest) case "account-concurrency", "account-limit": return accountConcurrencyCmd(rest) + case "spend-cap", "spend-caps": + return spendCapCmd(rest) case "account-weight", "account-weights": return accountWeightCmd(rest) case "queue": diff --git a/internal/cli/spend_cap_cli.go b/internal/cli/spend_cap_cli.go new file mode 100644 index 000000000..b09488813 --- /dev/null +++ b/internal/cli/spend_cap_cli.go @@ -0,0 +1,95 @@ +package cli + +import ( + "fmt" + "time" + + "github.com/yetone/magpie/internal/provider" + stats "github.com/yetone/magpie/internal/usage" +) + +const spendCapUsage = "magpie provider spend-cap [key [usd [day|month|total]|off]]" + +// spendCapCmd shows, or sets, how much a provider's API keys may spend +// (sparkling_lemur_62868 on Discord): in USD as the Usage page prices +// their calls, a day, a month or in all. At it, routing takes the key for +// used up (provider/key_spend.go). +func spendCapCmd(rest []string) error { + if len(rest) < 1 || len(rest) > 4 { + return fmt.Errorf("%s", spendCapUsage) + } + p, err := provider.Find(rest[0]) + if err != nil { + return err + } + if p.Account != nil { + return fmt.Errorf("%s is a subscription: a spend cap is for an API key (an account's cap is a share of its usage windows, magpie provider account-cap)", p.Name) + } + if len(rest) > 2 { + period := "" + if len(rest) > 3 { + period = rest[3] + } + c, err := provider.ParseSpendCap(rest[2], period) + if err != nil { + return err + } + if err := provider.SetKeySpendCap(p.ID, rest[1], c); err != nil { + return err + } + if p, err = provider.Find(p.ID); err != nil { + return err + } + } + keys := p.KeyList() + if len(rest) > 1 { + ref, ok := p.AccountRefOf(rest[1]) + if !ok { + return fmt.Errorf("%s has no key %q", p.Name, rest[1]) + } + for _, k := range keys { + if k.ID == ref { + keys = []provider.KeyInfo{k} + break + } + } + } + if len(keys) == 0 { + fmt.Println(muted.Render(p.Name + " has no key")) + return nil + } + now := time.Now() + for _, k := range keys { + name := k.Masked + " " + muted.Render(k.ID) + if k.Name != "" { + name = k.Name + " " + muted.Render(k.Masked+" · "+k.ID) + } + sc, ok := p.KeySpendCap(k.ID) + if !ok { + fmt.Println(name, muted.Render("· no spend cap")) + continue + } + start, reset := sc.Window(now) + spent := stats.KeySpent(k.ID, start) + line := fmt.Sprintf("%s · $%.2f of $%.2f %s", name, spent, sc.USD, spendCapPeriod(sc, start)) + switch { + case spent >= sc.USD && reset.IsZero(): + line += " · at its cap" + case spent >= sc.USD: + line += " · at its cap until " + reset.Format("Jan 2 15:04") + } + fmt.Println(line) + } + return nil +} + +// spendCapPeriod is the period of sc as a line tells it. +func spendCapPeriod(sc provider.SpendCap, start time.Time) string { + switch sc.Period { + case provider.SpendMonth: + return "this month" + case provider.SpendTotal: + return "in all since " + start.Local().Format("Jan 2 2006") + } + return "today" +} diff --git a/internal/cli/spend_cap_cli_test.go b/internal/cli/spend_cap_cli_test.go new file mode 100644 index 000000000..a214e6ec0 --- /dev/null +++ b/internal/cli/spend_cap_cli_test.go @@ -0,0 +1,63 @@ +package cli + +import ( + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// magpie provider spend-cap gives a key a spend cap in USD (by its name or +// id), a day by default, a month or in all; off takes it off. With no +// amount it lists the keys' caps. A key the provider hasn't, an amount or +// a period it doesn't know, and --help as a value are refused, and +// nothing is written for them. +func TestSpendCapCmd(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + t.Setenv("DSH_HOME", "") + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k1", KeyName: "Team", Chat: "http://127.0.0.1:1/v1"}); err != nil { + t.Fatal(err) + } + capOf := func() (provider.SpendCap, bool) { + t.Helper() + p, err := provider.Find("relay") + if err != nil { + t.Fatal(err) + } + return p.KeySpendCap(provider.KeyID("k1")) + } + if err := providerCmd([]string{"provider", "spend-cap", "relay", "Team", "20"}); err != nil { + t.Fatal(err) + } + if c, ok := capOf(); !ok || c.USD != 20 || c.Period != provider.SpendDay { + t.Fatalf("a day's cap: %+v %v", c, ok) + } + if err := providerCmd([]string{"provider", "spend-cap", "relay", provider.KeyID("k1"), "$300", "month"}); err != nil { + t.Fatal(err) + } + if c, ok := capOf(); !ok || c.USD != 300 || c.Period != provider.SpendMonth { + t.Fatalf("a month's cap: %+v %v", c, ok) + } + for _, args := range [][]string{{"relay"}, {"relay", "Team"}} { + if err := providerCmd(append([]string{"provider", "spend-cap"}, args...)); err != nil { + t.Fatal(args, err) + } + } + for _, bad := range [][]string{{"relay", "Team", "--help"}, {"relay", "Team", "lots"}, {"relay", "Team", "5", "week"}, {"relay", "Team", "0"}, {"relay", "nokey", "5"}, {"relay", "Team", "5", "day", "extra"}} { + if err := providerCmd(append([]string{"provider", "spend-cap"}, bad...)); err == nil { + t.Fatalf("%v taken", bad) + } + } + if c, _ := capOf(); c.USD != 300 || c.Period != provider.SpendMonth { + t.Fatalf("a refused value changed the cap: %+v", c) + } + if err := providerCmd([]string{"provider", "spend-cap", "relay", "Team", "off"}); err != nil { + t.Fatal(err) + } + if _, ok := capOf(); ok { + t.Fatal("off left the cap") + } +} diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index d9b52e644..639324457 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -22,11 +22,13 @@ import ( "fmt" "io" "log" + "math" "net/http" "net/url" "regexp" "slices" "sort" + "strconv" "strings" "sync" "time" @@ -35,6 +37,7 @@ import ( "github.com/yetone/magpie/internal/plugin" "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/usage" ) const fallbackCooldown = time.Minute @@ -101,6 +104,32 @@ type capHold struct { // unread: held by a careful provider as its usage can't be told, why // (carefulDoubt), cap then the account's own unread string + // spend: a key held at the spend cap set on it (provider.SpendCap), + // cap then 100 and used the share of it spent + spend *spendHold +} + +// spendHold is how a key is held at its spend cap: the cap, what magpie +// counted spent in its period, and the period (its start for one in all). +type spendHold struct { + usd, spent float64 + period string + since time.Time +} + +// spendHeld is how the key k of p is held at the spend cap set on it at +// now, nil when it has none or is below it. +func spendHeld(p provider.Provider, k provider.KeyAccount, now time.Time) *capHold { + sc, ok := p.KeySpendCap(provider.KeyID(k.Key)) + if !ok { + return nil + } + start, reset := sc.Window(now) + spent := usage.KeySpent(provider.KeyID(k.Key), start) + if spent < sc.USD { + return nil + } + return &capHold{cap: 100, used: 100 * spent / sc.USD, back: reset, spend: &spendHold{usd: sc.USD, spent: spent, period: sc.Period, since: start}} } // label names a candidate in a call's record: the provider, and the key @@ -395,6 +424,13 @@ func perKeyEvery(p provider.Provider, model string, from provider.Protocol) (out barred = append(barred, candidate{p: q, model: model, rest: rest, rank: i}) continue } + // a key at the spend cap set on it is used up for routing until + // the period renews: never tried, so the other keys and the + // fallbacks take the request (provider/key_spend.go) + if h := spendHeld(p, k, time.Now()); h != nil { + barred = append(barred, candidate{p: q, model: model, rest: rest, rank: i, capped: h}) + continue + } if !planHas(k) { planless = append(planless, candidate{p: q, model: model, rest: rest, rank: i}) continue @@ -921,7 +957,25 @@ func capHeld(p, acct provider.Provider, model string, now time.Time) *capHold { // would when all are used up; the soonest one is back is the wait. func cappedError(model string, ws []Weighed, now time.Time) (string, time.Time) { held, soonest := heldReasons(ws, now) + if spendOnly(ws) { + again := "once that period renews" + if soonest.IsZero() { + again = "once its cap is raised" + } + return fmt.Sprintf("spend cap reached: every key that serves %q has spent the spend cap set on it in magpie — %s. magpie uses it again %s; %s", model, strings.Join(held, "; "), again, spendAdvice), soonest + } capped, noCredits := heldBy(ws) + if slices.ContainsFunc(ws, func(w Weighed) bool { return w.SpendCap > 0 }) { + msg, _ := cappedError(model, slices.DeleteFunc(slices.Clone(ws), func(w Weighed) bool { return w.SpendCap > 0 }), now) + var spends []string + for _, w := range ws { + if w.SpendCap > 0 { + r, _ := heldReasons([]Weighed{w}, now) + spends = append(spends, r...) + } + } + return msg + "; and " + strings.Join(spends, "; ") + " (to use it, " + spendAdvice + ")", soonest + } if unread(ws) { return fmt.Sprintf("usage cap reached: every account that serves %q is held at the usage cap set on it in magpie, or held as its usage can't be told right now — %s. magpie reads it again at the next request and uses it once it is under its cap; %s, or turn off Check usage near the cap (Providers → the provider's accounts, or magpie provider pool --careful off)", model, strings.Join(held, "; "), heldAdvice(capped, noCredits)), soonest } @@ -954,6 +1008,9 @@ func heldReasons(ws []Weighed, now time.Time) ([]string, time.Time) { continue } s := fmt.Sprintf("%s (%s) is at %.0f%% of a usage window, past its %d%% cap", w.Name, w.Who, w.Used, w.Capped) + if w.SpendCap > 0 { + s = fmt.Sprintf("%s (%s) has spent %s of the %s spend cap set on it %s, as magpie's usage prices its calls", w.Name, w.Who, usd(w.Spent), usd(w.SpendCap), spendPeriod(w.SpendPeriod, w.SpendSince, now)) + } if w.NoCredits { s = fmt.Sprintf("%s (%s) has used up a usage window and is set not to spend its credits", w.Name, w.Who) } @@ -971,6 +1028,44 @@ func heldReasons(ws []Weighed, now time.Time) ([]string, time.Time) { return held, soonest } +// spendAdvice is how to go on past a key's spend cap. +const spendAdvice = "raise or lift the key's spend cap in magpie (Providers → the key's spend cap, or magpie provider spend-cap), or add a fallback" + +// spendOnly says whether every one of ws held is held at a key's spend +// cap. +func spendOnly(ws []Weighed) bool { + n := 0 + for _, w := range ws { + if w.Capped == 0 { + continue + } + if w.SpendCap == 0 { + return false + } + n++ + } + return n > 0 +} + +// usd is an amount in dollars as a spend cap is told: cents kept. +func usd(v float64) string { + return "$" + strconv.FormatFloat(math.Floor(v*100+0.5)/100, 'f', 2, 64) +} + +// spendPeriod is the period a spend cap counts over, as a reason tells it. +func spendPeriod(period string, since *time.Time, now time.Time) string { + switch period { + case provider.SpendMonth: + return "for this month" + case provider.SpendTotal: + if since == nil || since.IsZero() { + return "in all" + } + return "in all since " + since.In(now.Location()).Format("Jan 2 2006") + } + return "for today" +} + // heldAdvice is how to go on now past what heldBy says holds. func heldAdvice(capped, noCredits bool) string { switch { @@ -1008,6 +1103,9 @@ func checkpointCappedRecord(ws []Weighed) string { // cappedRecord is the call's record of the same refusal as cappedError, // told apart the same way. func cappedRecord(ws []Weighed) string { + if spendOnly(ws) { + return "every key at its spend cap" + } if unread(ws) { return "every account at its usage cap or its usage unread" } @@ -1051,7 +1149,7 @@ func creditsHeld(cs []candidate) []candidate { func capHeldOnly(cs []candidate) []candidate { var out []candidate for _, c := range cs { - if c.capped != nil && !c.capped.noCredits { + if c.capped != nil && !c.capped.noCredits && c.capped.spend == nil { out = append(out, c) } } @@ -1067,6 +1165,12 @@ func barredOf(cs []candidate, q provider.Provider, fallback bool, from provider. w.Unlisted, w.Via = true, via if h := c.capped; h != nil { w.Capped, w.Used, w.NoCredits, w.Unread = h.cap, h.used, h.noCredits, h.unread + if sp := h.spend; sp != nil { + w.SpendCap, w.Spent, w.SpendPeriod = sp.usd, sp.spent, sp.period + if sp.period == provider.SpendTotal { + w.SpendSince = &sp.since + } + } if !h.back.IsZero() { w.CapBack = &h.back } diff --git a/internal/gateway/key_spend_test.go b/internal/gateway/key_spend_test.go new file mode 100644 index 000000000..23eccf5e2 --- /dev/null +++ b/internal/gateway/key_spend_test.go @@ -0,0 +1,118 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/usage" +) + +// sparkling_lemur_62868 on Discord: a team's OpenAI key with credits that +// other services spend from too, and magpie to stop at a share of them. A +// key that has spent its spend cap, as the Usage page prices magpie's calls +// on it, is passed over: the provider's next key serves the request, then +// its fallback; with neither, the request is answered 429 with which key is +// at which cap and how to go on. The key never reaches the upstream. A +// spend cap is no usage cap: Stop at the caps doesn't hold the fallbacks +// back from it. +func TestKeySpendCapPassesTheKeyOver(t *testing.T) { + fresh(t) + s := settings.Load() + s.ModelPrices = map[string]settings.ModelPrice{ + "plan/m1": {Input: new(1.0), Output: new(1.0), CacheRead: new(0.0), CacheWrite: new(0.0)}, + } + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + var mu sync.Mutex + var keys []string + serve := func(name string) *httptest.Server { + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + keys = append(keys, name+" "+strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")) + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}`) + })) + t.Cleanup(up.Close) + return up + } + planUp, spareUp := serve("plan"), serve("spare") + since := time.Now().Add(-time.Hour).UTC().Truncate(time.Second) + plan := provider.Provider{ID: "plan", Name: "Plan", Key: "sk-team", KeyName: "Team", Keys: []provider.KeyAccount{{Name: "Spare", Key: "sk-spare"}}, + Chat: planUp.URL + "/v1", Models: []string{"m1"}, Routing: provider.Ordered, + KeySpendCaps: map[string]provider.SpendCap{provider.KeyID("sk-team"): {USD: 5, Period: provider.SpendTotal, Since: since}}} + if err := provider.Save(plan); err != nil { + t.Fatal(err) + } + // $6 spent on Team since its cap was set, $1 before it + usage.Append(usage.Record{Time: time.Now().Add(-30 * time.Minute), Agent: "codex", Provider: "plan", Model: "m1", ProviderKeyID: provider.KeyID("sk-team"), Input: 6e6, Status: 200}) + usage.Append(usage.Record{Time: since.Add(-time.Hour), Agent: "codex", Provider: "plan", Model: "m1", ProviderKeyID: provider.KeyID("sk-spare"), Input: 1e6, Status: 200}) + h := New().Handler() + post := func() (int, string, []string) { + t.Helper() + mu.Lock() + keys = nil + mu.Unlock() + w := httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(chatReq))) + mu.Lock() + defer mu.Unlock() + return w.Code, w.Body.String(), keys + } + // Team, first, is at its cap: Spare serves + if code, body, got := post(); code != 200 || len(got) != 1 || got[0] != "plan sk-spare" { + t.Fatalf("Team at its cap: %d %s, upstream got %v", code, body, got) + } + // raised past what it spent, Team serves again + if err := provider.SetKeySpendCap("plan", "Team", &provider.SpendCap{USD: 50, Period: provider.SpendTotal}); err != nil { + t.Fatal(err) + } + if code, body, got := post(); code != 200 || len(got) != 1 || got[0] != "plan sk-team" { + t.Fatalf("Team under its raised cap: %d %s, upstream got %v", code, body, got) + } + // both at their caps, with no fallback: a 429 says which and why + if err := provider.SetKeySpendCap("plan", "Team", &provider.SpendCap{USD: 5, Period: provider.SpendTotal}); err != nil { + t.Fatal(err) + } + if err := provider.SetKeySpendCap("plan", "Spare", &provider.SpendCap{USD: 0.000001, Period: provider.SpendDay}); err != nil { + t.Fatal(err) + } + code, body, got := post() + var e struct { + Error struct{ Message, Type string } + } + json.Unmarshal([]byte(body), &e) + if code != 429 || len(got) != 0 || !strings.Contains(e.Error.Message, "spend cap reached") || + !strings.Contains(e.Error.Message, "Team") || !strings.Contains(e.Error.Message, "$6.00 of the $5.00 spend cap") || + !strings.Contains(e.Error.Message, "Spare") || !strings.Contains(e.Error.Message, "for today") || !strings.Contains(e.Error.Message, "spend-cap") { + t.Fatalf("both at their caps: %d %s, upstream got %v", code, body, got) + } + // with a fallback, it serves + p, _ := provider.Find("plan") + p.Fallback = []string{"spare/m2"} + if err := provider.Save(*p); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "spare", Name: "Spare plan", Key: "sk-other", Chat: spareUp.URL + "/v1", Models: []string{"m2"}}); err != nil { + t.Fatal(err) + } + if code, body, got := post(); code != 200 || len(got) != 1 || got[0] != "spare sk-other" { + t.Fatalf("both at their caps, with a fallback: %d %s, upstream got %v", code, body, got) + } + // a spend cap is not a usage cap: Stop at the caps doesn't end there + if err := provider.SetCapStop("plan", true); err != nil { + t.Fatal(err) + } + if code, body, got := post(); code != 200 || len(got) != 1 || got[0] != "spare sk-other" { + t.Fatalf("both at their caps, Stop at the caps on: %d %s, upstream got %v", code, body, got) + } +} diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index ce319e8c4..967acaa40 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -344,6 +344,13 @@ type Weighed struct { // told, why: not read yet, the read failed, or too old near its cap // (provider.Provider.CapCareful) Unread string `json:"unread,omitempty"` + // SpendCap: held (Capped, at 100) as the key has spent the spend cap + // set on it, in USD: Spent of it over SpendPeriod (day, month or + // total, counted from SpendSince) + SpendCap float64 `json:"spendCap,omitempty"` + Spent float64 `json:"spent,omitempty"` + SpendPeriod string `json:"spendPeriod,omitempty"` + SpendSince *time.Time `json:"spendSince,omitempty"` // Credits: a Codex account that goes on past its allowance on its // credits, and is let spend them: all but used up, it still answers, // and goes before those used up with nothing to go on with diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index dc7ce1779..edc7afa58 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2852,6 +2852,15 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .acc .alane.queued { color: var(--amber); } .acc .alane:hover, .acc .alane.open { color: var(--fg); background: var(--pill-hover); } .acc .alane-in { width: 64px; } +/* a key's spend cap (sparkling_lemur_62868 on Discord): as the limit + pill, and marked when the key is held at it */ +.acc .aspend { flex: none; display: inline-flex; align-items: center; height: 20px; padding: 0 7px; font: inherit; font-size: 11px; color: var(--muted); border: 0; border-radius: 5px; background: none; box-shadow: inset 0 0 0 1px var(--line); white-space: nowrap; cursor: default; opacity: 0; transition: opacity .15s, background .12s, color .12s; font-variant-numeric: tabular-nums; } +.acc:hover .aspend, .acc.held .aspend, .acc .aspend.open, .acc .aspend.set { opacity: 1; } +.acc .aspend:focus-visible { opacity: 1; } +.acc .aspend.set { color: var(--fg); background: var(--pill-hover); box-shadow: none; } +.acc .aspend.at-cap { color: var(--accent); background: var(--accent-soft); font-weight: 500; } +.acc .aspend:hover, .acc .aspend.open { color: var(--fg); background: var(--pill-hover); } +.acc .aspend-in { width: 72px; } .acc .acap-held { color: var(--fg); } /* held for magpie's requests, not the agent signed in to it: a warning */ .acc .acap-held.acap-direct { color: var(--amber); } @@ -2912,9 +2921,9 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .accts.keys .acc[data-account-id] { flex-wrap: wrap; row-gap: 3px; } .accts.keys .acc > .n { flex: 1000 1 4.5em; max-width: max-content; min-width: 0; } .accts.keys .acc .plan { flex: 1000 1 3em; max-width: max-content; min-width: 0; overflow: hidden; text-overflow: ellipsis; } -.accts.keys .acc > :is(.amodels, .proto, .alane), .accts.keys .key-acts > .text.quiet { flex-shrink: 0; white-space: nowrap; } -.accts.keys .acc > :is(.amodels:not(.set), .proto:not(.set), .alane:not(.set)), .accts.keys .key-acts > .text.quiet { overflow: hidden; } -.accts.keys .acc:not(:hover):not(.held) > :is(.amodels:not(.set), .proto:not(.set), .alane:not(.set)):not(.open):not(:focus-visible), +.accts.keys .acc > :is(.amodels, .proto, .alane, .aspend), .accts.keys .key-acts > .text.quiet { flex-shrink: 0; white-space: nowrap; } +.accts.keys .acc > :is(.amodels:not(.set), .proto:not(.set), .alane:not(.set), .aspend:not(.set)), .accts.keys .key-acts > .text.quiet { overflow: hidden; } +.accts.keys .acc:not(:hover):not(.held) > :is(.amodels:not(.set), .proto:not(.set), .alane:not(.set), .aspend:not(.set)):not(.open):not(:focus-visible), .accts.keys .acc:not(:hover):not(.held) .key-acts > .text.quiet:not(:focus-visible) { min-width: 0; max-width: 0; padding-left: 0; padding-right: 0; box-shadow: none; } /* and hidden, the gap beside it too */ .accts.keys .acc:not(:hover):not(.held) > :is(.amodels:not(.set), .proto:not(.set)):not(.open):not(:focus-visible) { margin-left: -9px; } @@ -2922,17 +2931,17 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } /* the limit pill unset on a key's row is quiet text, as the row's other hover-only controls: no padding to keep, and hidden it takes back the gap before it too (#892) */ -.accts.keys .acc > .alane:not(.set):not(.open):not(:focus-visible) { padding: 0; box-shadow: none; background: none; } -.accts.keys .acc:not(:hover):not(.held) > .alane:not(.set):not(.open):not(:focus-visible) { margin-left: -9px; } +.accts.keys .acc > :is(.alane, .aspend):not(.set):not(.open):not(:focus-visible) { padding: 0; box-shadow: none; background: none; } +.accts.keys .acc:not(:hover):not(.held) > :is(.alane, .aspend):not(.set):not(.open):not(:focus-visible) { margin-left: -9px; } /* Safari before 15.4 has no :focus-visible and drops the rules above whole: there a focused control stays out on :focus instead */ @supports not selector(:focus-visible) { - .accts.keys .acc:not(:hover):not(.held) > :is(.amodels:not(.set), .proto:not(.set), .alane:not(.set)):not(.open):not(:focus), + .accts.keys .acc:not(:hover):not(.held) > :is(.amodels:not(.set), .proto:not(.set), .alane:not(.set), .aspend:not(.set)):not(.open):not(:focus), .accts.keys .acc:not(:hover):not(.held) .key-acts > .text.quiet:not(:focus) { min-width: 0; max-width: 0; padding-left: 0; padding-right: 0; box-shadow: none; } .accts.keys .acc:not(:hover):not(.held) > :is(.amodels:not(.set), .proto:not(.set)):not(.open):not(:focus) { margin-left: -9px; } .accts.keys .acc:not(:hover):not(.held) .key-acts > .text.quiet:not(:focus) { margin-right: -9px; } - .accts.keys .acc > .alane:not(.set):not(.open):not(:focus) { padding: 0; box-shadow: none; background: none; } - .accts.keys .acc:not(:hover):not(.held) > .alane:not(.set):not(.open):not(:focus) { margin-left: -9px; } + .accts.keys .acc > :is(.alane, .aspend):not(.set):not(.open):not(:focus) { padding: 0; box-shadow: none; background: none; } + .accts.keys .acc:not(:hover):not(.held) > :is(.alane, .aspend):not(.set):not(.open):not(:focus) { margin-left: -9px; } } .accts.keys .acc > .key-acts { flex: none; display: flex; align-items: center; gap: 9px; margin-left: auto; } .accts.keys .acc .using, .accts.keys .key-acts > .text:not(.quiet) { flex: none; white-space: nowrap; } @@ -4235,10 +4244,10 @@ body.panel .modal { padding: 16px 12px; } body.web .acc > .grow + * { margin-left: auto; } /* nothing hovers on a phone: what a row shows on hover is shown, and a key's row gives it back the room it folds away till a hover (#841) */ - body.web .acc :is(.text.quiet, .proto, .amodels, .alane) { opacity: 1; } + body.web .acc :is(.text.quiet, .proto, .amodels, .alane, .aspend) { opacity: 1; } body.web .acc .acc-more { opacity: 1; } - body.web .accts.keys .acc > :is(.amodels, .proto, .alane), body.web .accts.keys .key-acts > .text.quiet { max-width: none !important; padding: 0 7px !important; flex-shrink: 0 !important; } - body.web .accts.keys .acc > :is(.amodels, .proto, .alane):not(.set) { margin-left: 0 !important; } + body.web .accts.keys .acc > :is(.amodels, .proto, .alane, .aspend), body.web .accts.keys .key-acts > .text.quiet { max-width: none !important; padding: 0 7px !important; flex-shrink: 0 !important; } + body.web .accts.keys .acc > :is(.amodels, .proto, .alane, .aspend):not(.set) { margin-left: 0 !important; } body.web .accts.keys .key-acts > .text.quiet { margin-right: 0 !important; } body.web #gatewayKeys .acc > .key-quotas { max-width: none !important; padding: 0 7px !important; margin-left: 0 !important; flex-shrink: 0; } body.web #gatewayKeys .acc > .key-quotas:not(.set) { box-shadow: inset 0 0 0 1px var(--line) !important; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index e3016ddd1..b72ab5edd 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -14095,6 +14095,11 @@ function laneLimitPill(p, ref, who, name) { }; return pill; } +// a key's spend cap, in keyspend.js +function keySpend(row, p, k) { + if (window.keySpendFill) return keySpendFill(row, p, k); + import("./keyspend.js").then(() => keySpendFill(row, p, k), () => {}); +} // refreshLanes rewrites the pills in place, so nothing moves; with none // in sight its tick stops (#3185) until one is drawn async function refreshLanes() { @@ -14573,6 +14578,7 @@ function renderKeyAccounts(p) { row.append(acts); if (restLine) row.append(restLine); if (amBox) row.append(amBox), row.classList.add("with-am"); + keySpend(row, p, k); list.append(row); } list.append(...folds.after); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index d94cd401c..138bf35aa 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4,6 +4,32 @@ // works. {name} slots are filled by t(str, vars). const I18N = { zh: { + "No spend cap": "无消费上限", + "{spent} of {cap} today": "今日 {spent} / {cap}", + "{spent} of {cap} this month": "本月 {spent} / {cap}", + "{spent} of {cap} in all": "累计 {spent} / {cap}", + "a day": "每天", + "a month": "每月", + "in all": "累计", + "Stops at {cap} {period}, counted at the prices the Usage page shows for the calls magpie sends on this key. Past it, magpie goes on to the provider's other keys and its fallbacks. Requests under way still finish, so it can go a little past the cap, and a model with no known price counts nothing. Click to change": "{period}花到 {cap} 即停用,按「用量」页对 magpie 经此密钥发出的请求所标的价格计算。超过后,magpie 改用该提供商的其他密钥和备用提供商。进行中的请求仍会完成,所以可能略超上限;价格未知的模型不计费用。点击修改", + "No spend cap: magpie sends this key requests whatever they cost. Click to set how much it may spend, a day, a month or in all; past it, magpie goes on to the provider's other keys and its fallbacks": "无消费上限:无论花费多少,magpie 都会向此密钥发送请求。点击设置每天、每月或累计可花多少;超过后,magpie 改用该提供商的其他密钥和备用提供商", + "{who} has no spend cap": "{who} 已取消消费上限", + "{who} stops at {usd} a month": "{who} 每月花到 {usd} 即停用", + "{who} stops at {usd} in all": "{who} 累计花到 {usd} 即停用", + "{who} stops at {usd} a day": "{who} 每天花到 {usd} 即停用", + "Spend as much as the key has": "密钥余额有多少就用多少", + "Per day…": "每天…", + "Counts again each day": "每天重新计算", + "Per month…": "每月…", + "Counts again each month": "每月重新计算", + "In all…": "累计…", + "Counted from when it is set": "从设置时开始计算", + "Spend cap, in USD": "消费上限(美元)", + "A spend cap is an amount in USD above 0, up to 1,000,000": "消费上限是大于 0、不超过 1,000,000 的美元金额", + "Spend cap": "消费上限", + "At its spend cap · back {in}": "已达消费上限 · {in}恢复", + "At its spend cap · until it is raised": "已达消费上限 · 提高上限前不再使用", + "This key has spent its cap, so the gateway passes it over and tries the next key or a fallback. With none, requests are refused with a spend-cap error": "此密钥已花到上限,网关会跳过它,改用下一个密钥或备用提供商。都没有时,请求会以消费上限错误被拒绝", "Scroll to top": "回到顶部", "Scroll to bottom": "回到底部", "Claude Code runs as": "Claude Code 运行方式", @@ -4500,6 +4526,32 @@ const I18N = { "This report is no longer kept: magpie keeps the last 5.": "这份报告已经不在了:magpie 只保留最近 5 份。", }, "zh-TW": { + "No spend cap": "無消費上限", + "{spent} of {cap} today": "今日 {spent} / {cap}", + "{spent} of {cap} this month": "本月 {spent} / {cap}", + "{spent} of {cap} in all": "累計 {spent} / {cap}", + "a day": "每天", + "a month": "每月", + "in all": "累計", + "Stops at {cap} {period}, counted at the prices the Usage page shows for the calls magpie sends on this key. Past it, magpie goes on to the provider's other keys and its fallbacks. Requests under way still finish, so it can go a little past the cap, and a model with no known price counts nothing. Click to change": "{period}花到 {cap} 即停用,按「用量」頁對 magpie 經此金鑰發出的請求所標的價格計算。超過後,magpie 改用該供應商的其他金鑰和備用供應商。進行中的請求仍會完成,所以可能略超上限;價格未知的模型不計費用。點擊修改", + "No spend cap: magpie sends this key requests whatever they cost. Click to set how much it may spend, a day, a month or in all; past it, magpie goes on to the provider's other keys and its fallbacks": "無消費上限:無論花費多少,magpie 都會向此金鑰發送請求。點擊設定每天、每月或累計可花多少;超過後,magpie 改用該供應商的其他金鑰和備用供應商", + "{who} has no spend cap": "{who} 已取消消費上限", + "{who} stops at {usd} a month": "{who} 每月花到 {usd} 即停用", + "{who} stops at {usd} in all": "{who} 累計花到 {usd} 即停用", + "{who} stops at {usd} a day": "{who} 每天花到 {usd} 即停用", + "Spend as much as the key has": "金鑰餘額有多少就用多少", + "Per day…": "每天…", + "Counts again each day": "每天重新計算", + "Per month…": "每月…", + "Counts again each month": "每月重新計算", + "In all…": "累計…", + "Counted from when it is set": "從設定時開始計算", + "Spend cap, in USD": "消費上限(美元)", + "A spend cap is an amount in USD above 0, up to 1,000,000": "消費上限是大於 0、不超過 1,000,000 的美元金額", + "Spend cap": "消費上限", + "At its spend cap · back {in}": "已達消費上限 · {in}恢復", + "At its spend cap · until it is raised": "已達消費上限 · 提高上限前不再使用", + "This key has spent its cap, so the gateway passes it over and tries the next key or a fallback. With none, requests are refused with a spend-cap error": "此金鑰已花到上限,閘道會跳過它,改用下一個金鑰或備用供應商。都沒有時,請求會以消費上限錯誤被拒絕", "Scroll to top": "回到頂部", "Scroll to bottom": "回到底部", "Claude Code runs as": "Claude Code 執行方式", @@ -8981,6 +9033,32 @@ const I18N = { "This report is no longer kept: magpie keeps the last 5.": "這份報告已經不在了:magpie 只保留最近 5 份。", }, ja: { + "No spend cap": "支出上限なし", + "{spent} of {cap} today": "今日 {spent} / {cap}", + "{spent} of {cap} this month": "今月 {spent} / {cap}", + "{spent} of {cap} in all": "累計 {spent} / {cap}", + "a day": "1日あたり", + "a month": "1か月あたり", + "in all": "累計", + "Stops at {cap} {period}, counted at the prices the Usage page shows for the calls magpie sends on this key. Past it, magpie goes on to the provider's other keys and its fallbacks. Requests under way still finish, so it can go a little past the cap, and a model with no known price counts nothing. Click to change": "{period} {cap} に達すると止まります。magpie がこのキーで送った呼び出しを「使用量」ページの価格で数えます。超えると、magpie はプロバイダーの他のキーとフォールバックに進みます。進行中のリクエストは最後まで続くため上限を少し超えることがあり、価格が不明なモデルは数えません。クリックして変更", + "No spend cap: magpie sends this key requests whatever they cost. Click to set how much it may spend, a day, a month or in all; past it, magpie goes on to the provider's other keys and its fallbacks": "支出上限なし:費用に関係なく、magpie はこのキーにリクエストを送ります。クリックして 1日・1か月・累計でいくらまで使えるかを設定します。超えると、magpie はプロバイダーの他のキーとフォールバックに進みます", + "{who} has no spend cap": "{who} の支出上限を外しました", + "{who} stops at {usd} a month": "{who} は 1か月 {usd} で止まります", + "{who} stops at {usd} in all": "{who} は累計 {usd} で止まります", + "{who} stops at {usd} a day": "{who} は 1日 {usd} で止まります", + "Spend as much as the key has": "キーにある分だけ使う", + "Per day…": "1日あたり…", + "Counts again each day": "毎日数え直す", + "Per month…": "1か月あたり…", + "Counts again each month": "毎月数え直す", + "In all…": "累計…", + "Counted from when it is set": "設定した時点から数える", + "Spend cap, in USD": "支出上限(USD)", + "A spend cap is an amount in USD above 0, up to 1,000,000": "支出上限は 0 より大きく 1,000,000 以下の USD 金額です", + "Spend cap": "支出上限", + "At its spend cap · back {in}": "支出上限に到達 · {in}に復帰", + "At its spend cap · until it is raised": "支出上限に到達 · 上限を上げるまで使いません", + "This key has spent its cap, so the gateway passes it over and tries the next key or a fallback. With none, requests are refused with a spend-cap error": "このキーは上限まで使ったため、ゲートウェイはこれを飛ばして次のキーかフォールバックを試します。どちらもなければ、リクエストは支出上限エラーで拒否されます", "Scroll to top": "一番上へ", "Scroll to bottom": "一番下へ", "Claude Code runs as": "Claude Code の実行方式", @@ -13464,6 +13542,32 @@ const I18N = { "This report is no longer kept: magpie keeps the last 5.": "このレポートはもう残っていません。magpie は最新の 5 件だけを保存します。", }, de: { + "No spend cap": "Kein Ausgabenlimit", + "{spent} of {cap} today": "Heute {spent} von {cap}", + "{spent} of {cap} this month": "Diesen Monat {spent} von {cap}", + "{spent} of {cap} in all": "Insgesamt {spent} von {cap}", + "a day": "pro Tag", + "a month": "pro Monat", + "in all": "insgesamt", + "Stops at {cap} {period}, counted at the prices the Usage page shows for the calls magpie sends on this key. Past it, magpie goes on to the provider's other keys and its fallbacks. Requests under way still finish, so it can go a little past the cap, and a model with no known price counts nothing. Click to change": "Stoppt bei {cap} {period}, gezählt zu den Preisen, die die Nutzungsseite für die Aufrufe zeigt, die magpie mit diesem Schlüssel sendet. Darüber nutzt magpie die anderen Schlüssel des Anbieters und seine Fallbacks. Laufende Anfragen werden noch beendet, daher kann es etwas über das Limit gehen, und ein Modell ohne bekannten Preis zählt nichts. Klicken zum Ändern", + "No spend cap: magpie sends this key requests whatever they cost. Click to set how much it may spend, a day, a month or in all; past it, magpie goes on to the provider's other keys and its fallbacks": "Kein Ausgabenlimit: magpie sendet diesem Schlüssel Anfragen, was sie auch kosten. Klicken, um festzulegen, wie viel er pro Tag, pro Monat oder insgesamt ausgeben darf; darüber nutzt magpie die anderen Schlüssel des Anbieters und seine Fallbacks", + "{who} has no spend cap": "{who} hat kein Ausgabenlimit", + "{who} stops at {usd} a month": "{who} stoppt bei {usd} pro Monat", + "{who} stops at {usd} in all": "{who} stoppt bei insgesamt {usd}", + "{who} stops at {usd} a day": "{who} stoppt bei {usd} pro Tag", + "Spend as much as the key has": "So viel ausgeben, wie der Schlüssel hat", + "Per day…": "Pro Tag…", + "Counts again each day": "Zählt jeden Tag neu", + "Per month…": "Pro Monat…", + "Counts again each month": "Zählt jeden Monat neu", + "In all…": "Insgesamt…", + "Counted from when it is set": "Ab dem Festlegen gezählt", + "Spend cap, in USD": "Ausgabenlimit in USD", + "A spend cap is an amount in USD above 0, up to 1,000,000": "Ein Ausgabenlimit ist ein Betrag in USD über 0, bis 1.000.000", + "Spend cap": "Ausgabenlimit", + "At its spend cap · back {in}": "Am Ausgabenlimit · zurück {in}", + "At its spend cap · until it is raised": "Am Ausgabenlimit · bis es erhöht wird", + "This key has spent its cap, so the gateway passes it over and tries the next key or a fallback. With none, requests are refused with a spend-cap error": "Dieser Schlüssel hat sein Limit ausgegeben, daher überspringt das Gateway ihn und versucht den nächsten Schlüssel oder ein Fallback. Ohne beides werden Anfragen mit einem Ausgabenlimit-Fehler abgelehnt", "Scroll to top": "Nach ganz oben", "Scroll to bottom": "Nach ganz unten", "Claude Code runs as": "Claude Code läuft als", diff --git a/internal/gui/assets/keyspend.js b/internal/gui/assets/keyspend.js new file mode 100644 index 000000000..6443ce107 --- /dev/null +++ b/internal/gui/assets/keyspend.js @@ -0,0 +1,63 @@ +// A key's spend cap (sparkling_lemur_62868 on Discord: a team's OpenAI +// key, with credits other services spend from too): how much magpie may +// spend on it, in USD at the Usage page's prices, a day, a month or in +// all. Past it the gateway passes the key over, as a usage cap holds an +// account (provider/key_spend.go). app.js imports this when the provider +// editor draws a key's row (keySpend), so it weighs nothing on the core. +const usdText = (v) => "$" + (v >= 100 ? v.toFixed(0) : v.toFixed(2)); +const SPEND_PERIODS = { day: "a day", month: "a month", total: "in all" }; +function keySpendPill(p, k) { + const sc = k.spend, name = k.name || k.masked; + const pill = el("button", "aspend" + (sc ? " set" : "") + (sc?.held ? " at-cap" : "")); + pill.type = "button"; + const v = sc && { spent: usdText(sc.spent || 0), cap: usdText(sc.usd) }; + pill.textContent = !sc ? t("No spend cap") : t(sc.period === "month" ? "{spent} of {cap} this month" : sc.period === "total" ? "{spent} of {cap} in all" : "{spent} of {cap} today", v); + pill.title = sc ? t("Stops at {cap} {period}, counted at the prices the Usage page shows for the calls magpie sends on this key. Past it, magpie goes on to the provider's other keys and its fallbacks. Requests under way still finish, so it can go a little past the cap, and a model with no known price counts nothing. Click to change", { cap: v.cap, period: t(SPEND_PERIODS[sc.period] || "a day") }) + : t("No spend cap: magpie sends this key requests whatever they cost. Click to set how much it may spend, a day, a month or in all; past it, magpie goes on to the provider's other keys and its fallbacks"); + pill.setAttribute("aria-haspopup", "menu"); + pill.setAttribute("aria-expanded", "false"); + const set = (usd, period) => accountAction("provider/keyspendcap", { id: p.id, account: k.id, spend: usd ? { usd, period } : null }, + !usd ? t("{who} has no spend cap", { who: name }) + : t(period === "month" ? "{who} stops at {usd} a month" : period === "total" ? "{who} stops at {usd} in all" : "{who} stops at {usd} a day", { who: name, usd: usdText(usd) })); + const amount = (s) => { const n = Number(s.replace(/^\$/, "").trim()); return n > 0 && n <= 1e6 ? n : null; }; + pill.onclick = (e) => { + e.stopPropagation(); + if (pill.classList.contains("open")) return closeProtoMenu(); + const opts = [ + { v: "off", name: "No spend cap", note: "Spend as much as the key has" }, + { v: "day", name: "Per day…", note: "Counts again each day" }, + { v: "month", name: "Per month…", note: "Counts again each month" }, + { v: "total", name: "In all…", note: "Counted from when it is set" }, + ]; + openProtoMenu(pill, opts, sc?.period || "off", (per) => { + if (per === "off") return sc && set(0); + pillNumber(pill, sc ? String(sc.usd) : "", "USD", "aspend-in", t("Spend cap, in USD"), amount, t("A spend cap is an amount in USD above 0, up to 1,000,000"), sc?.period === per ? sc.usd : null, (usd) => set(usd, per)); + }, "Spend cap", "sess-menu"); + }; + return pill; +} +// keySpendLine: a key held at its spend cap, on a line under its row +function keySpendLine(k) { + const sc = k.spend; + if (!sc?.held) return null; + const s = el("span", "key-rest", sc.reset ? t("At its spend cap · back {in}", { in: untilText(new Date(sc.reset)) }) : t("At its spend cap · until it is raised")); + s.title = t("This key has spent its cap, so the gateway passes it over and tries the next key or a fallback. With none, requests are refused with a spend-cap error") + + (sc.reset ? "\n" + resetText(new Date(sc.reset), new Date(sc.reset).toLocaleString(intlLang())) : ""); + const line = el("div", "key-rest-line key-spend-line"); + line.append(s); + return line; +} + +// keySpendFill puts key k's spend cap pill in its row, before the gap, and +// its held line under the row's other lines +window.keySpendFill = function (row, p, k) { + row.querySelector(":scope > .aspend")?.remove(); + row.querySelector(":scope > .key-spend-line")?.remove(); + const pill = keySpendPill(p, k), gap = row.querySelector(":scope > .grow"); + gap ? gap.before(pill) : row.append(pill); + const line = keySpendLine(k); + if (!line) return; + const at = row.querySelector(":scope > .key-rest-line") || row.querySelector(":scope > .key-acts"); + at ? at.after(line) : row.append(line); + row.classList.add("resting"); +}; diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index 2731c0495..249f955d5 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -16,7 +16,7 @@ import ( // raises them and says why in its commit. const ( appScriptBudget = 1_316_874 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16); 1,250,533 with the quota refresh kept through redraws, the core's own since the tray panel draws it too, plus 1.5% (#2397); 1,269,083 with Free first's option in the provider editor's ROUTINGS, which the Routing page reads too, plus 1.5%; 1,272,726 with the Providers page drawing its last list at once (#1519), the core's page, and the Routing trace's account names read without Object.entries (#1481), plus 1.5%; a dialog growing out of the row that opened it and folding back into it, the core's own since every page's dialogs open through it (10-20); Codex's and Claude Code's own settings moved from Settings into the agent's row on the Agents page, the core's own since the tray panel and the window both draw them (10-20); 1,314,432 with Settings › Privacy's record of what was masked (its summary, the records view and the local model's controls), which belongs to Settings, the core's own, plus 1.5%; 1,336,481 with a provider's Names & levels saying Provider in model names is Settings' and opening it there (joe), and Settings' Image recognition saying where a custom provider's model is marked (nexnull), both in the core's own pages, with no room added (10-23); 1,337,633 with Settings › Models › Replies' Intent classifier timeout (#2934, reyoung), Settings' own row, drawn by waitRow, which the Image generation timeout's row now shares, with no room added; 1,337,735 with the provider editor's link naming a partner's page by its own host (siteHost) instead of usemagpie.ai's /go link, the core's own editor, with no room added (10-23); 1,338,084 with Check in now saying what the press came to (claimed +credits, already today, not available yet) where it said "refreshed" (#3326), the check-in row the tray panel draws too, the core's own, with no room added (10-23); 1,338,929 with a new partner's tile keeping a small dot until it is opened, in the add sheet, the core's own, with no room added (10-23); 1,343,324 with the sidebar's open-page row marked by one shape that moves on a spring (navTopGo), the window's own shell, which every page sits beside, with no room added (10-23); 1,343,465 with a dialog kept centred while its content comes in, until it is pressed (holdModal, every page's dialogs), the core's own, with no room added (10-24); 1,317,486 with what masking did moved out to Insights › Masking (plugins/redact), the budget lowered to it (10-24); 1,321,336 with Codex's one subagent model, its card's square saying plainly what each choice does and a row with a name in its sheet, where two squares read alike (the owner), the Agents page's, which the tray panel draws too, the core's own, with no room added (10-24); 1,321,424 with Settings › Models' Image generation MCP server row beside Image recognition's (JonahFu on X), the two drawn by one helper (mcpRow), Settings' own, with no room added (10-25); 1,321,994 with a provider of the user's set never to rest for a limit (zoecats), the provider editor's Advanced row, the core's own editor, with no room added (10-25); 1,322,289 with Settings › Privacy's Keep a key's form under Mask secrets (Charles Cao on X), Settings' own row, with no room added (10-25); 1,322,537 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,323,401 with the tray panel drawing its last allowances at once and asking for them beside the state (#3160, #3134), the tray panel's, the core's own, and the 4 bytes 84c50f032 added, with no room added (10-25); 1,326,105 with many releases' notes merged into one list by kind, each line with its version (the owner), in the update sheet and What's new, with no room added (10-25); 1,321,319 with Settings › Observability moved out to its plugin (plugins/otel/page.js) and its Langfuse setup there (an X user), the budget lowered to it (10-26); a quota card whose window is used but names no reset no longer saying "Not used yet" (windy on Discord) raised it to 1,321,347, and back to 1,321,319 with Settings' model pickers sharing one row helper (modelOpt) where six kept their own copy, no raise (10-26); 1,325,845 with every slow page's skeletons getting magpie's bird hopping bar to bar (skelBird, the owner after the Plugins page's README), one bird for the window over whatever page or dialog is loading, the core's own, with no room added (10-26); 1,310,129 with Settings › Network and sharing's gateway rows (its port, bare ids, local network, allowed addresses, web pages) moved out to the gateway plugin (plugins/gateway/settings.js), the budget lowered to it (10-27); 1,310,269 with Test models naming the first model that failed and its error in the status line, where it said only how many (ysm119 on Discord), the provider editor's, the core's own, with no room added (10-27); 1,310,460 with Settings › About's Website row linking usemagpie.ai (the owner), Settings' own row, with no room added (10-27); 1,309,669 with a pool's Stop at the caps and Check usage near a cap ticks under a provider's accounts (plugins#349), the core's own editor, its account rows' Remove and add rows each drawn by one helper (forgetOf, addRow), with no room added (10-28); 1,311,681 with Install another agent on the Agents page naming the agents Plugins has (More in Plugins) and opening Plugins at its Agents (the owner), the Agents page's, the core's own, with no room added (10-28); 1,311,735 with More in Plugins in sight while Install another agent is folded (the owner), with no room added (10-29); 1,313,704 with a window whose WebKit scrolls under wheels it never tells of (macOS 13) remembered once seen, a scroll at rest then waiting 120ms for a second the same way within 80ms before it is put back, kept for a late wheel to give back (waitsBack), and a load landing under the wheel keeping the reader's way (backAfterLoad, issennknight), the window's own scroll guard, with no room added (10-29); back to 1,311,735 with Settings › Models › Web search's rows (renderSearch, renderSearcher, the search APIs' keys) moved out to the search plugin (plugins/search/settings.js), app.js 1,292,527 after it, not lowered further since what is left plus 1.5% is over it (#4133, 10-29); 1,315,316 with the Agents row of a Claude Code or Codex not connected saying the account it is signed in to and switching it to another (Switch accounts only, the owner on X), in place of the failover line's ChatGPT accounts button, the Agents page's, the core's own, its comments cut down, with no room added (10-30); 1,317,705 with a Claude account added from a setup-token (sfss5362 on X): the sign-in's Use a setup-token instead…, its sheet, and its account row's magpie only, the provider editor's account rows, the core's own editor, its comments cut down, with no room added (10-30); back to 1,315,316 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, loaded when one is asked for (signAsk, 10-30); 1,315,479 with the provider editor lining its Advanced up with its fields (the owner: 高级这个折叠按钮为什么在一个前不着村后不着店的位置?) and a refresh on each of its accounts (在这里也要加上手动刷新用量的按钮), the core's own editor, with no room added (10-31); 1,315,603 with About's Log row, the path of the log the app writes and an Open for its folder (rayem1w on X), in app.js, its comment cut to one line, with no room added (10-31); 1,316,781 with a provider's model listed by an id of the user's (zeewell on X), the provider editor's Names & levels Listed as box beside Same as, the core's own editor, with no room added (10-31); 1,316,874 with a package manager's magpie (the AUR's magpie-bin) naming the command that updates it in Settings' Version row and lighting no Update pill (shuhai on Discord), the core's own update row, which the tray panel reads too, its comments cut to one line, with no room added (10-31); Settings › Sync's Kept on this computer row (hayden4608 on Discord) raised it to 1,317,497, which is no bound; the 1,316,874 it had came back once later trims left app.js at 1,308,363 (10-31) - coreScriptBudget = 1_533_802 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25); 1,529,542 with the limit-rest row (zoecats), with no room added (10-25); 1,529,837 with Keep a key's form (Charles Cao on X), with no room added (10-25); 1,530,050 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,530,631 with a plugin's page growing to its README on the dialog's spring instead of in one jump (the owner), the Plugins page's, in plugins.js, with no room added (10-25); 1,533,445 with the context map counting its tokens on as a live request grows, a tile pointed at keeping its tip, a tool's gathered results saying how many and the small files their folder (the owner, after flohoeller's map on X), in context.js, which the Routing page draws as well as Usage, and the 4 bytes 84c50f032 added to app.js (Settings' Version row) without a raise, with no room added (10-25); 1,534,312 with the tray panel's last allowances drawn at once (#3160, #3134), with no room added (10-25); 1,537,016 with many releases' notes merged into one list by kind (the owner), in app.js, with no room added (10-25); 1,542,244 with a plugin's README loading under magpie's bird bouncing down its lines instead of pulsing bars (the owner), the Plugins page's, in plugins.js, with no room added (10-26); 1,542,418 with a page plugin's sidebar tab coming and going as it is installed, switched on or off, or removed, instead of on the Plugins page's next load (the owner), in plugins.js, with no room added (10-26); 1,537,645 with Settings › Observability moved out to plugins/otel, lowered to it (10-26); 1,537,673 with a used window with no reset not "Not used yet" (windy on Discord), and back to 1,537,645 with Settings' model pickers sharing modelOpt (10-26); 1,541,967 with every slow page's skeletons getting magpie's bird (skelBird, the owner), in app.js, the README's bird sharing its drawing and styles, with no room added (10-26); 1,526,251 with Settings' gateway rows moved out to plugins/gateway/settings.js, lowered to it (10-27); 1,526,391 with Test models naming the first failed model and its error (ysm119 on Discord), in app.js, with no room added (10-27); 1,526,556 with About's Website row (the owner), in app.js, with no room added (10-27); 1,526,500 with a pool's cap ticks (plugins#349), in app.js, with no room added (10-28); 1,527,245 with About's Open-source licenses row and dialog (the owner), in app.js, with no room added (10-28); 1,528,076 with the Partners heading's light (the owner), in app.js, with no room added (10-28); 1,530,449 with Install another agent's More in Plugins row (the owner), in app.js, and Plugins opening at its Agents, in plugins.js, with no room added (10-28); 1,530,807 with layout.js measuring the scrollbar into --bar, which every page's right padding takes off so its sides match (the owner), the window's own shell, with no room added (10-28); 1,530,861 with More in Plugins in sight while Install another agent is folded (the owner), in app.js, with no room added (10-29); 1,532,830 with waitsBack and backAfterLoad (issennknight, macOS 13), the window's own scroll guard, in app.js, with no room added (10-29); the context map's tile wording (a4e929212) and Cindy's Add magpie (628ac36fc) had taken the core over it, and Web search's rows moved out to plugins/search/settings.js brought it back to 1,530,861 (#4133, 10-29); 1,532,459 with a provider editor's account rows on one line each, First or Make first at its right end and the settings that aren't set under ⋯ (the owner), the core's own editor, in app.js, which stays in its budget with its comments cut down, with no room added (10-29); 1,532,602 with a plugin's README waiting for its bird to land on three lines before it goes in, however soon it came (the owner, 10-30), in plugins.js, with no room added; 1,536,357 with Switch accounts only on the Agents row (the owner on X), in app.js, with no room added (10-30); 1,537,034 with a plugin's README read once shown at once, with no bird, when its page opens again and read again behind it, the last 20 kept (the owner), in plugins.js, with no room added (10-30); 1,539,423 with a Claude account added from a setup-token (sfss5362 on X), in app.js, with no room added (10-30); 1,538,975 with purposes.js written as compact JSON by genpurposes and the MCP tool purpose in it, 448 bytes less in all (ferock on Discord), lowered to it (10-30); 1,536,586 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, lowered by the 2,389 the setup-token raised it (10-30); 1,536,631 with the 45 bytes b62fa332f added to app.js (Send requests unmasked for subscriptions and plugin providers too) without a raise, with no room added (10-31); 1,537,356 with Settings › Models › Replies › Claude Code's interactive mode, a row beside Short Claude system prompt (the owner), in app.js, with no room added (10-31); Long conversations in Codex's row naming the config.toml keys Codex reads before it, with Take it out, and the window magpie tells Codex for the model it runs (zgjfjfl on Discord) raised it to 1,537,669, and it is back under 1,537,356 with the key list and the window's size written by the server (codexKeysText, tokensSize) and the row's words cut, no raise (10-31); 1,538,554 with the same two, with no room added (10-31); 1,538,678 with About's Log row (rayem1w on X), with no room added (10-31); 1,539,856 with a model's Listed as id (zeewell on X), in app.js, with no room added (10-31); Tuned for you's Codex row offering the advice to background compaction (herman_hong on Discord) and a package manager's magpie naming its command (shuhai on Discord) took it to 1,541,798, and the release notes' dialogs (What's new, the update's ask) moved out to whatsnew.js, loaded when one opens, brought it back under 1,539,856, no raise (10-31); 1,540,479 for Settings › Sync's Kept on this computer row (hayden4608 on Discord) was taken back to 1,539,856 once the core weighed 1,533,355, no raise (10-31); 1,532,958 with the context window card's head naming the agent and the model's lab (the owner), in context.js, after the card's part text viewer moved out to ctxtext.js (7,005 bytes), lowered to it (10-31); 1,533,105 with the provider editor's Claude Code runs as row moved above the accounts, its pill and hover card in claudemode.js, and Settings found at the row that draws anew (the owner), in app.js and i18n.js, with no room added (11-01); a Codex account's credits spent only after every other account, key and fallback (gokoshiki on Discord) fit in it with the Codex options' comments in app.js cut down, no raise (11-01); a plugin option's words in the window's language and the filtered-models note (plugins#590, anewuser6937 on Discord) fit in it with three of the provider editor's comments in app.js cut down, no raise (11-01); 1,533,802 with a closed Mac window telling its page it is out of sight (#4293, pipi-1997), in app.js, which every page needs, its comments cut to one line, with no room added (11-01); Warm up on a Codex or Claude account's Usage card (01huadalang on Discord), in plugins/usage/page.js, its one call in app.js paid for by two comments cut, no raise (11-01); Settings' Check in now for one account (xiaowu_95660), its row and press in checkinnow.js, loaded when Settings draws a check-in, its one call in app.js paid for by three check-in comments cut, no raise (11-02); a ChatGPT account's plan end under its row on Providers (danzi002 on Discord), its line in app.js paid for by two account-row comments cut, no raise (11-02); Scroll to top and Scroll to bottom (#1090, emo172), in scrollends.js, imported on the window's first scroll, its one line in app.js paid for by two comments cut, no raise (11-02); a new-api relay's User ID beside the balance token (zxc56823), in app.js, paid for by four comments cut, no raise (11-03); Air's opened rows saying whether Air's own Codex and Claude Agent go through magpie (jumy_18634 on Discord), in app.js, paid for by six Agents-page comments cut, no raise (11-03) + coreScriptBudget = 1_533_802 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25); 1,529,542 with the limit-rest row (zoecats), with no room added (10-25); 1,529,837 with Keep a key's form (Charles Cao on X), with no room added (10-25); 1,530,050 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,530,631 with a plugin's page growing to its README on the dialog's spring instead of in one jump (the owner), the Plugins page's, in plugins.js, with no room added (10-25); 1,533,445 with the context map counting its tokens on as a live request grows, a tile pointed at keeping its tip, a tool's gathered results saying how many and the small files their folder (the owner, after flohoeller's map on X), in context.js, which the Routing page draws as well as Usage, and the 4 bytes 84c50f032 added to app.js (Settings' Version row) without a raise, with no room added (10-25); 1,534,312 with the tray panel's last allowances drawn at once (#3160, #3134), with no room added (10-25); 1,537,016 with many releases' notes merged into one list by kind (the owner), in app.js, with no room added (10-25); 1,542,244 with a plugin's README loading under magpie's bird bouncing down its lines instead of pulsing bars (the owner), the Plugins page's, in plugins.js, with no room added (10-26); 1,542,418 with a page plugin's sidebar tab coming and going as it is installed, switched on or off, or removed, instead of on the Plugins page's next load (the owner), in plugins.js, with no room added (10-26); 1,537,645 with Settings › Observability moved out to plugins/otel, lowered to it (10-26); 1,537,673 with a used window with no reset not "Not used yet" (windy on Discord), and back to 1,537,645 with Settings' model pickers sharing modelOpt (10-26); 1,541,967 with every slow page's skeletons getting magpie's bird (skelBird, the owner), in app.js, the README's bird sharing its drawing and styles, with no room added (10-26); 1,526,251 with Settings' gateway rows moved out to plugins/gateway/settings.js, lowered to it (10-27); 1,526,391 with Test models naming the first failed model and its error (ysm119 on Discord), in app.js, with no room added (10-27); 1,526,556 with About's Website row (the owner), in app.js, with no room added (10-27); 1,526,500 with a pool's cap ticks (plugins#349), in app.js, with no room added (10-28); 1,527,245 with About's Open-source licenses row and dialog (the owner), in app.js, with no room added (10-28); 1,528,076 with the Partners heading's light (the owner), in app.js, with no room added (10-28); 1,530,449 with Install another agent's More in Plugins row (the owner), in app.js, and Plugins opening at its Agents, in plugins.js, with no room added (10-28); 1,530,807 with layout.js measuring the scrollbar into --bar, which every page's right padding takes off so its sides match (the owner), the window's own shell, with no room added (10-28); 1,530,861 with More in Plugins in sight while Install another agent is folded (the owner), in app.js, with no room added (10-29); 1,532,830 with waitsBack and backAfterLoad (issennknight, macOS 13), the window's own scroll guard, in app.js, with no room added (10-29); the context map's tile wording (a4e929212) and Cindy's Add magpie (628ac36fc) had taken the core over it, and Web search's rows moved out to plugins/search/settings.js brought it back to 1,530,861 (#4133, 10-29); 1,532,459 with a provider editor's account rows on one line each, First or Make first at its right end and the settings that aren't set under ⋯ (the owner), the core's own editor, in app.js, which stays in its budget with its comments cut down, with no room added (10-29); 1,532,602 with a plugin's README waiting for its bird to land on three lines before it goes in, however soon it came (the owner, 10-30), in plugins.js, with no room added; 1,536,357 with Switch accounts only on the Agents row (the owner on X), in app.js, with no room added (10-30); 1,537,034 with a plugin's README read once shown at once, with no bird, when its page opens again and read again behind it, the last 20 kept (the owner), in plugins.js, with no room added (10-30); 1,539,423 with a Claude account added from a setup-token (sfss5362 on X), in app.js, with no room added (10-30); 1,538,975 with purposes.js written as compact JSON by genpurposes and the MCP tool purpose in it, 448 bytes less in all (ferock on Discord), lowered to it (10-30); 1,536,586 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, lowered by the 2,389 the setup-token raised it (10-30); 1,536,631 with the 45 bytes b62fa332f added to app.js (Send requests unmasked for subscriptions and plugin providers too) without a raise, with no room added (10-31); 1,537,356 with Settings › Models › Replies › Claude Code's interactive mode, a row beside Short Claude system prompt (the owner), in app.js, with no room added (10-31); Long conversations in Codex's row naming the config.toml keys Codex reads before it, with Take it out, and the window magpie tells Codex for the model it runs (zgjfjfl on Discord) raised it to 1,537,669, and it is back under 1,537,356 with the key list and the window's size written by the server (codexKeysText, tokensSize) and the row's words cut, no raise (10-31); 1,538,554 with the same two, with no room added (10-31); 1,538,678 with About's Log row (rayem1w on X), with no room added (10-31); 1,539,856 with a model's Listed as id (zeewell on X), in app.js, with no room added (10-31); Tuned for you's Codex row offering the advice to background compaction (herman_hong on Discord) and a package manager's magpie naming its command (shuhai on Discord) took it to 1,541,798, and the release notes' dialogs (What's new, the update's ask) moved out to whatsnew.js, loaded when one opens, brought it back under 1,539,856, no raise (10-31); 1,540,479 for Settings › Sync's Kept on this computer row (hayden4608 on Discord) was taken back to 1,539,856 once the core weighed 1,533,355, no raise (10-31); 1,532,958 with the context window card's head naming the agent and the model's lab (the owner), in context.js, after the card's part text viewer moved out to ctxtext.js (7,005 bytes), lowered to it (10-31); 1,533,105 with the provider editor's Claude Code runs as row moved above the accounts, its pill and hover card in claudemode.js, and Settings found at the row that draws anew (the owner), in app.js and i18n.js, with no room added (11-01); a Codex account's credits spent only after every other account, key and fallback (gokoshiki on Discord) fit in it with the Codex options' comments in app.js cut down, no raise (11-01); a plugin option's words in the window's language and the filtered-models note (plugins#590, anewuser6937 on Discord) fit in it with three of the provider editor's comments in app.js cut down, no raise (11-01); 1,533,802 with a closed Mac window telling its page it is out of sight (#4293, pipi-1997), in app.js, which every page needs, its comments cut to one line, with no room added (11-01); Warm up on a Codex or Claude account's Usage card (01huadalang on Discord), in plugins/usage/page.js, its one call in app.js paid for by two comments cut, no raise (11-01); Settings' Check in now for one account (xiaowu_95660), its row and press in checkinnow.js, loaded when Settings draws a check-in, its one call in app.js paid for by three check-in comments cut, no raise (11-02); a ChatGPT account's plan end under its row on Providers (danzi002 on Discord), its line in app.js paid for by two account-row comments cut, no raise (11-02); Scroll to top and Scroll to bottom (#1090, emo172), in scrollends.js, imported on the window's first scroll, its one line in app.js paid for by two comments cut, no raise (11-02); a new-api relay's User ID beside the balance token (zxc56823), in app.js, paid for by four comments cut, no raise (11-03); Air's opened rows saying whether Air's own Codex and Claude Agent go through magpie (jumy_18634 on Discord), in app.js, paid for by six Agents-page comments cut, no raise (11-03); a key's spend cap on its row (sparkling_lemur_62868 on Discord), its pill and held line in keyspend.js, loaded when the provider editor draws a key, its one call in app.js, no raise (11-03) ) func TestCoreScriptBudget(t *testing.T) { diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 8b67be8e1..b91394c0e 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -24,6 +24,7 @@ import ( "github.com/yetone/magpie/internal/settings" "github.com/yetone/magpie/internal/update" "github.com/yetone/magpie/internal/upstream" + "github.com/yetone/magpie/internal/usage" ) // The providers page: the vendors the user added, the presets they can add @@ -778,6 +779,21 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs out.KeyList[i].Rest = &provider.KeyRest{Why: r.Why, Status: r.Status, Until: r.Until, Key: key, Probed: r.Probed} } } + // and one with a spend cap, what it has spent of it (the gateway + // holds it at the cap by the same count, gateway.spendHeld) + for i, k := range out.KeyList { + sc, ok := p.KeySpendCap(k.ID) + if !ok { + continue + } + start, reset := sc.Window(time.Now()) + ks := &provider.KeySpend{SpendCap: sc, Spent: usage.KeySpent(k.ID, start)} + ks.Held = ks.Spent >= sc.USD + if !reset.IsZero() { + ks.Reset = &reset + } + out.KeyList[i].Spend = ks + } if !out.Key.Set && p.Ready() { out.Key.Optional = true } @@ -1500,6 +1516,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) { // Weight, for accountweight: the account's share under By // weight routing, 1 to provider.MaxKeyWeight (0 or 1: none) Weight int `json:"weight"` + // Spend, for keyspendcap: the spend cap set on the key Account + // (its id), in USD a day, a month or in all; none, or an + // amount of 0, takes it off + Spend *provider.SpendCap `json:"spend"` // Alias, for accountname: the account's name of the user's // own, "" to take it off (#1515) Alias string `json:"alias"` @@ -1875,6 +1895,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { in.AccountConcurrency = old.AccountConcurrency in.AccountWeights = old.AccountWeights in.AccountNames = old.AccountNames // with accountname + in.KeySpendCaps = old.KeySpendCaps // with keyspendcap } // the image models unticked in its editor likewise: [] // shows them all (321sssrt on X) @@ -2124,6 +2145,15 @@ func providerRoutes(mux *http.ServeMux, w Windows) { fail(rw, err) return } + case "keyspendcap": + var c *provider.SpendCap + if req.Spend != nil && req.Spend.USD > 0 { + c = &provider.SpendCap{USD: req.Spend.USD, Period: req.Spend.Period} + } + if err := provider.SetKeySpendCap(in.ID, req.Account, c); err != nil { + fail(rw, err) + return + } case "accountweight": if err := provider.SetAccountWeight(in.ID, req.Account, req.Weight); err != nil { fail(rw, err) diff --git a/internal/gui/tests/key-spend-cap.test.cjs b/internal/gui/tests/key-spend-cap.test.cjs new file mode 100644 index 000000000..a7e989776 --- /dev/null +++ b/internal/gui/tests/key-spend-cap.test.cjs @@ -0,0 +1,181 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A key's spend cap (sparkling_lemur_62868 on Discord: a team's OpenAI key +// with credits other services spend from too, and magpie to stop at a +// share of them). Each key's row has a pill: what it spent of its cap +// today, this month or in all, else No spend cap (hover-only, as the +// row's other unset pills). A key at its cap is marked, with a line under +// its row that says so and when it is back. A click opens the app's own +// menu (no native select): No spend cap, or a period and then an amount +// typed in place, posted to provider/keyspendcap; an amount that isn't one +// is refused and nothing is posted. A click moves nothing; at a phone's +// width the row stays inside the window. In every language. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const fresh = () => ({ + id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "", + models: [{ id: "model-a", name: "Model A", on: true }], agents: [], fallback: [], headers: {}, + key: { set: true, masked: "sk-…one" }, + keyList: [ + { id: "k1", name: "Main", masked: "sk-…one", on: true, spend: { usd: 20, period: "day", spent: 7.5 } }, + { id: "k2", name: "Team", masked: "sk-…two", on: true, spend: { usd: 5, period: "month", spent: 6, held: true, reset: new Date(Date.now() + 3 * 864e5).toISOString() } }, + { id: "k3", name: "Spare", masked: "sk-…three", on: true }, + ], + balanceToken: { takes: false, set: false }, proxy: "", +}); + +function serve(lang, posts) { + const relay = fresh(); + const providers = { providers: [relay], presets: [], excluded: [], gateway: { running: true, window: true } }; + const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/lanes") return json({}); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname.startsWith("/api/provider/") && route.request().method() === "POST") { + const action = url.pathname.slice("/api/provider/".length), body = route.request().postDataJSON(); + posts.push({ action, body }); + if (action === "keyspendcap") { + const k = relay.keyList.find((x) => x.id === body.account); + if (body.spend) k.spend = { ...body.spend, spent: k.spend?.spent || 0 }; + else delete k.spend; + } + return json(providers); + } + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const words = { + en: { k1: "$7.50 of $20.00 today", k2: "$6.00 of $5.00 this month", none: "No spend cap", held: "At its spend cap · back ", menu: "Spend cap", month: "Per month…", k3: "$0.00 of $12.50 this month", bad: "A spend cap is an amount in USD above 0, up to 1,000,000" }, + zh: { k1: "今日 $7.50 / $20.00", k2: "本月 $6.00 / $5.00", none: "无消费上限", held: "已达消费上限 · ", menu: "消费上限", month: "每月…", k3: "本月 $0.00 / $12.50", bad: "消费上限是大于 0、不超过 1,000,000 的美元金额" }, + "zh-TW": { k1: "今日 $7.50 / $20.00", k2: "本月 $6.00 / $5.00", none: "無消費上限", held: "已達消費上限 · ", menu: "消費上限", month: "每月…", k3: "本月 $0.00 / $12.50", bad: "消費上限是大於 0、不超過 1,000,000 的美元金額" }, + ja: { k1: "今日 $7.50 / $20.00", k2: "今月 $6.00 / $5.00", none: "支出上限なし", held: "支出上限に到達 · ", menu: "支出上限", month: "1か月あたり…", k3: "今月 $0.00 / $12.50", bad: "支出上限は 0 より大きく 1,000,000 以下の USD 金額です" }, + de: { k1: "Heute $7.50 von $20.00", k2: "Diesen Monat $6.00 von $5.00", none: "Kein Ausgabenlimit", held: "Am Ausgabenlimit · zurück ", menu: "Ausgabenlimit", month: "Pro Monat…", k3: "Diesen Monat $0.00 von $12.50", bad: "Ein Ausgabenlimit ist ein Betrag in USD über 0, bis 1.000.000" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + for (const width of [900, 400]) { + const w = words[lang]; + test(`${engine} ${lang} ${width}px: a key's spend cap shows what it spent, marks one at its cap, and is set from the app's menu`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + let page; + t.after(async () => { + if (process.env.ARTIFACT_DIR && page) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-key-spend-cap.png`) }); + } + await browser.close(); + }); + page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const posts = []; + await page.route("**/*", serve(lang, posts)); + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: "Relay" }).first().click(); + await page.locator(".editor .accts .acc .aspend").first().waitFor({ state: "attached" }); + await page.waitForTimeout(300); + const row = (id) => page.locator(`.editor .accts .acc[data-account-id="${id}"]`); + const pill = (id) => row(id).locator(".aspend"); + const menu = page.locator(".proto-menu"); + const item = (name) => menu.locator(".pm-item", { has: page.locator(".pm-name", { hasText: new RegExp(`^${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`) }) }); + const scrolled = () => page.evaluate(() => [window.scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop > 0).map((e) => `${e.className}:${e.scrollTop}`)].join(" ")); + const still = async (id) => { + await row(id).hover(); + await page.waitForTimeout(150); + const before = await row(id).evaluate((e) => Math.round(e.getBoundingClientRect().top)), sc = await scrolled(); + await pill(id).click(); + await page.waitForTimeout(200); + assert.equal(await row(id).evaluate((e) => Math.round(e.getBoundingClientRect().top)), before, `${id}'s row moved`); + assert.equal(await scrolled(), sc, "a click scrolled"); + }; + const posted = async (n) => { + for (let i = 0; i < 60 && posts.length === n; i++) await new Promise((r) => setTimeout(r, 50)); + assert(posts.length > n, "nothing posted"); + return posts.at(-1); + }; + + assert.equal(await pill("k1").textContent(), w.k1); + assert.equal(await pill("k2").textContent(), w.k2); + assert.equal(await pill("k3").textContent(), w.none); + assert.equal(await page.locator("select").count(), 0, "no native select"); + // one at its cap is marked, with a line saying when it is back + assert.equal(await pill("k2").evaluate((e) => e.classList.contains("at-cap")), true); + assert.equal(await pill("k1").evaluate((e) => e.classList.contains("at-cap")), false); + const line = row("k2").locator(".key-spend-line"); + assert.equal(await line.count(), 1); + assert((await line.textContent()).startsWith(w.held), await line.textContent()); + assert.equal(await row("k1").locator(".key-spend-line").count(), 0); + // a cap set is always shown; none set only on a hover + await page.mouse.move(0, 0); + await page.waitForTimeout(250); + assert.equal(await pill("k1").evaluate((e) => getComputedStyle(e).opacity), "1"); + // inside the window at every width, the page not scrolled sideways + const over = await page.evaluate(() => [...document.querySelectorAll(".editor .accts .acc")].filter((e) => e.getBoundingClientRect().right > innerWidth + 1).length); + assert.equal(over, 0, "a key's row past the window's edge"); + assert.equal(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth + 1), true, "the page scrolls sideways"); + + // k3: a month's cap of 12.5, typed in place + await still("k3"); + await menu.waitFor(); + assert.equal(await menu.locator(".pm-head").textContent(), w.menu); + await item(w.month).click(); + const box = row("k3").locator("input.aspend-in"); + await box.waitFor(); + let n = posts.length; + await box.fill("lots"); + await box.press("Enter"); + await page.waitForTimeout(300); + assert.equal(posts.length, n, "a bad amount was posted"); + assert.equal(await page.locator("#status").textContent(), w.bad); + await box.waitFor({ state: "detached" }); + await pill("k3").waitFor(); + await page.waitForTimeout(300); + // the Enter that was refused can open the menu again on the pill + // drawn in the field's place: pick from it, else open it + if (!(await menu.isVisible())) await still("k3"); + await menu.waitFor(); + await item(w.month).click(); + await box.waitFor(); + await box.fill("12.5"); + await box.press("Enter"); + let p = await posted(n); + assert.equal(p.action, "keyspendcap"); + assert.deepEqual(p.body, { id: "relay", account: "k3", spend: { usd: 12.5, period: "month" } }); + await page.waitForTimeout(250); + assert.equal(await pill("k3").textContent(), w.k3); + + // k1's cap taken off + await still("k1"); + n = posts.length; + await item(w.none).click(); + p = await posted(n); + assert.deepEqual(p.body, { id: "relay", account: "k1", spend: null }); + await page.waitForTimeout(250); + assert.equal(await pill("k1").textContent(), w.none); + + // a left border thicker or another colour than the right one is a stripe + const stripes = await page.evaluate(() => [...document.querySelectorAll(".aspend, .aspend-in, .key-spend-line, .key-spend-line *")].map((e) => getComputedStyle(e)).filter((s) => parseFloat(s.borderLeftWidth) > parseFloat(s.borderRightWidth) || (parseFloat(s.borderLeftWidth) > 0 && s.borderLeftColor !== s.borderRightColor)).length); + assert.equal(stripes, 0, "no border stripes"); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/gui/tests/old-webkit.test.cjs b/internal/gui/tests/old-webkit.test.cjs index f136d3f57..887f65622 100644 --- a/internal/gui/tests/old-webkit.test.cjs +++ b/internal/gui/tests/old-webkit.test.cjs @@ -154,9 +154,10 @@ test("compat.js is the first of the page's own scripts", async () => { // quitask.js when a Quit asks first, checkinnow.js when Settings' Check // in now for one account is pressed, autobackup.js when Settings draws // Sync, scrollends.js on the window's first scroll, profilerename.js - // when a saved profile's Rename is pressed; the checks above + // when a saved profile's Rename is pressed, keyspend.js when the + // provider editor draws a key's row; the checks above // still read them - for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); + for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); }); test("the styles hold up in Safari 15.0", async () => { diff --git a/internal/provider/key_spend.go b/internal/provider/key_spend.go new file mode 100644 index 000000000..7b41f7611 --- /dev/null +++ b/internal/provider/key_spend.go @@ -0,0 +1,174 @@ +package provider + +// A key's spend cap: how much an API key may spend, in USD, as magpie's +// own usage prices its calls (sparkling_lemur_62868 on Discord: a team's +// OpenAI key, credits granted to it, that other services spend from too, +// with nothing on OpenAI's side to stop magpie at a share of it). Once +// what magpie sent on the key in the cap's period costs the cap or more, +// routing takes the key for used up — as a usage cap holds an account — +// and goes on to the provider's other keys and its fallbacks; with none, +// the request is answered 429 with why. The key is used again when the +// period renews: the next day or month, or never for a cap in all until +// it is raised or lifted. +// +// What is counted is what the Usage page prices the key's calls at +// (usage.KeySpent), not the vendor's bill: a price magpie doesn't know +// counts nothing, and requests already under way when the cap is reached +// still finish, so the key can go a little past it. + +import ( + "fmt" + "math" + "strconv" + "strings" + "time" +) + +// SpendCap is a key's spend cap: USD over Period, which is SpendDay, +// SpendMonth or SpendTotal (in all, counted from Since). +type SpendCap struct { + USD float64 `json:"usd"` + Period string `json:"period"` + // Since is when a cap in all was set, what it counts from; kept while + // the cap stays one in all, its amount changed or not + Since time.Time `json:"since,omitzero"` +} + +// The periods a spend cap counts over: a calendar day or month in local +// time, or in all since it was set. +const ( + SpendDay = "day" + SpendMonth = "month" + SpendTotal = "total" +) + +// MaxSpendCap bounds a spend cap, in USD. +const MaxSpendCap = 1_000_000 + +// Window is the period c counts over at now: when it began and when the +// next begins, zero for a cap in all, which never renews. +func (c SpendCap) Window(now time.Time) (start, reset time.Time) { + y, m, d := now.Date() + loc := now.Location() + switch c.Period { + case SpendMonth: + return time.Date(y, m, 1, 0, 0, 0, 0, loc), time.Date(y, m+1, 1, 0, 0, 0, 0, loc) + case SpendTotal: + return c.Since, time.Time{} + } + return time.Date(y, m, d, 0, 0, 0, 0, loc), time.Date(y, m, d+1, 0, 0, 0, 0, loc) +} + +// KeySpendCap is the spend cap of p's key keyID, and whether it has one. +func (p Provider) KeySpendCap(keyID string) (SpendCap, bool) { + c, ok := p.KeySpendCaps[strings.ToLower(keyID)] + return c, ok && c.USD > 0 +} + +// SetKeySpendCap gives the key ref (its id or name) of the provider id +// the spend cap c, nil to take its cap off. A cap in all keeps the Since +// it had while it stays one; else it counts from now. +func SetKeySpendCap(id, ref string, c *SpendCap) error { + if c != nil { + if err := checkSpendCap(*c); err != nil { + return err + } + } + p, err := Find(id) + if err != nil { + return err + } + if p.Account != nil { + return fmt.Errorf("%s is a subscription: a spend cap is for an API key (an account's cap is a share of its usage windows, magpie provider account-cap)", p.Name) + } + r, ok := p.accountRef(ref) + if !ok { + return fmt.Errorf("%s has no key %q", p.Name, ref) + } + k := strings.ToLower(r) + m := map[string]SpendCap{} + for id, v := range p.KeySpendCaps { + m[id] = v + } + if c == nil { + if _, had := m[k]; !had { + return nil + } + delete(m, k) + } else { + v := *c + v.Since = time.Time{} + if v.Period == SpendTotal { + v.Since = time.Now().UTC().Truncate(time.Second) + if was, had := m[k]; had && was.Period == SpendTotal && !was.Since.IsZero() { + v.Since = was.Since + } + } + m[k] = v + } + p.KeySpendCaps = m + return Save(*p) +} + +// checkSpendCap says what is wrong with c, nil when nothing is. +func checkSpendCap(c SpendCap) error { + switch c.Period { + case SpendDay, SpendMonth, SpendTotal: + default: + return fmt.Errorf("a spend cap is per %s, per %s or in all (%s), not %q", SpendDay, SpendMonth, SpendTotal, c.Period) + } + if !(c.USD > 0 && c.USD <= MaxSpendCap) || math.IsNaN(c.USD) { + return fmt.Errorf("a spend cap is an amount in USD above 0 and up to %d, not %v", MaxSpendCap, c.USD) + } + return nil +} + +// ParseSpendCap reads a spend cap as the CLI takes it: an amount in USD +// ("20", "$20", "12.5") and its period (day, month or total, per day by +// default); off for none (nil). +func ParseSpendCap(amount, period string) (*SpendCap, error) { + a := strings.ToLower(strings.TrimSpace(amount)) + switch a { + case "off", "none", "no", "-": + return nil, nil + } + usd, err := strconv.ParseFloat(strings.TrimPrefix(a, "$"), 64) + if err != nil { + return nil, fmt.Errorf("a spend cap is an amount in USD (20, 12.5) or off, not %q", amount) + } + per := strings.ToLower(strings.TrimSpace(period)) + switch per { + case "", "daily", "a-day", "per-day": + per = SpendDay + case "monthly", "a-month", "per-month": + per = SpendMonth + case "all", "in-all", "ever": + per = SpendTotal + } + c := SpendCap{USD: usd, Period: per} + if err := checkSpendCap(c); err != nil { + return nil, err + } + return &c, nil +} + +// normalKeySpendCaps is m as it is kept: key ids in lower case, caps that +// say nothing left out, a cap in all with no Since counting from the +// epoch (one written by hand); nil for none. +func normalKeySpendCaps(m map[string]SpendCap) map[string]SpendCap { + var out map[string]SpendCap + for k, c := range m { + k = strings.ToLower(strings.TrimSpace(k)) + if k == "" || checkSpendCap(c) != nil { + continue + } + if c.Period != SpendTotal { + c.Since = time.Time{} + } + if out == nil { + out = map[string]SpendCap{} + } + out[k] = c + } + return out +} diff --git a/internal/provider/key_spend_test.go b/internal/provider/key_spend_test.go new file mode 100644 index 000000000..1b9c30a18 --- /dev/null +++ b/internal/provider/key_spend_test.go @@ -0,0 +1,134 @@ +package provider + +import ( + "strings" + "testing" + "time" +) + +// A key's spend cap (sparkling_lemur_62868 on Discord) is set by the key's +// id or name, kept by its fingerprint in lower case, and taken off with +// nil. A cap in all counts from when it was set, and keeps that start +// while it stays one in all, its amount changed; a cap a day or a month +// keeps none. A key the provider hasn't and a cap out of range are +// refused, and a key's value replaced keeps its cap. +func TestKeySpendCapSet(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + if err := Save(Provider{ID: "relay", Name: "Relay", Chat: "https://relay.test/v1", Key: "sk-first", KeyName: "Team", + Keys: []KeyAccount{{Name: "Spare", Key: "sk-spare"}}}); err != nil { + t.Fatal(err) + } + first, spare := keyID("sk-first"), keyID("sk-spare") + capOf := func(ref string) (SpendCap, bool) { + t.Helper() + p, err := Find("relay") + if err != nil { + t.Fatal(err) + } + return p.KeySpendCap(ref) + } + if err := SetKeySpendCap("relay", "Team", &SpendCap{USD: 20, Period: SpendDay}); err != nil { + t.Fatal(err) + } + if c, ok := capOf(strings.ToUpper(first)); !ok || c.USD != 20 || c.Period != SpendDay || !c.Since.IsZero() { + t.Fatalf("Team's cap %+v %v", c, ok) + } + if _, ok := capOf(spare); ok { + t.Fatal("Spare got a cap it wasn't given") + } + before := time.Now().UTC().Truncate(time.Second) + if err := SetKeySpendCap("relay", spare, &SpendCap{USD: 100, Period: SpendTotal}); err != nil { + t.Fatal(err) + } + c, ok := capOf(spare) + if !ok || c.Period != SpendTotal || c.Since.Before(before) || c.Since.After(time.Now()) { + t.Fatalf("Spare's cap in all %+v %v", c, ok) + } + // set in all a while back, raised: it still counts from then + p, _ := Find("relay") + since := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + p.KeySpendCaps[spare] = SpendCap{USD: 100, Period: SpendTotal, Since: since} + if err := Save(*p); err != nil { + t.Fatal(err) + } + if err := SetKeySpendCap("relay", "Spare", &SpendCap{USD: 150, Period: SpendTotal}); err != nil { + t.Fatal(err) + } + if c, _ := capOf(spare); c.USD != 150 || !c.Since.Equal(since) { + t.Fatalf("raised in all, it counts from %v, not %v: %+v", c.Since, since, c) + } + // a month: no start of its own; in all again counts from now + if err := SetKeySpendCap("relay", spare, &SpendCap{USD: 150, Period: SpendMonth}); err != nil { + t.Fatal(err) + } + if c, _ := capOf(spare); c.Period != SpendMonth || !c.Since.IsZero() { + t.Fatalf("a month's cap %+v", c) + } + for _, bad := range []SpendCap{{USD: 0, Period: SpendDay}, {USD: -1, Period: SpendDay}, {USD: MaxSpendCap + 1, Period: SpendDay}, {USD: 5, Period: "week"}} { + if err := SetKeySpendCap("relay", spare, &bad); err == nil { + t.Fatalf("%+v was taken", bad) + } + } + if err := SetKeySpendCap("relay", "nobody", &SpendCap{USD: 1, Period: SpendDay}); err == nil { + t.Fatal("a key the provider hasn't got a cap") + } + // the value replaced, the cap goes with the key + if _, _, err := ReplaceKey("relay", first, "sk-first-2"); err != nil { + t.Fatal(err) + } + if c, ok := capOf(keyID("sk-first-2")); !ok || c.USD != 20 { + t.Fatalf("replaced, Team's cap %+v %v", c, ok) + } + if err := SetKeySpendCap("relay", "Team", nil); err != nil { + t.Fatal(err) + } + if _, ok := capOf(keyID("sk-first-2")); ok { + t.Fatal("the cap taken off is still there") + } +} + +// A day's cap counts from local midnight to the next, a month's from the +// 1st to the next month's, and one in all from its Since, never renewing. +func TestSpendCapWindow(t *testing.T) { + loc := time.FixedZone("far", 13*3600) + now := time.Date(2026, 12, 31, 23, 30, 0, 0, loc) + s, r := SpendCap{USD: 1, Period: SpendDay}.Window(now) + if !s.Equal(time.Date(2026, 12, 31, 0, 0, 0, 0, loc)) || !r.Equal(time.Date(2027, 1, 1, 0, 0, 0, 0, loc)) { + t.Fatalf("day %v %v", s, r) + } + s, r = SpendCap{USD: 1, Period: SpendMonth}.Window(now) + if !s.Equal(time.Date(2026, 12, 1, 0, 0, 0, 0, loc)) || !r.Equal(time.Date(2027, 1, 1, 0, 0, 0, 0, loc)) { + t.Fatalf("month %v %v", s, r) + } + since := time.Date(2026, 3, 4, 5, 6, 7, 0, time.UTC) + s, r = SpendCap{USD: 1, Period: SpendTotal, Since: since}.Window(now) + if !s.Equal(since) || !r.IsZero() { + t.Fatalf("in all %v %v", s, r) + } +} + +// The CLI's words for a cap: an amount, $ or not, a period by any of its +// names, a day when none; off for none; anything else refused. +func TestParseSpendCap(t *testing.T) { + for _, c := range []struct { + amount, period string + want *SpendCap + }{ + {"20", "", &SpendCap{USD: 20, Period: SpendDay}}, + {"$12.5", "monthly", &SpendCap{USD: 12.5, Period: SpendMonth}}, + {"100", "total", &SpendCap{USD: 100, Period: SpendTotal}}, + {"100", "all", &SpendCap{USD: 100, Period: SpendTotal}}, + {"off", "", nil}, + } { + got, err := ParseSpendCap(c.amount, c.period) + if err != nil || (got == nil) != (c.want == nil) || got != nil && *got != *c.want { + t.Fatalf("%q %q: %+v %v", c.amount, c.period, got, err) + } + } + for _, bad := range [][2]string{{"--help", ""}, {"twenty", ""}, {"0", ""}, {"-5", ""}, {"5", "week"}, {"NaN", ""}, {"2000000", ""}} { + if _, err := ParseSpendCap(bad[0], bad[1]); err == nil { + t.Fatalf("%q %q was taken", bad[0], bad[1]) + } + } +} diff --git a/internal/provider/keys.go b/internal/provider/keys.go index 080c6a883..184c6257d 100644 --- a/internal/provider/keys.go +++ b/internal/provider/keys.go @@ -54,6 +54,19 @@ type KeyInfo struct { // Rest is why the gateway passes it over now, after a failure, and // until when; nil while it takes requests. Rest *KeyRest `json:"rest,omitempty"` + // Spend is the spend cap set on it and what it has spent in its + // period; nil with none. + Spend *KeySpend `json:"spend,omitempty"` +} + +// KeySpend is a key's spend cap as its row tells it: the cap, what magpie +// counted spent in its period, when that renews (none for a cap in all), +// and whether routing holds the key at it now. +type KeySpend struct { + SpendCap + Spent float64 `json:"spent"` + Reset *time.Time `json:"reset,omitempty"` + Held bool `json:"held,omitempty"` } // KeyRest is a key's rest as the gateway keeps it: failQuota, failRate…, @@ -643,6 +656,7 @@ func ReplaceKey(id, keyRef, key string) (was, now string, err error) { moveKeyed(p.AccountModels, keyRef, now) moveKeyed(p.AccountProxies, keyRef, now) moveKeyed(p.AccountConcurrency, keyRef, now) + moveKeyed(p.KeySpendCaps, keyRef, now) return keyRef, now, Save(*p) } diff --git a/internal/provider/provider.go b/internal/provider/provider.go index f7ddb435b..d48017c1f 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -437,6 +437,11 @@ type Provider struct { // It is magpie's own: the vendor's or plugin's sign-in never sees it // (see account_names.go). AccountNames map[string]string `json:"accountNames,omitempty"` + // KeySpendCaps is, for a provider of API keys, how much each key the + // user capped may spend, in USD as the Usage page prices its calls, + // a day, a month or in all, by its KeyID: past it, routing takes the + // key for used up until the period renews (see key_spend.go). + KeySpendCaps map[string]SpendCap `json:"keySpendCaps,omitempty"` // BalanceURL, when set, is where the vendor tells what is left on a // key, asked with the key the way a chat request carries it; BalancePath @@ -789,6 +794,7 @@ func (p Provider) clone() Provider { p.AccountProxies = maps.Clone(p.AccountProxies) p.AccountCaps = maps.Clone(p.AccountCaps) p.AccountNames = maps.Clone(p.AccountNames) + p.KeySpendCaps = maps.Clone(p.KeySpendCaps) if p.AccountWindowCaps != nil { m := make(map[string]map[string]int, len(p.AccountWindowCaps)) for k, v := range p.AccountWindowCaps { @@ -1548,6 +1554,7 @@ func normalize(p Provider) Provider { p.AccountCaps = normalAccountCaps(p.AccountCaps) p.AccountWindowCaps = normalWindowCaps(p.AccountWindowCaps) p.AccountNames = normalAccountNames(p.AccountNames) + p.KeySpendCaps = normalKeySpendCaps(p.KeySpendCaps) if len(p.Models) > 0 { p.NoModels = false // a pick is no longer Select none } diff --git a/internal/usage/spend.go b/internal/usage/spend.go new file mode 100644 index 000000000..9c5ab1ea3 --- /dev/null +++ b/internal/usage/spend.go @@ -0,0 +1,133 @@ +package usage + +import ( + "sync" + "time" +) + +// spendMemo keeps what each API key has spent from a start on, read from +// usage.jsonl once and counted up by Append after: routing asks it on +// every request for a key with a spend cap (provider.SpendCap). +var spendMemo struct { + sync.Mutex + path string + // sums by key and start, each read again once it is spendFresh old: + // prices change, and the log can be cleared or rewritten + sums map[spendSlot]spendSum + // reading counts the reads of a key under way, dirty a call Append + // wrote for one meanwhile: such a read may have missed it or have it + // already, so it is not kept + reading map[string]int + dirty map[string]bool +} + +type spendSlot struct { + key string + start time.Time +} + +type spendSum struct { + usd float64 + at time.Time +} + +// spendFresh is how long a key's sum read from the log is kept, counted up +// by Append, before it is read again. +const spendFresh = 5 * time.Minute + +// spendCounts reports whether r spends from its key: a call magpie sent +// on it from this computer, not one turned away before it went out nor +// one an agent reported. +func spendCounts(r Record) bool { + return r.ProviderKeyID != "" && !r.IsRejected() && !r.IsReported() && r.Computer == "" +} + +// KeySpent is what the calls magpie sent on the API key keyID (its +// provider.KeyID) from start on cost, in USD at the Usage page's prices, +// under whichever provider sent them. A call with no known price counts +// nothing. +func KeySpent(keyID string, start time.Time) float64 { + path := Path() + slot := spendSlot{keyID, start.UTC()} + for try := 0; ; try++ { + spendMemo.Lock() + if spendMemo.path != path { + spendMemo.path, spendMemo.sums = path, nil + } + if v, ok := spendMemo.sums[slot]; ok && time.Since(v.at) < spendFresh && !v.at.After(time.Now()) { + spendMemo.Unlock() + return v.usd + } + if spendMemo.reading == nil { + spendMemo.reading, spendMemo.dirty = map[string]int{}, map[string]bool{} + } + spendMemo.reading[keyID]++ + if spendMemo.reading[keyID] == 1 { + delete(spendMemo.dirty, keyID) + } + spendMemo.Unlock() + read := time.Now() + v := readSpent(keyID, start) + spendMemo.Lock() + dirty := spendMemo.dirty[keyID] + if spendMemo.reading[keyID]--; spendMemo.reading[keyID] == 0 { + delete(spendMemo.reading, keyID) + } + // a read Append wrote a call of the key into meanwhile may count it + // or not: read again, and past three such reads go by what was read + if !dirty || try >= 2 { + if !dirty && spendMemo.path == path { + if spendMemo.sums == nil { + spendMemo.sums = map[spendSlot]spendSum{} + } + // a key's cap counts from one start: one it counted from + // before (yesterday, a cap since changed) is let go + for s := range spendMemo.sums { + if s.key == keyID { + delete(spendMemo.sums, s) + } + } + spendMemo.sums[slot] = spendSum{v, read} + } + spendMemo.Unlock() + return v + } + spendMemo.Unlock() + } +} + +func readSpent(keyID string, start time.Time) float64 { + cost := NewCoster() + var spent float64 + Visit(start, func(r Record) { + if r.ProviderKeyID == keyID && spendCounts(r) && !r.Time.Before(start) { + c, _ := cost(r) + spent += c + } + }) + return spent +} + +// spentNew counts a call Append wrote in the sums of its key kept. +func spentNew(r Record) { + if !spendCounts(r) { + return + } + spendMemo.Lock() + defer spendMemo.Unlock() + if spendMemo.reading[r.ProviderKeyID] > 0 { + spendMemo.dirty[r.ProviderKeyID] = true + } + var cost func(Record) (float64, bool) + for s, v := range spendMemo.sums { + if s.key != r.ProviderKeyID || r.Time.Before(s.start) { + continue + } + if cost == nil { + cost = NewCoster() + } + c, _ := cost(r) + v.usd += c + spendMemo.sums[s] = v + } +} diff --git a/internal/usage/spend_test.go b/internal/usage/spend_test.go new file mode 100644 index 000000000..fddd4d6b8 --- /dev/null +++ b/internal/usage/spend_test.go @@ -0,0 +1,79 @@ +package usage + +import ( + "math" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// spendHome is a home with relay/gpt-9 priced at $1 in and $2 out a +// million tokens, and spend's sums forgotten. +func spendHome(t *testing.T) { + t.Helper() + reportedHome(t) + s := settings.Load() + s.ModelPrices = map[string]settings.ModelPrice{ + "relay/gpt-9": {Input: new(1.0), Output: new(2.0), CacheRead: new(0.0), CacheWrite: new(0.0)}, + } + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "sk-a", Chat: "http://127.0.0.1:1/v1", Models: []string{"gpt-9"}}); err != nil { + t.Fatal(err) + } + spendMemo.Lock() + spendMemo.path, spendMemo.sums = "", nil + spendMemo.Unlock() +} + +// KeySpent (sparkling_lemur_62868's spend cap) is what magpie's calls on a +// key cost from a start on, at the Usage page's prices: the key's own calls +// alone, not another key's, not one before the start, not one turned away +// before it went out nor one an app reported (another computer's calls are +// in the shared files, which the log read here never holds). A call Append +// writes after the sum is read counts at once, though the sum is kept for +// minutes. +func TestKeySpentCountsTheKeysCalls(t *testing.T) { + spendHome(t) + a, b := provider.KeyID("sk-a"), provider.KeyID("sk-b") + now := time.Now() + start := now.Add(-2 * time.Hour) + call := func(at time.Time, key string, in int) Record { + return Record{Time: at, Agent: "codex", Provider: "relay", Model: "gpt-9", ProviderKeyID: key, Input: in, Output: 0, Status: 200} + } + Append(call(now.Add(-time.Hour), a, 1e6)) // $1 + Append(call(now.Add(-50*time.Minute), a, 2e6)) // $2 + Append(call(now.Add(-40*time.Minute), b, 5e6)) // another key's + Append(call(now.Add(-3*time.Hour), a, 7e6)) // before the start + rejected := call(now.Add(-30*time.Minute), a, 9e6) // turned away + rejected.Rejected = true + Append(rejected) + reported := call(now.Add(-20*time.Minute), a, 9e6) + reported.Source = SourceReported + Append(reported) + near := func(got, want float64) bool { return math.Abs(got-want) < 1e-9 } + if got := KeySpent(a, start); !near(got, 3) { + t.Fatalf("key a spent %v, want 3", got) + } + if got := KeySpent(b, start); !near(got, 5) { + t.Fatalf("key b spent %v, want 5", got) + } + // counted from earlier, the call before the old start is in + if got := KeySpent(a, now.Add(-4*time.Hour)); !near(got, 10) { + t.Fatalf("key a from 4h back spent %v, want 10", got) + } + if got := KeySpent(a, start); !near(got, 3) { + t.Fatalf("key a read again spent %v, want 3", got) + } + // a new call is counted in the sum kept, without a read of the log + Append(call(now, a, 4e6)) + if got := KeySpent(a, start); !near(got, 7) { + t.Fatalf("after a new call key a spent %v, want 7", got) + } + if got := KeySpent(provider.KeyID("sk-none"), start); got != 0 { + t.Fatalf("a key never used spent %v", got) + } +} diff --git a/internal/usage/usage.go b/internal/usage/usage.go index f180829d7..d94ae74f0 100644 --- a/internal/usage/usage.go +++ b/internal/usage/usage.go @@ -292,6 +292,7 @@ func Append(r Record) { observeLedger(r) } defer codexUsedNew(r) + defer spentNew(r) b, err := json.Marshal(r) if err != nil { return