Files
magpie/internal/cli/key_balance_cli.go
T
yetone c736906b17 providers: part of a key's typed balance may expire on a day
tenacious_eagle_96548 (Discord, #general): some vendors split a balance
into money that stays and credit good until a date. A key's balance typed
by hand can now carry that part (`expiring`: {amount, until, at}, in the
balance's currency, until = the last day it counts).

- Spending order: the expiring part is spent first, as DeepSeek spends
  its granted balance before money topped up. It takes the spend from its
  `at` up to its end (midnight after `until`, local time) or now; only
  what it took after `From` comes off the rest, so a refill or typing the
  balance again doesn't count it twice.
- Left is the whole balance. From its end the remainder counts no more,
  and unspent credit is gone.
- 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 no part and reads exactly as it did
  (TestTypedBalanceSavedBeforeExpiring).
- Set from the pill's menu: "Credit that expires…" asks the amount, then
  the last day (a day gone by, or the other currency's sign, refused);
  "No credit that expires" takes it off. GUI route provider/keyexpiring;
  CLI `magpie provider key-balance <id> <key> --expiring amount@yyyy-mm-dd|off`.
- Shown: the pill "≈$100.00 left · $30.00 expires in 30 days", the Usage
  page and panel line "Expires in 30 days ≈$30.00", amber from 7 days;
  TUI and `magpie quota` "($30.00 until Dec 7)". New strings in zh,
  zh-TW, ja and de.

Run (mote):
- go test of internal/provider, internal/gui, internal/cli (with
  TestCoreScriptBudget: the days' lines in app.js are paid for by five
  balance comments cut there, no raise; core 1,533,559 of 1,533,802); the new tests
  again with TZ=UTC and TZ=Pacific/Kiritimati (every clock held);
  gofmt -l clean; GOOS=linux and GOOS=windows go vet of those packages.
- GUI: key-balance-expiring.test.cjs 20/20 (chromium and webkit, 400px,
  en/zh/zh-TW/ja/de), with every balance-*, key-*, i18n-* file: 768
  pass, 6 red, each red the same alone on origin/main 691a10446:
  i18n-keys "a plugin's words are its own" (#5327) and key-replace's
  five webkit 420px cases (#4126, numbers added there).
- A real sandbox (own HOME, -tags nogui binary, ports 3591/3592): set
  $70 + $30 until +30d and ¥40 + ¥5 for +3d through the CLI, then
  through the pill's menu in the real page (¥8 for +6d, then removed);
  a past date shows the part no longer counting; retyping in USD dropped
  the CNY part; `magpie quota` shows the split. No page errors.

Broken by hand, each red:
- Go (TestTypedBalanceExpires): part not spent first; end taken in UTC
  (red under Kiritimati); part kept after its end; part kept across a
  currency change.
- GUI (key-balance-expiring): no soon class; soon only from 2 days; a
  past day accepted; the other currency's sign accepted.

Not tried: a real vendor's spend priced against the part; the GUI on
Windows or Linux. The full Go and GUI suites were queued on mote's
suite lock behind other sessions' and had not run when this was pushed.

Reported-by: tenacious_eagle_96548
2026-11-08 13:39:32 +08:00

175 lines
5.0 KiB
Go

package cli
import (
"fmt"
"strings"
"time"
"github.com/yetone/magpie/internal/provider"
)
const keyBalanceUsage = "magpie provider key-balance <id> [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|off] [--expiring amount@yyyy-mm-dd|off]]"
// keyBalanceCmd shows, or sets, the balance typed by hand on a provider's
// API keys whose vendor tells none (tenacious_eagle on Discord): what is
// 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.
func keyBalanceCmd(args []string) error {
var rest []string
var refill, expiring *string
for i := 0; i < len(args); i++ {
a := args[i]
switch {
case a == "--refill" && i+1 < len(args):
i++
refill = &args[i]
case strings.HasPrefix(a, "--refill="):
v := strings.TrimPrefix(a, "--refill=")
refill = &v
case a == "--expiring" && i+1 < len(args):
i++
expiring = &args[i]
case strings.HasPrefix(a, "--expiring="):
v := strings.TrimPrefix(a, "--expiring=")
expiring = &v
case strings.HasPrefix(a, "-") && a != "-":
// a flag magpie doesn't know, or a negative amount: never data
return fmt.Errorf("%s", keyBalanceUsage)
default:
rest = append(rest, a)
}
}
if len(rest) < 1 || len(rest) > 3 || ((refill != nil || expiring != nil) && len(rest) < 2) {
return fmt.Errorf("%s", keyBalanceUsage)
}
p, err := provider.Find(rest[0])
if err != nil {
return err
}
if p.Account != nil {
return fmt.Errorf("%s is a subscription: a balance typed by hand is for an API key", p.Name)
}
var r *provider.Refill
if refill != nil {
if r, err = provider.ParseRefill(*refill); err != nil {
return err
}
}
var x *provider.Expiring
if expiring != nil {
if x, err = provider.ParseExpiring(*expiring); err != nil {
return err
}
}
var b *provider.OwnBalance
if len(rest) > 2 {
if b, err = provider.ParseOwnBalance(rest[2]); err != nil {
return err
}
if b == nil && (refill != nil || expiring != nil) {
return fmt.Errorf("%s", keyBalanceUsage)
}
}
switch {
case b != nil:
b.Refill = r
if err := provider.SetKeyOwnBalance(p.ID, rest[1], b); err != nil {
return err
}
// typed again with --refill off: it refills no more
if refill != nil && r == nil {
if err := provider.SetKeyBalanceRefill(p.ID, rest[1], nil); err != nil {
return err
}
}
case len(rest) > 2:
if err := provider.SetKeyOwnBalance(p.ID, rest[1], nil); err != nil {
return err
}
case refill != nil:
if err := provider.SetKeyBalanceRefill(p.ID, rest[1], r); err != nil {
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 {
return err
}
}
if len(rest) > 2 || refill != nil || expiring != nil {
if p, err = provider.Find(p.ID); err != nil {
return err
}
}
keys := p.KeyList()
if len(rest) > 1 {
ref, ok := p.AccountRefOf(rest[1])
if !ok {
return fmt.Errorf("%s has no key %q", p.Name, rest[1])
}
for _, k := range keys {
if k.ID == ref {
keys = []provider.KeyInfo{k}
break
}
}
}
if len(keys) == 0 {
fmt.Println(muted.Render(p.Name + " has no key"))
return nil
}
if !p.TakesOwnBalance() {
fmt.Println(muted.Render(p.Name + " tells its balance itself: the Usage page shows that, not one typed"))
}
for _, k := range keys {
name := k.Masked + " " + muted.Render(k.ID)
if k.Name != "" {
name = k.Name + " " + muted.Render(k.Masked+" · "+k.ID)
}
e, ok := p.OwnBalanceEstimate(k.ID)
if !ok {
fmt.Println(name, muted.Render("· no balance typed"))
continue
}
fmt.Println(name, "·", keyBalanceLine(e))
}
return nil
}
// keyBalanceLine is what is left of a balance typed, as the CLI says it.
func keyBalanceLine(e provider.BalanceEstimate) string {
money := func(v float64) string {
if e.Currency == "cny" {
return fmt.Sprintf("¥%.2f", v)
}
return fmt.Sprintf("$%.2f", v)
}
left := "what is left can't be told yet: the dollar's rate in yuan isn't known"
if e.Left != nil {
left = "about " + money(*e.Left) + " left"
}
from := "typed " + e.At.Local().Format("Jan 2 15:04")
if e.From.After(e.At) {
from = "refilled " + e.From.Local().Format("Jan 2 15:04")
}
spent := fmt.Sprintf("$%.2f spent since", e.Spent)
if e.Currency == "cny" && e.Rate > 0 {
spent += fmt.Sprintf(" at ¥%.4g a dollar", e.Rate)
}
out := fmt.Sprintf("%s · %s %s, %s", left, money(e.Set), from, spent)
if e.Refill != nil && e.Next != nil {
out += " · refills " + e.Refill.String() + ", next " + e.Next.Local().Format("Jan 2")
}
if x := e.Expiring; x != nil && x.Left != nil {
out += fmt.Sprintf(" · of it %s expires (%s typed %s), counted through %s", money(*x.Left), money(x.Set),
x.At.Local().Format("Jan 2 15:04"), x.Ends.Add(-time.Second).Format("Jan 2"))
}
if e.Expired != nil {
out += " · the part that expired " + e.Expired.Add(-time.Second).Format("Jan 2") + " no longer counts"
}
return out
}