diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index ca358141b..d1c92d43f 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -347,6 +347,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`. - 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; within 5 points of its cap an account takes one turn at a time whatever they say, [gateway routing](gateway-routing.md); `SetCapStop`, `SetCapCareful`, GUI `provider/capstop` and `provider/capcareful`, ticks under the account list once an account has a cap). `UsageRead` says when an account's usage was last read well and whether the last try failed (a failed try keeps the good reading's time), and `ReadUsageNow` reads it again. `magpie provider pool [--accounts a,b,…] [--cap percent|off] [--stop on|off] [--careful on|off]` shows and sets the whole pool in one command: which accounts are on and in what order, each one's cap, and both settings, and names the accounts in use with no cap. - A key's spend cap (`KeySpendCaps`, by the key's fingerprint, [`key_spend.go`](../../internal/provider/key_spend.go); sparkling_lemur_62868 on Discord: a team's OpenAI key whose granted credits other services spend from too) is how much magpie may spend on an API key, in USD, per calendar day or month in local time, or in all since it was set (`Since`, kept while the cap stays one in all, its amount changed or not). What counts is what the Usage page prices magpie's own calls on the key at (`usage.KeySpent`: records whose `ProviderKeyID` is the key, not turned away, not reported by an app; the log is read once and each new call added by `Append`, read again after 5 minutes), not the vendor's bill: a model with no known price counts nothing, and requests under way when it is reached still finish, so the key can go a little past it. At or past the cap the gateway passes the key over ([gateway routing](gateway-routing.md)). Only a key has one: `SetKeySpendCap` refuses a subscription, an amount not above 0 or over `MaxSpendCap` (1,000,000) and a period it doesn't know. `ReplaceKey` carries it to the new value. Set from the key's row in the editor (a pill: "$7.50 of $20.00 today", the app's menu, then the amount typed in place, drawn by `keyspend.js`, which app.js imports when it draws a key's row; GUI `provider/keyspendcap`, `key-spend-cap.test.cjs`) or `magpie provider spend-cap [key [usd [day|month|total]|off]]`, which also lists each key's spend. `TestKeySpendCapSet`, `TestSpendCapWindow`, `TestParseSpendCap`, `TestKeySpentCountsTheKeysCalls`, `TestSpendCapCmd`. +- A key's balance typed by hand (`KeyOwnBalances`, by the key's fingerprint: `{usd, at}`, [`key_balance_own.go`](../../internal/provider/key_balance_own.go); tenacious_eagle on Discord) is for a key whose vendor tells no balance magpie can read (`TakesOwnBalance`: an API key with no balance source, not Cline's or OpenCode Zen's, not on a plan's windows). The user types what the vendor's page says is left; the key's card on the Usage page and the tray then shows it less what the Usage page prices magpie's own calls on the key at since then (`usage.KeySpent` from `at`, through the `provider.KeySpent` hook usage sets), as `≈$12.50` with `Estimate` (`set`, `at`, `spent`) and below nothing as `≈$-2.00`. Typing it again counts from then. It is an estimate, not a reading: it is kept out of the balance history (no trend or runs-out), is never shared, and routing reads nothing from it; a low-balance alert reads its number. A balance the vendor tells always wins: with a Balance URL or a source magpie knows the card is the vendor's, and a relay whose query is looked for shows the typed one only when none is found (`errNoBalance`); the typed value stays saved as the user left it. `SetKeyOwnBalance` (GUI `provider/keyownbalance`, a pill in the key's row, "≈$12.50 left" or "Set balance", drawn by `keybalance.js` while `takesOwnBalance` and no balance was found; `magpie provider key-balance [key [usd|off]]`) refuses a subscription and an amount outside 0 to `MaxOwnBalance` (1,000,000); nil takes it off, `ReplaceKey` carries it to the new value, and saving the editor keeps it. Each key with one gets `balance` in `/api/providers`' `keyList`. `TestTypedBalanceCountsDown`, `TestToldBalanceWinsOverTyped`, `TestOwnBalanceParsed`, `TestKeyOwnBalanceRoutes`, `key-own-balance.test.cjs`. - A window whose reset time has passed has started again, whatever share it was read at (`resetPassed`). That holds for a reading kept from before (`AsOf`) and for a fresh one: Claude Code's `/usage` gives a reset to the minute and can lag it, so a run just after a reset can still say 100% with that reset. `claudeWindows` hands such a window back empty on every path, and `usedPast`, `usedUp`, `BackAt` and `capReached` leave it out when they judge an account spent, for Codex, Claude Code and `magpie quota wait` alike. A card can still show a kept reading as it was read (`reported`, for a Claude card while `/usage` is unavailable); that changes what it shows, never which account is used. A reset `/usage` gives as a time alone ("resets 3pm") can be read as its next one, a day on (`claudeResetTime`), and is then not seen as passed here. - 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 diff --git a/internal/cli/key_balance_cli.go b/internal/cli/key_balance_cli.go new file mode 100644 index 000000000..24183d931 --- /dev/null +++ b/internal/cli/key_balance_cli.go @@ -0,0 +1,73 @@ +package cli + +import ( + "fmt" + + "github.com/yetone/magpie/internal/provider" + stats "github.com/yetone/magpie/internal/usage" +) + +const keyBalanceUsage = "magpie provider key-balance [key [usd|off]]" + +// keyBalanceCmd shows, or sets, the balance typed by hand on a provider's +// API keys whose vendor tells none (tenacious_eagle on Discord): what is +// left of it is the amount less what magpie priced the key's calls at +// since it was typed (provider/key_balance_own.go). +func keyBalanceCmd(rest []string) error { + if len(rest) < 1 || len(rest) > 3 { + return fmt.Errorf("%s", keyBalanceUsage) + } + p, err := provider.Find(rest[0]) + if err != nil { + return err + } + if p.Account != nil { + return fmt.Errorf("%s is a subscription: a balance typed by hand is for an API key", p.Name) + } + if len(rest) > 2 { + usd, err := provider.ParseOwnBalance(rest[2]) + if err != nil { + return err + } + if err := provider.SetKeyOwnBalance(p.ID, rest[1], usd); 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 + } + if !p.TakesOwnBalance() { + fmt.Println(muted.Render(p.Name + " tells its balance itself: the Usage page shows that, not one typed")) + } + for _, k := range keys { + name := k.Masked + " " + muted.Render(k.ID) + if k.Name != "" { + name = k.Name + " " + muted.Render(k.Masked+" · "+k.ID) + } + b, ok := p.KeyOwnBalance(k.ID) + if !ok { + fmt.Println(name, muted.Render("· no balance typed")) + continue + } + spent := stats.KeySpent(k.ID, b.At) + fmt.Printf("%s · about $%.2f left · $%.2f typed %s, $%.2f spent since\n", name, b.USD-spent, b.USD, b.At.Local().Format("Jan 2 15:04"), spent) + } + return nil +} diff --git a/internal/cli/key_balance_cli_test.go b/internal/cli/key_balance_cli_test.go new file mode 100644 index 000000000..cc4c0d3f7 --- /dev/null +++ b/internal/cli/key_balance_cli_test.go @@ -0,0 +1,55 @@ +package cli + +import ( + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// magpie provider key-balance sets, shows and takes off a key's balance +// typed by hand (tenacious_eagle on Discord), and a flag or an amount +// that isn't one is refused without writing anything. +func TestKeyBalanceCmd(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) + } + typed := func() (provider.OwnBalance, bool) { + t.Helper() + p, err := provider.Find("relay") + if err != nil { + t.Fatal(err) + } + return p.KeyOwnBalance(provider.KeyID("k1")) + } + if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "$1,250.5"}); err != nil { + t.Fatal(err) + } + if b, ok := typed(); !ok || b.USD != 1250.5 || b.At.IsZero() { + t.Fatalf("typed: %+v %v", b, ok) + } + for _, args := range [][]string{{"relay"}, {"relay", "Team"}} { + if err := providerCmd(append([]string{"provider", "key-balance"}, args...)); err != nil { + t.Fatal(args, err) + } + } + for _, bad := range [][]string{{"relay", "Team", "--help"}, {"relay", "--help"}, {"relay", "Team", "lots"}, {"relay", "Team", "-3"}, {"relay", "nokey", "5"}, {"relay", "Team", "5", "extra"}} { + if err := providerCmd(append([]string{"provider", "key-balance"}, bad...)); err == nil { + t.Fatalf("%v taken", bad) + } + } + if b, _ := typed(); b.USD != 1250.5 { + t.Fatalf("a refused value changed the balance: %+v", b) + } + if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "off"}); err != nil { + t.Fatal(err) + } + if _, ok := typed(); ok { + t.Fatal("off left a balance") + } +} diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index 78c122064..a1daddd54 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -98,6 +98,9 @@ const providerUsage = `usage: 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 key-balance [key [usd|off]] + the balance on an API key whose vendor tells none, typed from its own page: + the Usage page shows it less what magpie prices the key's calls at since 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) @@ -642,6 +645,8 @@ func providerCmd(args []string) error { return poolCmd(rest) case "account-concurrency", "account-limit": return accountConcurrencyCmd(rest) + case "key-balance", "key-balances": + return keyBalanceCmd(rest) case "spend-cap", "spend-caps": return spendCapCmd(rest) case "account-weight", "account-weights": diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 0954cbb77..933d73cdb 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2877,13 +2877,13 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .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 :is(.aspend, .abal) { 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 :is(.aspend, .abal), .acc.held :is(.aspend, .abal), .acc :is(.aspend, .abal).open, .acc :is(.aspend, .abal).set { opacity: 1; } +.acc :is(.aspend, .abal):focus-visible { opacity: 1; } +.acc :is(.aspend, .abal).set { color: var(--fg); background: var(--pill-hover); box-shadow: none; } +.acc :is(.aspend, .abal).at-cap { color: var(--accent); background: var(--accent-soft); font-weight: 500; } +.acc :is(.aspend, .abal):hover, .acc :is(.aspend, .abal).open { color: var(--fg); background: var(--pill-hover); } +.acc :is(.aspend-in, .abal-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); } @@ -2944,9 +2944,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, .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 > :is(.amodels, .proto, .alane, .aspend, .abal), .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), .abal: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), .abal: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; } @@ -2954,17 +2954,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 > :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; } +.accts.keys .acc > :is(.alane, .aspend, .abal):not(.set):not(.open):not(:focus-visible) { padding: 0; box-shadow: none; background: none; } +.accts.keys .acc:not(:hover):not(.held) > :is(.alane, .aspend, .abal):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), .aspend: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), .abal: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 > :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 > :is(.alane, .aspend, .abal):not(.set):not(.open):not(:focus) { padding: 0; box-shadow: none; background: none; } + .accts.keys .acc:not(:hover):not(.held) > :is(.alane, .aspend, .abal):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; } @@ -4297,10 +4297,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, .aspend) { opacity: 1; } + body.web .acc :is(.text.quiet, .proto, .amodels, .alane, .aspend, .abal) { opacity: 1; } body.web .acc .acc-more { opacity: 1; } - 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 .acc > :is(.amodels, .proto, .alane, .aspend, .abal), 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, .abal):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/i18n.js b/internal/gui/assets/i18n.js index ddf2717fe..a164a5d67 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -34,6 +34,17 @@ const I18N = { "In all…": "累计…", "Counted from when it is set": "从设置时开始计算", "Spend cap, in USD": "消费上限(美元)", + "≈{usd} left": "≈{usd} 剩余", + "Set balance": "设置余额", + "An estimate: {set} typed {when}, less {spent} magpie counted spent on this key since, at the prices the Usage page shows. Click to type it again": "估算:{when} 填写的 {set},减去此后 magpie 按用量页价格算出的这个 key 已花费的 {spent}。点击重新填写", + "Type what the vendor's page says this key has left, and magpie counts down from it as it sends requests": "填入服务商页面显示的这个 key 剩余余额,magpie 会随请求从中扣减", + "{who} has no balance typed": "{who} 未填写余额", + "{who} has {usd} left": "{who} 剩余 {usd}", + "Balance, in USD": "余额(美元)", + "A balance is an amount in USD from 0 to 1,000,000": "余额是 0 到 1,000,000 之间的美元金额", + "Enter balance…": "填写余额…", + "Counts down from now": "从现在开始扣减", + "No balance": "无余额", "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}恢复", @@ -4715,6 +4726,17 @@ const I18N = { "In all…": "累計…", "Counted from when it is set": "從設定時開始計算", "Spend cap, in USD": "消費上限(美元)", + "≈{usd} left": "≈{usd} 剩餘", + "Set balance": "設定餘額", + "An estimate: {set} typed {when}, less {spent} magpie counted spent on this key since, at the prices the Usage page shows. Click to type it again": "估算:{when} 填寫的 {set},減去此後 magpie 依用量頁價格算出的這個 key 已花費的 {spent}。點擊重新填寫", + "Type what the vendor's page says this key has left, and magpie counts down from it as it sends requests": "填入服務商頁面顯示的這個 key 剩餘餘額,magpie 會隨請求從中扣減", + "{who} has no balance typed": "{who} 未填寫餘額", + "{who} has {usd} left": "{who} 剩餘 {usd}", + "Balance, in USD": "餘額(美元)", + "A balance is an amount in USD from 0 to 1,000,000": "餘額是 0 到 1,000,000 之間的美元金額", + "Enter balance…": "填寫餘額…", + "Counts down from now": "從現在開始扣減", + "No balance": "無餘額", "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}恢復", @@ -9381,6 +9403,17 @@ const I18N = { "In all…": "累計…", "Counted from when it is set": "設定した時点から数える", "Spend cap, in USD": "支出上限(USD)", + "≈{usd} left": "残り ≈{usd}", + "Set balance": "残高を設定", + "An estimate: {set} typed {when}, less {spent} magpie counted spent on this key since, at the prices the Usage page shows. Click to type it again": "推定:{when} に入力した {set} から、その後 magpie が使用量ページの価格でこのキーに数えた支出 {spent} を引いた額。クリックで入力し直す", + "Type what the vendor's page says this key has left, and magpie counts down from it as it sends requests": "ベンダーのページに表示されるこのキーの残高を入力すると、magpie がリクエストごとに差し引きます", + "{who} has no balance typed": "{who} の残高は未入力", + "{who} has {usd} left": "{who} の残り {usd}", + "Balance, in USD": "残高(USD)", + "A balance is an amount in USD from 0 to 1,000,000": "残高は 0 から 1,000,000 までの USD 金額です", + "Enter balance…": "残高を入力…", + "Counts down from now": "今から差し引く", + "No balance": "残高なし", "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}に復帰", @@ -14049,6 +14082,17 @@ const I18N = { "In all…": "Insgesamt…", "Counted from when it is set": "Ab dem Festlegen gezählt", "Spend cap, in USD": "Ausgabenlimit in USD", + "≈{usd} left": "≈{usd} übrig", + "Set balance": "Guthaben festlegen", + "An estimate: {set} typed {when}, less {spent} magpie counted spent on this key since, at the prices the Usage page shows. Click to type it again": "Geschätzt: {set}, eingegeben {when}, abzüglich {spent}, die magpie seitdem für diesen Schlüssel zu den Preisen der Nutzungsseite gezählt hat. Klicken, um es neu einzugeben", + "Type what the vendor's page says this key has left, and magpie counts down from it as it sends requests": "Gib ein, was die Seite des Anbieters für diesen Schlüssel als Guthaben zeigt, und magpie zählt davon mit jeder Anfrage herunter", + "{who} has no balance typed": "{who} hat kein eingegebenes Guthaben", + "{who} has {usd} left": "{who} hat noch {usd}", + "Balance, in USD": "Guthaben in USD", + "A balance is an amount in USD from 0 to 1,000,000": "Ein Guthaben ist ein Betrag in USD von 0 bis 1.000.000", + "Enter balance…": "Guthaben eingeben…", + "Counts down from now": "Zählt ab jetzt herunter", + "No balance": "Kein Guthaben", "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}", diff --git a/internal/gui/assets/keybalance.js b/internal/gui/assets/keybalance.js new file mode 100644 index 000000000..863d2852f --- /dev/null +++ b/internal/gui/assets/keybalance.js @@ -0,0 +1,40 @@ +// A key's balance typed by hand (tenacious_eagle on Discord): for a key +// whose vendor tells no balance magpie can read, the user types what the +// vendor's page says is left, and magpie counts down from it by what its +// own usage prices the calls it sends on the key (provider/ +// key_balance_own.go). Typing it again sets it anew. keyspend.js imports this +// when the provider editor draws a key's row, so it weighs nothing on the +// core. +const usdText = (v) => (v < 0 ? "-$" : "$") + Math.abs(v).toFixed(2); +function keyBalancePill(p, k) { + const b = k.balance, name = k.name || k.masked; + const pill = el("button", "abal" + (b ? " set" : "")); + pill.type = "button"; + const left = b ? b.set - (b.spent || 0) : 0; + pill.textContent = b ? t("≈{usd} left", { usd: usdText(left) }) : t("Set balance"); + pill.title = b ? t("An estimate: {set} typed {when}, less {spent} magpie counted spent on this key since, at the prices the Usage page shows. Click to type it again", { set: usdText(b.set), when: new Date(b.at).toLocaleString(intlLang()), spent: usdText(b.spent || 0) }) + : t("Type what the vendor's page says this key has left, and magpie counts down from it as it sends requests"); + const set = (usd) => accountAction("provider/keyownbalance", { id: p.id, account: k.id, balance: usd }, + usd == null ? t("{who} has no balance typed", { who: name }) : t("{who} has {usd} left", { who: name, usd: usdText(usd) })); + const amount = (s) => { const n = Number(s.replace(/^\$/, "").replace(/,/g, "").trim()); return s && n >= 0 && n <= 1e6 ? n : null; }; + const type = () => pillNumber(pill, b ? String(b.set) : "", "USD", "abal-in", t("Balance, in USD"), amount, t("A balance is an amount in USD from 0 to 1,000,000"), null, set); + pill.onclick = (e) => { + e.stopPropagation(); + if (!b) return type(); + if (pill.classList.contains("open")) return closeProtoMenu(); + openProtoMenu(pill, [ + { v: "set", name: "Enter balance…", note: "Counts down from now" }, + { v: "off", name: "No balance", note: "" }, + ], "", (v) => v === "off" ? set(null) : type(), "Balance", "sess-menu"); + }; + return pill; +} + +// keyBalanceFill puts key k's typed balance pill in its row, before the +// gap, when p's vendor tells no balance of its own +window.keyBalanceFill = function (row, p, k) { + row.querySelector(":scope > .abal")?.remove(); + if (!p.takesOwnBalance || p.balanceFound) return; + const pill = keyBalancePill(p, k), gap = row.querySelector(":scope > .grow"); + gap ? gap.before(pill) : row.append(pill); +}; diff --git a/internal/gui/assets/keyspend.js b/internal/gui/assets/keyspend.js index 6443ce107..59607d1fe 100644 --- a/internal/gui/assets/keyspend.js +++ b/internal/gui/assets/keyspend.js @@ -51,6 +51,9 @@ function keySpendLine(k) { // 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) { + // and its typed balance, in keybalance.js, for a provider that takes one + if (window.keyBalanceFill) keyBalanceFill(row, p, k); + else if (p.takesOwnBalance) import("./keybalance.js").then(() => keyBalanceFill(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"); diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index 5cf38821d..1ed75f0b0 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); 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); Claude Code's status line square beside ultracode (steven_4422 on Discord), in app.js, paid for by foldSame's comment cut, no raise (11-03); Codex's Restart the app when magpie switches its account tick (atom0964 on Discord), in app.js, paid for by five account-row comments cut, no raise (11-03); over it at 1,534,154 (#5139), 1,533,125 at e928b57f0, 677 bytes under it, and 1,525,207 with Settings › Sync's server form (davForm: WebDAV, S3 and GitHub) moved out to syncfiles.js, loaded when it opens, not lowered since what is left plus 1.5% is over it (11-04); a Mac window's page letting go of its layers after 30s out of sight (#5530, Matrix on Discord), in app.js, paid for by four comments cut, no raise (11-06); a plugin's tools hidden from every agent from its Plugins row (chengming0v0 on Discord), in plugins.js, paid for by two comments cut, no raise (11-07) + 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); Claude Code's status line square beside ultracode (steven_4422 on Discord), in app.js, paid for by foldSame's comment cut, no raise (11-03); Codex's Restart the app when magpie switches its account tick (atom0964 on Discord), in app.js, paid for by five account-row comments cut, no raise (11-03); over it at 1,534,154 (#5139), 1,533,125 at e928b57f0, 677 bytes under it, and 1,525,207 with Settings › Sync's server form (davForm: WebDAV, S3 and GitHub) moved out to syncfiles.js, loaded when it opens, not lowered since what is left plus 1.5% is over it (11-04); a Mac window's page letting go of its layers after 30s out of sight (#5530, Matrix on Discord), in app.js, paid for by four comments cut, no raise (11-06); a plugin's tools hidden from every agent from its Plugins row (chengming0v0 on Discord), in plugins.js, paid for by two comments cut, no raise (11-07); a key's balance typed by hand (tenacious_eagle on Discord), its pill in keybalance.js, loaded by keyspend.js when the provider editor draws a key of a provider that takes one, nothing in app.js, no raise (11-08) ) func TestCoreScriptBudget(t *testing.T) { diff --git a/internal/gui/key_own_balance_test.go b/internal/gui/key_own_balance_test.go new file mode 100644 index 000000000..a119e7cc2 --- /dev/null +++ b/internal/gui/key_own_balance_test.go @@ -0,0 +1,83 @@ +package gui + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// A key's balance typed by hand (tenacious_eagle on Discord), through the +// GUI's own routes: provider/keyownbalance sets it, /api/providers says +// the provider takes one and what is left of it, saving the editor keeps +// it, and none takes it off. +func TestKeyOwnBalanceRoutes(t *testing.T) { + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("APPDATA", filepath.Join(h, "AppData")) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) + t.Setenv("XDG_DATA_HOME", filepath.Join(h, ".data")) + mux := http.NewServeMux() + providerRoutes(mux, nil) + call := func(method, path, body string) string { + t.Helper() + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body))) + if w.Code != 200 { + t.Fatalf("%s: %d %s", path, w.Code, w.Body) + } + return w.Body.String() + } + key := provider.KeyID("sk-a") + type keyRow struct { + ID string `json:"id"` + Balance *provider.BalanceEstimate `json:"balance"` + } + listed := func() (bool, *provider.BalanceEstimate) { + t.Helper() + var out struct { + Providers []struct { + ID string `json:"id"` + TakesOwnBalance bool `json:"takesOwnBalance"` + KeyList []keyRow `json:"keyList"` + } `json:"providers"` + } + if err := json.Unmarshal([]byte(call("GET", "/api/providers", "")), &out); err != nil { + t.Fatal(err) + } + for _, p := range out.Providers { + if p.ID != "relay" { + continue + } + for _, k := range p.KeyList { + if k.ID == key { + return p.TakesOwnBalance, k.Balance + } + } + } + t.Fatal("relay's key not listed") + return false, nil + } + call("POST", "/api/provider/save", `{"id":"relay","name":"Relay","chat":"http://127.0.0.1:1/v1","key":"sk-a","new":true}`) + if takes, b := listed(); !takes || b != nil { + t.Fatalf("before: takes %v, balance %+v", takes, b) + } + call("POST", "/api/provider/keyownbalance", `{"id":"relay","account":"`+key+`","balance":20}`) + if _, b := listed(); b == nil || b.Set != 20 || b.At.IsZero() { + t.Fatalf("typed 20: %+v", b) + } + call("POST", "/api/provider/save", `{"id":"relay","from":"relay","name":"Relay 2","chat":"http://127.0.0.1:1/v1","key":""}`) + if _, b := listed(); b == nil || b.Set != 20 { + t.Fatalf("the editor saved, the balance typed is gone: %+v", b) + } + call("POST", "/api/provider/keyownbalance", `{"id":"relay","account":"`+key+`","balance":null}`) + if _, b := listed(); b != nil { + t.Fatalf("taken off: %+v", b) + } +} diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 228feee36..6a4e7c956 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -193,7 +193,10 @@ type providerJSON struct { // Balance URL, and its field (provider.BalanceFound) BalanceFound string `json:"balanceFound,omitempty"` BalanceFoundField string `json:"balanceFoundField,omitempty"` - ModelsURL string `json:"modelsURL,omitempty"` + // its keys may have a balance typed by hand, their vendor telling + // none (provider.TakesOwnBalance) + TakesOwnBalance bool `json:"takesOwnBalance,omitempty"` + ModelsURL string `json:"modelsURL,omitempty"` // an account-wide balance token (provider.BalanceToken): whether the // vendor takes one, and whether one is saved; never the token itself BalanceToken struct { @@ -856,6 +859,16 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs } out.KeyList[i].Spend = ks } + // and one with a balance typed, what is left of it (the card on the + // Usage page shows the same, provider.ownBalanceCard) + out.TakesOwnBalance = p.TakesOwnBalance() + for i, k := range out.KeyList { + b, ok := p.KeyOwnBalance(k.ID) + if !ok { + continue + } + out.KeyList[i].Balance = &provider.BalanceEstimate{Set: b.USD, At: b.At, Spent: usage.KeySpent(k.ID, b.At)} + } if !out.Key.Set && p.Ready() { out.Key.Optional = true } @@ -1634,6 +1647,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) { // (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"` + // Balance, for keyownbalance: the balance in USD typed for the + // key Account (its id), counted from now; none takes it off + Balance *float64 `json:"balance"` // Alias, for accountname: the account's name of the user's // own, "" to take it off (#1515) Alias string `json:"alias"` @@ -2038,8 +2054,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) { in.AccountCaps, in.AccountWindowCaps = old.AccountCaps, old.AccountWindowCaps in.AccountConcurrency = old.AccountConcurrency in.AccountWeights = old.AccountWeights - in.AccountNames = old.AccountNames // with accountname - in.KeySpendCaps = old.KeySpendCaps // with keyspendcap + in.AccountNames = old.AccountNames // with accountname + in.KeySpendCaps = old.KeySpendCaps // with keyspendcap + in.KeyOwnBalances = old.KeyOwnBalances // with keyownbalance } // the image models unticked in its editor likewise: [] // shows them all (321sssrt on X) @@ -2326,6 +2343,11 @@ func providerRoutes(mux *http.ServeMux, w Windows) { fail(rw, err) return } + case "keyownbalance": + if err := provider.SetKeyOwnBalance(in.ID, req.Account, req.Balance); 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-own-balance.test.cjs b/internal/gui/tests/key-own-balance.test.cjs new file mode 100644 index 000000000..b4ffaa6ba --- /dev/null +++ b/internal/gui/tests/key-own-balance.test.cjs @@ -0,0 +1,178 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A key's balance typed by hand (tenacious_eagle on Discord: a provider +// with no balance URL). Where the vendor tells no balance, each key's row +// has a pill: what is left of the balance typed, marked as an estimate +// (≈), else Set balance (hover-only, as the row's other unset pills). +// Set balance opens the amount in place; a balance set opens the app's +// menu (no native select): Enter balance… or No balance, posted to +// provider/keyownbalance. 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" }, + takesOwnBalance: true, + keyList: [ + { id: "k1", name: "Main", masked: "sk-…one", on: true, balance: { set: 20, at: new Date(Date.now() - 864e5).toISOString(), spent: 7.5 } }, + { id: "k2", name: "Team", masked: "sk-…two", 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 === "keyownbalance") { + const k = relay.keyList.find((x) => x.id === body.account); + if (body.balance != null) k.balance = { set: body.balance, at: new Date().toISOString(), spent: 0 }; + else delete k.balance; + } + 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: "≈$12.50 left", none: "Set balance", menu: "Balance", enter: "Enter balance…", off: "No balance", k2: "≈$5.00 left", k1again: "≈$40.00 left", bad: "A balance is an amount in USD from 0 to 1,000,000" }, + zh: { k1: "≈$12.50 剩余", none: "设置余额", menu: "余额", enter: "填写余额…", off: "无余额", k2: "≈$5.00 剩余", k1again: "≈$40.00 剩余", bad: "余额是 0 到 1,000,000 之间的美元金额" }, + "zh-TW": { k1: "≈$12.50 剩餘", none: "設定餘額", menu: "餘額", enter: "填寫餘額…", off: "無餘額", k2: "≈$5.00 剩餘", k1again: "≈$40.00 剩餘", bad: "餘額是 0 到 1,000,000 之間的美元金額" }, + ja: { k1: "残り ≈$12.50", none: "残高を設定", menu: "残高", enter: "残高を入力…", off: "残高なし", k2: "残り ≈$5.00", k1again: "残り ≈$40.00", bad: "残高は 0 から 1,000,000 までの USD 金額です" }, + de: { k1: "≈$12.50 übrig", none: "Guthaben festlegen", menu: "Guthaben", enter: "Guthaben eingeben…", off: "Kein Guthaben", k2: "≈$5.00 übrig", k1again: "≈$40.00 übrig", bad: "Ein Guthaben ist ein Betrag in USD von 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 balance typed by hand shows what is left as an estimate, and is typed again or taken off`, 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-own-balance.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 .abal").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(".abal"); + const box = (id) => row(id).locator("input.abal-in"); + 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.none); + assert.equal(await page.locator("select").count(), 0, "no native select"); + // a balance typed is always shown; none 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"); + 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"); + + // k2: none typed, so the amount opens in place; a bad one is refused + await still("k2"); + await box("k2").waitFor(); + let n = posts.length; + await box("k2").fill("lots"); + await box("k2").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); + // the Enter that was refused can press the pill drawn in the + // field's place, which opens the field again: type in it, else + // press the pill + await page.waitForTimeout(300); + if (!(await box("k2").isVisible())) await still("k2"); + await box("k2").waitFor(); + await box("k2").fill("$5"); + await box("k2").press("Enter"); + let p = await posted(n); + assert.equal(p.action, "keyownbalance"); + assert.deepEqual(p.body, { id: "relay", account: "k2", balance: 5 }); + await page.waitForTimeout(250); + assert.equal(await pill("k2").textContent(), w.k2); + + // k1: typed again from the menu, then taken off + await still("k1"); + await menu.waitFor(); + assert.equal(await menu.locator(".pm-head").textContent(), w.menu); + await item(w.enter).click(); + await box("k1").waitFor(); + assert.equal(await box("k1").inputValue(), "20"); + n = posts.length; + await box("k1").fill("40"); + await box("k1").press("Enter"); + p = await posted(n); + assert.deepEqual(p.body, { id: "relay", account: "k1", balance: 40 }); + await page.waitForTimeout(250); + assert.equal(await pill("k1").textContent(), w.k1again); + await still("k1"); + await menu.waitFor(); + n = posts.length; + await item(w.off).click(); + p = await posted(n); + assert.deepEqual(p.body, { id: "relay", account: "k1", balance: null }); + await page.waitForTimeout(250); + assert.equal(await pill("k1").textContent(), w.none); + + const stripes = await page.evaluate(() => [...document.querySelectorAll(".abal, .abal-in")].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 83e459667..58ffa22ec 100644 --- a/internal/gui/tests/old-webkit.test.cjs +++ b/internal/gui/tests/old-webkit.test.cjs @@ -159,9 +159,10 @@ test("compat.js is the first of the page's own scripts", async () => { // Export or Import opens, agentcompact.js when an agent sheet holds Long // conversations, balfound.js when the editor draws a relay's balance // with no Balance URL, passerrors.js when it draws a key provider's - // Errors; the checks above + // Errors, keybalance.js when it draws a key whose vendor tells no + // balance; 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", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.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", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "keybalance.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/balance.go b/internal/provider/balance.go index 30c90643b..2f694c02f 100644 --- a/internal/provider/balance.go +++ b/internal/provider/balance.go @@ -1642,6 +1642,8 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { type job struct { p Provider user string + // own: the key's balance typed by hand, with nothing to ask + own bool } var jobs []job for _, p := range All() { @@ -1651,12 +1653,18 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { src, ok := balanceSourceOf(p) zen := !ok && openCodeZen(p) if !ok && !clineKeyCard(p) && !zen && !probesBalance(p) { + // a key with a balance the user typed: what is left of it + if p.TakesOwnBalance() { + for _, k := range ownBalanceKeys(p) { + jobs = append(jobs, job{k.p, k.user, true}) + } + } continue } others := 0 if src.token != "" || zen { // the account's balance is the same whichever key asks - jobs = append(jobs, job{p, ""}) + jobs = append(jobs, job{p, "", false}) continue } for _, k := range p.Keys { @@ -1670,7 +1678,7 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { keyCard := func(q Provider) bool { return !ok || hasBalanceSource(q) } if others == 0 { if keyCard(p.atKeyPlan(p.KeyPlan)) { - jobs = append(jobs, job{p, ""}) + jobs = append(jobs, job{p, "", false}) } continue } @@ -1681,7 +1689,7 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { // each key asked at its own plan's host (KeyAccount.Plan): // SiliconFlow's China key and its international one if q := p.atKeyPlan(p.KeyPlan); keyCard(q) { - jobs = append(jobs, job{q, first}) + jobs = append(jobs, job{q, first, false}) } for _, k := range p.Keys { if k.Off || k.Key == "" || k.Key == p.Key { @@ -1696,7 +1704,7 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { if name == "" { name = Mask(k.Key) } - jobs = append(jobs, job{q, name}) + jobs = append(jobs, job{q, name, false}) } } jobs = slices.DeleteFunc(jobs, func(j job) bool { @@ -1710,6 +1718,10 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { go func() { defer wg.Done() defer slots.take(ctx, j.p.ID)() + if j.own { + out[i], _ = ownBalanceCard(j.p, j.p.Key, j.user) + return + } q := SubscriptionQuota{Provider: j.p.ID, Name: j.p.Name, Icon: j.p.Icon, User: j.user, Windows: []QuotaWindow{}} if clineKeyCard(j.p) { // ClinePass's limits beside the credits (cline_usage.go) @@ -1727,7 +1739,12 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { } amount, parts, split, ws, wide, _, err := balanceRead(ctx, j.p) if errors.Is(err, errNoBalance) { - return // a reply with no balance for this key: no card + // a reply with no balance for this key, or a relay where + // none was found: the balance typed for it, else no card + if j.p.TakesOwnBalance() { + out[i], _ = ownBalanceCard(j.p, j.p.Key, j.user) + } + return } if errors.Is(err, errOpenCodeNoBalance) { // nothing to read or keep: where the balance is shown @@ -1762,8 +1779,9 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { wg.Wait() out = slices.DeleteFunc(out, func(q SubscriptionQuota) bool { return q.Provider == "" }) if ctx.Err() == nil { - // each balance kept, and drawn over time with its runs-out - noteBalanceHistory(out, time.Now()) + // each balance kept, and drawn over time with its runs-out; not + // one estimated from a balance typed, which is no reading + noteBalanceHistory(slices.DeleteFunc(slices.Clone(out), func(q SubscriptionQuota) bool { return q.Estimate != nil }), time.Now()) // the history of the cards read now and of those kept, a partial // read (one card's refresh) keeping the others h := sharedBalanceHist(slices.Concat(kept, out)) diff --git a/internal/provider/key_balance_own.go b/internal/provider/key_balance_own.go new file mode 100644 index 000000000..18cd2112b --- /dev/null +++ b/internal/provider/key_balance_own.go @@ -0,0 +1,231 @@ +package provider + +// A key's balance typed by hand (tenacious_eagle on Discord): for a key +// whose vendor tells no balance, at no Balance URL magpie knows or finds, +// the user types what the vendor's own page says is left. The key's card +// then shows that less what magpie's own usage prices the calls it sent +// on the key since, marked as an estimate ("≈$12.34"). Typing the balance +// again sets it anew, from then. +// +// A balance the vendor tells always wins: a key with a balance source, or +// whose relay's query is found (balance_probe.go), shows that, and the +// typed one stays saved, unused, as the user left it. + +import ( + "fmt" + "math" + "strconv" + "strings" + "time" +) + +// OwnBalance is a key's balance as the user typed it: USD left at At. +type OwnBalance struct { + USD float64 `json:"usd"` + At time.Time `json:"at"` +} + +// MaxOwnBalance bounds a balance typed by hand, in USD. +const MaxOwnBalance = 1_000_000 + +// BalanceEstimate is what a card shows of a balance typed by hand: the +// amount typed, when, and what magpie counted spent on the key since. +type BalanceEstimate struct { + Set float64 `json:"set"` + At time.Time `json:"at"` + Spent float64 `json:"spent"` +} + +// KeySpent is usage.KeySpent, which package usage sets: what the calls +// magpie sent on the key keyID from start on cost, in USD. nil (a test +// of this package alone) counts nothing. +var KeySpent func(keyID string, start time.Time) float64 + +// KeyOwnBalance is the balance typed for p's key keyID, and whether it +// has one. +func (p Provider) KeyOwnBalance(keyID string) (OwnBalance, bool) { + b, ok := p.KeyOwnBalances[strings.ToLower(keyID)] + return b, ok +} + +// TakesOwnBalance says p's keys may have a balance typed by hand: keys +// whose vendor tells none magpie knows where to ask. A relay whose query +// is looked for (probesBalance) takes one too: when none is found, the +// typed balance is shown. +func (p Provider) TakesOwnBalance() bool { + if p.Account != nil || p.Key == "" { + return false + } + if hasBalanceSource(p) || clineKeyCard(p) || openCodeZen(p) { + return false + } + _, plan := planQuotaSourceOf(p) + return !plan +} + +// ownBalanceCard is the card of key (one of p's) with a balance typed by +// hand, user naming it when p has several: what was typed less what was +// spent since. false when the key has none. +func ownBalanceCard(p Provider, key, user string) (SubscriptionQuota, bool) { + id := keyID(key) + b, ok := p.KeyOwnBalance(id) + if !ok { + return SubscriptionQuota{}, false + } + var spent float64 + if KeySpent != nil { + spent = KeySpent(id, b.At) + } + now := time.Now() + return SubscriptionQuota{ + Provider: p.ID, Name: p.Name, Icon: p.Icon, User: user, Windows: []QuotaWindow{}, + Balance: ownBalanceText(b.USD - spent), + Estimate: &BalanceEstimate{Set: b.USD, At: b.At, Spent: spent}, + ReadAt: &now, + }, true +} + +// ownBalanceText is an estimated balance as a card shows it, "≈$12.34", +// below nothing as "≈$-1.20": the calls priced since went past it. +func ownBalanceText(usd float64) string { + if math.Abs(usd) < 0.005 { + usd = 0 + } + return fmt.Sprintf("≈$%.2f", usd) +} + +// SetKeyOwnBalance gives the key ref (its id or name) of the provider id +// the balance usd, counted from now; nil takes it off. +func SetKeyOwnBalance(id, ref string, usd *float64) error { + if usd != nil { + if err := checkOwnBalance(*usd); 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 balance typed by hand is for an API key", 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]OwnBalance{} + for id, v := range p.KeyOwnBalances { + m[id] = v + } + if usd == nil { + if _, had := m[k]; !had { + return nil + } + delete(m, k) + } else { + m[k] = OwnBalance{USD: *usd, At: time.Now().UTC()} + } + p.KeyOwnBalances = m + if err := Save(*p); err != nil { + return err + } + // the cards are drawn again with it; what routing knows of each + // key's allowance stays, as a typed balance tells routing nothing + keyBalanceCache.Lock() + keyBalanceCache.data = nil + keyBalanceCache.Unlock() + return nil +} + +// checkOwnBalance says what is wrong with a balance typed, nil when +// nothing is. +func checkOwnBalance(usd float64) error { + if !(usd >= 0 && usd <= MaxOwnBalance) { + return fmt.Errorf("a balance is an amount in USD from 0 to %d, not %v", MaxOwnBalance, usd) + } + return nil +} + +// ParseOwnBalance reads a balance as the CLI takes it, an amount in USD +// ("20", "$20", "12.5"); off for none (nil). +func ParseOwnBalance(amount string) (*float64, error) { + a := strings.ToLower(strings.TrimSpace(amount)) + switch a { + case "off", "none", "no", "-": + return nil, nil + } + usd, err := strconv.ParseFloat(strings.ReplaceAll(strings.TrimPrefix(a, "$"), ",", ""), 64) + if err != nil { + return nil, fmt.Errorf("a balance is an amount in USD (20, 12.5) or off, not %q", amount) + } + if err := checkOwnBalance(usd); err != nil { + return nil, err + } + return &usd, nil +} + +// normalKeyOwnBalances is m as it is kept: key ids in lower case, a +// balance out of bounds left out; nil for none. One written by hand with +// no date counts from the start of the usage log. +func normalKeyOwnBalances(m map[string]OwnBalance) map[string]OwnBalance { + var out map[string]OwnBalance + for k, b := range m { + k = strings.ToLower(strings.TrimSpace(k)) + if k == "" || checkOwnBalance(b.USD) != nil { + continue + } + if out == nil { + out = map[string]OwnBalance{} + } + out[k] = b + } + return out +} + +// ownKey is one of a provider's keys with a balance typed for it: the +// provider as asked with that key, and the card's user, its name when +// the provider has several keys on, as KeyBalances names a key's card. +type ownKey struct { + p Provider + user string +} + +// ownBalanceKeys are p's keys on that have a balance typed for them. +func ownBalanceKeys(p Provider) []ownKey { + if len(p.KeyOwnBalances) == 0 { + return nil + } + others := 0 + for _, k := range p.Keys { + if !k.Off && k.Key != "" && k.Key != p.Key { + others++ + } + } + var out []ownKey + if _, ok := p.KeyOwnBalance(keyID(p.Key)); ok { + user := "" + if others > 0 { + if user = p.KeyName; user == "" { + user = Mask(p.Key) + } + } + out = append(out, ownKey{p, user}) + } + for _, k := range p.Keys { + if k.Off || k.Key == "" || k.Key == p.Key { + continue + } + if _, ok := p.KeyOwnBalance(keyID(k.Key)); !ok { + continue + } + q := p + q.Key = k.Key + name := k.Name + if name == "" { + name = Mask(k.Key) + } + out = append(out, ownKey{q, name}) + } + return out +} diff --git a/internal/provider/key_balance_own_test.go b/internal/provider/key_balance_own_test.go new file mode 100644 index 000000000..5c6a4ad4f --- /dev/null +++ b/internal/provider/key_balance_own_test.go @@ -0,0 +1,200 @@ +package provider + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" +) + +// spentStub counts what each key spent, as usage.KeySpent would, and +// what start it was asked from. +func spentStub(t *testing.T, spent map[string]float64) map[string]time.Time { + t.Helper() + asked := map[string]time.Time{} + var mu sync.Mutex // the cards are drawn at once + old := KeySpent + KeySpent = func(id string, start time.Time) float64 { + mu.Lock() + defer mu.Unlock() + asked[id] = start + return spent[id] + } + t.Cleanup(func() { KeySpent = old }) + return asked +} + +func ownCards(t *testing.T) map[string]SubscriptionQuota { + t.Helper() + keyBalanceCache.Lock() + keyBalanceCache.data = nil + keyBalanceCache.Unlock() + out := map[string]SubscriptionQuota{} + for _, q := range KeyBalances(context.Background()) { + out[q.Provider+"|"+q.User] = q + } + return out +} + +// A key whose vendor tells no balance (tenacious_eagle on Discord): the +// user types what the vendor's page says is left, and its card shows that +// less what magpie priced the calls it sent on the key since, marked as +// an estimate. Typing it again counts from then; off takes the card +// away. A key with none typed has no card, nor does a key turned off, and +// an estimate is no reading the balance history keeps. +func TestTypedBalanceCountsDown(t *testing.T) { + probeSandbox(t) + probeLocal = false // a relay on this computer is never looked at + main, spare, off := keyID("sk-main"), keyID("sk-spare"), keyID("sk-off") + asked := spentStub(t, map[string]float64{main: 7.5, spare: 3, off: 1}) + if err := Save(Provider{ID: "plain", Name: "Plain", Chat: "http://127.0.0.1:1/v1", Key: "sk-main", KeyName: "Main", + Keys: []KeyAccount{{Name: "Spare", Key: "sk-spare"}, {Name: "Idle", Key: "sk-idle"}, {Name: "Off", Key: "sk-off", Off: true}}}); err != nil { + t.Fatal(err) + } + p, _ := Find("plain") + if !p.TakesOwnBalance() { + t.Fatal("a key with no balance source takes none typed") + } + if c := ownCards(t); len(c) != 0 { + t.Fatalf("cards with nothing typed: %+v", c) + } + twenty, one := 20.0, 1.0 + before := time.Now().UTC() + for _, s := range []struct { + ref string + usd *float64 + }{{"Main", &twenty}, {spare, &one}, {"Off", &one}} { + if err := SetKeyOwnBalance("plain", s.ref, s.usd); err != nil { + t.Fatal(err) + } + } + c := ownCards(t) + m, ok := c["plain|Main"] + if !ok || m.Balance != "≈$12.50" || m.Estimate == nil || m.Estimate.Set != 20 || m.Estimate.Spent != 7.5 || m.Estimate.At.Before(before) { + t.Fatalf("Main's card %+v (estimate %+v), want ≈$12.50 of 20 less 7.5 from now", m, m.Estimate) + } + if !asked[main].Equal(m.Estimate.At) { + t.Errorf("spent counted from %v, not from when it was typed %v", asked[main], m.Estimate.At) + } + if s := c["plain|Spare"]; s.Balance != "≈$-2.00" { + t.Errorf("Spare spent past what was typed: %q, want ≈$-2.00", s.Balance) + } + if n, ok := BalanceNumber(m.Balance); !ok || n != 12.5 { + t.Errorf("a low-balance alert reads %v %v from %q", n, ok, m.Balance) + } + if len(c) != 2 { + t.Errorf("cards %v: Idle has none typed and Off is off", c) + } + if bh := readBalanceHist(); len(bh) != 0 { + t.Errorf("an estimate kept in the balance history: %+v", bh) + } + + // typed again: counted from now + time.Sleep(10 * time.Millisecond) + thirty := 30.0 + if err := SetKeyOwnBalance("plain", "Main", &thirty); err != nil { + t.Fatal(err) + } + if again := ownCards(t)["plain|Main"]; again.Balance != "≈$22.50" || !again.Estimate.At.After(m.Estimate.At) { + t.Fatalf("typed again: %+v %+v", again, again.Estimate) + } + // off: no card, and nothing to take off is no error + if err := SetKeyOwnBalance("plain", "Main", nil); err != nil { + t.Fatal(err) + } + if err := SetKeyOwnBalance("plain", "Main", nil); err != nil { + t.Fatal(err) + } + if _, ok := ownCards(t)["plain|Main"]; ok { + t.Fatal("Main's card after its balance was taken off") + } + // the key's value replaced: its balance goes with it + if _, _, err := ReplaceKey("plain", spare, "sk-spare-2"); err != nil { + t.Fatal(err) + } + p, _ = Find("plain") + if b, ok := p.KeyOwnBalance(keyID("sk-spare-2")); !ok || b.USD != 1 { + t.Fatalf("the replaced key's balance %+v %v", b, ok) + } + // refused: a key the provider hasn't, an amount out of bounds + if err := SetKeyOwnBalance("plain", "nobody", &one); err == nil { + t.Error("a key the provider hasn't got a balance") + } + for _, bad := range []float64{-1, MaxOwnBalance + 1} { + if err := SetKeyOwnBalance("plain", "Spare", &bad); err == nil { + t.Errorf("%v was taken", bad) + } + } +} + +// A balance the vendor tells always wins: with a Balance URL the card is +// the vendor's, and the balance typed before stays saved as the user left +// it. A relay whose query is looked for and found none shows the typed one. +func TestToldBalanceWinsOverTyped(t *testing.T) { + probeSandbox(t) + spentStub(t, map[string]float64{keyID("sk-told"): 4}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/balance" { + w.Write([]byte(`{"left":2}`)) + return + } + w.Write([]byte(`ok`)) // no relay's query answers here + })) + defer srv.Close() + at := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC) + typed := map[string]OwnBalance{keyID("sk-told"): {USD: 50, At: at}} + if err := Save(Provider{ID: "told", Name: "Told", Chat: srv.URL + "/v1", Key: "sk-told", KeyOwnBalances: typed, + BalanceURL: srv.URL + "/balance", BalancePath: "$left"}); err != nil { + t.Fatal(err) + } + if err := Save(Provider{ID: "probed", Name: "Probed", Chat: srv.URL + "/v1", Key: "sk-told", KeyOwnBalances: typed}); err != nil { + t.Fatal(err) + } + p, _ := Find("told") + if p.TakesOwnBalance() { + t.Error("a provider with a Balance URL takes a balance typed") + } + c := ownCards(t) + if q := c["told|"]; q.Balance != "$2.00" || q.Estimate != nil { + t.Errorf("the vendor's balance %+v, want $2.00 and no estimate", q) + } + if q := c["probed|"]; q.Balance != "≈$46.00" || q.Estimate == nil { + t.Errorf("a relay with no balance found: %+v, want the typed ≈$46.00", q) + } + p, _ = Find("told") + if b, ok := p.KeyOwnBalance(keyID("sk-told")); !ok || b.USD != 50 || !b.At.Equal(at) { + t.Errorf("the typed balance was changed: %+v %v", b, ok) + } +} + +// What the CLI and a hand-edited providers.json may hold. +func TestOwnBalanceParsed(t *testing.T) { + for in, want := range map[string]float64{"20": 20, "$12.5": 12.5, " 1,234.50 ": 1234.5, "0": 0} { + if got, err := ParseOwnBalance(in); err != nil || got == nil || *got != want { + t.Errorf("%q: %v %v, want %v", in, got, err, want) + } + } + for _, in := range []string{"off", "none", "-"} { + if got, err := ParseOwnBalance(in); err != nil || got != nil { + t.Errorf("%q: %v %v, want none", in, got, err) + } + } + for _, in := range []string{"lots", "-5", "1000001", "NaN"} { + if _, err := ParseOwnBalance(in); err == nil { + t.Errorf("%q was taken", in) + } + } + n := normalKeyOwnBalances(map[string]OwnBalance{"ABC": {USD: 5}, "bad": {USD: -1}, " ": {USD: 1}}) + if len(n) != 1 || n["abc"].USD != 5 { + t.Errorf("normalised %+v", n) + } + if got := ownBalanceText(-0.001); got != "≈$0.00" { + t.Errorf("a hair below nothing reads %q", got) + } + if !strings.HasPrefix(ownBalanceText(3), "≈") { + t.Error("an estimate not marked") + } +} diff --git a/internal/provider/keys.go b/internal/provider/keys.go index 58825c92e..77836ef77 100644 --- a/internal/provider/keys.go +++ b/internal/provider/keys.go @@ -57,6 +57,9 @@ type KeyInfo struct { // Spend is the spend cap set on it and what it has spent in its // period; nil with none. Spend *KeySpend `json:"spend,omitempty"` + // Balance is the balance the user typed for it and what is left of + // it by magpie's count (key_balance_own.go); nil with none. + Balance *BalanceEstimate `json:"balance,omitempty"` } // KeySpend is a key's spend cap as its row tells it: the cap, what magpie @@ -666,6 +669,7 @@ func ReplaceKey(id, keyRef, key string) (was, now string, err error) { moveKeyed(p.AccountProxies, keyRef, now) moveKeyed(p.AccountConcurrency, keyRef, now) moveKeyed(p.KeySpendCaps, keyRef, now) + moveKeyed(p.KeyOwnBalances, keyRef, now) return keyRef, now, Save(*p) } diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 14c3cd42e..6ddf1bafe 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -506,6 +506,11 @@ type Provider struct { // 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"` + // KeyOwnBalances is, for a provider of API keys whose vendor tells no + // balance, what the user typed is left on each key, by its KeyID: the + // key's card shows it less what magpie priced its calls at since + // (see key_balance_own.go). + KeyOwnBalances map[string]OwnBalance `json:"keyOwnBalances,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 @@ -884,6 +889,7 @@ func (p Provider) clone() Provider { p.AccountCaps = maps.Clone(p.AccountCaps) p.AccountNames = maps.Clone(p.AccountNames) p.KeySpendCaps = maps.Clone(p.KeySpendCaps) + p.KeyOwnBalances = maps.Clone(p.KeyOwnBalances) if p.AccountWindowCaps != nil { m := make(map[string]map[string]int, len(p.AccountWindowCaps)) for k, v := range p.AccountWindowCaps { @@ -1665,6 +1671,7 @@ func normalize(p Provider) Provider { p.AccountWindowCaps = normalWindowCaps(p.AccountWindowCaps) p.AccountNames = normalAccountNames(p.AccountNames) p.KeySpendCaps = normalKeySpendCaps(p.KeySpendCaps) + p.KeyOwnBalances = normalKeyOwnBalances(p.KeyOwnBalances) if len(p.Models) > 0 { p.NoModels = false // a pick is no longer Select none } diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index 79078efc7..5f072a96d 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -166,6 +166,10 @@ type SubscriptionQuota struct { // BalanceTrend is the Balance over time, as magpie read it, and when // it runs out at that pace (balance_history.go) BalanceTrend *BalanceTrend `json:"balanceTrend,omitempty"` + // Estimate is set when the Balance is one the user typed less what + // magpie priced the key's calls at since (key_balance_own.go), not a + // vendor's reading + Estimate *BalanceEstimate `json:"estimate,omitempty"` // SharedBalance is set on each key of a provider found to read one // account's balance with others (balance_shared.go): the name of the // first of them, whose card shows it once for all diff --git a/internal/usage/spend.go b/internal/usage/spend.go index 9c5ab1ea3..0be86bd32 100644 --- a/internal/usage/spend.go +++ b/internal/usage/spend.go @@ -3,8 +3,13 @@ package usage import ( "sync" "time" + + "github.com/yetone/magpie/internal/provider" ) +// a key's balance typed by hand is shown less what this counts spent +func init() { provider.KeySpent = KeySpent } + // 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).