diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index d2cfbf365..0cedd8c11 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -361,7 +361,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 | cny, at, refill}`, [`key_balance_own.go`](../../internal/provider/key_balance_own.go); tenacious_eagle on Discord) is for a key whose vendor tells no balance magpie can read (`TakesOwnBalance`: an API key with no balance source, not Cline's or OpenCode Zen's, not on a plan's windows). The user types what the vendor's page says is left; the key's card on the Usage page and the tray then shows it less what the Usage page prices magpie's own calls on the key at since then (`usage.KeySpent` from `at`, through the `provider.KeySpent` hook usage sets), as `≈$12.50` with `Estimate` (`set`, `at`, `spent`) and below nothing as `≈$-2.00`. Typing it again counts from then. It is an estimate, not a reading: it is kept out of the balance history (no trend or runs-out), is never shared, and routing reads nothing from it; a low-balance alert reads its number. A balance the vendor tells always wins: with a Balance URL or a source magpie knows the card is the vendor's, and a relay whose query is looked for shows the typed one only when none is found (`errNoBalance`); the typed value stays saved as the user left it. `SetKeyOwnBalance` (GUI `provider/keyownbalance`, a pill in the key's row, "≈$12.50 left" or "Set balance", drawn by `keybalance.js` while `takesOwnBalance` and no balance was found; `magpie provider key-balance [key [usd|¥cny|off] [--refill …]]`) refuses a subscription, an amount outside 0 to `MaxOwnBalance` (1,000,000) in either currency, and any currency but USD and CNY; nil takes it off, `ReplaceKey` carries it to the new value, and saving the editor keeps it. It may be typed in yuan (`cny`, "¥100", or a bare number with ¥ CNY picked in the currency button beside the field, which starts at the balance's own currency, else Settings' one; picking keeps the number typed and posts nothing until the field is left or Enter is pressed, so a balance's currency changes without clearing it or going to Settings, tenacious_eagle on Discord): what is spent is counted in USD and turned into yuan at `fx.Known()`, the rate `internal/fx` last fetched (cached 12h in `fxrate.json`, fetched again in the background, never on the request path); `fx.Known` never hands out `fx.Fallback`, so with no rate fetched yet and something spent the left is unknown (`left` null, the card's `Error` says why) rather than a guess. It may refill (`refill`: `{every: month, day: 1–31}`, a day past the month's end meaning its last, or `{every: week, day: 1 Monday–7 Sunday}`), at midnight in the user's local time: nothing is stored on a refill; the spend is counted from the last refill boundary after `at` (`From`), and `Next` is the next one. Typing the amount again keeps the refill. `SetKeyBalanceRefill` (GUI `provider/keybalancerefill`, the pill's menu: Refills each month…, Refills each week…, Never refills; CLI `--refill monthly[:day]|weekly[:mon…sun]|off`) refuses a key with no balance. Each key with one gets `balance` in `/api/providers`' `keyList` (`set`, `at`, `spent`, `currency`, `rate`, `left`, `from`, `refill`, `next`). `TestKnownIsNeverAGuess`, `TestTypedBalanceInYuan`, `TestTypedBalanceRefills`, `TestRefillDays`, `TestTypedBalanceCountsDown`, `TestToldBalanceWinsOverTyped`, `TestOwnBalanceParsed`, `TestKeyOwnBalanceRoutes`, `key-own-balance.test.cjs`. +- A key's balance typed by hand (`KeyOwnBalances`, by the key's fingerprint: `{usd | cny, at, refill, expiring}`, [`key_balance_own.go`](../../internal/provider/key_balance_own.go); tenacious_eagle on Discord) is for a key whose vendor tells no balance magpie can read (`TakesOwnBalance`: an API key with no balance source, not Cline's or OpenCode Zen's, not on a plan's windows). The user types what the vendor's page says is left; the key's card on the Usage page and the tray then shows it less what the Usage page prices magpie's own calls on the key at since then (`usage.KeySpent` from `at`, through the `provider.KeySpent` hook usage sets), as `≈$12.50` with `Estimate` (`set`, `at`, `spent`) and below nothing as `≈$-2.00`. Typing it again counts from then. It is an estimate, not a reading: it is kept out of the balance history (no trend or runs-out), is never shared, and routing reads nothing from it; a low-balance alert reads its number. A balance the vendor tells always wins: with a Balance URL or a source magpie knows the card is the vendor's, and a relay whose query is looked for shows the typed one only when none is found (`errNoBalance`); the typed value stays saved as the user left it. `SetKeyOwnBalance` (GUI `provider/keyownbalance`, a pill in the key's row, "≈$12.50 left" or "Set balance", drawn by `keybalance.js` while `takesOwnBalance` and no balance was found; `magpie provider key-balance [key [usd|¥cny|off] [--refill …]]`) refuses a subscription, an amount outside 0 to `MaxOwnBalance` (1,000,000) in either currency, and any currency but USD and CNY; nil takes it off, `ReplaceKey` carries it to the new value, and saving the editor keeps it. It may be typed in yuan (`cny`, "¥100", or a bare number with ¥ CNY picked in the currency button beside the field, which starts at the balance's own currency, else Settings' one; picking keeps the number typed and posts nothing until the field is left or Enter is pressed, so a balance's currency changes without clearing it or going to Settings, tenacious_eagle on Discord): what is spent is counted in USD and turned into yuan at `fx.Known()`, the rate `internal/fx` last fetched (cached 12h in `fxrate.json`, fetched again in the background, never on the request path); `fx.Known` never hands out `fx.Fallback`, so with no rate fetched yet and something spent the left is unknown (`left` null, the card's `Error` says why) rather than a guess. It may refill (`refill`: `{every: month, day: 1–31}`, a day past the month's end meaning its last, or `{every: week, day: 1 Monday–7 Sunday}`), at midnight in the user's local time: nothing is stored on a refill; the spend is counted from the last refill boundary after `at` (`From`), and `Next` is the next one. Typing the amount again keeps the refill. `SetKeyBalanceRefill` (GUI `provider/keybalancerefill`, the pill's menu: Refills each month…, Refills each week…, Never refills; CLI `--refill monthly[:day]|weekly[:mon…sun]|off`) refuses a key with no balance. Part of it may expire (`expiring`: `{amount, until, at}`, the amount in the balance's currency, `until` the last day it counts as 2006-01-02; tenacious_eagle_96548 on Discord: money that stays and credit good until a date). That part is spent first, as DeepSeek spends its granted balance before the money topped up: it takes the spend from its `at` up to its end (midnight after `until`, local time) or now, and only what it took after `From` is off the rest, so a refill or typing the balance again doesn't count it twice. `left` is the whole balance, that part's remainder included; from its end the remainder counts no more (`expired`, the end), and unspent credit is simply gone. `SetKeyExpiring` (GUI `provider/keyexpiring` `{expiring: {amount, until} | null}`, the pill's menu: Credit that expires… takes the amount, then the last day, a day gone by refused; No credit that expires; CLI `--expiring amount@yyyy-mm-dd|off`) refuses a key with no balance typed (type the rest first, 0 when all of it expires), an amount not above 0 or past `MaxOwnBalance`, and a date that isn't one. Typing the balance again keeps the part in the same currency and drops it in the other, where its amount would mean another sum. A balance saved before has none and is counted as it was. The estimate's `expiring` (`set`, `at`, `left`, `ends`) is the pill's "≈$60.00 left · $20.00 expires in 30 days", and the card's `BalanceSplit` a line with `expires`, which the Usage page and the panel label "Expires in 30 days" (`expiresIn` in app.js), amber from a week; the TUI and CLI quota say "$20.00 until Dec 31" (`SplitWords`). Each key with one gets `balance` in `/api/providers`' `keyList` (`set`, `at`, `spent`, `currency`, `rate`, `left`, `from`, `refill`, `next`, `expiring`, `expired`). `TestTypedBalanceExpires`, `TestTypedBalanceSavedBeforeExpiring`, `TestExpiringParsed`, `key-balance-expiring.test.cjs`, `TestKnownIsNeverAGuess`, `TestTypedBalanceInYuan`, `TestTypedBalanceRefills`, `TestRefillDays`, `TestTypedBalanceCountsDown`, `TestToldBalanceWinsOverTyped`, `TestOwnBalanceParsed`, `TestKeyOwnBalanceRoutes`, `key-own-balance.test.cjs`. - A window whose reset time has passed has started again, whatever share it was read at (`resetPassed`). That holds for a reading kept from before (`AsOf`) and for a fresh one: Claude Code's `/usage` gives a reset to the minute and can lag it, so a run just after a reset can still say 100% with that reset. `claudeWindows` hands such a window back empty on every path, and `usedPast`, `usedUp`, `BackAt` and `capReached` leave it out when they judge an account spent, for Codex, Claude Code and `magpie quota wait` alike. A card can still show a kept reading as it was read (`reported`, for a Claude card while `/usage` is unavailable); that changes what it shows, never which account is used. A reset `/usage` gives as a time alone ("resets 3pm") can be read as its next one, a day on (`claudeResetTime`), and is then not seen as passed here. - 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 index b78887e6c..9adb3d410 100644 --- a/internal/cli/key_balance_cli.go +++ b/internal/cli/key_balance_cli.go @@ -3,11 +3,12 @@ package cli import ( "fmt" "strings" + "time" "github.com/yetone/magpie/internal/provider" ) -const keyBalanceUsage = "magpie provider key-balance [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|off]]" +const keyBalanceUsage = "magpie provider key-balance [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|off] [--expiring amount@yyyy-mm-dd|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 @@ -17,7 +18,7 @@ const keyBalanceUsage = "magpie provider key-balance [key [usd|¥cny|off] [ // counted down at the dollar's rate magpie last learned. func keyBalanceCmd(args []string) error { var rest []string - var refill *string + var refill, expiring *string for i := 0; i < len(args); i++ { a := args[i] switch { @@ -27,6 +28,12 @@ func keyBalanceCmd(args []string) error { case strings.HasPrefix(a, "--refill="): v := strings.TrimPrefix(a, "--refill=") refill = &v + case a == "--expiring" && i+1 < len(args): + i++ + expiring = &args[i] + case strings.HasPrefix(a, "--expiring="): + v := strings.TrimPrefix(a, "--expiring=") + expiring = &v case strings.HasPrefix(a, "-") && a != "-": // a flag magpie doesn't know, or a negative amount: never data return fmt.Errorf("%s", keyBalanceUsage) @@ -34,7 +41,7 @@ func keyBalanceCmd(args []string) error { rest = append(rest, a) } } - if len(rest) < 1 || len(rest) > 3 || (refill != nil && len(rest) < 2) { + if len(rest) < 1 || len(rest) > 3 || ((refill != nil || expiring != nil) && len(rest) < 2) { return fmt.Errorf("%s", keyBalanceUsage) } p, err := provider.Find(rest[0]) @@ -50,12 +57,18 @@ func keyBalanceCmd(args []string) error { return err } } + var x *provider.Expiring + if expiring != nil { + if x, err = provider.ParseExpiring(*expiring); err != nil { + return err + } + } var b *provider.OwnBalance if len(rest) > 2 { if b, err = provider.ParseOwnBalance(rest[2]); err != nil { return err } - if b == nil && refill != nil { + if b == nil && (refill != nil || expiring != nil) { return fmt.Errorf("%s", keyBalanceUsage) } } @@ -80,7 +93,13 @@ func keyBalanceCmd(args []string) error { return err } } - if len(rest) > 2 || refill != nil { + // the part that expires, set after the balance it is part of + if expiring != nil { + if err := provider.SetKeyExpiring(p.ID, rest[1], x); err != nil { + return err + } + } + if len(rest) > 2 || refill != nil || expiring != nil { if p, err = provider.Find(p.ID); err != nil { return err } @@ -144,5 +163,12 @@ func keyBalanceLine(e provider.BalanceEstimate) string { if e.Refill != nil && e.Next != nil { out += " · refills " + e.Refill.String() + ", next " + e.Next.Local().Format("Jan 2") } + if x := e.Expiring; x != nil && x.Left != nil { + out += fmt.Sprintf(" · of it %s expires (%s typed %s), counted through %s", money(*x.Left), money(x.Set), + x.At.Local().Format("Jan 2 15:04"), x.Ends.Add(-time.Second).Format("Jan 2")) + } + if e.Expired != nil { + out += " · the part that expired " + e.Expired.Add(-time.Second).Format("Jan 2") + " no longer counts" + } return out } diff --git a/internal/cli/key_balance_cli_test.go b/internal/cli/key_balance_cli_test.go index 8571d0037..4bcd796b6 100644 --- a/internal/cli/key_balance_cli_test.go +++ b/internal/cli/key_balance_cli_test.go @@ -74,6 +74,32 @@ func TestKeyBalanceCmd(t *testing.T) { if b, _ := typed(); b.Refill != nil || b.CNY == nil { t.Fatalf("refill off: %+v", b) } + // credit that expires (tenacious_eagle_96548): set beside the rest, + // kept when the balance is typed again in its currency, taken off + if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "--expiring", "200@2099-12-31"}); err != nil { + t.Fatal(err) + } + if b, _ := typed(); b.Expiring == nil || b.Expiring.Amount != 200 || b.Expiring.Until != "2099-12-31" || b.Expiring.At.IsZero() || *b.CNY != 700 { + t.Fatalf("--expiring 200@2099-12-31: %+v", b) + } + for _, bad := range [][]string{{"relay", "Team", "--expiring", "200"}, {"relay", "Team", "--expiring", "200@soon"}, {"relay", "Team", "--expiring", "¥200@2099-12-31"}, + {"relay", "Team", "--expiring", "0@2099-12-31"}, {"relay", "--expiring", "1@2099-12-31"}, {"relay", "Team", "off", "--expiring", "1@2099-12-31"}} { + if err := providerCmd(append([]string{"provider", "key-balance"}, bad...)); err == nil { + t.Fatalf("%v taken", bad) + } + } + if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "¥650"}); err != nil { + t.Fatal(err) + } + if b, _ := typed(); b.Expiring == nil || b.Expiring.Amount != 200 { + t.Fatalf("typed again in yuan, the part that expires went: %+v", b) + } + if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "--expiring=off"}); err != nil { + t.Fatal(err) + } + if b, _ := typed(); b.Expiring != nil || *b.CNY != 650 { + t.Fatalf("--expiring off: %+v", b) + } if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "off"}); err != nil { t.Fatal(err) } diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index 1d2a895f4..feb91146e 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -98,10 +98,11 @@ 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|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|off]] + magpie provider key-balance [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|off] [--expiring amount@yyyy-mm-dd|off]] the balance on an API key whose vendor tells none, typed from its own page in USD or in yuan (¥100): the Usage page shows it less what magpie prices the - key's calls at since; with --refill it is whole again each month or week + key's calls at since; with --refill it is whole again each month or week; + --expiring adds credit that counts through a day and is spent first 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) diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 93d47c429..82eb95480 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -1167,6 +1167,8 @@ body.masked :hover > .acct-eye, body.masked .pq-card:hover .acct-eye, body.maske .bal-part > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .bal-part b { font-size: 12.5px; color: var(--fg-2); } .bal-part.lead b { font-size: 15px; color: var(--fg); } +/* credit that expires within a week */ +.bal-part.soon, .bal-part.soon b, .pq-bp.soon, .pq-bp.soon b { color: var(--amber); } .bal-part .quota-track, .pq-card.bal .quota-track { grid-column: 1 / -1; margin-top: 4px; } .quota-track.full i { background: var(--amber); } .quota-read { flex-basis: 100%; margin-top: 2px; font-size: 10px; color: var(--muted); font-variant-numeric: tabular-nums; } @@ -2887,8 +2889,11 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .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 .abal-in.abal-day { width: 88px; } .acc .abal-cur { flex: none; display: inline-flex; align-items: center; gap: 1px; height: 24px; margin-left: -5px; padding: 0 3px 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); cursor: default; } .acc .abal-cur:hover, .acc .abal-cur.open { color: var(--fg); background: var(--pill-hover); } +.acc .abal .abal-exp { margin-left: .3em; } +.acc .abal .abal-exp.soon { color: var(--amber); } .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); } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index cc22e417e..0255f3611 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -17574,7 +17574,7 @@ function panelBalances(bals) { amount.append(el("b", "pq-amt", balanceText(p)), el("span", "", p.label)); card.append(amount); } else { - amount = el("span", "pq-sub pq-bp"); + amount = el("span", "pq-sub pq-bp" + (p.soon ? " soon" : "")); amount.append(el("span", "", p.label || ""), el("b", "", balanceText(p))); card.append(amount); } @@ -18358,8 +18358,6 @@ function fitQuotas() { quotaFitting.clear(); } function fitQuota(g) { - // a count's own width, its parts laid end to end: once stacked it spans - // the row and may be two lines, so its box no longer says const wide = (e) => [...e.children].reduce((w, c) => w + c.getBoundingClientRect().width, 0) + 4 * (e.children.length - 1); const wraps = [...g.querySelectorAll(".quota-labels")].some((l) => { const [name, n] = l.children; @@ -18372,20 +18370,16 @@ function fitQuota(g) { for (const l of ls) if (top[l.offsetTop] > h(l) + 0.5) l.style.minHeight = top[l.offsetTop] + "px"; } -// balanceRow: what is left on an account, as a figure; a balance field -// with several amounts, each on a line of its own, its label quiet and the -// first the one that counts, a percent a meter (amber from 90%, as the -// panel's rings) (#420). Under it, when it was read, unless the card -// says that under its windows (when false). +// balanceRow: what is left, a line per amount, the first the one that +// counts (#420); when it was read under it unless when is false function balanceRow(sub, why, when = true) { const parts = balanceShown(sub); const b = el("div", "quota-balance" + (parts?.length ? " parts" : "")); b.title = t(why); if (!parts?.length) b.append(el("span", "", t("Balance")), el("b", "", sub.balance)); for (const [i, p] of (parts || []).entries()) { - const row = el("div", "bal-part" + (i ? "" : " lead")); + const row = el("div", "bal-part" + (i ? "" : " lead") + (p.soon ? " soon" : "")); row.append(el("span", "", p.label || (i ? "" : t("Balance"))), el("b", "", balanceText(p))); - // an amount the reply hadn't, "—": why, on hover (#1993) if (p.error) row.title = p.error; if (p.percent != null) row.append(balanceMeter(p.percent)); b.append(row); @@ -18395,14 +18389,17 @@ function balanceRow(sub, why, when = true) { return b; } -// balanceShown: a balance's amounts each on a line, when it has several: -// a balance field's own, or the figure and what the vendor says it is -// made of (DeepSeek's granted credit and the money topped up, wwcraft_ on -// Discord), those labels in the user's language. null for one figure. +// balanceShown: a balance's amounts, when it has several (wwcraft_); a +// part that expires says in how many days (tenacious_eagle) function balanceShown(q) { if (q.balanceParts?.length) return q.balanceParts; if (!q.balanceSplit?.length) return null; - return [{ text: q.balance }, ...q.balanceSplit.map((p) => ({ ...p, label: t(p.label) }))]; + return [{ text: q.balance }, ...q.balanceSplit.map((p) => p.expires ? { ...p, ...expiresIn(p.expires) } : { ...p, label: t(p.label) })]; +} +// expiresIn: days until ends, soon within a week +function expiresIn(ends) { + const day = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate()), n = Math.round((day(new Date(new Date(ends) - 1)) - day(new Date())) / 864e5); + return { days: n, soon: n <= 7, label: n <= 0 ? t("Expires today") : n === 1 ? t("Expires tomorrow") : t("Expires in {n} days", { n }) }; } // balanceMeter: a balance field's percent, as a meter, filled as Left or diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 8d6c41986..4a3b9d4c6 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -48,6 +48,23 @@ const I18N = { "Balance, in CNY": "余额(人民币)", "The dollar's rate in yuan isn't known yet, so what is left can't be counted": "还不知道美元兑人民币的汇率,暂时算不出剩余多少", "Refills to {set} on {when}": "{when} 恢复为 {set}", + "Expires today": "今天到期", + "Expires tomorrow": "明天到期", + "Expires in {n} days": "{n} 天后到期", + "{amount} expires today": "{amount} 今天到期", + "{amount} expires tomorrow": "{amount} 明天到期", + "{amount} expires in {n} days": "{amount} {n} 天后到期", + "Of it, {left} of the {set} typed {when} is spent first and counts through {last}": "其中限期额度剩 {left}({when} 填写 {set}),优先扣除,算到 {last}", + "The credit that expired on {last} no longer counts": "{last} 到期的限期额度已不再计入", + "{who} has no credit that expires": "{who} 已去掉限期额度", + "{who} has {amount} that counts through {last}": "{who} 有 {amount} 限期额度,算到 {last}", + "Credit that expires, in CNY": "限期额度(人民币)", + "Credit that expires, in USD": "限期额度(美元)", + "Credit that expires is an amount above 0, in the balance's currency": "限期额度是大于 0 的金额,用余额的货币", + "Last day it counts": "最后一天", + "The last day is a date from today on, as 2026-12-31": "最后一天是今天或以后的日期,如 2026-12-31", + "Credit that expires…": "限期额度…", + "No credit that expires": "去掉限期额度", "Refills each month…": "每月恢复…", "Refills each week…": "每周恢复…", "Never refills": "不恢复", @@ -4767,6 +4784,23 @@ const I18N = { "Balance, in CNY": "餘額(人民幣)", "The dollar's rate in yuan isn't known yet, so what is left can't be counted": "還不知道美元兌人民幣的匯率,暫時算不出剩餘多少", "Refills to {set} on {when}": "{when} 恢復為 {set}", + "Expires today": "今天到期", + "Expires tomorrow": "明天到期", + "Expires in {n} days": "{n} 天後到期", + "{amount} expires today": "{amount} 今天到期", + "{amount} expires tomorrow": "{amount} 明天到期", + "{amount} expires in {n} days": "{amount} {n} 天後到期", + "Of it, {left} of the {set} typed {when} is spent first and counts through {last}": "其中限期額度剩 {left}({when} 填寫 {set}),優先扣除,算到 {last}", + "The credit that expired on {last} no longer counts": "{last} 到期的限期額度已不再計入", + "{who} has no credit that expires": "{who} 已去掉限期額度", + "{who} has {amount} that counts through {last}": "{who} 有 {amount} 限期額度,算到 {last}", + "Credit that expires, in CNY": "限期額度(人民幣)", + "Credit that expires, in USD": "限期額度(美元)", + "Credit that expires is an amount above 0, in the balance's currency": "限期額度是大於 0 的金額,用餘額的貨幣", + "Last day it counts": "最後一天", + "The last day is a date from today on, as 2026-12-31": "最後一天是今天或以後的日期,如 2026-12-31", + "Credit that expires…": "限期額度…", + "No credit that expires": "去掉限期額度", "Refills each month…": "每月恢復…", "Refills each week…": "每週恢復…", "Never refills": "不恢復", @@ -9471,6 +9505,23 @@ const I18N = { "Balance, in CNY": "残高(人民元)", "The dollar's rate in yuan isn't known yet, so what is left can't be counted": "ドルの人民元レートがまだ分からないため、残りを計算できません", "Refills to {set} on {when}": "{when} に {set} へ戻る", + "Expires today": "今日で失効", + "Expires tomorrow": "明日で失効", + "Expires in {n} days": "{n} 日後に失効", + "{amount} expires today": "{amount} は今日で失効", + "{amount} expires tomorrow": "{amount} は明日で失効", + "{amount} expires in {n} days": "{amount} は {n} 日後に失効", + "Of it, {left} of the {set} typed {when} is spent first and counts through {last}": "うち期限付きクレジット {left}({when} に {set} と入力)は先に使われ、{last} まで有効", + "The credit that expired on {last} no longer counts": "{last} に失効したクレジットはもう数えません", + "{who} has no credit that expires": "{who} の期限付きクレジットを外しました", + "{who} has {amount} that counts through {last}": "{who} の期限付きクレジット {amount} は {last} まで有効", + "Credit that expires, in CNY": "期限付きクレジット(CNY)", + "Credit that expires, in USD": "期限付きクレジット(USD)", + "Credit that expires is an amount above 0, in the balance's currency": "期限付きクレジットは 0 より大きい金額です(残高の通貨で)", + "Last day it counts": "有効な最終日", + "The last day is a date from today on, as 2026-12-31": "最終日は今日以降の日付です(例: 2026-12-31)", + "Credit that expires…": "期限付きクレジット…", + "No credit that expires": "期限付きクレジットなし", "Refills each month…": "毎月戻す…", "Refills each week…": "毎週戻す…", "Never refills": "戻さない", @@ -14177,6 +14228,23 @@ const I18N = { "Balance, in CNY": "Guthaben in CNY", "The dollar's rate in yuan isn't known yet, so what is left can't be counted": "Der Dollarkurs in Yuan ist noch nicht bekannt, daher lässt sich der Rest nicht berechnen", "Refills to {set} on {when}": "Wird am {when} wieder auf {set} aufgefüllt", + "Expires today": "Läuft heute ab", + "Expires tomorrow": "Läuft morgen ab", + "Expires in {n} days": "Läuft in {n} Tagen ab", + "{amount} expires today": "{amount} läuft heute ab", + "{amount} expires tomorrow": "{amount} läuft morgen ab", + "{amount} expires in {n} days": "{amount} läuft in {n} Tagen ab", + "Of it, {left} of the {set} typed {when} is spent first and counts through {last}": "Davon {left} der am {when} eingegebenen {set}: wird zuerst verbraucht und zählt bis {last}", + "The credit that expired on {last} no longer counts": "Das am {last} abgelaufene Guthaben zählt nicht mehr", + "{who} has no credit that expires": "{who} hat kein ablaufendes Guthaben", + "{who} has {amount} that counts through {last}": "{who} hat {amount}, das bis {last} zählt", + "Credit that expires, in CNY": "Ablaufendes Guthaben, in CNY", + "Credit that expires, in USD": "Ablaufendes Guthaben, in USD", + "Credit that expires is an amount above 0, in the balance's currency": "Ablaufendes Guthaben ist ein Betrag über 0, in der Währung des Guthabens", + "Last day it counts": "Letzter gültiger Tag", + "The last day is a date from today on, as 2026-12-31": "Der letzte Tag ist ein Datum ab heute, etwa 2026-12-31", + "Credit that expires…": "Ablaufendes Guthaben…", + "No credit that expires": "Kein ablaufendes Guthaben", "Refills each month…": "Monatlich auffüllen…", "Refills each week…": "Wöchentlich auffüllen…", "Never refills": "Nie auffüllen", diff --git a/internal/gui/assets/keybalance.js b/internal/gui/assets/keybalance.js index aaca195ed..0ae7f4939 100644 --- a/internal/gui/assets/keybalance.js +++ b/internal/gui/assets/keybalance.js @@ -4,7 +4,10 @@ // own usage prices the calls it sends on the key (provider/ // key_balance_own.go). Typing it again sets it anew. It may be typed in // yuan ("¥100", or picked beside the field, which starts at the balance's -// own currency, else Settings' one), and may refill each month or week. keyspend.js imports this when the +// own currency, else Settings' one), and may refill each month or week. +// Part of it may expire on a day (credit good until a date): the pill +// says how much and in how many days, amber from a week, and the rest of +// the balance is what stays after it. keyspend.js imports this when the // provider editor draws a key's row, so it weighs nothing on the core. const moneyText = (v, cny) => (v < 0 ? "-" : "") + (cny ? "¥" : "$") + Math.abs(v).toFixed(2); // balanceAmount reads what was typed: an amount and whether it is in @@ -18,12 +21,29 @@ function balanceAmount(s, unit) { const n = Number(a); return a && n >= 0 && n <= 1e6 ? { n, cny } : null; } +// dayOf: a day as the date it is here, 2026-12-31; dateText: one shown +const dayOf = (d) => [d.getFullYear(), d.getMonth() + 1, d.getDate()].map((n) => String(n).padStart(2, "0")).join("-"); +const dateText = (s) => new Date(s + "T00:00").toLocaleDateString(intlLang(), { dateStyle: "medium" }); +// lastDay reads the last day credit counts: 2026-12-31 (or with / or .), +// from today on; null else +function lastDay(s) { + const m = s.trim().match(/^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})$/); + if (!m) return null; + const d = new Date(+m[1], m[2] - 1, +m[3]); + return d.getMonth() === m[2] - 1 && d.getDate() === +m[3] && dayOf(d) >= dayOf(new Date()) ? dayOf(d) : null; +} const weekdayName = (d) => new Date(2026, 10, 1 + d).toLocaleDateString(intlLang(), { weekday: "long" }); // 2026-11-02 is a Monday function keyBalancePill(p, k) { const b = k.balance, name = k.name || k.masked, cny = b?.currency === "cny"; const pill = el("button", "abal" + (b ? " set" : "")); pill.type = "button"; pill.textContent = b ? t("≈{usd} left", { usd: b.left == null ? (cny ? "¥" : "$") + "…" : moneyText(b.left, cny) }) : t("Set balance"); + const x = b?.expiring, xin = x && expiresIn(x.ends), xlast = x && dayOf(new Date(new Date(x.ends) - 1)); + if (x?.left > 0) { + const amount = moneyText(x.left, cny); + pill.append(" · ", el("span", "abal-exp" + (xin.soon ? " soon" : ""), xin.days <= 0 ? t("{amount} expires today", { amount }) + : xin.days === 1 ? t("{amount} expires tomorrow", { amount }) : t("{amount} expires in {n} days", { amount, n: xin.days }))); + } pill.title = !b ? t("Type what the vendor's page says this key has left, and magpie counts down from it as it sends requests") : [t("An estimate: {set} from {when}, less {spent} magpie counted spent on this key since, at the prices the Usage page shows. Click to change", { set: moneyText(b.set, cny), when: new Date(b.from || b.at).toLocaleString(intlLang()), @@ -31,6 +51,9 @@ function keyBalancePill(p, k) { }), b.left == null ? t("The dollar's rate in yuan isn't known yet, so what is left can't be counted") : "", b.refill && b.next ? t("Refills to {set} on {when}", { set: moneyText(b.set, cny), when: new Date(b.next).toLocaleString(intlLang(), { dateStyle: "medium" }) }) : "", + x ? t("Of it, {left} of the {set} typed {when} is spent first and counts through {last}", { left: x.left == null ? "…" : moneyText(x.left, cny), set: moneyText(x.set, cny), + when: new Date(x.at).toLocaleString(intlLang()), last: dateText(xlast) }) : "", + b.expired ? t("The credit that expired on {last} no longer counts", { last: dateText(dayOf(new Date(new Date(b.expired) - 1))) }) : "", ].filter(Boolean).join("\n"); const set = (v) => accountAction("provider/keyownbalance", { id: p.id, account: k.id, balance: v ? v.n : null, ...v?.cny && { currency: "cny" } }, !v ? t("{who} has no balance typed", { who: name }) : t("{who} has {usd} left", { who: name, usd: moneyText(v.n, v.cny) })); @@ -38,6 +61,22 @@ function keyBalancePill(p, k) { !r ? t("{who} no longer refills", { who: name }) : r.every === "week" ? t("{who} refills each {weekday}", { who: name, weekday: weekdayName(r.day) }) : t("{who} refills on day {day} of each month", { who: name, day: r.day })); + const expiring = (v) => accountAction("provider/keyexpiring", { id: p.id, account: k.id, expiring: v }, + !v ? t("{who} has no credit that expires", { who: name }) : t("{who} has {amount} that counts through {last}", { who: name, amount: moneyText(v.amount, cny), last: dateText(v.until) })); + // credit that expires: its amount, in the balance's currency, then the + // last day it counts, each typed where the pill was + const credit = () => { + const at = pill.parentNode, own = cny ? "cny" : "usd"; + pillNumber(pill, x ? String(x.set) : "", cny ? "¥" : "$", "abal-in", t(cny ? "Credit that expires, in CNY" : "Credit that expires, in USD"), + (s) => { const v = balanceAmount(s, own); return v && v.n > 0 && v.cny === cny ? v.n : null; }, + t("Credit that expires is an amount above 0, in the balance's currency"), null, (amount) => { + const i = at?.querySelector(":scope > .abal-in"); + if (!i) return; + pillNumber(i, xlast || "", "2026-12-31", "abal-in abal-day", t("Last day it counts"), lastDay, + t("The last day is a date from today on, as 2026-12-31"), null, (until) => expiring({ amount, until })); + at.querySelector(":scope > .abal-day").inputMode = "text"; + }); + }; // a bare number is in the currency the button beside the field shows: // the balance's own, else Settings' one, until the user picks the other // there (tenacious_eagle: no clearing it and going to Settings). Picking @@ -93,11 +132,13 @@ function keyBalancePill(p, k) { if (pill.classList.contains("open")) return closeProtoMenu(); openProtoMenu(pill, [ { v: "set", name: "Enter balance…", note: "Counts down from now" }, + { v: "exp", name: "Credit that expires…", note: "" }, + ...x || b.expired ? [{ v: "noexp", name: "No credit that expires", note: "" }] : [], { v: "month", name: "Refills each month…", note: "" }, { v: "week", name: "Refills each week…", note: "" }, { v: "never", name: "Never refills", note: "" }, { v: "off", name: "No balance", note: "" }, - ], b.refill?.every || "never", (v) => v === "off" ? set(null) : v === "month" ? monthly() : v === "week" ? weekly() + ], b.refill?.every || "never", (v) => v === "off" ? set(null) : v === "exp" ? credit() : v === "noexp" ? expiring(null) : v === "month" ? monthly() : v === "week" ? weekly() : v === "never" ? b.refill && refill(null) : type(), "Balance", "sess-menu"); }; return pill; diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index 3b4307212..100639fe0 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); 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); a key's provider's model list off (axelburks on Discord), its tick in app.js, paid for by four Models-section comments cut, no raise (11-08); a model's own headers in Model settings (axelburks on Discord), the core's own editor, paid for by sixteen of its comments cut, no raise (11-08); a model asked on System One (axelburks on Discord), in app.js, paid for by three of the editor's comments cut, no raise (11-08) + 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); a key's provider's model list off (axelburks on Discord), its tick in app.js, paid for by four Models-section comments cut, no raise (11-08); a model's own headers in Model settings (axelburks on Discord), the core's own editor, paid for by sixteen of its comments cut, no raise (11-08); a model asked on System One (axelburks on Discord), in app.js, paid for by three of the editor's comments cut, no raise (11-08); a typed balance's part that expires (tenacious_eagle_96548 on Discord), its days on the Usage page and the panel in app.js (expiresIn), paid for by five balance comments cut, 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 index 3242bae4e..eaf9e591a 100644 --- a/internal/gui/key_own_balance_test.go +++ b/internal/gui/key_own_balance_test.go @@ -99,6 +99,24 @@ func TestKeyOwnBalanceRoutes(t *testing.T) { if _, b := listed(); b == nil || b.Refill != nil || b.Set != 700 { t.Fatalf("refill off: %+v", b) } + // a part that expires (tenacious_eagle_96548): ¥50 through a day far + // ahead, listed apart and in the left; a date that isn't one refused; + // none takes it off and leaves the rest + call("POST", "/api/provider/keyexpiring", `{"id":"relay","account":"`+key+`","expiring":{"amount":50,"until":"2099-12-31"}}`) + if _, b := listed(); b == nil || b.Set != 700 || *b.Left != 750 || b.Expiring == nil || *b.Expiring.Left != 50 || b.Expiring.Ends.Year() != 2100 { + t.Fatalf("¥700 and ¥50 that expires: %+v %+v", b, b.Expiring) + } + for _, body := range []string{`{"amount":50,"until":"next week"}`, `{"amount":0,"until":"2099-12-31"}`} { + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/provider/keyexpiring", strings.NewReader(`{"id":"relay","account":"`+key+`","expiring":`+body+`}`))) + if w.Code == 200 { + t.Errorf("%s taken", body) + } + } + call("POST", "/api/provider/keyexpiring", `{"id":"relay","account":"`+key+`","expiring":null}`) + if _, b := listed(); b == nil || b.Expiring != nil || *b.Left != 700 { + t.Fatalf("expiring off: %+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 93d715ed0..91ee1eb19 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -1676,6 +1676,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) { // Refill, for keybalancerefill: when the key's balance typed // is whole again; none for never Refill *provider.Refill `json:"refill"` + // Expiring, for keyexpiring: the part of the key's balance + // typed that expires, {amount, until}; none takes it off + Expiring *provider.Expiring `json:"expiring"` // Alias, for accountname: the account's name of the user's // own, "" to take it off (#1515) Alias string `json:"alias"` @@ -2401,6 +2404,11 @@ func providerRoutes(mux *http.ServeMux, w Windows) { fail(rw, err) return } + case "keyexpiring": + if err := provider.SetKeyExpiring(in.ID, req.Account, req.Expiring); 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-balance-expiring.test.cjs b/internal/gui/tests/key-balance-expiring.test.cjs new file mode 100644 index 000000000..34ce3e095 --- /dev/null +++ b/internal/gui/tests/key-balance-expiring.test.cjs @@ -0,0 +1,239 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A key's balance typed by hand may have a part that expires +// (tenacious_eagle_96548 on Discord: money that stays and credit good +// until a date). The key's pill says how much of that credit is left and +// in how many days it goes, amber from a week; the Usage page's card and +// the panel's Balances say it on a line under the balance, amber the same +// way. From the pill's menu (the app's, no native select), Credit that +// expires… takes its amount, in the balance's currency, then its last +// day, and posts provider/keyexpiring; a sign of the other currency or a +// day gone by is refused and nothing posted. No credit that expires takes +// it off, and is offered for credit that has expired too, which the +// pill's title says no longer counts. In every language, at a phone's +// width the row stays inside the window. +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"); +// the end of credit whose last day is n days from today: midnight after +// it, here +const ends = (n) => { const d = new Date(); return new Date(d.getFullYear(), d.getMonth(), d.getDate() + n + 1).toISOString(); }; +const dayIn = (n) => { const d = new Date(); d.setDate(d.getDate() + n); return [d.getFullYear(), d.getMonth() + 1, d.getDate()].map((x) => String(x).padStart(2, "0")).join("-"); }; +const ago = new Date(Date.now() - 864e5).toISOString(); +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: 70, at: ago, spent: 10, left: 60, expiring: { set: 30, at: ago, left: 20, ends: ends(30) } } }, + { id: "k2", name: "Team", masked: "sk-…two", on: true, balance: { set: 40, at: ago, spent: 0, left: 40, currency: "cny", rate: 7.2, expiring: { set: 5, at: ago, left: 5, ends: ends(3) } } }, + { id: "k3", name: "Spare", masked: "sk-…three", on: true, balance: { set: 10, at: ago, spent: 0, left: 10, expired: ends(-1) } }, + ], + balanceToken: { takes: false, set: false }, proxy: "", +}); + +const quotas = [ + { provider: "relay", name: "Relay", icon: "generic", user: "Main", windows: [], balance: "$60.00", balanceSplit: [{ text: "$20.00", expires: ends(30) }] }, + { provider: "relay", name: "Relay", icon: "generic", user: "Team", windows: [], balance: "¥40.00", balanceSplit: [{ text: "¥5.00", expires: ends(3) }] }, + { provider: "relay", name: "Relay", icon: "generic", user: "Last", windows: [], balance: "$9.00", balanceSplit: [{ text: "$1.00", expires: ends(0) }] }, +]; + +function serve(lang, posts, relay) { + const providers = { providers: [relay], presets: [], excluded: [], gateway: { running: true, window: true } }; + const settings = { lang, theme: "light", tray: "panel", quotaLeft: true, currency: "usd", usageOrder: [], panelUsageHidden: [] }; + 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({ agents: [], profiles: [], settings }); + if (url.pathname === "/api/settings") return json(settings); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/usage/quotas") return json(quotas); + if (url.pathname === "/api/usage") return json({ days: [] }); + if (url.pathname === "/api/lanes") return json({}); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + 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 === "keyexpiring") { + const b = relay.keyList.find((x) => x.id === body.account).balance; + delete b.expired; + if (body.expiring) { + const [y, m, d] = body.expiring.until.split("-").map(Number); + b.expiring = { set: body.expiring.amount, at: new Date().toISOString(), left: body.expiring.amount, ends: new Date(y, m - 1, d + 1).toISOString() }; + } else delete b.expiring; + } + 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)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +const words = { + en: { k1: "≈$60.00 left · $20.00 expires in 30 days", k2: "≈¥40.00 left · ¥5.00 expires in 3 days", k1off: "≈$60.00 left", k3: "≈$10.00 left", k3new: "≈$10.00 left · $15.00 expires in 10 days", + in30: "Expires in 30 days", in3: "Expires in 3 days", today: "Expires today", exp: "Credit that expires…", noexp: "No credit that expires", + badAmount: "Credit that expires is an amount above 0, in the balance's currency", badDay: "The last day is a date from today on, as 2026-12-31", gone: "no longer counts" }, + zh: { k1: "≈$60.00 剩余 · $20.00 30 天后到期", k2: "≈¥40.00 剩余 · ¥5.00 3 天后到期", k1off: "≈$60.00 剩余", k3: "≈$10.00 剩余", k3new: "≈$10.00 剩余 · $15.00 10 天后到期", + in30: "30 天后到期", in3: "3 天后到期", today: "今天到期", exp: "限期额度…", noexp: "去掉限期额度", + badAmount: "限期额度是大于 0 的金额,用余额的货币", badDay: "最后一天是今天或以后的日期,如 2026-12-31", gone: "已不再计入" }, + "zh-TW": { k1: "≈$60.00 剩餘 · $20.00 30 天後到期", k2: "≈¥40.00 剩餘 · ¥5.00 3 天後到期", k1off: "≈$60.00 剩餘", k3: "≈$10.00 剩餘", k3new: "≈$10.00 剩餘 · $15.00 10 天後到期", + in30: "30 天後到期", in3: "3 天後到期", today: "今天到期", exp: "限期額度…", noexp: "去掉限期額度", + badAmount: "限期額度是大於 0 的金額,用餘額的貨幣", badDay: "最後一天是今天或以後的日期,如 2026-12-31", gone: "已不再計入" }, + ja: { k1: "残り ≈$60.00 · $20.00 は 30 日後に失効", k2: "残り ≈¥40.00 · ¥5.00 は 3 日後に失効", k1off: "残り ≈$60.00", k3: "残り ≈$10.00", k3new: "残り ≈$10.00 · $15.00 は 10 日後に失効", + in30: "30 日後に失効", in3: "3 日後に失効", today: "今日で失効", exp: "期限付きクレジット…", noexp: "期限付きクレジットなし", + badAmount: "期限付きクレジットは 0 より大きい金額です(残高の通貨で)", badDay: "最終日は今日以降の日付です(例: 2026-12-31)", gone: "もう数えません" }, + de: { k1: "≈$60.00 übrig · $20.00 läuft in 30 Tagen ab", k2: "≈¥40.00 übrig · ¥5.00 läuft in 3 Tagen ab", k1off: "≈$60.00 übrig", k3: "≈$10.00 übrig", k3new: "≈$10.00 übrig · $15.00 läuft in 10 Tagen ab", + in30: "Läuft in 30 Tagen ab", in3: "Läuft in 3 Tagen ab", today: "Läuft heute ab", exp: "Ablaufendes Guthaben…", noexp: "Kein ablaufendes Guthaben", + badAmount: "Ablaufendes Guthaben ist ein Betrag über 0, in der Währung des Guthabens", badDay: "Der letzte Tag ist ein Datum ab heute, etwa 2026-12-31", gone: "zählt nicht mehr" }, +}; + +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 has credit that expires, said in days and amber from a week`, 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-balance-expiring.png`) }); + } + await browser.close(); + }); + const context = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" }); + await context.addInitScript(() => { try { localStorage.setItem("magpie.panelTab", "usage"); } catch {} }); + page = await context.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const posts = [], relay = fresh(); + await page.route("**/*", serve(lang, posts, relay)); + + // the Usage page's cards: a line under the balance, amber within a week + await page.goto("http://magpie.test/?view=usage&tab=usage"); + await page.waitForFunction(() => document.querySelectorAll("#subscriptionUsage .bal-part").length >= 6); + const lines = () => page.evaluate(() => [...document.querySelectorAll("#subscriptionUsage .quota-balance")].map((b) => + [...b.querySelectorAll(".bal-part:not(.lead)")].map((r) => [r.querySelector("span").textContent, r.querySelector("b").textContent, r.classList.contains("soon")]))); + assert.deepEqual(await lines(), [[[w.in30, "$20.00", false]], [[w.in3, "¥5.00", true]], [[w.today, "$1.00", true]]]); + const soonColor = () => page.evaluate(() => { + const e = document.createElement("i"); + e.style.color = "var(--amber)"; + document.body.append(e); + const a = getComputedStyle(e).color; + e.remove(); + return [...document.querySelectorAll(".bal-part.soon b, .abal .abal-exp.soon")].map((b) => getComputedStyle(b).color === a); + }); + assert.deepEqual(await soonColor(), [true, true], "credit going within a week isn't amber"); + assert.equal(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth + 1), true, "the Usage page scrolls sideways"); + + // the panel's Balances: the same lines + const panel = await context.newPage(); + panel.on("pageerror", (e) => errors.push(e.message)); + await panel.route("**/*", serve(lang, [], fresh())); + await panel.goto("http://magpie.test/?mode=panel"); + await panel.waitForFunction(() => document.querySelectorAll("#panelQuota .pq-bp").length >= 3); + assert.deepEqual(await panel.evaluate(() => [...document.querySelectorAll("#panelQuota .pq-bp")].map((r) => [r.querySelector("span").textContent, r.querySelector("b").textContent, r.classList.contains("soon")])), + [[w.in30, "$20.00", false], [w.in3, "¥5.00", true], [w.today, "$1.00", true]]); + await panel.close(); + + // the key's pills in the provider's editor + 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 open = async (id) => { + if (await menu.isVisible()) await page.keyboard.press("Escape"); + await page.waitForTimeout(150); + await row(id).hover(); + await pill(id).click(); + await menu.waitFor(); + }; + 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); + }; + const over = () => page.evaluate(() => [...document.querySelectorAll(".editor .accts .acc")].filter((e) => e.getBoundingClientRect().right > innerWidth + 1).length); + + assert.equal(await pill("k1").textContent(), w.k1); + assert.equal(await pill("k2").textContent(), w.k2); + assert.equal(await pill("k3").textContent(), w.k3); + assert.deepEqual(await page.evaluate(() => [...document.querySelectorAll(".abal .abal-exp")].map((e) => e.classList.contains("soon"))), [false, true]); + assert.deepEqual(await soonColor(), [true], "the pill's credit going within a week isn't amber"); + assert.match(await pill("k3").getAttribute("title"), new RegExp(w.gone)); + assert.equal(await page.locator("select").count(), 0, "no native select"); + assert.equal(await over(), 0, "a key's row past the window's edge"); + + // k3: a sign of the other currency is refused, then a day gone by + await open("k3"); + await item(w.exp).click(); + await box("k3").waitFor(); + let n = posts.length; + await box("k3").fill("¥15"); + await box("k3").press("Enter"); + await page.waitForTimeout(300); + assert.equal(posts.length, n, "an amount in the other currency was posted"); + assert.equal(await page.locator("#status").textContent(), w.badAmount); + await page.waitForTimeout(300); + await open("k3"); + await item(w.exp).click(); + await box("k3").waitFor(); + await box("k3").fill("15"); + await box("k3").press("Enter"); + const day = row("k3").locator("input.abal-day"); + await day.waitFor(); + assert.equal(await day.evaluate((e) => e === document.activeElement), true, "the day's field hasn't the focus"); + assert.equal(await over(), 0, "the day's row past the window's edge"); + await day.fill(dayIn(-1)); + await day.press("Enter"); + await page.waitForTimeout(300); + assert.equal(posts.length, n, "a day gone by was posted"); + assert.equal(await page.locator("#status").textContent(), w.badDay); + await page.waitForTimeout(300); + await open("k3"); + await item(w.exp).click(); + await box("k3").waitFor(); + await box("k3").fill("15"); + await box("k3").press("Enter"); + await day.waitFor(); + await day.fill(dayIn(10).replace(/-/g, "/")); + await day.press("Enter"); + let p = await posted(n); + assert.equal(p.action, "keyexpiring"); + assert.deepEqual(p.body, { id: "relay", account: "k3", expiring: { amount: 15, until: dayIn(10) } }); + await page.waitForTimeout(250); + assert.equal(await pill("k3").textContent(), w.k3new); + assert.equal(await over(), 0, "a key's row past the window's edge"); + + // k1's taken off + await open("k1"); + n = posts.length; + await item(w.noexp).click(); + p = await posted(n); + assert.deepEqual(p.body, { id: "relay", account: "k1", expiring: null }); + await page.waitForTimeout(250); + assert.equal(await pill("k1").textContent(), w.k1off); + + const stripes = await page.evaluate(() => [...document.querySelectorAll(".abal, .abal-in, .bal-part, .pq-bp")].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/provider/balance.go b/internal/provider/balance.go index 2f694c02f..88b5abaa2 100644 --- a/internal/provider/balance.go +++ b/internal/provider/balance.go @@ -399,6 +399,11 @@ const ( func SplitWords(split []BalancePart) string { out := make([]string, 0, len(split)) for _, p := range split { + if p.Expires != nil { + // through the last day it counts: "¥20.00 until Nov 13" + out = append(out, p.Text+" until "+p.Expires.Add(-time.Second).Format("Jan 2")) + continue + } out = append(out, strings.ToLower(p.Label)+" "+p.Text) } return strings.Join(out, " · ") @@ -760,6 +765,10 @@ type BalancePart struct { Percent *float64 `json:"percent,omitempty"` // Error is why the amount couldn't be read, its Text then "—". Error string `json:"error,omitempty"` + // Expires is when the part counts no more, for a balance typed with + // credit that expires (key_balance_own.go); the GUI says in how many + // days, its Label then empty + Expires *time.Time `json:"expires,omitempty"` } // joinBalanceParts is the amounts on one line, as Balance tells them: diff --git a/internal/provider/key_balance_own.go b/internal/provider/key_balance_own.go index d25852092..105f8d2d6 100644 --- a/internal/provider/key_balance_own.go +++ b/internal/provider/key_balance_own.go @@ -19,6 +19,13 @@ package provider // at midnight local time on a day of the month or of the week, the amount // typed is whole again and the spend counted from then. +// It may have a second part that expires (the same user: some vendors +// split a balance into money that stays and credit good until a date). +// That part is spent first, as DeepSeek spends its granted balance before +// the money topped up, and from the end of its last day, local time, it +// counts no more; the card says how much of it is left and in how many +// days it goes. A balance typed before has none and is counted as it was. + import ( "fmt" "math" @@ -37,6 +44,40 @@ type OwnBalance struct { CNY *float64 `json:"cny,omitempty"` At time.Time `json:"at"` Refill *Refill `json:"refill,omitempty"` + // Expiring is a part of the balance, in its currency, good until a + // day; nil for none + Expiring *Expiring `json:"expiring,omitempty"` +} + +// Expiring is credit on a key that is gone after a day: Amount (in the +// balance's currency) as it stood At, spent before the rest of the +// balance, and counted through Until (a date, 2006-01-02), to midnight +// after it in the user's local time. +type Expiring struct { + Amount float64 `json:"amount"` + Until string `json:"until"` + At time.Time `json:"at"` +} + +// End is when the credit counts no more: midnight after Until, in loc. +// false when Until is no date. +func (x Expiring) End(loc *time.Location) (time.Time, bool) { + d, err := time.ParseInLocation(time.DateOnly, x.Until, loc) + if err != nil { + return time.Time{}, false + } + return time.Date(d.Year(), d.Month(), d.Day()+1, 0, 0, 0, 0, loc), true +} + +// check says what is wrong with x, nil when nothing is. +func (x Expiring) check() error { + if !(x.Amount > 0 && x.Amount <= MaxOwnBalance) { + return fmt.Errorf("credit that expires is an amount above 0 and up to %d, not %v", MaxOwnBalance, x.Amount) + } + if _, ok := x.End(time.UTC); !ok { + return fmt.Errorf("credit expires on a date (2026-12-31), not %q", x.Until) + } + return nil } // Amount is the balance typed and its currency, "cny" or "usd". @@ -133,6 +174,23 @@ type BalanceEstimate struct { From time.Time `json:"from"` Refill *Refill `json:"refill,omitempty"` Next *time.Time `json:"next,omitempty"` + // Expiring is the part of the balance that expires, when it has one + // and that part hasn't expired yet + Expiring *ExpiringLeft `json:"expiring,omitempty"` + // Expired is the end of a part that has expired; Left no longer + // counts it + Expired *time.Time `json:"expired,omitempty"` +} + +// ExpiringLeft is what is left of a balance's part that expires: Set as +// typed, At, Left of it now (in the balance's currency; nil while Left +// is) and Ends when it counts no more. Left is part of the estimate's +// Left, not on top of it. +type ExpiringLeft struct { + Set float64 `json:"set"` + At time.Time `json:"at"` + Left *float64 `json:"left"` + Ends time.Time `json:"ends"` } // KeySpent is usage.KeySpent, which package usage sets: what the calls @@ -178,20 +236,65 @@ func (p Provider) OwnBalanceEstimate(keyID string) (BalanceEstimate, bool) { next := r.Next(now) e.Next = &next } - if KeySpent != nil { - e.Spent = KeySpent(keyID, e.From) + spent := func(start time.Time) float64 { + if KeySpent == nil || !start.Before(now) { + return 0 + } + return KeySpent(keyID, start) } - left := amount - e.Spent + e.Spent = spent(e.From) + // the spend in the balance's currency; false while it can't be told + inCur := func(usd float64) (float64, bool) { return usd, true } if cur == "cny" { e.Currency = cur rate, known := cnyPerUSD() - switch { - case known: + if known { e.Rate = rate - left = amount - e.Spent*rate - case e.Spent != 0: - return e, true // spend counted at no rate: unknown } + inCur = func(usd float64) (float64, bool) { + if usd == 0 { + return 0, true + } + return usd * rate, known + } + } + // a part that expires takes the spend first, from when it was typed + // to its end; what it took after From is not the rest's to pay + took := 0.0 + if x := b.Expiring; x != nil { + if end, ok := x.End(now.Location()); ok { + between := func(from, to time.Time) float64 { return spent(from) - spent(to) } + stop := minTime(end, now) + usd := 0.0 + if x.At.Before(stop) { + usd = between(x.At, stop) + } + before := 0.0 + if x.At.Before(e.From) { + before = between(x.At, minTime(e.From, stop)) + } + s, ok1 := inCur(usd) + sb, ok2 := inCur(before) + if !ok1 || !ok2 { + return e, true // spend counted at no rate: unknown + } + used := min(x.Amount, s) + took = max(0, used-min(x.Amount, sb)) + if end.After(now) { + l := x.Amount - used + e.Expiring = &ExpiringLeft{Set: x.Amount, At: x.At, Left: &l, Ends: end} + } else { + e.Expired = &end + } + } + } + s, ok := inCur(e.Spent) + if !ok { + return e, true // spend counted at no rate: unknown + } + left := amount - (s - took) + if e.Expiring != nil { + left += *e.Expiring.Left } e.Left = &left return e, true @@ -230,6 +333,11 @@ func ownBalanceCard(p Provider, key, user string) (SubscriptionQuota, bool) { q.Error = "the dollar's rate in yuan isn't known yet, so what is left of the balance in yuan can't be counted" } else { q.Balance = ownBalanceText(*e.Left, e.Currency) + // of it, the part that expires, and when (a line of its own) + if x := e.Expiring; x != nil && *x.Left > 0 { + ends := x.Ends + q.BalanceSplit = []BalancePart{{Text: ownBalanceText(*x.Left, e.Currency), Expires: &ends}} + } } return q, true } @@ -250,7 +358,9 @@ func ownBalanceText(v float64, currency string) string { // SetKeyOwnBalance gives the key ref (its id or name) of the provider id // the balance b (its amount, in USD or CNY), counted from now; nil takes -// it off. With no Refill of its own, b keeps the one the key had. +// it off. With no Refill of its own, b keeps the one the key had, and with +// no Expiring, the part that expires the key had in the same currency (in +// the other, its amount would mean another sum, so it goes). func SetKeyOwnBalance(id, ref string, b *OwnBalance) error { if b != nil { if err := checkOwnBalance(*b); err != nil { @@ -266,10 +376,39 @@ func SetKeyOwnBalance(id, ref string, b *OwnBalance) error { if v.Refill == nil && ok { v.Refill = had.Refill } + if v.Expiring == nil && ok && (v.CNY == nil) == (had.CNY == nil) { + v.Expiring = had.Expiring + } return &v, nil }) } +// SetKeyExpiring gives the balance typed for the key ref of the provider +// id the part x that expires, in the balance's currency, counted from now; +// nil takes it off. The rest of the balance stays as it was. A key with +// no balance typed takes none: type the balance that stays first, 0 when +// all of it expires. +func SetKeyExpiring(id, ref string, x *Expiring) error { + if x != nil { + if err := x.check(); err != nil { + return err + } + } + return editOwnBalance(id, ref, func(had OwnBalance, ok bool) (*OwnBalance, error) { + if !ok { + return nil, fmt.Errorf("the key has no balance typed: type the balance that stays first (0 when all of it expires)") + } + if x == nil { + had.Expiring = nil + return &had, nil + } + v := *x + v.At = ownNow().UTC() + had.Expiring = &v + return &had, nil + }) +} + // SetKeyBalanceRefill gives the balance typed for the key ref of the // provider id the refill r, nil for none; its amount and when it was // typed stay. A key with no balance typed takes none. @@ -342,12 +481,42 @@ func checkOwnBalance(b OwnBalance) error { if b.CNY != nil && b.USD != 0 { return fmt.Errorf("a balance is in USD or in yuan, not both") } + if b.Expiring != nil { + if err := b.Expiring.check(); err != nil { + return err + } + } if b.Refill != nil { return b.Refill.check() } return nil } +// ParseExpiring reads credit that expires as the CLI takes it, an amount +// and the last day it counts: "20@2026-12-31", the amount in the +// balance's currency (so no sign of its own); off for none (nil). +func ParseExpiring(s string) (*Expiring, error) { + a := strings.TrimSpace(s) + switch strings.ToLower(a) { + case "off", "none", "no", "-": + return nil, nil + } + bad := fmt.Errorf("credit that expires is amount@date (20@2026-12-31) or off, not %q", s) + amount, until, ok := strings.Cut(a, "@") + if !ok { + return nil, bad + } + v, err := strconv.ParseFloat(strings.ReplaceAll(strings.TrimSpace(amount), ",", ""), 64) + if err != nil { + return nil, bad + } + x := Expiring{Amount: v, Until: strings.TrimSpace(until)} + if err := x.check(); err != nil { + return nil, err + } + return &x, nil +} + // ParseOwnBalance reads a balance as the CLI takes it, an amount in USD // ("20", "$20", "12.5 usd") or in yuan ("¥100", "100cny", "100 rmb", // "100元"); off for none (nil). @@ -436,6 +605,9 @@ func normalKeyOwnBalances(m map[string]OwnBalance) map[string]OwnBalance { if b.Refill != nil && b.Refill.check() != nil { b.Refill = nil // a refill that isn't one, written by hand } + if b.Expiring != nil && b.Expiring.check() != nil { + b.Expiring = nil // nor credit that expires + } if k == "" || checkOwnBalance(b) != nil { continue } diff --git a/internal/provider/key_balance_own_test.go b/internal/provider/key_balance_own_test.go index f1a202cf7..20e39c8c4 100644 --- a/internal/provider/key_balance_own_test.go +++ b/internal/provider/key_balance_own_test.go @@ -2,6 +2,7 @@ package provider import ( "context" + "encoding/json" "net/http" "net/http/httptest" "strings" @@ -419,3 +420,195 @@ func TestOwnBalanceParsedInYuanAndRefill(t *testing.T) { t.Errorf("a refill that isn't one, written by hand: %+v", n) } } + +// spendAt stubs usage.KeySpent with calls at given times: what the key +// spent from start up to the clock ownNow holds. +func spendAt(t *testing.T, calls map[time.Time]float64) { + t.Helper() + old := KeySpent + KeySpent = func(_ string, start time.Time) float64 { + n, sum := ownNow(), 0.0 + for at, usd := range calls { + if !at.Before(start) && !at.After(n) { + sum += usd + } + } + return sum + } + t.Cleanup(func() { KeySpent = old }) +} + +// A balance with a part that expires (tenacious_eagle_96548: a vendor's +// money that stays and credit good until a date): the part is spent +// first, as DeepSeek spends granted credit before money topped up; it +// counts through its last day to local midnight and then no more, what +// it took before then never charged to the rest. Held in UTC+14, UTC-10 +// and UTC, so the local day ends it, not UTC's. +func TestTypedBalanceExpires(t *testing.T) { + probeSandbox(t) + probeLocal = false + rateStub(t, 7, true) + if err := Save(Provider{ID: "gift", Name: "Gift", Chat: "http://127.0.0.1:1/v1", Key: "sk-g"}); err != nil { + t.Fatal(err) + } + k := keyID("sk-g") + for _, zone := range []string{"Pacific/Kiritimati", "Pacific/Honolulu", "UTC"} { + loc, err := time.LoadLocation(zone) + if err != nil { + t.Fatal(err) + } + at := func(d, h, m int) time.Time { return time.Date(2026, 11, d, h, m, 0, 0, loc) } + spendAt(t, map[time.Time]float64{at(2, 10, 0): 2, at(5, 10, 0): 4, at(12, 10, 0): 1}) + clockStub(t, at(1, 9, 0)) + if err := SetKeyOwnBalance("gift", k, &OwnBalance{USD: 10}); err != nil { + t.Fatal(err) + } + if err := SetKeyExpiring("gift", k, &Expiring{Amount: 5, Until: "2026-11-10"}); err != nil { + t.Fatal(err) + } + left := func(when time.Time) BalanceEstimate { + t.Helper() + clockStub(t, when) + p, _ := Find("gift") + e, _ := p.OwnBalanceEstimate(k) + return e + } + // $2 spent: all of it from the part that expires + e := left(at(3, 12, 0)) + if *e.Left != 13 || e.Expiring == nil || *e.Expiring.Left != 3 || !e.Expiring.Ends.Equal(at(11, 0, 0)) || e.Expired != nil { + t.Fatalf("%s, $2 spent: left %v, expiring %+v", zone, *e.Left, e.Expiring) + } + q := ownCards(t)["gift|"] + if q.Balance != "≈$13.00" || len(q.BalanceSplit) != 1 || q.BalanceSplit[0].Text != "≈$3.00" || !q.BalanceSplit[0].Expires.Equal(at(11, 0, 0)) { + t.Fatalf("%s card: %+v", zone, q) + } + // $6 spent: $5 of it the part's, $1 the rest's; nothing of the part + // left, so the card has no line for it + e = left(at(10, 23, 59)) + if *e.Left != 9 || e.Expiring == nil || *e.Expiring.Left != 0 { + t.Fatalf("%s, $6 spent before the end: left %v, expiring %+v", zone, *e.Left, e.Expiring) + } + if q := ownCards(t)["gift|"]; q.Balance != "≈$9.00" || len(q.BalanceSplit) != 0 { + t.Fatalf("%s card with the part spent: %+v", zone, q) + } + // past midnight local: expired, the $5 it took still not the rest's + e = left(at(13, 0, 0)) + if *e.Left != 8 || e.Expiring != nil || e.Expired == nil || !e.Expired.Equal(at(11, 0, 0)) { + t.Fatalf("%s after it expired, $1 more: left %v, expired %v", zone, *e.Left, e.Expired) + } + } + + // unspent credit that expires counts no more after its day; spend + // after it is the rest's alone + loc := time.UTC + at := func(d, h int) time.Time { return time.Date(2026, 11, d, h, 0, 0, 0, loc) } + spendAt(t, map[time.Time]float64{at(20, 1): 3}) + clockStub(t, at(15, 9)) + if err := SetKeyOwnBalance("gift", k, &OwnBalance{USD: 10}); err != nil { + t.Fatal(err) + } + if err := SetKeyExpiring("gift", k, &Expiring{Amount: 50, Until: "2026-11-16"}); err != nil { + t.Fatal(err) + } + clockStub(t, at(21, 0)) + p, _ := Find("gift") + if e, _ := p.OwnBalanceEstimate(k); *e.Left != 7 || e.Expiring != nil { + t.Fatalf("$50 expired unspent, $3 after: %+v", e) + } + + // typed again: the part stays in the same currency, and the spend it + // took after the retype isn't the rest's; in the other currency it + // would mean another sum, so it goes + spendAt(t, map[time.Time]float64{at(22, 1): 1, at(23, 1): 2}) + clockStub(t, at(21, 12)) + if err := SetKeyExpiring("gift", k, &Expiring{Amount: 2, Until: "2026-12-31"}); err != nil { + t.Fatal(err) + } + clockStub(t, at(22, 12)) + if err := SetKeyOwnBalance("gift", k, &OwnBalance{USD: 20}); err != nil { + t.Fatal(err) + } + clockStub(t, at(24, 0)) + p, _ = Find("gift") + // the part took $1 before the retype and $1 after; the rest pays $1 + if e, _ := p.OwnBalanceEstimate(k); e.Expiring == nil || *e.Expiring.Left != 0 || *e.Left != 19 { + t.Fatalf("typed again in USD: left %v, expiring %+v", *e.Left, e.Expiring) + } + cny := 100.0 + if err := SetKeyOwnBalance("gift", k, &OwnBalance{CNY: &cny}); err != nil { + t.Fatal(err) + } + p, _ = Find("gift") + if b, _ := p.KeyOwnBalance(k); b.Expiring != nil { + t.Fatalf("typed again in yuan, the part in dollars kept: %+v", b) + } + + // in yuan: the part is in yuan too, the spend at the rate (7) + clockStub(t, at(24, 0)) + spendAt(t, map[time.Time]float64{at(24, 1): 1}) + if err := SetKeyExpiring("gift", k, &Expiring{Amount: 30, Until: "2026-12-31"}); err != nil { + t.Fatal(err) + } + clockStub(t, at(24, 2)) + p, _ = Find("gift") + if e, _ := p.OwnBalanceEstimate(k); *e.Left != 123 || *e.Expiring.Left != 23 { + t.Fatalf("¥100 and ¥30 less $1 at 7: %v, %v", *e.Left, *e.Expiring.Left) + } + if q := ownCards(t)["gift|"]; q.Balance != "≈¥123.00" || q.BalanceSplit[0].Text != "≈¥23.00" || SplitWords(q.BalanceSplit) != "≈¥23.00 until Dec 31" { + t.Fatalf("card in yuan: %+v (%q)", q, SplitWords(q.BalanceSplit)) + } + rateStub(t, 0, false) + if q := ownCards(t)["gift|"]; q.Balance != "" || q.Error == "" || len(q.BalanceSplit) != 0 { + t.Fatalf("spend at no rate is unknown, the part too: %+v", q) + } + + // refused: none for a key with no balance, an amount or date that + // isn't one; a part written by hand that isn't one is dropped + if err := Save(Provider{ID: "bare", Name: "Bare", Chat: "http://127.0.0.1:1/v1", Key: "sk-b"}); err != nil { + t.Fatal(err) + } + if err := SetKeyExpiring("bare", keyID("sk-b"), &Expiring{Amount: 5, Until: "2026-12-31"}); err == nil { + t.Error("credit that expires on a key with no balance") + } + for _, bad := range []Expiring{{Amount: 0, Until: "2026-12-31"}, {Amount: -1, Until: "2026-12-31"}, {Amount: 2e6, Until: "2026-12-31"}, {Amount: 5, Until: "12/31"}, {Amount: 5}} { + if err := SetKeyExpiring("gift", k, &bad); err == nil { + t.Errorf("%+v taken", bad) + } + } + n := normalKeyOwnBalances(map[string]OwnBalance{"a": {USD: 5, Expiring: &Expiring{Amount: 5, Until: "soon"}}}) + if n["a"].USD != 5 || n["a"].Expiring != nil { + t.Errorf("a part that isn't one, written by hand: %+v", n) + } +} + +// A balance saved before parts that expire is read and counted as it was. +func TestTypedBalanceSavedBeforeExpiring(t *testing.T) { + var b OwnBalance + if err := json.Unmarshal([]byte(`{"cny":100,"at":"2026-11-01T01:00:00Z","refill":{"every":"month","day":1}}`), &b); err != nil { + t.Fatal(err) + } + if b.Expiring != nil || *b.CNY != 100 || b.Refill.Day != 1 { + t.Fatalf("%+v", b) + } + out, _ := json.Marshal(b) + if strings.Contains(string(out), "expiring") { + t.Errorf("saved again with a part it never had: %s", out) + } +} + +// What the CLI takes for credit that expires. +func TestExpiringParsed(t *testing.T) { + for in, want := range map[string]Expiring{"20@2026-12-31": {Amount: 20, Until: "2026-12-31"}, " 1,000.5 @ 2027-01-02 ": {Amount: 1000.5, Until: "2027-01-02"}} { + if x, err := ParseExpiring(in); err != nil || x == nil || *x != want { + t.Errorf("%q: %+v %v", in, x, err) + } + } + if x, err := ParseExpiring("off"); err != nil || x != nil { + t.Errorf("off: %+v %v", x, err) + } + for _, in := range []string{"20", "@2026-12-31", "20@", "20@2026-13-01", "¥20@2026-12-31", "0@2026-12-31", "--help"} { + if _, err := ParseExpiring(in); err == nil { + t.Errorf("%q taken", in) + } + } +}