Files
magpie/internal/usage/spend.go
T
yetone f8525323dd providers: a key with no balance URL takes a balance typed by hand, counted down by magpie's own usage
Some API-key providers tell no balance magpie can read (no Balance URL,
no relay query found), so their keys showed none. Now the user types what
the vendor's page says is left, on the key's row in the provider editor
(Set balance) or with `magpie provider key-balance <id> [key [usd|off]]`.
The key's card shows that less what magpie's usage priced the calls it
sent on the key since it was typed (usage.KeySpent, the spend caps'
count), marked as an estimate: "≈$12.50", the pill "≈$12.50 left", its
title saying what was typed, when, and what was counted since. Typing it
again counts from then; No balance takes it off.

A balance the vendor tells always wins: a provider with a Balance URL, a
plan source, Cline's or OpenCode Zen's card takes none typed, and a relay
whose query is found shows its own; when the probe finds none
(errNoBalance) the typed one is shown. A typed balance stays saved as the
user left it: the editor's save keeps it, a key's replaced value carries
it. An estimate is never kept in the balance history and tells routing
nothing (the routing allowances cache is left alone).

keybalance.js is loaded by keyspend.js (itself loaded when the editor
draws a key) for a provider that takes one, so app.js and the core's
script budget are unchanged. Words in zh, zh-TW, ja and de.

Run at this tree (mote):
- go vet ./... (darwin), GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... at base 46b10af87; at this tree go vet of
  gui, provider, cli and usage;
- go test -tags nogui -count=1 ./internal/gui ./internal/provider
  ./internal/cli ./internal/usage: provider and usage ok; gui and cli
  red only on #5644 below; TestCoreScriptBudget ok (1,533,747, as main)
- the provider tests under -race -count=3;
- GUI: key-own-balance (new: Chromium and WebKit, en zh zh-TW ja de,
  900 and 400px, 20/20), key-spend-cap, old-webkit, i18n-keys, gui-de,
  gui-ja, gui-zh-tw, balance-found, key-balance-card, i18n-en-no-cjk:
  104 pass, 1 fail, i18n-keys "a plugin's words are its own", red the
  same on origin/main 7a2946caf (#5327, #5332, #5482, #5426).

Broken by hand, each went red:
- estimates kept in the balance history: TestTypedBalanceCountsDown;
- no fallback to the typed balance on errNoBalance:
  TestToldBalanceWinsOverTyped;
- the editor's save dropping KeyOwnBalances: TestKeyOwnBalanceRoutes.

Red on main, not this change: TestSettingsSaveKeepsWhatItDoesNotSend
and TestSettingsCLISetsWhatTheWindowSaves (groupSink, groupFirstToken,
groupPatience from 6b7ee4a98), filed as #5644.

Not tried: a real relay account with no balance URL (the cost counted is
magpie's own estimate, so a vendor pricing differently drifts until the
balance is typed again); the full Go and GUI suites before the push (run
after it, under the suite lock); the GUI in the real Windows and Linux
apps; routing does not use the estimate.

Reported-by: tenacious_eagle (Discord)
2026-11-08 02:54:25 +08:00

139 lines
3.8 KiB
Go

package usage
import (
"sync"
"time"
"github.com/yetone/magpie/internal/provider"
)
// a key's balance typed by hand is shown less what this counts spent
func init() { provider.KeySpent = KeySpent }
// spendMemo keeps what each API key has spent from a start on, read from
// usage.jsonl once and counted up by Append after: routing asks it on
// every request for a key with a spend cap (provider.SpendCap).
var spendMemo struct {
sync.Mutex
path string
// sums by key and start, each read again once it is spendFresh old:
// prices change, and the log can be cleared or rewritten
sums map[spendSlot]spendSum
// reading counts the reads of a key under way, dirty a call Append
// wrote for one meanwhile: such a read may have missed it or have it
// already, so it is not kept
reading map[string]int
dirty map[string]bool
}
type spendSlot struct {
key string
start time.Time
}
type spendSum struct {
usd float64
at time.Time
}
// spendFresh is how long a key's sum read from the log is kept, counted up
// by Append, before it is read again.
const spendFresh = 5 * time.Minute
// spendCounts reports whether r spends from its key: a call magpie sent
// on it from this computer, not one turned away before it went out nor
// one an agent reported.
func spendCounts(r Record) bool {
return r.ProviderKeyID != "" && !r.IsRejected() && !r.IsReported() && r.Computer == ""
}
// KeySpent is what the calls magpie sent on the API key keyID (its
// provider.KeyID) from start on cost, in USD at the Usage page's prices,
// under whichever provider sent them. A call with no known price counts
// nothing.
func KeySpent(keyID string, start time.Time) float64 {
path := Path()
slot := spendSlot{keyID, start.UTC()}
for try := 0; ; try++ {
spendMemo.Lock()
if spendMemo.path != path {
spendMemo.path, spendMemo.sums = path, nil
}
if v, ok := spendMemo.sums[slot]; ok && time.Since(v.at) < spendFresh && !v.at.After(time.Now()) {
spendMemo.Unlock()
return v.usd
}
if spendMemo.reading == nil {
spendMemo.reading, spendMemo.dirty = map[string]int{}, map[string]bool{}
}
spendMemo.reading[keyID]++
if spendMemo.reading[keyID] == 1 {
delete(spendMemo.dirty, keyID)
}
spendMemo.Unlock()
read := time.Now()
v := readSpent(keyID, start)
spendMemo.Lock()
dirty := spendMemo.dirty[keyID]
if spendMemo.reading[keyID]--; spendMemo.reading[keyID] == 0 {
delete(spendMemo.reading, keyID)
}
// a read Append wrote a call of the key into meanwhile may count it
// or not: read again, and past three such reads go by what was read
if !dirty || try >= 2 {
if !dirty && spendMemo.path == path {
if spendMemo.sums == nil {
spendMemo.sums = map[spendSlot]spendSum{}
}
// a key's cap counts from one start: one it counted from
// before (yesterday, a cap since changed) is let go
for s := range spendMemo.sums {
if s.key == keyID {
delete(spendMemo.sums, s)
}
}
spendMemo.sums[slot] = spendSum{v, read}
}
spendMemo.Unlock()
return v
}
spendMemo.Unlock()
}
}
func readSpent(keyID string, start time.Time) float64 {
cost := NewCoster()
var spent float64
Visit(start, func(r Record) {
if r.ProviderKeyID == keyID && spendCounts(r) && !r.Time.Before(start) {
c, _ := cost(r)
spent += c
}
})
return spent
}
// spentNew counts a call Append wrote in the sums of its key kept.
func spentNew(r Record) {
if !spendCounts(r) {
return
}
spendMemo.Lock()
defer spendMemo.Unlock()
if spendMemo.reading[r.ProviderKeyID] > 0 {
spendMemo.dirty[r.ProviderKeyID] = true
}
var cost func(Record) (float64, bool)
for s, v := range spendMemo.sums {
if s.key != r.ProviderKeyID || r.Time.Before(s.start) {
continue
}
if cost == nil {
cost = NewCoster()
}
c, _ := cost(r)
v.usd += c
spendMemo.sums[s] = v
}
}