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