usage: a key's balance card carries its curve again

nf1qaz2w on Discord: Usage -> Overview showed the subscriptions' curves
and no "Balance over time" for any API key. f8525323d (v0.1.3281) kept
typed estimates out of the balance history by passing KeyBalances'
cards through slices.Clone before noteBalanceHistory. noteBalanceHistory
sets each card's BalanceTrend on the slice it is given, so every trend
went onto the copy and was thrown away: since v0.1.3281 no key's card
has had one. The history file kept growing, so the curves come back
with their past readings.

Now KeyBalances notes the history on its own cards, and
noteBalanceHistory itself leaves an Estimate out: no point kept and no
trend given, for KeyBalances and for noteCardHistory alike.

Run (mote):
- TestKeyBalancesCarryTheirTrend (new): a key read at $3 an hour ago and
  $2 now has a two-point trend. It is red at the old balance.go ("trend
  <nil>").
- Broken by hand: no Estimate guard in balancePointsOf makes
  TestTypedBalanceCountsDown go red (an estimate kept in the history).
- go test -run 'Balance|Typed|OwnBalance' ./internal/provider: ok.
- gofmt -l clean; go vet (darwin, GOOS=linux -tags nogui, GOOS=windows)
  of internal/provider and internal/gui; go test -tags nogui -count=1
  ./internal/provider ./internal/gui under mote's suite lock: ok.
- GUI: balance-curve, balance-*, usage-*, quota-* among the 293 files
  run for the commit before this one, same tree: no red of their own.
- Rebased onto origin/main 4436b7d98 and run again there: the provider
  balance tests ok; routing-calm-in-flight and balance-curve 14 of 14 ok;
  TestCoreScriptBudget red, the same at 4436b7d98 alone (1,534,166 bytes
  either way, these commits add none to the core), filed as #5720.

Not tried: the full go test ./... and the whole GUI suite; a real
account's curve in the built app. No GUI change: the
page draws a trend when the card has one.

Reported-by: nf1qaz2w (Discord)
This commit is contained in:
yetone
2026-11-09 04:06:39 +08:00
parent 50eec4994a
commit ed0ab567cb
3 changed files with 57 additions and 6 deletions
+3 -3
View File
@@ -1788,9 +1788,9 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota {
wg.Wait()
out = slices.DeleteFunc(out, func(q SubscriptionQuota) bool { return q.Provider == "" })
if ctx.Err() == nil {
// each balance kept, and drawn over time with its runs-out; not
// one estimated from a balance typed, which is no reading
noteBalanceHistory(slices.DeleteFunc(slices.Clone(out), func(q SubscriptionQuota) bool { return q.Estimate != nil }), time.Now())
// each balance kept, and drawn over time with its runs-out, on
// the cards themselves (an estimate is neither: noteBalanceHistory)
noteBalanceHistory(out, time.Now())
// the history of the cards read now and of those kept, a partial
// read (one card's refresh) keeping the others
h := sharedBalanceHist(slices.Concat(kept, out))
+5 -3
View File
@@ -124,7 +124,8 @@ func addBalancePoint(pts []BalancePoint, n BalancePoint) []BalancePoint {
// under, if it is one to keep: one under the card's key, or, told in
// several currencies, one for each under the card's key and the currency.
func balancePointsOf(q SubscriptionQuota, now time.Time) map[string]BalancePoint {
if q.Error != "" || q.AsOf != nil || q.Provider == "" || q.Balance == "" || len(q.BalanceParts) > 0 {
// an estimate counted down from a balance typed is no reading
if q.Error != "" || q.AsOf != nil || q.Estimate != nil || q.Provider == "" || q.Balance == "" || len(q.BalanceParts) > 0 {
return nil
}
at := now
@@ -187,7 +188,8 @@ func balanceCurrencies(s string) []currencyAmount {
func currencyHistKey(key, sign string) string { return key + "|" + strings.TrimSpace(sign) }
// noteBalanceHistory keeps the balance each card among qs tells, and gives
// every card with a balance its trend.
// every card with a balance its trend, on qs itself. A balance estimated
// from one typed (Estimate) is neither kept nor given one.
func noteBalanceHistory(qs []SubscriptionQuota, now time.Time) {
balanceHistMu.Lock()
defer balanceHistMu.Unlock()
@@ -236,7 +238,7 @@ func noteBalanceHistory(qs []SubscriptionQuota, now time.Time) {
writeBalanceHist(h)
}
for i, q := range qs {
if q.Balance == "" || len(q.BalanceParts) > 0 {
if q.Balance == "" || len(q.BalanceParts) > 0 || q.Estimate != nil {
continue
}
if h == nil {
@@ -0,0 +1,49 @@
package provider
import (
"context"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"time"
"github.com/yetone/magpie/internal/agentenv"
)
// A key's balance card carries its trend: the Usage page's "Balance over
// time" is drawn from it. f8525323d noted the history on a copy of the
// cards, so every key's card went out with none (nf1qaz2w on Discord).
func TestKeyBalancesCarryTheirTrend(t *testing.T) {
isolate(t)
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
t.Setenv("PATH", h)
for _, v := range agentenv.Vars {
t.Setenv(v, "")
}
keyBalanceCache.data = nil
t.Cleanup(func() { keyBalanceCache.data = nil })
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"data":{"total_available":1000000}}`))
}))
defer srv.Close()
if err := Save(Provider{ID: "relay", Name: "Relay", Chat: srv.URL + "/v1", Key: "sk-one", KeyName: "main",
BalanceURL: srv.URL + "/api/usage/token", BalancePath: "$data.total_available / 500000"}); err != nil {
t.Fatal(err)
}
// read an hour ago at $3
before := time.Now().Add(-time.Hour).UTC().Truncate(time.Second)
writeBalanceHist(balanceHist{quotaHistKey("relay", ""): {{At: before, Amount: 3}}})
got := KeyBalances(context.Background())
if len(got) != 1 || got[0].Balance != "$2.00" {
t.Fatalf("cards %+v", got)
}
tr := got[0].BalanceTrend
if tr == nil || len(tr.Points) != 2 || tr.Points[0].Amount != 3 || tr.Points[1].Amount != 2 {
t.Fatalf("the key's card has trend %+v, want $3 an hour ago then $2", tr)
}
}