From 70f4593e623e0847fcc2d869240565ce5f73a67a Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 13 Nov 2026 11:44:04 +0800 Subject: [PATCH] provider: a key's typed balance can refill each day (Kelen_Yc on X) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A key's balance typed by hand refilled each month or each week. A relay key with a daily allowance had no way to say so. Now it can refill each day, at local midnight, like the others: - provider: Refill{Every: "day", Day: 0} (RefillDay). Last is today's midnight in now's location, Next tomorrow's. check takes it with day 0 only; ParseRefill reads daily/day/d (daily:1 refused); String is "daily". A magpie before this drops such a refill on read, as one written by hand that isn't one, and counts from when it was typed. - CLI: `magpie provider key-balance --refill daily`; usage lines updated. - GUI: the pill's menu has "Refills each day" after "Refills each week…", posting {every: day, day: 0} at once (no day to pick, so no ellipsis), with its toast; en, zh, zh-TW, ja, de. - docs/subsystems/providers-accounts.md names it. Tests: TestRefillDays gains daily rows (midday, exactly midnight, a month's and a year's end, Asia/Shanghai). New TestTypedBalanceRefillsDaily holds the clock in Pacific/Kiritimati (UTC+14), Pacific/Pago_Pago (UTC-11) and UTC: a minute before local midnight the spend counts from when it was typed, a minute after it counts from local midnight and the next refill is the following one. TestOwnBalanceParsedInYuanAndRefill and TestTypedBalanceRefills cover parsing, the bad {day, 1}, and read-back; TestKeyBalanceCmd sets --refill daily. key-own-balance.test.cjs picks Refills each day in every language, both engines, 900 and 400px, checks the post and that the menu then shows it picked. Run on mica at 889758605 + this: go test -count=1 ./internal/provider ./internal/cli ./internal/gui ok; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok; gofmt clean; GUI key-own-balance, i18n-keys, i18n-en-no-cjk, key-balance-expiring in chromium and webkit ok (48/48). Rebased on c5adcbaab (library, site; nothing of this change's files), then at the pushed head: go test ./internal/gui, ./internal/provider -run Refill|TypedBalance|OwnBalance| KeyOwnBalance|Budget ok, i18n-keys and i18n-en-no-cjk ok. key-balance-card is red in de at 560px (view-usage 635>560) in both engines on the clean base 889758605 too: #6414. Broken by hand: daily Last taken from UTC's midnight instead of local: TestRefillDays and TestTypedBalanceRefillsDaily (Kiritimati) red. Not tried: the real app with a real relay key; the full suite (started after the tag). --- docs/subsystems/providers-accounts.md | 2 +- internal/cli/key_balance_cli.go | 2 +- internal/cli/key_balance_cli_test.go | 9 ++++ internal/cli/providers_cli.go | 2 +- internal/gui/assets/i18n.js | 8 +++ internal/gui/assets/keybalance.js | 6 ++- internal/gui/tests/key-own-balance.test.cjs | 27 +++++++--- internal/provider/key_balance_own.go | 33 +++++++++--- internal/provider/key_balance_own_test.go | 58 +++++++++++++++++++-- 9 files changed, 125 insertions(+), 22 deletions(-) diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index bbc7e7d94..fa3ec7b09 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -420,7 +420,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`. - 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 window counted in a unit with its total (`QuotaWindow.Amount`, `Limit`, `Unit`: WorkBuddy's credits, a plan's requests) can instead be capped at a fixed amount of that unit (`AccountWindowAmounts`, by account and `capId`; 9won_25273 on Discord). `SetWindowAmount` (GUI `provider/windowcap` with `amount` in place of `cap`, the meter's menu's Amount…, typed in place) sets it, 0 lifts it; a window has a share of its own or an amount, never both, and setting one clears the other. `limitShare` makes the amount a share of the window's total for marks and `NearCap`, while `CapHeld` and `capReached` hold the account once the count reaches the amount (`past`); `CapHold` and the trace carry `Amount`, `Count` and `Unit`, and `cappedError` says "has used 300 credits … past its cap of 300". A reading with no total leaves the amount aside and the account's share applies. Every cap reads the vendor's own count of the window, so what the account spent outside magpie (the vendor's app, another machine) counts toward it as the vendor reports it, from the next reading on; magpie can only hold back its own requests (`TestWindowAmountCapHeld`, `TestSetWindowAmount`, `window-cap.test.cjs`). A config without window caps reads as before. A key of a provider whose windows magpie reads (`TakesUsageCap`) has the same caps, by its key id (GUI `provider/accountcap` and `windowcap` with the key's id, `magpie provider account-cap`), kept when `ReplaceKey` changes the key's value; `KeyInfo.UsageCap` and `CapHeld` give its row's pill and held note (`TestKeyTakesUsageCap`, `key-usage-cap.test.cjs`). 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 wallet's window, one that tells only what is left (`QuotaWindow.Balance`, no share and no total: AStudio's 通用积分 and 星火积分, SuperMagic's points), has its spend counted by magpie ([`wallet_spend.go`](../../internal/provider/wallet_spend.go), #5770, 9won on Discord: an account capped at 4 spent over 1,000 credits past it, since the wallet read 0% used until it was empty). Each reading a plugin's usage gives (`pluginLoginQuota` → `withWalletSpend`) is set against the one before: a fall is spent, a rise (a top-up, a daily grant) is not. The count runs over the window's own period when it tells a reset, else the local day, and starts at 0 at the period's first reading; what was spent before it, or between one period's last reading and the next's first, isn't known and isn't counted. Each window carries it as `spent` and `spentSince`. On an account with a usage cap (`WindowCaps.Holds`) the window reads as `amount` spent of `limit`, what the period had (spent plus what is left), and `used` that share, so a cap by share holds it in routing and on the GUI's row as it holds any window; without a cap the window is its balance alone, and routing goes by that (`Allowance.Left`). A cap set is judged from the next reading on. The counts are kept in `wallet-spend.json` beside providers.json, by provider, account and window, a period over for a week dropped; one that can't be read starts each count again. `holdsBounds` leaves a wallet out of a window's holds (no whole). `TestWalletSpendCounted`, `TestWalletCapHolds`, `TestPluginWalletCapHolds`. - 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, 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 ±`MaxOwnBalance` (1,000,000) in either currency (below 0 is a key the vendor let run past its balance, so typed as it reads: -1.84, -$1.84; AlanWang1027713 on X), 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 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 ±`MaxOwnBalance` (1,000,000) in either currency (below 0 is a key the vendor let run past its balance, so typed as it reads: -1.84, -$1.84; AlanWang1027713 on X), 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}`, or `{every: day, day: 0}`, every midnight, Kelen_Yc on X), 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…, Refills each day, Never refills; CLI `--refill monthly[:day]|weekly[:mon…sun]|daily|off`); a magpie before daily refills drops a `day` refill as one written by hand that isn't one 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 7121cba38..c5edbb44e 100644 --- a/internal/cli/key_balance_cli.go +++ b/internal/cli/key_balance_cli.go @@ -8,7 +8,7 @@ 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]… [--expiring-remove [amount@]yyyy-mm-dd]…]" +const keyBalanceUsage = "magpie provider key-balance [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|daily|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 diff --git a/internal/cli/key_balance_cli_test.go b/internal/cli/key_balance_cli_test.go index 2dfb7ea9f..991c0191d 100644 --- a/internal/cli/key_balance_cli_test.go +++ b/internal/cli/key_balance_cli_test.go @@ -60,6 +60,15 @@ func TestKeyBalanceCmd(t *testing.T) { if b, _ := typed(); b.CNY == nil || *b.CNY != 700 || b.Refill == nil || *b.Refill != (provider.Refill{Every: provider.RefillWeek, Day: 5}) { t.Fatalf("weekly:fri: %+v", b) } + if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "--refill", "daily"}); err != nil { + t.Fatal(err) + } + if b, _ := typed(); b.CNY == nil || *b.CNY != 700 || b.Refill == nil || *b.Refill != (provider.Refill{Every: provider.RefillDay}) { + t.Fatalf("daily: %+v", b) + } + if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "--refill=weekly:fri"}); err != nil { + t.Fatal(err) + } for _, bad := range [][]string{{"relay", "Team", "--refill", "yearly"}, {"relay", "--refill", "monthly"}, {"relay", "Team", "off", "--refill", "monthly"}, {"relay", "Team", "--refill"}} { if err := providerCmd(append([]string{"provider", "key-balance"}, bad...)); err == nil { t.Fatalf("%v taken", bad) diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index d3fd439d9..279de231e 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -108,7 +108,7 @@ 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]… [--expiring-remove [amount@]yyyy-mm-dd]…] + magpie provider key-balance [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|daily|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; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index af14055ef..bec6b7eda 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -147,12 +147,14 @@ const I18N = { "No credit that expires": "去掉限期额度", "Refills each month…": "每月恢复…", "Refills each week…": "每周恢复…", + "Refills each day": "每日恢复", "Never refills": "不恢复", "Refills on": "恢复于", "Refill day of the month": "每月恢复的日期", "A day of the month is a whole number from 1 to 31": "每月的日期是 1 到 31 之间的整数", "{who} no longer refills": "{who} 不再恢复余额", "{who} refills each {weekday}": "{who} 每{weekday}恢复余额", + "{who} refills each day": "{who} 每日恢复余额", "{who} refills on day {day} of each month": "{who} 每月 {day} 日恢复余额", "A spend cap is an amount in USD above 0, up to 1,000,000": "消费上限是大于 0、不超过 1,000,000 的美元金额", "Spend cap": "消费上限", @@ -5300,12 +5302,14 @@ const I18N = { "No credit that expires": "去掉限期額度", "Refills each month…": "每月恢復…", "Refills each week…": "每週恢復…", + "Refills each day": "每日恢復", "Never refills": "不恢復", "Refills on": "恢復於", "Refill day of the month": "每月恢復的日期", "A day of the month is a whole number from 1 to 31": "每月的日期是 1 到 31 之間的整數", "{who} no longer refills": "{who} 不再恢復餘額", "{who} refills each {weekday}": "{who} 每{weekday}恢復餘額", + "{who} refills each day": "{who} 每日恢復餘額", "{who} refills on day {day} of each month": "{who} 每月 {day} 日恢復餘額", "A spend cap is an amount in USD above 0, up to 1,000,000": "消費上限是大於 0、不超過 1,000,000 的美元金額", "Spend cap": "消費上限", @@ -10438,12 +10442,14 @@ const I18N = { "No credit that expires": "期限付きクレジットなし", "Refills each month…": "毎月戻す…", "Refills each week…": "毎週戻す…", + "Refills each day": "毎日戻す", "Never refills": "戻さない", "Refills on": "戻す曜日", "Refill day of the month": "毎月戻す日", "A day of the month is a whole number from 1 to 31": "日付は 1 から 31 までの整数です", "{who} no longer refills": "{who} の残高はもう戻りません", "{who} refills each {weekday}": "{who} の残高は毎週{weekday}に戻ります", + "{who} refills each day": "{who} の残高は毎日戻ります", "{who} refills on day {day} of each month": "{who} の残高は毎月 {day} 日に戻ります", "A spend cap is an amount in USD above 0, up to 1,000,000": "支出上限は 0 より大きく 1,000,000 以下の USD 金額です", "Spend cap": "支出上限", @@ -15578,12 +15584,14 @@ const I18N = { "No credit that expires": "Kein ablaufendes Guthaben", "Refills each month…": "Monatlich auffüllen…", "Refills each week…": "Wöchentlich auffüllen…", + "Refills each day": "Täglich auffüllen", "Never refills": "Nie auffüllen", "Refills on": "Auffüllen am", "Refill day of the month": "Tag des Monats zum Auffüllen", "A day of the month is a whole number from 1 to 31": "Ein Tag des Monats ist eine ganze Zahl von 1 bis 31", "{who} no longer refills": "{who} wird nicht mehr aufgefüllt", "{who} refills each {weekday}": "{who} wird jeden {weekday} aufgefüllt", + "{who} refills each day": "{who} wird jeden Tag aufgefüllt", "{who} refills on day {day} of each month": "{who} wird am {day}. jedes Monats aufgefüllt", "A spend cap is an amount in USD above 0, up to 1,000,000": "Ein Ausgabenlimit ist ein Betrag in USD über 0, bis 1.000.000", "Spend cap": "Ausgabenlimit", diff --git a/internal/gui/assets/keybalance.js b/internal/gui/assets/keybalance.js index ed8d74cc9..931ff4a72 100644 --- a/internal/gui/assets/keybalance.js +++ b/internal/gui/assets/keybalance.js @@ -4,7 +4,8 @@ // own usage prices the calls it sends on the key (provider/ // key_balance_own.go). Typing it again sets it anew. It may be typed in // yuan ("¥100", or picked beside the field, which starts at the balance's -// own currency, else Settings' one), and may refill each month or week. +// own currency, else Settings' one), and may refill each month, week or +// day (Kelen_Yc on X). // 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 @@ -71,6 +72,7 @@ function keyBalancePill(p, k) { const refill = (r) => accountAction("provider/keybalancerefill", { id: p.id, account: k.id, refill: r }, !r ? t("{who} no longer refills", { who: name }) : r.every === "week" ? t("{who} refills each {weekday}", { who: name, weekday: weekdayName(r.day) }) + : r.every === "day" ? t("{who} refills each day", { who: name }) : 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) })); @@ -187,9 +189,11 @@ function keyBalancePill(p, k) { ...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: "day", name: "Refills each day", 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 === "day" ? refill({ every: "day", day: 0 }) : 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"); diff --git a/internal/gui/tests/key-own-balance.test.cjs b/internal/gui/tests/key-own-balance.test.cjs index 3b414ee78..c00849971 100644 --- a/internal/gui/tests/key-own-balance.test.cjs +++ b/internal/gui/tests/key-own-balance.test.cjs @@ -67,11 +67,11 @@ function serve(lang, posts) { } const words = { - en: { currency: "Currency", yuan40: "≈¥40.00 left", usd100: "≈$100.00 left", k1: "≈$12.50 left", none: "Set balance", menu: "Balance", enter: "Enter balance…", off: "No balance", k2: "≈$5.00 left", k1again: "≈$40.00 left", yuan: "≈¥100.00 left", bad: "A balance is an amount from -1,000,000 to 1,000,000, in USD or in yuan (¥)", month: "Refills each month…", week: "Refills each week…", never: "Never refills", on: "Refills on", refills: "Refills to $40.00 on" }, - zh: { currency: "货币", yuan40: "≈¥40.00 剩余", usd100: "≈$100.00 剩余", k1: "≈$12.50 剩余", none: "设置余额", menu: "余额", enter: "填写余额…", off: "无余额", k2: "≈$5.00 剩余", k1again: "≈$40.00 剩余", yuan: "≈¥100.00 剩余", bad: "余额是 -1,000,000 到 1,000,000 之间的金额,美元或人民币(¥)", month: "每月恢复…", week: "每周恢复…", never: "不恢复", on: "恢复于", refills: "恢复为 $40.00" }, - "zh-TW": { currency: "貨幣", yuan40: "≈¥40.00 剩餘", usd100: "≈$100.00 剩餘", k1: "≈$12.50 剩餘", none: "設定餘額", menu: "餘額", enter: "填寫餘額…", off: "無餘額", k2: "≈$5.00 剩餘", k1again: "≈$40.00 剩餘", yuan: "≈¥100.00 剩餘", bad: "餘額是 -1,000,000 到 1,000,000 之間的金額,美元或人民幣(¥)", month: "每月恢復…", week: "每週恢復…", never: "不恢復", on: "恢復於", refills: "恢復為 $40.00" }, - ja: { currency: "通貨", yuan40: "残り ≈¥40.00", usd100: "残り ≈$100.00", k1: "残り ≈$12.50", none: "残高を設定", menu: "残高", enter: "残高を入力…", off: "残高なし", k2: "残り ≈$5.00", k1again: "残り ≈$40.00", yuan: "残り ≈¥100.00", bad: "残高は -1,000,000 から 1,000,000 までの金額です(USD または人民元 ¥)", month: "毎月戻す…", week: "毎週戻す…", never: "戻さない", on: "戻す曜日", refills: "$40.00 へ戻る" }, - de: { currency: "Währung", yuan40: "≈¥40.00 übrig", usd100: "≈$100.00 übrig", k1: "≈$12.50 übrig", none: "Guthaben festlegen", menu: "Guthaben", enter: "Guthaben eingeben…", off: "Kein Guthaben", k2: "≈$5.00 übrig", k1again: "≈$40.00 übrig", yuan: "≈¥100.00 übrig", bad: "Ein Guthaben ist ein Betrag von -1.000.000 bis 1.000.000, in USD oder in Yuan (¥)", month: "Monatlich auffüllen…", week: "Wöchentlich auffüllen…", never: "Nie auffüllen", on: "Auffüllen am", refills: "wieder auf $40.00 aufgefüllt" }, + en: { currency: "Currency", yuan40: "≈¥40.00 left", usd100: "≈$100.00 left", k1: "≈$12.50 left", none: "Set balance", menu: "Balance", enter: "Enter balance…", off: "No balance", k2: "≈$5.00 left", k1again: "≈$40.00 left", yuan: "≈¥100.00 left", bad: "A balance is an amount from -1,000,000 to 1,000,000, in USD or in yuan (¥)", month: "Refills each month…", week: "Refills each week…", day: "Refills each day", never: "Never refills", on: "Refills on", refills: "Refills to $40.00 on" }, + zh: { currency: "货币", yuan40: "≈¥40.00 剩余", usd100: "≈$100.00 剩余", k1: "≈$12.50 剩余", none: "设置余额", menu: "余额", enter: "填写余额…", off: "无余额", k2: "≈$5.00 剩余", k1again: "≈$40.00 剩余", yuan: "≈¥100.00 剩余", bad: "余额是 -1,000,000 到 1,000,000 之间的金额,美元或人民币(¥)", month: "每月恢复…", week: "每周恢复…", day: "每日恢复", never: "不恢复", on: "恢复于", refills: "恢复为 $40.00" }, + "zh-TW": { currency: "貨幣", yuan40: "≈¥40.00 剩餘", usd100: "≈$100.00 剩餘", k1: "≈$12.50 剩餘", none: "設定餘額", menu: "餘額", enter: "填寫餘額…", off: "無餘額", k2: "≈$5.00 剩餘", k1again: "≈$40.00 剩餘", yuan: "≈¥100.00 剩餘", bad: "餘額是 -1,000,000 到 1,000,000 之間的金額,美元或人民幣(¥)", month: "每月恢復…", week: "每週恢復…", day: "每日恢復", never: "不恢復", on: "恢復於", refills: "恢復為 $40.00" }, + ja: { currency: "通貨", yuan40: "残り ≈¥40.00", usd100: "残り ≈$100.00", k1: "残り ≈$12.50", none: "残高を設定", menu: "残高", enter: "残高を入力…", off: "残高なし", k2: "残り ≈$5.00", k1again: "残り ≈$40.00", yuan: "残り ≈¥100.00", bad: "残高は -1,000,000 から 1,000,000 までの金額です(USD または人民元 ¥)", month: "毎月戻す…", week: "毎週戻す…", day: "毎日戻す", never: "戻さない", on: "戻す曜日", refills: "$40.00 へ戻る" }, + de: { currency: "Währung", yuan40: "≈¥40.00 übrig", usd100: "≈$100.00 übrig", k1: "≈$12.50 übrig", none: "Guthaben festlegen", menu: "Guthaben", enter: "Guthaben eingeben…", off: "Kein Guthaben", k2: "≈$5.00 übrig", k1again: "≈$40.00 übrig", yuan: "≈¥100.00 übrig", bad: "Ein Guthaben ist ein Betrag von -1.000.000 bis 1.000.000, in USD oder in Yuan (¥)", month: "Monatlich auffüllen…", week: "Wöchentlich auffüllen…", day: "Täglich auffüllen", never: "Nie auffüllen", on: "Auffüllen am", refills: "wieder auf $40.00 aufgefüllt" }, }; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { @@ -196,7 +196,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.deepEqual(p.body, { id: "relay", account: "k1", balance: 40 }); await page.waitForTimeout(250); - // k1 refills on a day of each month, then each Friday, then never + // k1 refills on a day of each month, then each Friday, then each day, then never await still("k1"); await menu.waitFor(); await item(w.month).click(); @@ -233,6 +233,21 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", p = await posted(n); assert.deepEqual(p.body, { id: "relay", account: "k1", refill: { every: "week", day: 5 } }); await page.waitForTimeout(250); + // each day (Kelen_Yc on X): picked at once, no day to choose, and + // the menu shows it picked + await still("k1"); + await menu.waitFor(); + n = posts.length; + await item(w.day).click(); + p = await posted(n); + assert.deepEqual(p.body, { id: "relay", account: "k1", refill: { every: "day", day: 0 } }); + await page.waitForTimeout(250); + assert.equal(await page.locator(".proto-menu").count(), 0, "a daily refill asked for more"); + await still("k1"); + await menu.waitFor(); + assert.equal(await item(w.day).getAttribute("aria-checked"), "true"); + await page.keyboard.press("Escape"); + await page.waitForTimeout(200); await still("k1"); await menu.waitFor(); n = posts.length; diff --git a/internal/provider/key_balance_own.go b/internal/provider/key_balance_own.go index a8d94fcd5..e3d5a9e4d 100644 --- a/internal/provider/key_balance_own.go +++ b/internal/provider/key_balance_own.go @@ -16,8 +16,9 @@ package provider // learned (internal/fx, fetched behind the page and cached), and while it // has never learned one what is left is unknown, never counted at a guess. // It may refill (the same user: $10 a month from the 1st): at each refill, -// 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. +// at midnight local time on a day of the month or of the week, or every +// midnight (Kelen_Yc on X: a relay key with a daily allowance), the +// amount typed is whole again and the spend counted from then. // 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 @@ -118,7 +119,7 @@ func (b OwnBalance) Amount() (float64, string) { // Refill is when a balance typed is whole again: at midnight, local time, // on Day of each month (1–31, a month without that day on its last) or of -// each week (1 Monday to 7 Sunday). +// each week (1 Monday to 7 Sunday), or each day (Day 0). type Refill struct { Every string `json:"every"` Day int `json:"day"` @@ -128,12 +129,16 @@ type Refill struct { const ( RefillMonth = "month" RefillWeek = "week" + RefillDay = "day" ) // Last is the last refill at or before now, in now's location. func (r Refill) Last(now time.Time) time.Time { y, m, d := now.Date() loc := now.Location() + if r.Every == RefillDay { + return time.Date(y, m, d, 0, 0, 0, 0, loc) + } if r.Every == RefillWeek { iso := (int(now.Weekday())+6)%7 + 1 return time.Date(y, m, d-(iso-r.Day+7)%7, 0, 0, 0, 0, loc) @@ -149,6 +154,9 @@ func (r Refill) Last(now time.Time) time.Time { func (r Refill) Next(now time.Time) time.Time { l := r.Last(now) y, m, d := l.Date() + if r.Every == RefillDay { + return time.Date(y, m, d+1, 0, 0, 0, 0, l.Location()) + } if r.Every == RefillWeek { return time.Date(y, m, d+7, 0, 0, 0, 0, l.Location()) } @@ -167,14 +175,18 @@ func (r Refill) check() error { switch { case r.Every == RefillMonth && r.Day >= 1 && r.Day <= 31: case r.Every == RefillWeek && r.Day >= 1 && r.Day <= 7: + case r.Every == RefillDay && r.Day == 0: default: - return fmt.Errorf("a balance refills each month on a day from 1 to 31, or each week on a day from 1 (Monday) to 7 (Sunday), not %s %d", r.Every, r.Day) + return fmt.Errorf("a balance refills each month on a day from 1 to 31, each week on a day from 1 (Monday) to 7 (Sunday), or each day (day 0), not %s %d", r.Every, r.Day) } return nil } -// String is r as the CLI takes and shows it: monthly:1, weekly:mon. +// String is r as the CLI takes and shows it: monthly:1, weekly:mon, daily. func (r Refill) String() string { + if r.Every == RefillDay { + return "daily" + } if r.Every == RefillWeek { return "weekly:" + strings.ToLower(time.Weekday(r.Day % 7).String()[:3]) } @@ -746,8 +758,8 @@ func ParseOwnBalance(amount string) (*OwnBalance, error) { } // ParseRefill reads a refill as the CLI takes it: monthly (on the 1st), -// monthly:15, weekly (on Monday), weekly:fri or weekly:5; off or never -// for none (nil). +// monthly:15, weekly (on Monday), weekly:fri or weekly:5, daily (each +// midnight); off or never for none (nil). func ParseRefill(s string) (*Refill, error) { a := strings.ToLower(strings.TrimSpace(s)) switch a { @@ -755,7 +767,7 @@ func ParseRefill(s string) (*Refill, error) { return nil, nil } every, day, _ := strings.Cut(a, ":") - bad := fmt.Errorf("a refill is monthly[:day 1-31], weekly[:mon…sun] or off, not %q", s) + bad := fmt.Errorf("a refill is monthly[:day 1-31], weekly[:mon…sun], daily or off, not %q", s) var r Refill switch every { case "monthly", "month", "m": @@ -767,6 +779,11 @@ func ParseRefill(s string) (*Refill, error) { } r.Day = n } + case "daily", "day", "d": + if day != "" { + return nil, bad + } + r = Refill{Every: RefillDay} case "weekly", "week", "w": r = Refill{Every: RefillWeek, Day: 1} if day != "" { diff --git a/internal/provider/key_balance_own_test.go b/internal/provider/key_balance_own_test.go index fd40c5a84..c02df9c0d 100644 --- a/internal/provider/key_balance_own_test.go +++ b/internal/provider/key_balance_own_test.go @@ -344,7 +344,7 @@ func TestTypedBalanceRefills(t *testing.T) { t.Fatalf("no refill: %+v", e) } // refused: a refill that isn't one; one for a key with no balance - for _, bad := range []Refill{{RefillMonth, 0}, {RefillMonth, 32}, {RefillWeek, 8}, {"year", 1}} { + for _, bad := range []Refill{{RefillMonth, 0}, {RefillMonth, 32}, {RefillWeek, 8}, {"year", 1}, {RefillDay, 1}} { if err := SetKeyBalanceRefill("monthly", keyID("sk-r"), &bad); err == nil { t.Errorf("%+v taken", bad) } @@ -357,6 +357,47 @@ func TestTypedBalanceRefills(t *testing.T) { } } +// A balance that refills each day (Kelen_Yc on X: a relay key with a +// daily allowance) is whole again at local midnight, not UTC's: held in +// UTC+14 and UTC-11, where the local day and UTC's differ, the spend is +// counted from the midnight just past and the next is the one after. +func TestTypedBalanceRefillsDaily(t *testing.T) { + probeSandbox(t) + probeLocal = false + asked := spentStub(t, map[string]float64{keyID("sk-d"): 2}) + if err := Save(Provider{ID: "daily", Name: "Daily", Chat: "http://127.0.0.1:1/v1", Key: "sk-d"}); err != nil { + t.Fatal(err) + } + for _, zone := range []string{"Pacific/Kiritimati", "Pacific/Pago_Pago", "UTC"} { + loc, err := time.LoadLocation(zone) + if err != nil { + t.Fatal(err) + } + typed := time.Date(2026, 11, 12, 9, 0, 0, 0, loc) + clockStub(t, typed) + if err := SetKeyOwnBalance("daily", keyID("sk-d"), &OwnBalance{USD: 5, Refill: &Refill{Every: RefillDay}}); err != nil { + t.Fatal(err) + } + // the same local day, a minute before midnight: from when typed + clockStub(t, time.Date(2026, 11, 12, 23, 59, 0, 0, loc)) + p, _ := Find("daily") + e, _ := p.OwnBalanceEstimate(keyID("sk-d")) + if !e.From.Equal(typed) || *e.Left != 3 || !e.Next.Equal(time.Date(2026, 11, 13, 0, 0, 0, 0, loc)) { + t.Fatalf("%s before midnight: from %v next %v left %v", zone, e.From, e.Next, *e.Left) + } + // a minute past local midnight: whole again, counted from then + clockStub(t, time.Date(2026, 11, 13, 0, 1, 0, 0, loc)) + q := ownCards(t)["daily|"] + mid := time.Date(2026, 11, 13, 0, 0, 0, 0, loc) + if !q.Estimate.From.Equal(mid) || !asked[keyID("sk-d")].Equal(mid) || q.Balance != "≈$3.00" { + t.Fatalf("%s after midnight: %+v from %v, asked from %v", zone, q, q.Estimate.From, asked[keyID("sk-d")]) + } + if !q.Estimate.Next.Equal(time.Date(2026, 11, 14, 0, 0, 0, 0, loc)) { + t.Errorf("%s next refill %v", zone, q.Estimate.Next) + } + } +} + // When each refill falls: on the day, at local midnight; a month without // the day refills on its last; a week from Monday (1) to Sunday (7). func TestRefillDays(t *testing.T) { @@ -381,6 +422,12 @@ func TestRefillDays(t *testing.T) { {Refill{RefillWeek, 1}, at(2026, 11, 8, 10), at(2026, 11, 2, 0), at(2026, 11, 9, 0)}, {Refill{RefillWeek, 7}, at(2026, 11, 8, 10), at(2026, 11, 8, 0), at(2026, 11, 15, 0)}, {Refill{RefillWeek, 5}, at(2026, 11, 8, 10), at(2026, 11, 6, 0), at(2026, 11, 13, 0)}, + // each day (Kelen_Yc on X): the midnight before, the one after, + // across a month's and a year's end + {Refill{RefillDay, 0}, at(2026, 11, 8, 10), at(2026, 11, 8, 0), at(2026, 11, 9, 0)}, + {Refill{RefillDay, 0}, at(2026, 11, 8, 0), at(2026, 11, 8, 0), at(2026, 11, 9, 0)}, + {Refill{RefillDay, 0}, at(2026, 11, 30, 23), at(2026, 11, 30, 0), at(2026, 12, 1, 0)}, + {Refill{RefillDay, 0}, at(2026, 12, 31, 23), at(2026, 12, 31, 0), at(2027, 1, 1, 0)}, } { if l, n := c.r.Last(c.now), c.r.Next(c.now); !l.Equal(c.last) || !n.Equal(c.next) { t.Errorf("%+v at %v: last %v next %v, want %v and %v", c.r, c.now, l, n, c.last, c.next) @@ -416,7 +463,7 @@ func TestOwnBalanceParsedInYuanAndRefill(t *testing.T) { } } for in, want := range map[string]Refill{"monthly": {RefillMonth, 1}, "monthly:15": {RefillMonth, 15}, "weekly": {RefillWeek, 1}, - "weekly:fri": {RefillWeek, 5}, "weekly:Sunday": {RefillWeek, 7}, "weekly:3": {RefillWeek, 3}} { + "weekly:fri": {RefillWeek, 5}, "weekly:Sunday": {RefillWeek, 7}, "weekly:3": {RefillWeek, 3}, "daily": {RefillDay, 0}, "Day": {RefillDay, 0}} { if r, err := ParseRefill(in); err != nil || r == nil || *r != want { t.Errorf("%q: %+v %v, want %+v", in, r, err, want) } @@ -427,15 +474,18 @@ func TestOwnBalanceParsedInYuanAndRefill(t *testing.T) { if r, err := ParseRefill("off"); err != nil || r != nil { t.Errorf("off: %+v %v", r, err) } - for _, in := range []string{"monthly:0", "monthly:32", "monthly:x", "weekly:x", "yearly", "--help"} { + for _, in := range []string{"monthly:0", "monthly:32", "monthly:x", "weekly:x", "yearly", "--help", "daily:1"} { if _, err := ParseRefill(in); err == nil { t.Errorf("%q taken", in) } } - n := normalKeyOwnBalances(map[string]OwnBalance{"a": {USD: 5, Refill: &Refill{"year", 1}}}) + n := normalKeyOwnBalances(map[string]OwnBalance{"a": {USD: 5, Refill: &Refill{"year", 1}}, "b": {USD: 5, Refill: &Refill{RefillDay, 0}}}) if n["a"].USD != 5 || n["a"].Refill != nil { t.Errorf("a refill that isn't one, written by hand: %+v", n) } + if n["b"].Refill == nil || *n["b"].Refill != (Refill{RefillDay, 0}) { + t.Errorf("a daily refill was dropped as read back: %+v", n["b"]) + } } // spendAt stubs usage.KeySpent with calls at given times: what the key