providers: a key with no balance URL takes a balance typed by hand, counted down by magpie's own usage
Some API-key providers tell no balance magpie can read (no Balance URL, no relay query found), so their keys showed none. Now the user types what the vendor's page says is left, on the key's row in the provider editor (Set balance) or with `magpie provider key-balance <id> [key [usd|off]]`. The key's card shows that less what magpie's usage priced the calls it sent on the key since it was typed (usage.KeySpent, the spend caps' count), marked as an estimate: "≈$12.50", the pill "≈$12.50 left", its title saying what was typed, when, and what was counted since. Typing it again counts from then; No balance takes it off. A balance the vendor tells always wins: a provider with a Balance URL, a plan source, Cline's or OpenCode Zen's card takes none typed, and a relay whose query is found shows its own; when the probe finds none (errNoBalance) the typed one is shown. A typed balance stays saved as the user left it: the editor's save keeps it, a key's replaced value carries it. An estimate is never kept in the balance history and tells routing nothing (the routing allowances cache is left alone). keybalance.js is loaded by keyspend.js (itself loaded when the editor draws a key) for a provider that takes one, so app.js and the core's script budget are unchanged. Words in zh, zh-TW, ja and de. Run at this tree (mote): - go vet ./... (darwin), GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... at base 46b10af87; at this tree go vet of gui, provider, cli and usage; - go test -tags nogui -count=1 ./internal/gui ./internal/provider ./internal/cli ./internal/usage: provider and usage ok; gui and cli red only on #5644 below; TestCoreScriptBudget ok (1,533,747, as main) - the provider tests under -race -count=3; - GUI: key-own-balance (new: Chromium and WebKit, en zh zh-TW ja de, 900 and 400px, 20/20), key-spend-cap, old-webkit, i18n-keys, gui-de, gui-ja, gui-zh-tw, balance-found, key-balance-card, i18n-en-no-cjk: 104 pass, 1 fail, i18n-keys "a plugin's words are its own", red the same on origin/main7a2946caf(#5327, #5332, #5482, #5426). Broken by hand, each went red: - estimates kept in the balance history: TestTypedBalanceCountsDown; - no fallback to the typed balance on errNoBalance: TestToldBalanceWinsOverTyped; - the editor's save dropping KeyOwnBalances: TestKeyOwnBalanceRoutes. Red on main, not this change: TestSettingsSaveKeepsWhatItDoesNotSend and TestSettingsCLISetsWhatTheWindowSaves (groupSink, groupFirstToken, groupPatience from6b7ee4a98), filed as #5644. Not tried: a real relay account with no balance URL (the cost counted is magpie's own estimate, so a vendor pricing differently drifts until the balance is typed again); the full Go and GUI suites before the push (run after it, under the suite lock); the GUI in the real Windows and Linux apps; routing does not use the estimate. Reported-by: tenacious_eagle (Discord)
This commit is contained in:
@@ -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 <id> [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 <id> <account> --window <name>`) 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 <id> [--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 <id> [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 <id> [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
|
||||
|
||||
@@ -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 <id> [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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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 <id> [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 <id> [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":
|
||||
|
||||
+18
-18
@@ -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; }
|
||||
|
||||
@@ -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}",
|
||||
|
||||
@@ -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);
|
||||
};
|
||||
@@ -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");
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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(`<html>ok</html>`)) // 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")
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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).
|
||||
|
||||
Reference in New Issue
Block a user