Files
magpie/internal/provider/balance_shared.go
T
yetone c3b0484a96 usage: keys of one account show its balance once (mimi)
mimi on Discord (#feedback): "同一个网站,添加多个key时,余额会重复展示" -
a site's keys 1-A031-Pro, 2-S009-Plus and 3-S010-Team-2 each showed the
account's $8.39 and its own curve.

KeyBalances still reads, keeps and charts every key on its own. What
changed is what the Usage page draws:
- balanceRead says whether the reading is the account's (balanceAccountWide),
  going by the source, not the vendor's name:
  - account-wide: a balance token (new-api /api/user/self, sub2api
    /api/v1/user/profile, AiHubMix), a known host's account query
    (DeepSeek, Moonshot, OpenRouter credits, SiliconFlow, StepFun, ...),
    and sub2api /v1/usage when its mode is "unrestricted" (wallet or the
    group's subscription, per sub2api's gateway_handler.go Usage);
  - per key: AiHubMix's /dashboard/billing/remain, new-api's
    /api/usage/token, sub2api in quota_limited mode, any other Balance
    URL the user named.
- Two such keys of one provider with the same amount are one account only
  when their balances moved together: the same latest change (from and
  to), first read within balanceHistGap. Two accounts with the same
  amount stay apart until one is spent from; keys whose amounts differ
  are never one. SharedBalance (the first key's name) says so in
  /api/usage/quotas, magpie quota --json and /v1/magpie/quotas.
- Refreshing a shared card reads every key it stands for (sharesAskedCard),
  so it stays one card. The history is read outside the cache's lock.
- The Usage page draws them as one row, one balance, one curve, with
  "+2 keys" beside the key and the keys on hover; the head's sum counts
  the account once. The code is in plugins/usage/page.js, so app.js is 9
  bytes smaller than before; no budget raised.

Run (mote-run, at the pre-rebase base d50f84c9f):
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./...: ok. gofmt -l: clean.
- go test -tags nogui -timeout 45m ./...: every package ok except
  internal/gui's TestCoreScriptBudget (app.js 676 bytes over; fixed by
  moving the code into the Usage plugin, then ok) and internal/update's
  TestRelaunchOpenTriedAgain (TempDir cleanup under load, #3881; 3 of 3 ok
  alone).
- go test -race on internal/provider's balance tests: ok.
- GUI, both engines, en and zh: 122 files (balance-*, usage-*, quota-*,
  tray-*, panel-*, gui-ja/de/zh-tw, i18n-keys, key-balance-card,
  routing-wallet-balance, ...): 1637 pass, 42 fail in 6 files, all the
  same at base a05b37353 run alone and all filed (#3679 quota-refresh-
  order, #3404 quota-count-wrap, #3414 usage-agents-hide, #3415
  usage-fold, #3104 usage-ledger, #3897 i18n-keys "Runs as"). After the
  move into the plugin, 17 of those files again: only #3897's red.

Broken by hand, each red:
- SharedBalance never set (the old code): "after they moved together".
- Shared on equal amount alone: "first reading" ("other" merged).
- Every query taken as account-wide: quota'd and new-api token keys
  merged.
- No sharesAskedCard: the shared card's refresh didn't read sk-plus.
- keyCards without sharedBalances: usage-shared-balance red in all four
  (chromium/webkit x en/zh).

Not tried: a real sub2api or new-api account (fake server with sub2api's
literal replies). A key's balance is shown once only after the account's
next change is seen by every key, not on the first read. Multi-currency
balances (DeepSeek "$ · ¥") and balances with parts are never shared.
2026-10-28 10:52:46 +08:00

124 lines
3.9 KiB
Go

package provider
// One account's balance read through several of its keys (mimi on
// Discord: a site's three keys each showed its $8.39 and its own curve).
// A balance query that tells the account's (balanceAccountWide) answers
// every key of the account the same, so its card would be shown once a
// key. Two keys are taken for one account only when their balances moved
// together: the same amount before and after their latest change, read
// within balanceHistGap of each other. Two accounts with the same amount
// (a fresh grant each, or both at zero) stay apart until one is spent
// from, and keys whose amounts differ are never one. A key's own query
// (new-api's /api/usage/token, a quota of its own) is never shared.
//
// Each key is still read, kept and drawn over time on its own; the keys
// found to be one account are told by SharedBalance, the first one's
// name, for the Usage page to show their balance once.
import (
"context"
"strings"
"time"
)
// balanceMove is a balance's latest change: from one amount to another,
// the new one first read at At.
type balanceMove struct {
from, to float64
at time.Time
}
// lastBalanceMove is the latest change in pts; false when it has none.
func lastBalanceMove(pts []BalancePoint) (balanceMove, bool) {
k := len(pts)
if k < 2 {
return balanceMove{}, false
}
to := pts[k-1].Amount
i := k - 1
for i > 0 && pts[i-1].Amount == to {
i--
}
if i == 0 {
return balanceMove{}, false
}
return balanceMove{pts[i-1].Amount, to, pts[i].At}, true
}
// movedTogether says two balances' latest changes were the same change,
// at the same time.
func movedTogether(a, b []BalancePoint) bool {
ma, ok := lastBalanceMove(a)
mb, ok2 := lastBalanceMove(b)
if !ok || !ok2 || ma.from != mb.from || ma.to != mb.to {
return false
}
d := ma.at.Sub(mb.at)
return d <= balanceHistGap && -d <= balanceHistGap
}
// sharesAccountBalance says q is a key's card whose balance, read just
// now, is its account's: one amount, nothing kept from before.
func sharesAccountBalance(q SubscriptionQuota) bool {
return q.wideBalance && q.User != "" && q.Balance != "" && q.Error == "" && q.AsOf == nil &&
len(q.BalanceParts) == 0 && balanceCurrencies(q.Balance) == nil
}
// sharedBalanceHist is the balances' history shareBalances goes by, read
// before the cards' lock is taken; nil when none of cards is an account's
// balance, as then none is shared.
func sharedBalanceHist(cards []SubscriptionQuota) balanceHist {
for _, q := range cards {
if sharesAccountBalance(q) {
balanceHistMu.Lock()
defer balanceHistMu.Unlock()
return readBalanceHist()
}
}
return nil
}
// shareBalances sets SharedBalance on the keys of qs found to read one
// account's balance (see above) by their history h, afresh each time, in
// place: qs is a copy of the caller's.
func shareBalances(qs []SubscriptionQuota, h balanceHist) []SubscriptionQuota {
for i := range qs {
qs[i].SharedBalance = ""
}
if h == nil {
return qs
}
for i := range qs {
a := &qs[i]
if a.SharedBalance != "" || !sharesAccountBalance(*a) {
continue
}
for j := i + 1; j < len(qs); j++ {
b := &qs[j]
if b.SharedBalance != "" || b.Provider != a.Provider || b.From != a.From || b.Balance != a.Balance || !sharesAccountBalance(*b) {
continue
}
if movedTogether(h[quotaHistKey(a.Provider, a.User)], h[quotaHistKey(b.Provider, b.User)]) {
a.SharedBalance, b.SharedBalance = a.User, a.User
}
}
}
return qs
}
// sharesAskedCard says the key user of provider shows its balance on the
// card a refresh asks for (another key's, SharedBalance): read again with
// it, so the card stays one.
func sharesAskedCard(ctx context.Context, kept []SubscriptionQuota, provider, user string) bool {
r, ok := refreshing(ctx)
if !ok || r.user == "" {
return false
}
for _, q := range kept {
if q.Provider == provider && strings.EqualFold(q.User, user) && q.SharedBalance != "" {
return r.wants(provider, q.SharedBalance)
}
}
return false
}