diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 674f1bd67..e4b280e7c 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -362,7 +362,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, 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 key's balance typed by hand (`KeyOwnBalances`, by the key's fingerprint: `{usd | cny, at, refill, expirings}`, [`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, in grants (`expirings`: a list of `{amount, until, at}`, up to `MaxExpiring` (20), each amount in the balance's currency, `until` the last day it counts as 2006-01-02, `at` when it was typed; tenacious_eagle_96548 on Discord: money that stays and promotional credit twice, one good until tomorrow and one the day after). Grants are spent first, as DeepSeek spends its granted balance before the money topped up, and of them the one that ends soonest first (`spendGrants`): the spend is taken piece by piece over the times between `From`, now, and each grant's `at` and end (midnight after `until`, local time), each piece going to the live grant that ends first, and only what grants 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, the grants' remainders included; from a grant's end its remainder counts no more (`expired`, the latest such end), and unspent credit is simply gone. A grant whose end is at or before `From` is dropped on the next write (`liveGrants`). `AddKeyExpiring` (GUI `provider/keyexpiring` `{expiring: {amount, until}}`), `RemoveKeyExpiring` (`{expiring: {at, until}, remove: true}`, matched by `at`, else by `until` and the amount when given; nothing matched is an error) and `ClearKeyExpiring` (`{expiring: null}`) edit them. The pill's menu has Add credit that expires…, which opens one small form (`.abal-form`, the app's popover, no native control but the date field) with the amount, in the balance's currency, and the last day, a month ahead to begin with: Add or Enter saves, Escape or a click outside leaves it, an amount in the other currency or a day gone by is refused with the form kept; then a Remove {amount} for each grant with when it goes beside it, and No credit that expires with two or more, or one that expired. The CLI takes `--expiring amount@yyyy-mm-dd` and `--expiring-remove [amount@]yyyy-mm-dd`, each as often as wanted and applied in order after the balance, every value read before anything is written; `--expiring off` takes every grant off. Each 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. A v0.1.3305 balance's one `expiring` object is read as the first grant (`UnmarshalJSON`) and saved as `expirings` on the next write; a magpie before this reads `expirings` as no grant, so going back loses them from the estimate, not from the file until it writes. Typing the balance again keeps the grants in the same currency and drops them 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`, one per grant soonest first (`set`, `at`, `until`, `left`, `ends`), is the pill's "≈$60.00 left · $5.00 expires tomorrow · $20.00 expires in 30 days" (wrapping at a grant on a narrow row), and the card's `BalanceSplit` a line each 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`, `TestTypedBalanceGrantsSoonestFirst`, `TestTypedBalanceGrantsEdited`, `TestTypedBalanceOneGrantMigrated`, `TestExpiringParsed`, `TestExpiringDayParsed`, `TestKeyBalanceCmd`, `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 9adb3d410..7121cba38 100644 --- a/internal/cli/key_balance_cli.go +++ b/internal/cli/key_balance_cli.go @@ -8,17 +8,31 @@ import ( "github.com/yetone/magpie/internal/provider" ) -const keyBalanceUsage = "magpie provider key-balance [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|off] [--expiring amount@yyyy-mm-dd|off]]" +const keyBalanceUsage = "magpie provider key-balance [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|off] [--expiring amount@yyyy-mm-dd|off]… [--expiring-remove [amount@]yyyy-mm-dd]…]" // keyBalanceCmd shows, or sets, the balance typed by hand on a provider's // API keys whose vendor tells none (tenacious_eagle on Discord): what is // left of it is the amount less what magpie priced the key's calls at // since it was typed, or since it last refilled // (provider/key_balance_own.go). An amount in yuan ("¥100", "100cny") is -// counted down at the dollar's rate magpie last learned. +// counted down at the dollar's rate magpie last learned. Each --expiring +// adds a grant of credit that expires (tenacious_eagle_96548: promotional +// credit twice, gone on two days), off takes every one off, and each +// --expiring-remove takes off the grants through its day (of its amount, +// when given); they are done in the order given, after the balance. func keyBalanceCmd(args []string) error { var rest []string - var refill, expiring *string + var refill *string + type grantOp struct { + x *provider.Expiring // nil: every grant off + remove bool + } + var grants []grantOp + type grantArg struct { + v string + remove bool + } + var grantArgs []grantArg for i := 0; i < len(args); i++ { a := args[i] switch { @@ -28,12 +42,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): + case (a == "--expiring" || a == "--expiring-remove") && i+1 < len(args): i++ - expiring = &args[i] - case strings.HasPrefix(a, "--expiring="): - v := strings.TrimPrefix(a, "--expiring=") - expiring = &v + grantArgs = append(grantArgs, grantArg{args[i], a == "--expiring-remove"}) + case strings.HasPrefix(a, "--expiring=") || strings.HasPrefix(a, "--expiring-remove="): + k, v, _ := strings.Cut(a, "=") + grantArgs = append(grantArgs, grantArg{v, k == "--expiring-remove"}) case strings.HasPrefix(a, "-") && a != "-": // a flag magpie doesn't know, or a negative amount: never data return fmt.Errorf("%s", keyBalanceUsage) @@ -41,7 +55,8 @@ func keyBalanceCmd(args []string) error { rest = append(rest, a) } } - if len(rest) < 1 || len(rest) > 3 || ((refill != nil || expiring != nil) && len(rest) < 2) { + expiring := len(grantArgs) > 0 + if len(rest) < 1 || len(rest) > 3 || ((refill != nil || expiring) && len(rest) < 2) { return fmt.Errorf("%s", keyBalanceUsage) } p, err := provider.Find(rest[0]) @@ -57,18 +72,28 @@ func keyBalanceCmd(args []string) error { return err } } - var x *provider.Expiring - if expiring != nil { - if x, err = provider.ParseExpiring(*expiring); err != nil { + // every grant read before anything is written + for _, g := range grantArgs { + if g.remove { + x, err := provider.ParseExpiringDay(g.v) + if err != nil { + return err + } + grants = append(grants, grantOp{x, true}) + continue + } + x, err := provider.ParseExpiring(g.v) + if err != nil { return err } + grants = append(grants, grantOp{x, false}) } var b *provider.OwnBalance if len(rest) > 2 { if b, err = provider.ParseOwnBalance(rest[2]); err != nil { return err } - if b == nil && (refill != nil || expiring != nil) { + if b == nil && (refill != nil || expiring) { return fmt.Errorf("%s", keyBalanceUsage) } } @@ -93,13 +118,21 @@ func keyBalanceCmd(args []string) error { return err } } - // 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 { + // credit that expires, after the balance it is on top of + for _, g := range grants { + switch { + case g.x == nil: + err = provider.ClearKeyExpiring(p.ID, rest[1]) + case g.remove: + err = provider.RemoveKeyExpiring(p.ID, rest[1], *g.x) + default: + err = provider.AddKeyExpiring(p.ID, rest[1], *g.x) + } + if err != nil { return err } } - if len(rest) > 2 || refill != nil || expiring != nil { + if len(rest) > 2 || refill != nil || expiring { if p, err = provider.Find(p.ID); err != nil { return err } @@ -163,12 +196,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 { + for _, x := range e.Expiring { 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" + out += " · the credit 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 4bcd796b6..2dfb7ea9f 100644 --- a/internal/cli/key_balance_cli_test.go +++ b/internal/cli/key_balance_cli_test.go @@ -74,30 +74,50 @@ 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 { + // credit that expires (tenacious_eagle_96548): a grant each + // --expiring, beside the rest, kept when the balance is typed again in + // its currency, taken off one by one or all + if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "--expiring", "200@2099-12-30", "--expiring=50@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) + if b, _ := typed(); len(b.Expiring) != 2 || b.Expiring[0].Amount != 200 || b.Expiring[0].Until != "2099-12-30" || b.Expiring[0].At.IsZero() || + b.Expiring[1].Amount != 50 || *b.CNY != 700 { + t.Fatalf("--expiring 200@2099-12-30 --expiring 50@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"}} { + {"relay", "Team", "--expiring", "0@2099-12-31"}, {"relay", "--expiring", "1@2099-12-31"}, {"relay", "Team", "off", "--expiring", "1@2099-12-31"}, + {"relay", "Team", "--expiring", "1@2099-12-31", "--expiring", "--help"}, {"relay", "Team", "--expiring-remove", "off"}, + {"relay", "Team", "--expiring-remove", "2099-01-01"}, {"relay", "Team", "--expiring-remove"}} { if err := providerCmd(append([]string{"provider", "key-balance"}, bad...)); err == nil { t.Fatalf("%v taken", bad) } } + if b, _ := typed(); len(b.Expiring) != 2 { + t.Fatalf("a refused --expiring changed them: %+v", b) + } 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 b, _ := typed(); len(b.Expiring) != 2 { + t.Fatalf("typed again in yuan, the credit that expires went: %+v", b) } - if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "--expiring=off"}); err != nil { + if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "--expiring-remove", "200@2099-12-30"}); err != nil { t.Fatal(err) } - if b, _ := typed(); b.Expiring != nil || *b.CNY != 650 { + if b, _ := typed(); len(b.Expiring) != 1 || b.Expiring[0].Amount != 50 { + t.Fatalf("--expiring-remove 200@2099-12-30: %+v", b) + } + // off, then one again: in the order given + if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "--expiring=off", "--expiring", "9@2099-12-29"}); err != nil { + t.Fatal(err) + } + if b, _ := typed(); len(b.Expiring) != 1 || b.Expiring[0].Amount != 9 { + t.Fatalf("--expiring off --expiring 9@2099-12-29: %+v", b) + } + if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "--expiring", "off"}); err != nil { + t.Fatal(err) + } + if b, _ := typed(); len(b.Expiring) != 0 || *b.CNY != 650 { t.Fatalf("--expiring off: %+v", b) } if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "off"}); err != nil { diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index feb91146e..5040af9db 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -98,11 +98,12 @@ 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] [--expiring amount@yyyy-mm-dd|off]] + magpie provider key-balance [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|off] [--expiring amount@yyyy-mm-dd|off]… [--expiring-remove [amount@]yyyy-mm-dd]…] 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; --expiring adds credit that counts through a day and is spent first + (each one a grant, the soonest spent first; off takes every one off) 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 25100cb6f..8173a16a5 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2889,11 +2889,22 @@ 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); } +.sess-menu .pm-note.soon { color: var(--amber); } +/* a grant's amount and last day, added together */ +.pop.abal-form { width: 248px; padding: 0 12px 12px; } +.abal-form .abal-f-h { padding: 10px 0 8px; font-size: 12px; font-weight: 600; } +.abal-form .abal-f { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; } +.abal-form .abal-f-l { flex: none; width: 72px; font-size: 12px; color: var(--muted); } +.abal-form .abal-f-m, .abal-form .abal-f-d { flex: 1; min-width: 0; display: flex; align-items: center; height: 28px; box-sizing: border-box; padding: 0 8px; border: 1px solid var(--line); border-radius: 7px; background: var(--pill); color: var(--fg); font: inherit; font-size: 12.5px; } +.abal-form .abal-f-m:focus-within, .abal-form .abal-f-d:focus { border-color: var(--accent, var(--fg)); outline: none; } +.abal-form .abal-f-c { color: var(--muted); margin-right: 3px; } +.abal-form input.abal-f-n { flex: 1; min-width: 0; height: 26px; padding: 0; border: 0; background: none; color: inherit; font: inherit; font-variant-numeric: tabular-nums; outline: none; } +.abal-form [aria-invalid], .abal-form .abal-f-m.bad { border-color: var(--red); } +.abal-form .abal-f-bar { display: flex; justify-content: flex-end; margin-top: 4px; } .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); } @@ -2967,6 +2978,10 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .accts.keys .acc > :is(.alane, .aspend, .abal):not(.set):not(.open):not(:focus) { padding: 0; box-shadow: none; background: none; } } .accts.keys .acc > .key-acts { flex: none; display: flex; align-items: center; gap: 9px; margin-left: auto; } +/* grants of credit that expire, several on a key: the pill wraps at its + amounts rather than run past the row */ +.accts .acc > .abal.abal-many { display: block; flex: 0 1 auto; min-width: 0; height: auto; min-height: 20px; padding-block: 2px; white-space: normal; text-align: left; line-height: 16px; } +.acc .abal .abal-exp { white-space: nowrap; } .accts.keys .acc .using, .accts.keys .key-acts > .text:not(.quiet) { flex: none; white-space: nowrap; } /* Switch off on hover, beside Remove (wei_VC on X): in a narrow weighted list the weight pill and Make first leave no room for it, and the name @@ -4305,6 +4320,7 @@ body.panel .modal { padding: 16px 12px; } body.web .acc .acc-more { opacity: 1; } body.web .accts.keys .acc > :is(.amodels, .proto, .alane, .aspend, .abal), body.web .accts.keys .key-acts > .text.quiet { max-width: none !important; padding: 0 7px !important; flex-shrink: 0 !important; } body.web .accts.keys .acc > :is(.amodels, .proto, .alane, .aspend, .abal):not(.set) { margin-left: 0 !important; } + body.web .accts.keys .acc > .abal.abal-many { flex-shrink: 1 !important; padding-block: 2px !important; } body.web .accts.keys .key-acts > .text.quiet { margin-right: 0 !important; } body.web #gatewayKeys .acc > .key-quotas { max-width: none !important; padding: 0 7px !important; margin-left: 0 !important; flex-shrink: 0; } body.web #gatewayKeys .acc > .key-quotas:not(.set) { box-shadow: inset 0 0 0 1px var(--line) !important; } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 4a3b9d4c6..98ca333e1 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -63,7 +63,10 @@ const I18N = { "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…": "限期额度…", + "Add credit that expires…": "添加限期额度…", + "Add credit that expires": "添加限期额度", + "Remove {amount}": "去掉 {amount}", + "{who} no longer has {amount} that counts through {last}": "{who} 已去掉算到 {last} 的 {amount} 限期额度", "No credit that expires": "去掉限期额度", "Refills each month…": "每月恢复…", "Refills each week…": "每周恢复…", @@ -4799,7 +4802,10 @@ const I18N = { "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…": "限期額度…", + "Add credit that expires…": "新增限期額度…", + "Add credit that expires": "新增限期額度", + "Remove {amount}": "移除 {amount}", + "{who} no longer has {amount} that counts through {last}": "{who} 已移除算到 {last} 的 {amount} 限期額度", "No credit that expires": "去掉限期額度", "Refills each month…": "每月恢復…", "Refills each week…": "每週恢復…", @@ -9520,7 +9526,10 @@ const I18N = { "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…": "期限付きクレジット…", + "Add credit that expires…": "期限付きクレジットを追加…", + "Add credit that expires": "期限付きクレジットを追加", + "Remove {amount}": "{amount} を外す", + "{who} no longer has {amount} that counts through {last}": "{who} の {last} まで有効な {amount} を外しました", "No credit that expires": "期限付きクレジットなし", "Refills each month…": "毎月戻す…", "Refills each week…": "毎週戻す…", @@ -14243,7 +14252,10 @@ const I18N = { "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…", + "Add credit that expires…": "Ablaufendes Guthaben hinzufügen…", + "Add credit that expires": "Ablaufendes Guthaben hinzufügen", + "Remove {amount}": "{amount} entfernen", + "{who} no longer has {amount} that counts through {last}": "{who} hat die {amount} bis {last} nicht mehr", "No credit that expires": "Kein ablaufendes Guthaben", "Refills each month…": "Monatlich auffüllen…", "Refills each week…": "Wöchentlich auffüllen…", diff --git a/internal/gui/assets/keybalance.js b/internal/gui/assets/keybalance.js index 0ae7f4939..4f007a4e0 100644 --- a/internal/gui/assets/keybalance.js +++ b/internal/gui/assets/keybalance.js @@ -5,10 +5,13 @@ // 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. -// 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. +// Credit may come on top that expires on a day, in grants (promotional +// credit twice, gone on two days: tenacious_eagle_96548), the one that +// goes soonest spent first: the pill says how much of each is left and in +// how many days, amber from a week; each is added in one small form, +// amount and last day together, and taken off from the menu. 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 // yuan, a sign or a word saying which, else unit; null for none @@ -38,12 +41,17 @@ function keyBalancePill(p, k) { 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) { + // each grant still counting, soonest first as the server lists them + const xs = (b?.expiring || []).map((x) => ({ ...x, in: expiresIn(x.ends), last: dayOf(new Date(new Date(x.ends) - 1)) })); + for (const x of xs) { + if (!(x.left > 0)) continue; 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.append(" · ", el("span", "abal-exp" + (x.in.soon ? " soon" : ""), x.in.days <= 0 ? t("{amount} expires today", { amount }) + : x.in.days === 1 ? t("{amount} expires tomorrow", { amount }) : t("{amount} expires in {n} days", { amount, n: x.in.days }))); } + // two or more wrap at a grant on a narrow row (a class, not :has(), + // which Safari before 15.4 drops the rule for) + pill.classList.toggle("abal-many", pill.querySelectorAll(".abal-exp").length > 1); 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()), @@ -51,8 +59,8 @@ 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) }) : "", + ...xs.map((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(x.last) })), 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" } }, @@ -63,19 +71,55 @@ function keyBalancePill(p, k) { : 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 unexpiring = (x) => accountAction("provider/keyexpiring", { id: p.id, account: k.id, expiring: { at: x.at, until: x.until }, remove: true }, + t("{who} no longer has {amount} that counts through {last}", { who: name, amount: moneyText(x.set, cny), last: dateText(x.last) })); + // a grant of credit that expires: its amount, in the balance's + // currency, and its last day, in one small form under the pill; Add or + // Enter saves, Escape or a click outside leaves it 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"; - }); + const own = cny ? "cny" : "usd", head = t("Add credit that expires"); + const box = el("div", "pop abal-form"); + box.setAttribute("role", "dialog"); + box.setAttribute("aria-label", head); + const amount = el("input", "abal-f-n"), day = el("input", "abal-f-d"), add = el("button", "text primary", t("Add")); + amount.type = "text"; + amount.inputMode = "decimal"; + amount.autocomplete = "off"; + amount.placeholder = "0.00"; + amount.setAttribute("aria-label", t(cny ? "Credit that expires, in CNY" : "Credit that expires, in USD")); + day.type = "date"; + day.min = dayOf(new Date()); + // a month from today: a promotion's usual run, and the picker opens there + const soon = new Date(); + soon.setDate(soon.getDate() + 30); + day.value = dayOf(soon); + day.setAttribute("aria-label", t("Last day it counts")); + add.type = "button"; + const field = (label, ...kids) => { const f = el("label", "abal-f"); f.append(el("span", "abal-f-l", label), ...kids); return f; }; + const money = el("span", "abal-f-m"); + money.append(el("span", "abal-f-c", cny ? "¥" : "$"), amount); + const bar = el("div", "abal-f-bar"); + bar.append(add); + box.append(el("div", "abal-f-h", head), field(t("Amount"), money), field(t("Last day it counts"), day), bar); + const save = () => { + const v = balanceAmount(amount.value, own), n = v && v.n > 0 && v.cny === cny ? v.n : null, until = lastDay(day.value); + amount.toggleAttribute("aria-invalid", n == null); + money.classList.toggle("bad", n == null); + day.toggleAttribute("aria-invalid", n != null && !until); + if (n == null) { status(t("Credit that expires is an amount above 0, in the balance's currency"), "err"); return amount.focus(NO_SCROLL); } + if (!until) { status(t("The last day is a date from today on, as 2026-12-31"), "err"); return day.focus(NO_SCROLL); } + closeProtoMenu(); + expiring({ amount: n, until }); + }; + add.onclick = (e) => { e.stopPropagation(); save(); }; + box.onclick = (e) => e.stopPropagation(); + document.body.append(box); + placeMenu(box, pill); + pill.classList.add("open"); + holdMenu(box, pill, (e) => { + if (e.key === "Enter" && box.contains(e.target) && e.target !== add) { e.preventDefault(); e.stopPropagation(); save(); } + }, (e) => { if (scrollCloses(box, e)) closeProtoMenu(); }); + amount.focus(NO_SCROLL); }; // 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 @@ -130,16 +174,23 @@ function keyBalancePill(p, k) { e.stopPropagation(); if (!b) return type(); if (pill.classList.contains("open")) return closeProtoMenu(); + const grants = xs.map((x, i) => ({ v: "x" + i, name: t("Remove {amount}", { amount: moneyText(x.set, cny) }), literalName: true, note: x.in.label, + title: 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(x.last) }) })); 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: "exp", name: "Add credit that expires…", note: "" }, + ...grants, + ...xs.length > 1 || 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 === "exp" ? credit() : v === "noexp" ? expiring(null) : v === "month" ? monthly() : v === "week" ? weekly() - : v === "never" ? b.refill && refill(null) : type(), "Balance", "sess-menu"); + : v === "never" ? b.refill && refill(null) : v[0] === "x" ? unexpiring(xs[+v.slice(1)]) : type(), "Balance", "sess-menu"); + // a grant that goes within a week says so in amber, as on the pill + const items = protoMenu?.box.querySelectorAll(".pm-item"); + xs.forEach((x, i) => x.in.soon && items?.[2 + i]?.querySelector(".pm-note").classList.add("soon")); }; return pill; } diff --git a/internal/gui/key_own_balance_test.go b/internal/gui/key_own_balance_test.go index eaf9e591a..8bcdac473 100644 --- a/internal/gui/key_own_balance_test.go +++ b/internal/gui/key_own_balance_test.go @@ -103,9 +103,26 @@ func TestKeyOwnBalanceRoutes(t *testing.T) { // 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 { + if _, b := listed(); b == nil || b.Set != 700 || *b.Left != 750 || len(b.Expiring) != 1 || *b.Expiring[0].Left != 50 || b.Expiring[0].Ends.Year() != 2100 { t.Fatalf("¥700 and ¥50 that expires: %+v %+v", b, b.Expiring) } + // a second grant, sooner: listed first, both in the left; one taken + // off by when it was typed leaves the other + call("POST", "/api/provider/keyexpiring", `{"id":"relay","account":"`+key+`","expiring":{"amount":20,"until":"2099-12-30"}}`) + _, b := listed() + if b == nil || *b.Left != 770 || len(b.Expiring) != 2 || b.Expiring[0].Set != 20 || b.Expiring[0].Until != "2099-12-30" || b.Expiring[1].Set != 50 { + t.Fatalf("¥50 and ¥20 that expire: %+v", b) + } + at, _ := json.Marshal(b.Expiring[1].At) + call("POST", "/api/provider/keyexpiring", `{"id":"relay","account":"`+key+`","expiring":{"at":`+string(at)+`,"until":"2099-12-31"},"remove":true}`) + if _, b := listed(); b == nil || *b.Left != 720 || len(b.Expiring) != 1 || b.Expiring[0].Set != 20 { + t.Fatalf("¥50 taken off: %+v", b) + } + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/provider/keyexpiring", strings.NewReader(`{"id":"relay","account":"`+key+`","expiring":{"at":`+string(at)+`,"until":"2099-12-31"},"remove":true}`))) + if w.Code == 200 { + t.Error("taking off a grant already gone") + } 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+`}`))) @@ -114,7 +131,7 @@ func TestKeyOwnBalanceRoutes(t *testing.T) { } } call("POST", "/api/provider/keyexpiring", `{"id":"relay","account":"`+key+`","expiring":null}`) - if _, b := listed(); b == nil || b.Expiring != nil || *b.Left != 700 { + if _, b := listed(); b == nil || len(b.Expiring) != 0 || *b.Left != 700 { t.Fatalf("expiring off: %+v", b) } call("POST", "/api/provider/keyownbalance", `{"id":"relay","account":"`+key+`","balance":null}`) diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 91ee1eb19..11da690b3 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -1676,9 +1676,12 @@ 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, for keyexpiring: a grant of credit that expires + // on the key's balance typed, {amount, until}, added beside + // the others; with Remove, the grant {at} (or every one + // {until}) taken off; none takes every grant off Expiring *provider.Expiring `json:"expiring"` + Remove bool `json:"remove"` // Alias, for accountname: the account's name of the user's // own, "" to take it off (#1515) Alias string `json:"alias"` @@ -2405,7 +2408,16 @@ func providerRoutes(mux *http.ServeMux, w Windows) { return } case "keyexpiring": - if err := provider.SetKeyExpiring(in.ID, req.Account, req.Expiring); err != nil { + var err error + switch { + case req.Expiring == nil: + err = provider.ClearKeyExpiring(in.ID, req.Account) + case req.Remove: + err = provider.RemoveKeyExpiring(in.ID, req.Account, *req.Expiring) + default: + err = provider.AddKeyExpiring(in.ID, req.Account, *req.Expiring) + } + if err != nil { fail(rw, err) return } diff --git a/internal/gui/tests/key-balance-expiring.test.cjs b/internal/gui/tests/key-balance-expiring.test.cjs index 34ce3e095..71f6c809a 100644 --- a/internal/gui/tests/key-balance-expiring.test.cjs +++ b/internal/gui/tests/key-balance-expiring.test.cjs @@ -1,16 +1,21 @@ // 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. +// A key's balance typed by hand may have credit on top that expires, in +// grants (tenacious_eagle_96548 on Discord: money that stays, and +// promotional credit twice, one gone tomorrow and one the day after). +// The key's pill says how much of each is left and in how many days it +// goes, amber from a week; the Usage page's card and the panel's Balances +// say each on a line under the balance, amber the same way. From the +// pill's menu (the app's, no native select), Add credit that expires… +// opens one small form with the amount, in the balance's currency, and +// the last day together, the day a month ahead to begin with: Add or +// Enter posts provider/keyexpiring, a sign of the other currency or a day +// gone by is refused with the form kept, and Escape leaves it with +// nothing posted. Each grant is in the menu as Remove {amount}, with when +// it goes (amber within a week), and posts its removal by when it was +// typed; No credit that expires takes every one off, offered with two or +// more, or credit that has expired, which the pill's title says no longer +// counts. In every language, at a phone's width the rows and the form +// stay inside the window. const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); const path = require("node:path"); @@ -23,22 +28,25 @@ const assets = path.resolve(__dirname, "../assets"); 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 grant = (set, left, n, at = ago) => ({ set, at, until: dayIn(n), left, ends: ends(n) }); 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: "k1", name: "Main", masked: "sk-…one", on: true, balance: { set: 70, at: ago, spent: 10, left: 80, expiring: [grant(30, 20, 30)] } }, + // the reporter's: two grants, tomorrow's and the day after's + { id: "k2", name: "Team", masked: "sk-…two", on: true, balance: { set: 40, at: ago, spent: 0, left: 53, currency: "cny", rate: 7.2, + expiring: [grant(5, 5, 1, new Date(Date.now() - 2 * 864e5).toISOString()), grant(8, 8, 2)] } }, { 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: "Main", windows: [], balance: "$80.00", balanceSplit: [{ text: "$20.00", expires: ends(30) }] }, + { provider: "relay", name: "Relay", icon: "generic", user: "Team", windows: [], balance: "¥53.00", balanceSplit: [{ text: "¥5.00", expires: ends(1) }, { text: "¥8.00", expires: ends(2) }] }, { provider: "relay", name: "Relay", icon: "generic", user: "Last", windows: [], balance: "$9.00", balanceSplit: [{ text: "$1.00", expires: ends(0) }] }, ]; @@ -50,6 +58,7 @@ function serve(lang, posts, relay) { 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") posts.state = (posts.state || 0) + 1; 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); @@ -60,14 +69,23 @@ function serve(lang, posts, relay) { 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 }); + posts.push({ action, body, state: posts.state || 0 }); if (action === "keyexpiring") { - const b = relay.keyList.find((x) => x.id === body.account).balance; + // as the server: a grant added, one taken off by when it was + // typed, or every one; the soonest to go listed first + const b = relay.keyList.find((x) => x.id === body.account).balance, xs = b.expiring || []; delete b.expired; - if (body.expiring) { + if (!body.expiring) { for (const x of xs) b.left -= x.left; b.expiring = []; } + else if (body.remove) { + const x = xs.find((x) => x.at === body.expiring.at); + b.left -= x.left; + b.expiring = xs.filter((y) => y !== x); + } else { 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; + b.left += body.expiring.amount; + b.expiring = [...xs, { set: body.expiring.amount, at: new Date().toISOString(), until: body.expiring.until, left: body.expiring.amount, ends: new Date(y, m - 1, d + 1).toISOString() }] + .sort((a, c) => new Date(a.ends) - new Date(c.ends)); + } } return json(providers); } @@ -78,29 +96,32 @@ function serve(lang, posts, relay) { }; } +// each language's words, from its i18n templates +const lang = (o) => ({ ...o, left: (v) => o.left.replace("{usd}", v), expIn: (a, n) => o.expIn.replace("{amount}", a).replace("{n}", n), + expTomorrow: (a) => o.expTomorrow.replace("{amount}", a), inN: (n) => o.inN.replace("{n}", n), remove: (a) => o.remove.replace("{amount}", a) }); 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" }, + en: lang({ left: "≈{usd} left", expIn: "{amount} expires in {n} days", expTomorrow: "{amount} expires tomorrow", inN: "Expires in {n} days", tomorrow: "Expires tomorrow", + today: "Expires today", exp: "Add credit that expires…", head: "Add credit that expires", add: "Add", remove: "Remove {amount}", 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: lang({ left: "≈{usd} 剩余", expIn: "{amount} {n} 天后到期", expTomorrow: "{amount} 明天到期", inN: "{n} 天后到期", tomorrow: "明天到期", + today: "今天到期", exp: "添加限期额度…", head: "添加限期额度", add: "添加", remove: "去掉 {amount}", noexp: "去掉限期额度", + badAmount: "限期额度是大于 0 的金额,用余额的货币", badDay: "最后一天是今天或以后的日期,如 2026-12-31", gone: "已不再计入" }), + "zh-TW": lang({ left: "≈{usd} 剩餘", expIn: "{amount} {n} 天後到期", expTomorrow: "{amount} 明天到期", inN: "{n} 天後到期", tomorrow: "明天到期", + today: "今天到期", exp: "新增限期額度…", head: "新增限期額度", add: "新增", remove: "移除 {amount}", noexp: "去掉限期額度", + badAmount: "限期額度是大於 0 的金額,用餘額的貨幣", badDay: "最後一天是今天或以後的日期,如 2026-12-31", gone: "已不再計入" }), + ja: lang({ left: "残り ≈{usd}", expIn: "{amount} は {n} 日後に失効", expTomorrow: "{amount} は明日で失効", inN: "{n} 日後に失効", tomorrow: "明日で失効", + today: "今日で失効", exp: "期限付きクレジットを追加…", head: "期限付きクレジットを追加", add: "追加", remove: "{amount} を外す", noexp: "期限付きクレジットなし", + badAmount: "期限付きクレジットは 0 より大きい金額です(残高の通貨で)", badDay: "最終日は今日以降の日付です(例: 2026-12-31)", gone: "もう数えません" }), + de: lang({ left: "≈{usd} übrig", expIn: "{amount} läuft in {n} Tagen ab", expTomorrow: "{amount} läuft morgen ab", inN: "Läuft in {n} Tagen ab", tomorrow: "Läuft morgen ab", + today: "Läuft heute ab", exp: "Ablaufendes Guthaben hinzufügen…", head: "Ablaufendes Guthaben hinzufügen", add: "Hinzufügen", remove: "{amount} entfernen", 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) => { + test(`${engine} ${lang} ${width}px: a key's grants of credit that expires, each said in days, added in one form and taken off one by one`, async (t) => { const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); let page; t.after(async () => { @@ -120,21 +141,22 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", 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 + // the Usage page's cards: a line under the balance for each grant, + // amber within a week await page.goto("http://magpie.test/?view=usage&tab=usage"); - await page.waitForFunction(() => document.querySelectorAll("#subscriptionUsage .bal-part").length >= 6); + await page.waitForFunction(() => document.querySelectorAll("#subscriptionUsage .bal-part").length >= 7); 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(() => { + assert.deepEqual(await lines(), [[[w.inN(30), "$20.00", false]], [[w.tomorrow, "¥5.00", true], [w.inN(2), "¥8.00", true]], [[w.today, "$1.00", true]]]); + const amber = (sel) => page.evaluate((sel) => { 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"); + return [...document.querySelectorAll(sel)].map((b) => getComputedStyle(b).color === a); + }, sel); + assert.deepEqual(await amber(".bal-part.soon b"), [true, 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 @@ -142,23 +164,24 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", 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); + await panel.waitForFunction(() => document.querySelectorAll("#panelQuota .pq-bp").length >= 4); 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]]); + [[w.inN(30), "$20.00", false], [w.tomorrow, "¥5.00", true], [w.inN(2), "¥8.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); + await page.waitForLoadState("networkidle"); 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 form = page.locator(".abal-form"); + const amount = form.locator("input.abal-f-n"), day = form.locator("input.abal-f-d"), add = form.locator("button"); 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"); + if (await menu.isVisible() || await form.isVisible()) await page.keyboard.press("Escape"); await page.waitForTimeout(150); await row(id).hover(); await pill(id).click(); @@ -167,70 +190,118 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", 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"); + // the save is done once the app has read its state again, which + // it does after drawing the providers' rows + for (let i = 0; i < 60 && (posts.state || 0) <= posts.at(-1).state; i++) await new Promise((r) => setTimeout(r, 50)); + await page.waitForTimeout(200); return posts.at(-1); }; - const over = () => page.evaluate(() => [...document.querySelectorAll(".editor .accts .acc")].filter((e) => e.getBoundingClientRect().right > innerWidth + 1).length); + // a row, or anything in it, past the list's edge or the window's, + // or the form past the window's + const over = () => page.evaluate(() => { + const list = document.querySelector(".editor .accts").getBoundingClientRect(), edge = Math.min(innerWidth, list.right); + return [...document.querySelectorAll(".editor .accts .acc, .editor .accts .acc *")].filter((e) => e.getBoundingClientRect().right > edge + 1).map((e) => e.className) + .concat([...document.querySelectorAll(".abal-form")].filter((e) => e.getBoundingClientRect().right > innerWidth + 1 || e.getBoundingClientRect().left < -1).map(() => "abal-form")); + }); - 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.equal(await pill("k1").textContent(), w.left("$80.00") + " · " + w.expIn("$20.00", 30)); + assert.equal(await pill("k2").textContent(), w.left("¥53.00") + " · " + w.expTomorrow("¥5.00") + " · " + w.expIn("¥8.00", 2)); + assert.equal(await pill("k3").textContent(), w.left("$10.00")); + assert.deepEqual(await page.evaluate(() => [...document.querySelectorAll(".abal .abal-exp")].map((e) => e.classList.contains("soon"))), [false, true, true]); + assert.deepEqual(await amber(".abal .abal-exp.soon"), [true, 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"); + assert.deepEqual(await over(), [], "a key's row past the window's edge"); - // k3: a sign of the other currency is refused, then a day gone by + // k2's menu: each grant to take off, when it goes said beside it + await open("k2"); + assert.deepEqual(await menu.locator(".pm-item").evaluateAll((es) => es.map((e) => [e.querySelector(".pm-name").textContent, e.querySelector(".pm-note").textContent, e.querySelector(".pm-note").classList.contains("soon")]).slice(1, 5)), + [[w.exp, "", false], [w.remove("¥5.00"), w.tomorrow, true], [w.remove("¥8.00"), w.inN(2), true], [w.noexp, "", false]]); + assert.deepEqual(await amber(".proto-menu .pm-note.soon"), [true, true], "a grant going within a week isn't amber in the menu"); + + // k3: the form, amount and day together, the day a month ahead await open("k3"); + assert.equal(await item(w.noexp).count(), 1, "credit that expired can't be taken off"); await item(w.exp).click(); - await box("k3").waitFor(); + await form.waitFor(); + assert.equal(await form.getAttribute("aria-label"), w.head); + assert.equal(await add.textContent(), w.add); + assert.equal(await amount.evaluate((e) => e === document.activeElement), true, "the amount hasn't the focus"); + assert.equal(await day.inputValue(), dayIn(30)); + assert.deepEqual(await over(), [], "the form past the window's edge"); let n = posts.length; - await box("k3").fill("¥15"); - await box("k3").press("Enter"); - await page.waitForTimeout(300); + // a sign of the other currency: refused, the form kept + await amount.fill("¥15"); + await add.click(); + await page.waitForTimeout(200); 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"); + assert.equal(await form.isVisible(), true, "a refused amount closed the form"); + assert.equal(await form.locator(".abal-f-m.bad").count(), 1, "the refused amount isn't marked"); + // a day gone by: refused, the form kept + await amount.fill("15"); await day.fill(dayIn(-1)); - await day.press("Enter"); - await page.waitForTimeout(300); + await amount.press("Enter"); + await page.waitForTimeout(200); assert.equal(posts.length, n, "a day gone by was posted"); assert.equal(await page.locator("#status").textContent(), w.badDay); - await page.waitForTimeout(300); + assert.equal(await form.isVisible(), true, "a refused day closed the form"); + // Escape leaves it, nothing posted + await page.keyboard.press("Escape"); + await form.waitFor({ state: "detached" }); + assert.equal(posts.length, n, "Escape posted"); + // Enter adds, with the day it began with 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"); + await form.waitFor(); + await amount.fill("15"); + await amount.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"); + assert.deepEqual(p.body, { id: "relay", account: "k3", expiring: { amount: 15, until: dayIn(30) } }); + await form.waitFor({ state: "detached" }); + assert.equal(await pill("k3").textContent(), w.left("$25.00") + " · " + w.expIn("$15.00", 30)); + // Add adds a second, sooner: listed first + await open("k3"); + await item(w.exp).click(); + await form.waitFor(); + n = posts.length; + await amount.fill("4"); + await day.fill(dayIn(10)); + await add.click(); + p = await posted(n); + assert.deepEqual(p.body, { id: "relay", account: "k3", expiring: { amount: 4, until: dayIn(10) } }); + assert.equal(await pill("k3").textContent(), w.left("$29.00") + " · " + w.expIn("$4.00", 10) + " · " + w.expIn("$15.00", 30)); + assert.deepEqual(await over(), [], "a key's row with two grants past the window's edge"); - // k1's taken off + // k2's day after's taken off, by when it was typed: the second, + // not the first in the list + const k2at = relay.keyList[1].balance.expiring[1].at; + await open("k2"); + n = posts.length; + await item(w.remove("¥8.00")).click(); + p = await posted(n); + assert.deepEqual(p.body, { id: "relay", account: "k2", expiring: { at: k2at, until: dayIn(2) }, remove: true }); + assert.equal(await pill("k2").textContent(), w.left("¥45.00") + " · " + w.expTomorrow("¥5.00")); + + // k1's one grant is taken off as itself; with one, no "every one" await open("k1"); + assert.equal(await item(w.noexp).count(), 0, "every one offered for one grant"); + n = posts.length; + await item(w.remove("$30.00")).click(); + p = await posted(n); + assert.equal(p.body.remove, true); + assert.equal(await pill("k1").textContent(), w.left("$60.00")); + + // k3's two taken off at once + await open("k3"); 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); + assert.deepEqual(p.body, { id: "relay", account: "k3", expiring: null }); + assert.equal(await pill("k3").textContent(), w.left("$10.00")); - 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); + const stripes = await page.evaluate(() => [...document.querySelectorAll(".abal, .abal-form, .abal-form *, .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/key_balance_own.go b/internal/provider/key_balance_own.go index 105f8d2d6..9c236b0f4 100644 --- a/internal/provider/key_balance_own.go +++ b/internal/provider/key_balance_own.go @@ -19,16 +19,22 @@ 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. +// It may have credit that expires on top of it (the same user: some +// vendors split a balance into money that stays and credit good until a +// date), several grants of it each to its own day (promotional credit +// twice, gone tomorrow and the day after). Credit is spent before the +// money that stays, as DeepSeek spends its granted balance before the +// money topped up, and of the grants the one that goes soonest first; +// from the end of its last day, local time, a grant counts no more. The +// card says how much of each is left and in how many days it goes. A +// balance typed before has none and is counted as it was, and one saved +// by v0.1.3305 with its one grant (`expiring`) is read with that grant. import ( + "encoding/json" "fmt" "math" + "slices" "strconv" "strings" "time" @@ -44,15 +50,37 @@ 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 the credit on top of the balance, in its currency, each + // grant good until a day; none for none + Expiring []Expiring `json:"expirings,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. +// MaxExpiring bounds the grants of credit that expires on one key. +const MaxExpiring = 20 + +// UnmarshalJSON reads b as saved, and a v0.1.3305 balance's one grant +// (`expiring`, an object) as the first of its grants: an older magpie +// reads the list's field as nothing, never as a balance it can't parse. +func (b *OwnBalance) UnmarshalJSON(data []byte) error { + type plain OwnBalance + var v struct { + plain + One *Expiring `json:"expiring"` + } + if err := json.Unmarshal(data, &v); err != nil { + return err + } + *b = OwnBalance(v.plain) + if v.One != nil && !slices.Contains(b.Expiring, *v.One) { + b.Expiring = append([]Expiring{*v.One}, b.Expiring...) + } + return nil +} + +// Expiring is a grant of 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"` @@ -174,23 +202,24 @@ 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 + // Expiring is the grants of credit that expires not expired yet, + // the soonest to go first + Expiring []ExpiringLeft `json:"expiring,omitempty"` + // Expired is the end of the last grant that has expired and still + // tells what the rest paid; 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. +// ExpiringLeft is what is left of a grant of credit that expires: Set as +// typed, At, Until (the last day it counts, as typed), Left of it now (in +// the balance's currency) 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"` + Set float64 `json:"set"` + At time.Time `json:"at"` + Until string `json:"until"` + Left *float64 `json:"left"` + Ends time.Time `json:"ends"` } // KeySpent is usage.KeySpent, which package usage sets: what the calls @@ -258,48 +287,118 @@ func (p Provider) OwnBalanceEstimate(keyID string) (BalanceEstimate, bool) { 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 - } - } + // credit that expires takes the spend first, the grant that goes + // soonest before the others; what it took after From is not the + // rest's to pay + took, unknown := 0.0, false + e.Expiring, e.Expired, took, unknown = spendGrants(b.Expiring, e.From, now, spent, inCur) + if unknown { + e.Expiring, e.Expired = nil, nil + return e, true // spend counted at no rate: unknown } 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 + for _, x := range e.Expiring { + left += *x.Left } e.Left = &left return e, true } +// spendGrants lays the spend on a key over its grants of credit that +// expires: from the first grant's At (or from, if sooner) to now, each +// stretch between one grant's start or end and the next is spent from the +// grants counting through it, the one that ends soonest first, and what +// they don't cover falls to the rest of the balance. spent(t) is the USD +// spent from t to now; inCur turns it into the balance's currency, false +// while it can't. It says what is left of each grant still counting, the +// end of the last one gone, what the grants took from from on, and true +// when the spend couldn't be counted. +func spendGrants(grants []Expiring, from, now time.Time, spent func(time.Time) float64, inCur func(float64) (float64, bool)) (left []ExpiringLeft, expired *time.Time, took float64, unknown bool) { + type grant struct { + x Expiring + end time.Time + used float64 + usedFrom float64 + } + var gs []*grant + for _, x := range grants { + if end, ok := x.End(now.Location()); ok { + gs = append(gs, &grant{x: x, end: end}) + } + } + if len(gs) == 0 { + return nil, nil, 0, false + } + // soonest end first; of two ending together, the one given first + slices.SortStableFunc(gs, func(a, c *grant) int { + if n := a.end.Compare(c.end); n != 0 { + return n + } + return a.x.At.Compare(c.x.At) + }) + marks := []time.Time{from, now} + for _, g := range gs { + marks = append(marks, g.x.At, g.end) + } + slices.SortFunc(marks, time.Time.Compare) + marks = slices.CompactFunc(marks, time.Time.Equal) + // spent is asked once a mark: it reads the usage ledger + sp := map[int]float64{} + spentAt := func(i int) float64 { + v, ok := sp[i] + if !ok { + v = spent(marks[i]) + sp[i] = v + } + return v + } + for i := 0; i+1 < len(marks); i++ { + a := marks[i] + if !a.Before(now) { + break + } + var live []*grant + for _, g := range gs { + if !g.x.At.After(a) && g.end.After(a) && g.used < g.x.Amount { + live = append(live, g) + } + } + if len(live) == 0 { + continue + } + s, ok := inCur(spentAt(i) - spentAt(i+1)) + if !ok { + return nil, nil, 0, true + } + for _, g := range live { + if s <= 0 { + break + } + u := min(s, g.x.Amount-g.used) + g.used += u + s -= u + if !a.Before(from) { + g.usedFrom += u + } + } + } + for _, g := range gs { + took += g.usedFrom + if g.end.After(now) { + l := g.x.Amount - g.used + left = append(left, ExpiringLeft{Set: g.x.Amount, At: g.x.At, Until: g.x.Until, Left: &l, Ends: g.end}) + } else if expired == nil || g.end.After(*expired) { + end := g.end + expired = &end + } + } + return left, expired, took, false +} + // TakesOwnBalance says p's keys may have a balance typed by hand: keys // whose vendor tells none magpie knows where to ask. A relay whose query // is looked for (probesBalance) takes one too: when none is found, the @@ -333,10 +432,13 @@ 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}} + // of it, each grant of credit that expires, and when (a line + // each, the soonest to go first) + for _, x := range e.Expiring { + if *x.Left > 0 { + ends := x.Ends + q.BalanceSplit = append(q.BalanceSplit, BalancePart{Text: ownBalanceText(*x.Left, e.Currency), Expires: &ends}) + } } } return q, true @@ -359,8 +461,8 @@ 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, 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). +// no Expiring, the credit that expires the key had in the same currency +// (in the other, its amounts would mean other sums, so they go). func SetKeyOwnBalance(id, ref string, b *OwnBalance) error { if b != nil { if err := checkOwnBalance(*b); err != nil { @@ -376,35 +478,65 @@ 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) { + if len(v.Expiring) == 0 && 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 - } +// AddKeyExpiring gives the balance typed for the key ref of the provider +// id a grant x of credit that expires, in the balance's currency, counted +// from now, beside the grants it has. A key with no balance typed takes +// none: type the balance that stays first, 0 when all of it expires. +func AddKeyExpiring(id, ref string, x Expiring) error { + 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 + if len(had.Expiring) >= MaxExpiring { + return nil, fmt.Errorf("a key has at most %d grants of credit that expires: remove one first", MaxExpiring) } - v := *x - v.At = ownNow().UTC() - had.Expiring = &v + x.At = ownNow().UTC() + had.Expiring = append(slices.Clone(had.Expiring), x) + return &had, nil + }) +} + +// RemoveKeyExpiring takes a grant of credit that expires off the balance +// typed for the key ref of the provider id: the one given At, or with no +// At every one through Until (of Amount, when given). One that matches +// none is an error, and the rest of the balance stays as it was. +func RemoveKeyExpiring(id, ref string, x Expiring) error { + return editOwnBalance(id, ref, func(had OwnBalance, ok bool) (*OwnBalance, error) { + if !ok { + return nil, fmt.Errorf("the key has no balance typed") + } + keep := slices.DeleteFunc(slices.Clone(had.Expiring), func(g Expiring) bool { + if !x.At.IsZero() { + return g.At.Equal(x.At) + } + return g.Until == x.Until && (x.Amount == 0 || g.Amount == x.Amount) + }) + if len(keep) == len(had.Expiring) { + return nil, fmt.Errorf("the key has no such credit that expires: %s", x.Until) + } + had.Expiring = keep + return &had, nil + }) +} + +// ClearKeyExpiring takes every grant of credit that expires off the +// balance typed for the key ref of the provider id; the rest stays. +func ClearKeyExpiring(id, ref string) error { + return editOwnBalance(id, ref, func(had OwnBalance, ok bool) (*OwnBalance, error) { + if !ok { + return nil, fmt.Errorf("the key has no balance typed") + } + had.Expiring = nil return &had, nil }) } @@ -451,6 +583,9 @@ func editOwnBalance(id, ref string, edit func(had OwnBalance, ok bool) (*OwnBala if err != nil { return err } + if b != nil { + b.Expiring = liveGrants(*b, ownNow()) + } if b == nil { if !ok { return nil @@ -471,6 +606,26 @@ func editOwnBalance(id, ref string, edit func(had OwnBalance, ok bool) (*OwnBala return nil } +// liveGrants are b's grants of credit that expires that still tell +// something: those that ended before what b's spend is counted from (it +// was typed, or refilled) took nothing the rest paid for, so they go. +func liveGrants(b OwnBalance, now time.Time) []Expiring { + from := b.At + if b.Refill != nil { + if l := b.Refill.Last(now); l.After(from) { + from = l + } + } + keep := slices.DeleteFunc(slices.Clone(b.Expiring), func(x Expiring) bool { + end, ok := x.End(now.Location()) + return ok && !end.After(from) + }) + if len(keep) == 0 { + return nil + } + return keep +} + // checkOwnBalance says what is wrong with a balance typed, nil when // nothing is. func checkOwnBalance(b OwnBalance) error { @@ -481,8 +636,11 @@ 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 { + if len(b.Expiring) > MaxExpiring { + return fmt.Errorf("a key has at most %d grants of credit that expires, not %d", MaxExpiring, len(b.Expiring)) + } + for _, x := range b.Expiring { + if err := x.check(); err != nil { return err } } @@ -517,6 +675,25 @@ func ParseExpiring(s string) (*Expiring, error) { return &x, nil } +// ParseExpiringDay reads which grants of credit that expires to take off, +// as the CLI takes it: a day, "2026-12-31", every grant through it, or +// "20@2026-12-31", the one of that amount. +func ParseExpiringDay(s string) (*Expiring, error) { + a := strings.TrimSpace(s) + if !strings.Contains(a, "@") { + x := Expiring{Until: a} + if _, ok := x.End(time.UTC); !ok { + return nil, fmt.Errorf("credit to take off is a day (2026-12-31) or amount@day (20@2026-12-31), not %q", s) + } + return &x, nil + } + x, err := ParseExpiring(a) + if err != nil || x == nil { + return nil, fmt.Errorf("credit to take off is a day (2026-12-31) or amount@day (20@2026-12-31), not %q", s) + } + 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). @@ -605,8 +782,13 @@ 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 + // nor a grant of credit that expires + b.Expiring = slices.DeleteFunc(slices.Clone(b.Expiring), func(x Expiring) bool { return x.check() != nil }) + if len(b.Expiring) > MaxExpiring { + b.Expiring = b.Expiring[:MaxExpiring] + } + if len(b.Expiring) == 0 { + b.Expiring = nil } 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 20e39c8c4..236bee69d 100644 --- a/internal/provider/key_balance_own_test.go +++ b/internal/provider/key_balance_own_test.go @@ -463,7 +463,10 @@ func TestTypedBalanceExpires(t *testing.T) { 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 { + if err := ClearKeyExpiring("gift", k); err != nil { + t.Fatal(err) + } + if err := AddKeyExpiring("gift", k, Expiring{Amount: 5, Until: "2026-11-10"}); err != nil { t.Fatal(err) } left := func(when time.Time) BalanceEstimate { @@ -475,7 +478,7 @@ func TestTypedBalanceExpires(t *testing.T) { } // $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 { + if *e.Left != 13 || len(e.Expiring) != 1 || *e.Expiring[0].Left != 3 || !e.Expiring[0].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|"] @@ -485,7 +488,7 @@ func TestTypedBalanceExpires(t *testing.T) { // $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 { + if *e.Left != 9 || len(e.Expiring) != 1 || *e.Expiring[0].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 { @@ -507,7 +510,7 @@ func TestTypedBalanceExpires(t *testing.T) { 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 { + if err := AddKeyExpiring("gift", k, Expiring{Amount: 50, Until: "2026-11-16"}); err != nil { t.Fatal(err) } clockStub(t, at(21, 0)) @@ -521,7 +524,7 @@ func TestTypedBalanceExpires(t *testing.T) { // 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 { + if err := AddKeyExpiring("gift", k, Expiring{Amount: 2, Until: "2026-12-31"}); err != nil { t.Fatal(err) } clockStub(t, at(22, 12)) @@ -531,7 +534,7 @@ func TestTypedBalanceExpires(t *testing.T) { 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 { + if e, _ := p.OwnBalanceEstimate(k); len(e.Expiring) != 1 || *e.Expiring[0].Left != 0 || *e.Left != 19 { t.Fatalf("typed again in USD: left %v, expiring %+v", *e.Left, e.Expiring) } cny := 100.0 @@ -539,20 +542,20 @@ func TestTypedBalanceExpires(t *testing.T) { t.Fatal(err) } p, _ = Find("gift") - if b, _ := p.KeyOwnBalance(k); b.Expiring != nil { + if b, _ := p.KeyOwnBalance(k); len(b.Expiring) != 0 { 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 { + if err := AddKeyExpiring("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 e, _ := p.OwnBalanceEstimate(k); *e.Left != 123 || len(e.Expiring) != 1 || *e.Expiring[0].Left != 23 { + t.Fatalf("¥100 and ¥30 less $1 at 7: %v, %+v", *e.Left, e.Expiring) } 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)) @@ -567,16 +570,16 @@ func TestTypedBalanceExpires(t *testing.T) { 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 { + if err := AddKeyExpiring("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 { + if err := AddKeyExpiring("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 { + n := normalKeyOwnBalances(map[string]OwnBalance{"a": {USD: 5, Expiring: []Expiring{{Amount: 5, Until: "soon"}, {Amount: 3, Until: "2026-12-31"}}}}) + if n["a"].USD != 5 || len(n["a"].Expiring) != 1 || n["a"].Expiring[0].Amount != 3 { t.Errorf("a part that isn't one, written by hand: %+v", n) } } @@ -587,11 +590,11 @@ func TestTypedBalanceSavedBeforeExpiring(t *testing.T) { 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 { + if len(b.Expiring) != 0 || *b.CNY != 100 || b.Refill.Day != 1 { t.Fatalf("%+v", b) } out, _ := json.Marshal(b) - if strings.Contains(string(out), "expiring") { + if strings.Contains(string(out), "expiring") || strings.Contains(string(out), "expirings") { t.Errorf("saved again with a part it never had: %s", out) } } @@ -612,3 +615,225 @@ func TestExpiringParsed(t *testing.T) { } } } + +// Two grants of credit that expires on one key (tenacious_eagle_96548: +// promotional credit going tomorrow and the day after): the spend goes to +// the one that ends soonest, whichever was typed first, never to one +// typed after it; each counts to its own midnight, and what an expired +// grant left unspent never reaches the rest. +func TestTypedBalanceGrantsSoonestFirst(t *testing.T) { + probeSandbox(t) + probeLocal = false + if err := Save(Provider{ID: "promo", Name: "Promo", Chat: "http://127.0.0.1:1/v1", Key: "sk-p"}); err != nil { + t.Fatal(err) + } + k := keyID("sk-p") + for _, zone := range []string{"Pacific/Kiritimati", "UTC"} { + loc, err := time.LoadLocation(zone) + if err != nil { + t.Fatal(err) + } + 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(9, 10): 3, at(10, 10): 4, at(11, 2): 3}) + clockStub(t, at(9, 9)) + if err := SetKeyOwnBalance("promo", k, &OwnBalance{USD: 10}); err != nil { + t.Fatal(err) + } + if err := ClearKeyExpiring("promo", k); err != nil { + t.Fatal(err) + } + // the day after's typed first; tomorrow's two hours later + if err := AddKeyExpiring("promo", k, Expiring{Amount: 5, Until: "2026-11-11"}); err != nil { + t.Fatal(err) + } + clockStub(t, at(9, 11)) + if err := AddKeyExpiring("promo", 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("promo") + e, _ := p.OwnBalanceEstimate(k) + return e + } + // $3 at 10:00 went to the day after's, the only one then; $4 the + // next day to tomorrow's, which ends first + e := left(at(10, 12)) + if *e.Left != 13 || len(e.Expiring) != 2 || e.Expiring[0].Until != "2026-11-10" || *e.Expiring[0].Left != 1 || + e.Expiring[1].Until != "2026-11-11" || *e.Expiring[1].Left != 2 || e.Expired != nil { + t.Fatalf("%s: left %v, grants %+v", zone, *e.Left, e.Expiring) + } + q := ownCards(t)["promo|"] + if q.Balance != "≈$13.00" || len(q.BalanceSplit) != 2 || q.BalanceSplit[0].Text != "≈$1.00" || !q.BalanceSplit[0].Expires.Equal(at(11, 0)) || + q.BalanceSplit[1].Text != "≈$2.00" || !q.BalanceSplit[1].Expires.Equal(at(12, 0)) { + t.Fatalf("%s card: %+v", zone, q) + } + // tomorrow's gone with $1 unspent; the $3 after it: $2 the day + // after's, $1 the rest's + e = left(at(11, 3)) + if *e.Left != 9 || len(e.Expiring) != 1 || *e.Expiring[0].Left != 0 || e.Expired == nil || !e.Expired.Equal(at(11, 0)) { + t.Fatalf("%s, tomorrow's gone: left %v, grants %+v, expired %v", zone, *e.Left, e.Expiring, e.Expired) + } + e = left(at(12, 1)) + if *e.Left != 9 || len(e.Expiring) != 0 || e.Expired == nil || !e.Expired.Equal(at(12, 0)) { + t.Fatalf("%s, both gone: left %v, grants %+v, expired %v", zone, *e.Left, e.Expiring, e.Expired) + } + } +} + +// Grants are added and taken off one at a time, by when each was typed +// or by its day; off takes them all; a key holds MaxExpiring; one that +// ended before the balance was typed again goes when the key is next +// written. +func TestTypedBalanceGrantsEdited(t *testing.T) { + probeSandbox(t) + probeLocal = false + spendAt(t, nil) + if err := Save(Provider{ID: "promo", Name: "Promo", Chat: "http://127.0.0.1:1/v1", Key: "sk-p"}); err != nil { + t.Fatal(err) + } + k := keyID("sk-p") + at := func(d, h int) time.Time { return time.Date(2026, 11, d, h, 0, 0, 0, time.UTC) } + clockStub(t, at(9, 9)) + if err := SetKeyOwnBalance("promo", k, &OwnBalance{USD: 0}); err != nil { + t.Fatal(err) + } + grants := func() []Expiring { + t.Helper() + p, _ := Find("promo") + b, _ := p.KeyOwnBalance(k) + return b.Expiring + } + for i, x := range []Expiring{{Amount: 5, Until: "2026-11-10"}, {Amount: 7, Until: "2026-11-11"}, {Amount: 9, Until: "2026-11-11"}} { + clockStub(t, at(9, 10+i)) + if err := AddKeyExpiring("promo", k, x); err != nil { + t.Fatal(err) + } + } + if g := grants(); len(g) != 3 || !g[1].At.Equal(at(9, 11)) { + t.Fatalf("three added: %+v", g) + } + p, _ := Find("promo") + if e, _ := p.OwnBalanceEstimate(k); *e.Left != 21 { + t.Fatalf("0 and 5+7+9: %v", *e.Left) + } + // by when it was typed: only that one + if err := RemoveKeyExpiring("promo", k, Expiring{At: at(9, 11)}); err != nil { + t.Fatal(err) + } + if g := grants(); len(g) != 2 || g[0].Amount != 5 || g[1].Amount != 9 { + t.Fatalf("the 7 taken off: %+v", g) + } + // by day and amount; one that matches nothing is refused and changes nothing + if err := RemoveKeyExpiring("promo", k, Expiring{Amount: 1, Until: "2026-11-11"}); err == nil { + t.Error("taking off a grant there isn't") + } + if err := RemoveKeyExpiring("promo", k, Expiring{At: at(1, 1)}); err == nil { + t.Error("taking off a grant typed at no such time") + } + if err := RemoveKeyExpiring("promo", k, Expiring{Amount: 9, Until: "2026-11-11"}); err != nil { + t.Fatal(err) + } + if g := grants(); len(g) != 1 || g[0].Amount != 5 { + t.Fatalf("the 9 taken off: %+v", g) + } + // MaxExpiring and no more + for len(grants()) < MaxExpiring { + if err := AddKeyExpiring("promo", k, Expiring{Amount: 1, Until: "2026-12-31"}); err != nil { + t.Fatal(err) + } + } + if err := AddKeyExpiring("promo", k, Expiring{Amount: 1, Until: "2026-12-31"}); err == nil { + t.Errorf("grant %d taken", MaxExpiring+1) + } + // by day: every one through it + if err := RemoveKeyExpiring("promo", k, Expiring{Until: "2026-12-31"}); err != nil { + t.Fatal(err) + } + if g := grants(); len(g) != 1 || g[0].Amount != 5 { + t.Fatalf("2026-12-31's taken off: %+v", g) + } + // typed again after the 5's day: it took nothing the new balance + // pays for, so it goes + clockStub(t, at(12, 9)) + if err := SetKeyOwnBalance("promo", k, &OwnBalance{USD: 4}); err != nil { + t.Fatal(err) + } + if g := grants(); len(g) != 0 { + t.Fatalf("a grant over before the balance was typed kept: %+v", g) + } + if err := AddKeyExpiring("promo", k, Expiring{Amount: 2, Until: "2026-12-01"}); err != nil { + t.Fatal(err) + } + if err := AddKeyExpiring("promo", k, Expiring{Amount: 3, Until: "2026-12-02"}); err != nil { + t.Fatal(err) + } + if err := ClearKeyExpiring("promo", k); err != nil { + t.Fatal(err) + } + p, _ = Find("promo") + if b, _ := p.KeyOwnBalance(k); len(b.Expiring) != 0 || b.USD != 4 { + t.Fatalf("off: %+v", b) + } +} + +// A v0.1.3305 balance's one grant (`expiring`, an object) is read as the +// first of its grants and saved in the list (`expirings`), counted as it +// was; a balance carrying both keeps each grant once. +func TestTypedBalanceOneGrantMigrated(t *testing.T) { + var b OwnBalance + old := `{"usd":10,"at":"2026-11-01T01:00:00Z","expiring":{"amount":5,"until":"2026-11-10","at":"2026-11-01T02:00:00Z"}}` + if err := json.Unmarshal([]byte(old), &b); err != nil { + t.Fatal(err) + } + want := Expiring{Amount: 5, Until: "2026-11-10", At: time.Date(2026, 11, 1, 2, 0, 0, 0, time.UTC)} + if b.USD != 10 || len(b.Expiring) != 1 || !b.Expiring[0].At.Equal(want.At) || b.Expiring[0].Amount != 5 || b.Expiring[0].Until != want.Until { + t.Fatalf("%+v", b) + } + out, _ := json.Marshal(b) + if !strings.Contains(string(out), `"expirings":[{"amount":5,"until":"2026-11-10"`) || strings.Contains(string(out), `"expiring":`) { + t.Fatalf("saved again: %s", out) + } + var again OwnBalance + if err := json.Unmarshal(out, &again); err != nil || len(again.Expiring) != 1 { + t.Fatalf("read again: %+v %v", again, err) + } + both := `{"usd":10,"at":"2026-11-01T01:00:00Z","expiring":{"amount":5,"until":"2026-11-10","at":"2026-11-01T02:00:00Z"},` + + `"expirings":[{"amount":5,"until":"2026-11-10","at":"2026-11-01T02:00:00Z"},{"amount":3,"until":"2026-11-11","at":"2026-11-01T03:00:00Z"}]}` + if err := json.Unmarshal([]byte(both), &b); err != nil || len(b.Expiring) != 2 || b.Expiring[1].Amount != 3 { + t.Fatalf("both: %+v %v", b, err) + } + + // counted as v0.1.3305 counted it: $2 spent of 10 and 5 that expires + probeSandbox(t) + probeLocal = false + at := func(d, h int) time.Time { return time.Date(2026, 11, d, h, 0, 0, 0, time.UTC) } + spendAt(t, map[time.Time]float64{at(2, 10): 2}) + clockStub(t, at(3, 9)) + if err := json.Unmarshal([]byte(old), &b); err != nil { + t.Fatal(err) + } + if err := Save(Provider{ID: "old", Name: "Old", Chat: "http://127.0.0.1:1/v1", Key: "sk-o", KeyOwnBalances: map[string]OwnBalance{keyID("sk-o"): b}}); err != nil { + t.Fatal(err) + } + p, _ := Find("old") + if e, _ := p.OwnBalanceEstimate(keyID("sk-o")); *e.Left != 13 || len(e.Expiring) != 1 || *e.Expiring[0].Left != 3 { + t.Fatalf("migrated: %+v", e) + } +} + +// What the CLI takes for credit to take off. +func TestExpiringDayParsed(t *testing.T) { + if x, err := ParseExpiringDay("2026-12-31"); err != nil || *x != (Expiring{Until: "2026-12-31"}) { + t.Errorf("a day: %+v %v", x, err) + } + if x, err := ParseExpiringDay("20@2026-12-31"); err != nil || *x != (Expiring{Amount: 20, Until: "2026-12-31"}) { + t.Errorf("amount@day: %+v %v", x, err) + } + for _, in := range []string{"", "off", "20", "12/31", "20@", "--help"} { + if _, err := ParseExpiringDay(in); err == nil { + t.Errorf("%q taken", in) + } + } +}