provider: a plugin's usage window can be a prepaid wallet's balance (#3950)

SuperMagic's accounts (mycf_711's magicrew plugin) are prepaid wallets of
points with no total. A plugin can now send a usage window as
{name, balance: 6291, unit: "积分"} with no used or limit.

- host.js passes a finite balance on (at least 0), anything else as null.
  plugin.UsageWindow.Balance and provider.QuotaWindow.Balance are *float64.
- quotaOfPlugin keeps the figure and does not make the window Text or
  Aside, so routing knows the account with no Used invented. allowanceOf
  copies it into Limit.Balance; an empty wallet counts as used up.
  Allowance.Left(model) is the least balance of the windows that count
  the model.
- weighRouted fills routes.Seat.Left and Seat.LeftIn (the account's
  provider and unit). Smart, pace and usage (least used) put the seat
  with more left first where they would otherwise tie (byLeft), only
  when every seat with a balance shares one LeftIn: balances in two
  units or two providers are never compared. Tiers still come first.
- The Usage card, the Routing page (Weighed.Balance: the small row's
  text, no bar, a why sentence, the account list), magpie accounts and
  the status line show the figure, "6,291 积分 left", never a share.
- Docs: provider-plugins (new section), gateway-routing,
  providers-accounts, plugin-runtime, host.js typings and the site's
  plugins page (en, zh, ja).

Run, at base f13aafa87, on mote:
- go test -tags nogui -timeout 45m ./...: 72 packages ok; red were
  TestQuotaSpanCarriesEveryWindowField (this change's: its fixture now
  sets Balance, green after), and on the unchanged base too
  TestWSLColdPlaceOpensNothing (#3924), TestFetchAsksASharedBaseOnce and
  two siblings (#3854), TestTUIFetchesSubscriptionModels (#3919), all
  fixed on main since and run again after the rebase; and
  TestPluginStreamsPastTheBudgetWait (#3946), green alone on both.
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/..., go
  build ./..., gofmt -l: clean.
- New tests: TestPluginWalletBalanceIsAReading, TestAllowanceLeftIsTheLeastBalance,
  TestPluginHostPassesABalanceOn (through real Bun and host.js),
  TestWalletsGoByWhatTheyHaveLeft, TestWalletLeftWithinItsTier,
  TestWalletWithMoreLeftGoesFirst, TestQuotaCell's balance cases;
  usage-wallet-balance.test.cjs and routing-wallet-balance.test.cjs,
  34 of 34 in Chromium and WebKit, en zh zh-TW ja de, 1100/900/420/390px.
- GUI: every quota*, usage*, panel*, routing*, i18n* and tray* file (220
  files, 2928 tests), concurrency 4: 130 red, in 21 files. Those 21 files
  run again on an unchanged base copy and on this change, concurrency 2:
  the same 19 files red on both (126 and 131), the differing subtests
  being routing-rule-remove / rules-line / intent-entry flaps that go
  both ways. Each is filed (#3679, #2115, #3410, #3404, #3411, #3897,
  #1905, #3096, #3593, #3408, #3409, #3799, #3789, #3412, #3947, #3415,
  #3414, #1345); routing-story-shrinks had none and is #3954.

After rebasing on origin/main 833f51adc, on mote: Linux and Windows vet,
go build, gofmt clean; go test -tags nogui of internal/routes, provider,
gateway, cli, plugin, gui (the script budgets), agent and tui: all ok;
the two wallet GUI files and i18n-keys: 37 of 38, the red being
i18n-keys' "Runs as" (#3897, not this change).

Broken by hand, each red then restored: quotaReport's Balance copy
removed (TestQuotaSpanCarriesEveryWindowField red); byLeft always nil (routes and
gateway tests red); host.js's balance line removed (host test red);
quotaOfPlugin's balance copy removed (provider tests red); app.js and
client.js at base (both GUI files 34 of 34 red, "0% used" / "已用 0%").

Not tried: a real SuperMagic account or the magicrew plugin (it isn't
in the community repo; it needs to send balance), Windows and Linux
GUI apps, and the WebKitGTK app.
This commit is contained in:
yetone
2026-10-28 08:28:56 +08:00
parent 9901303d1f
commit 8bade6c5e2
29 changed files with 658 additions and 33 deletions
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -194,7 +194,7 @@ the core. The seven other routings are the built-in plugin `rotation`'s.
| Part | What it does | Source |
| --- | --- | --- |
| `routes.Strategy` | `Order(pool, seats) []int`: a permutation of the seats' indexes. `pool` is a provider's id or `group/<id>`, for a strategy that keeps a round per pool. `Exact` keeps the order as given; otherwise a provider's API keys that fit the request better go first, each in its order. `ByUse` puts each seat's recent tokens in the trace; `ByFree` has the gateway fill `Seat.Free`, and `BySpeed` `Seat.TTFT` and `TPS` (its speed lately, gateway `speed.go`), each only for a strategy that asks. | [`routes.go`](../../internal/routes/routes.go) |
| `routes.Seat` | What a strategy weighs, read by `weighRouted` under the routing state's lock: its rest key, whether it is an account, whether its allowance is known or it learns it as it answers, the share used, when its windows renew, its weekly pace, its key's weight, whether it rests now, its tokens of the last hours, and, when the strategy asks, whether its model is free and its ms to the first token and tokens a second lately. | [`routes.go`](../../internal/routes/routes.go), [`routing.go`](../../internal/gateway/routing.go) |
| `routes.Seat` | What a strategy weighs, read by `weighRouted` under the routing state's lock: its rest key, whether it is an account, whether its allowance is known or it learns it as it answers, the share used, when its windows renew, its weekly pace, its key's weight, whether it rests now, its tokens of the last hours, a prepaid wallet's balance and the provider and unit it is in (`Left`, `LeftIn`, #3950), and, when the strategy asks, whether its model is free and its ms to the first token and tokens a second lately. | [`routes.go`](../../internal/routes/routes.go), [`routing.go`](../../internal/gateway/routing.go) |
| `Register`, `Find`, `Apply` | `Register(routing, s)` serves a routing until its remove; registering again stacks, and the last one serves. `Find("")` is `Smart` always. `Apply` fails open: a strategy that panics, or answers what isn't a permutation, leaves the pool in its listed order, logged. Every route is still tried. | [`routes.go`](../../internal/routes/routes.go) |
| Strategies | `Smart` (core), and `Ordered`, `Rotate`, `LeastUsed`, `Pace`, `Weighted`, `FreeFirst` and `Fastest` in `routes.Builtin`. `Rotate` keeps a turn per pool and `Weighted` a smooth weighted round (`Round`, `MoveRound`), both moved out of the gateway, and `Fastest` a probe count per pool, so a seat not measured lately gets one request in `ProbeEvery`; `Forget` clears them. | [`strategies.go`](../../internal/routes/strategies.go), [`round.go`](../../internal/routes/round.go) |
| Off | A routing no strategy serves is its listed order. `routingOf` in the gateway reads it as `order` wherever the core asks about a routing (a turn's mark, `sinks`, a rotate group's sessions, a group's heads), so nothing of the routing is left half on. | [`routing.go`](../../internal/gateway/routing.go) |
+4
View File
@@ -42,6 +42,10 @@ The gateway parses the field into `Usage.Deferred` ([`cUsage`](../../internal/ga
A usage window's `used` (percent) may be left out when the plugin can't tell it: the Loomy plugins send only `display` ([#3650](https://github.com/yetone/magpie/issues/3650)). Left out is not 0. The host passes it on as `null` (`usageOf` in [`host.js`](../../internal/plugin/host.js)), `plugin.UsageWindow.Used` is a `*float64`, and [`quotaOfPlugin`](../../internal/provider/plugin_usage.go) makes such a window `Text` and `Aside`: the card shows its `display` (else "No allowance reported"), never a percentage or a meter (`quotaNoShare` in `app.js`), and `allowanceOf` leaves it out. An account whose windows all tell no share has no allowance, so routing counts it not known (`routedAllowance` in [`routing.go`](../../internal/provider/routing.go), for a fresh reading and the one kept on disk alike), as one never read, rather than as the one with all of it left. A window that says `used: 0` is a reading at 0, as before. [`plugin_usage_absent_test.go`](../../internal/provider/plugin_usage_absent_test.go) and `usage-no-reading.test.cjs` cover both.
## A wallet's balance
A prepaid wallet (SuperMagic's points, [#3950](https://github.com/yetone/magpie/issues/3950)) has a balance and nothing it is a share of. A usage window may send `balance` (a number, in `unit`) and leave out `used`, `limit` and `aside`: `{name: "积分", balance: 6291, unit: "积分"}`. The host passes a finite number on, at least 0, and anything else as `null` (`usageOf` in [`host.js`](../../internal/plugin/host.js)); `plugin.UsageWindow.Balance` and `provider.QuotaWindow.Balance` are `*float64`. [`quotaOfPlugin`](../../internal/provider/plugin_usage.go) keeps the figure and does not make the window `Text` or `Aside`, so the account is known to routing with no `Used` invented. `allowanceOf` copies it into `Limit.Balance`, and an empty wallet (0) counts as used up. `Allowance.Left(model)` is the least balance of the windows that count the model, with its unit. `weighRouted` sets `routes.Seat.Left` to it and `Seat.LeftIn` to the account's provider and unit; Smart, `pace` and `usage` put the seat with more left first where they would otherwise tie (`byLeft` in [`strategies.go`](../../internal/routes/strategies.go)), and only when every seat that has a balance shares one `LeftIn`, so balances in two units or two providers are never weighed against each other. The card, the Routing page (`Weighed.Balance`) and the CLI show the figure ("6,291 积分 left", `provider.BalanceText`) and no meter. Tests: `TestPluginWalletBalanceIsAReading`, `TestPluginHostPassesABalanceOn`, `TestWalletsGoByWhatTheyHaveLeft`, `TestWalletWithMoreLeftGoesFirst`, `usage-wallet-balance.test.cjs`, `routing-wallet-balance.test.cjs`.
## Cache a vendor doesn't count
A plugin whose vendor counts no cache tokens says so with `usage.magpie_cache_unknown: true` in its Anthropic usage, and leaves the cache fields out. Kiro does this: it caches on its side (a repeated prompt costs about half the credits), but its replies carry credits and a context share, never tokens (opencode-kiro-auth 0.1.16, zeewell on X). The gateway reads the field in [`aUsage`](../../internal/gateway/anthropic.go) into `Usage.cacheUnknown`, ORed across a reply's usage events. [`routeUsage`](../../internal/gateway/trace.go) then sets `RouteUsage.CacheUnknown` on a try that counted no cache read or write. The Routing page's `promptOf` (`plugins/routing/client.js`) leaves such a try out of the hit rate, so the request shows none, not 0%. The field is never told to a client: `Usage.anthropic()` leaves it out, and a passthrough forwards the plugin's bytes as they are. The usage ledger carries it too ([#3464](https://github.com/yetone/magpie/issues/3464)): the gateway records `usage.Record.CacheUnknown` on a call that counted no cache (`Usage.cacheNotCounted`), the ledger keeps it as row flag 8192 (`rowCacheUnknown`), and `usage.Totals` sums such calls' prompt into `cache_unknown` and their count into `cache_unknown_calls`. Every hit rate leaves that prompt out of its denominator: `Totals.HitRate`, and `cacheHitOf` in app.js, used by the tray panel's card, the Usage page's agent rows and cache tile, the requests' Cache hit rate card (which says how many it left out, `cacheLeftOut`) and each ranking row. One of only such calls shows no rate. A request row's cache cells show "—" and its details say the vendor doesn't count the cache. Calls kept before Kiro's plugin said so carry no flag, so a Kiro call (`kiro` or `kiro-plugin`) with no cache counted is read as one (`usage.CountsNoCache`): in the ledger's `rowChunk.row`, in `Totals.countCache`, and for Routing's history in `pricedRoutes` (`cacheCounted`, `internal/gui/trace.go`). The context view (`internal/gui/context.go`, `context.js`) shows no cache for such a call and doesn't score it as a miss. Not covered: hit rates read from agents' own session files (`sessions.Tokens`: the TUI and CLI session lists, the Sessions tab's totals), which carry Kiro's 0 as a miss. [`cache_unknown_test.go`](../../internal/gateway/cache_unknown_test.go) covers the passthrough and translated replies, both whole and streamed.
File diff suppressed because one or more lines are too long
+5 -2
View File
@@ -360,7 +360,7 @@ func accountRows(ls []provider.Login, now time.Time) []accountRow {
// a pool's own windows stand in for the models' drawing on it,
// as the usage page shows them
for _, w := range provider.PooledWindows(q.Windows) {
s := quotaSpan{Name: w.Name, Used: w.Used, Remaining: max(0, 100-w.Used), ResetsAt: w.ResetsAt, Display: w.Display, Text: w.Text, Pool: w.Pool}
s := quotaSpan{Name: w.Name, Used: w.Used, Remaining: max(0, 100-w.Used), ResetsAt: w.ResetsAt, Display: w.Display, Text: w.Text, Pool: w.Pool, Unit: w.Unit, Balance: w.Balance}
if s.ResetsAt == nil && w.ResetSecs > 0 {
t := now.Add(time.Duration(w.ResetSecs) * time.Second)
s.ResetsAt = &t
@@ -382,7 +382,10 @@ func quotaCell(w quotaSpan, now time.Time) string {
return name + " unlimited"
}
cell := fmt.Sprintf("%s %.0f%%", name, w.Used)
if w.Text {
if w.Balance != nil {
// a wallet tells what is left, never a share (#3950)
cell = name + " " + provider.BalanceText(*w.Balance, w.Unit)
} else if w.Text {
// a row of text alone has no share to tell
cell = name + " " + w.Display
} else if w.Display != "" {
+13
View File
@@ -151,6 +151,19 @@ func TestQuotaCell(t *testing.T) {
if got := statuslineCard(provider.Quota{Provider: "autoclaw-plugin", Windows: []provider.QuotaSpan{{Name: "积分余额", Display: "1,234 积分", Text: true}, {Name: "5 hours", Used: 40}}}, now); got != "autoclaw-plugin 积分余额 1,234 积分 5h 40%" {
t.Fatalf("status line: %q", got)
}
// a wallet's balance is its figure in its unit, not 0% (#3950)
bal := 6291.0
if got := quotaCell(quotaSpan{Name: "积分", Balance: &bal, Unit: "积分"}, now); got != "积分 6,291 积分 left" {
t.Fatalf("balance: %q", got)
}
if got := statuslineCard(provider.Quota{Provider: "magicrew-plugin", Windows: []provider.QuotaSpan{{Name: "Wallet", Balance: &bal, Unit: "积分"}}}, now); got != "magicrew-plugin Wallet 6,291 积分 left" {
t.Fatalf("status line balance: %q", got)
}
for b, want := range map[float64]string{0: "0 pts left", 1234567.5: "1,234,567.5 pts left", 12.345: "12.35 pts left"} {
if got := provider.BalanceText(b, "pts"); got != want {
t.Errorf("BalanceText(%v): %q, want %q", b, got, want)
}
}
}
// accountRows shows a pool's own windows in place of its models', as the
+3
View File
@@ -155,6 +155,9 @@ func statuslineCard(q provider.Quota, now time.Time) string {
switch {
case w.Unlimited:
cells = append(cells, n+" ∞")
case w.Balance != nil:
// a wallet's figure in its unit, never a share (#3950)
cells = append(cells, n+" "+provider.BalanceText(*w.Balance, w.Unit))
case w.Text:
// a row of text alone (a plugin's balance) has no share
cells = append(cells, n+" "+w.Display)
+16 -2
View File
@@ -1618,6 +1618,11 @@ type left struct {
// credits: a Codex account that goes on on its credits once its
// allowance is used up (spendsCredits)
credits bool
// bal is a prepaid wallet's balance in balUnit (Allowance.Left,
// #3950); balIn says whose wallet it is, provider and unit, and is
// empty when no balance was told: routes.Seat.LeftIn
bal float64
balUnit, balIn string
}
// learns: c is a subscription whose allowance isn't known yet, of an agent
@@ -1673,12 +1678,14 @@ func weighRouted(p provider.Provider, cs []candidate, model string, from provide
for _, c := range cs {
var a provider.Allowance
var ok bool
whose := c.p.ID // whose wallet a balance is in
if c.p.Account == nil {
// a key that reads its own windows is weighed by them as an
// account is; any other key isn't known
a, ok = keyAllowance(c.p)
} else {
ag := c.p.Account.UsageAgent()
whose = ag
if _, had := known[ag]; !had {
known[ag] = allowances(ag)
}
@@ -1689,8 +1696,14 @@ func weighRouted(p provider.Provider, cs []candidate, model string, from provide
pc, due := a.Pace(c.model, now)
amt, of, unit := a.Count(c.model, now)
rs := a.Restarts(now)
wg.lefts[c.allowanceKey()] = left{used: u, renews: r, fullest: a.Fullest(c.model, now), soon: a.Renewal(c.model, now), lapse: a.Lapse(c.model, now), pace: pc, due: due, amount: amt, of: of, unit: unit,
l := left{used: u, renews: r, fullest: a.Fullest(c.model, now), soon: a.Renewal(c.model, now), lapse: a.Lapse(c.model, now), pace: pc, due: due, amount: amt, of: of, unit: unit,
restarts: rs, dueRestart: !rs.IsZero() && due.Equal(rs), credits: spendsCredits(c.p, a)} // one not known counts as unused
if b, bu, has := a.Left(c.model); has {
// a wallet's figure is weighed only against the same
// provider's in the same unit (routes.Seat.LeftIn)
l.bal, l.balUnit, l.balIn = b, bu, whose+"\x00"+bu
}
wg.lefts[c.allowanceKey()] = l
}
}
if len(cs) < 2 {
@@ -1711,7 +1724,8 @@ func weighRouted(p provider.Provider, cs []candidate, model string, from provide
pace = provider.FreshPace
}
seats[i] = routes.Seat{Key: c.rest, Account: c.p.Account != nil, Known: known, Learns: learns(c, wg.lefts),
Used: l.used, Soon: l.soon, Lapse: l.lapse, Pace: pace, Weight: keyWeight(c), Resting: resting(c), Tokens: routed.used[c.restKey()].now(now), Credits: l.credits}
Used: l.used, Soon: l.soon, Lapse: l.lapse, Pace: pace, Weight: keyWeight(c), Resting: resting(c), Tokens: routed.used[c.restKey()].now(now), Credits: l.credits,
Left: l.bal, LeftIn: l.balIn}
}
routed.Unlock()
if st.ByUse {
+10 -3
View File
@@ -258,9 +258,12 @@ type Weighed struct {
Used float64 `json:"used"` // share of the allowance counting the model, used
// Amount of Limit in Unit: the count that share is of, when the
// vendor counts it so (WorkBuddy's credits, #659)
Amount float64 `json:"amount,omitempty"`
Limit float64 `json:"limit,omitempty"`
Unit string `json:"unit,omitempty"`
Amount float64 `json:"amount,omitempty"`
Limit float64 `json:"limit,omitempty"`
Unit string `json:"unit,omitempty"`
// Balance is a prepaid wallet's left in Unit (left.bal, #3950): the
// Routing page tells the figure, not a share
Balance *float64 `json:"balance,omitempty"`
Renews []time.Time `json:"renews,omitempty"` // when those windows renew, the biggest first
Pace float64 `json:"pace,omitempty"` // remaining allowance per hour until its window resets
Due *time.Time `json:"due,omitempty"` // when the allowance window used for pace resets
@@ -462,6 +465,10 @@ func weighed(c candidate, p provider.Provider, wg weighing, fallback bool, from
if l.of > 0 {
w.Amount, w.Limit, w.Unit = l.amount, l.of, l.unit
}
if l.balIn != "" {
b := l.bal
w.Balance, w.Unit = &b, l.balUnit
}
if !l.due.IsZero() {
due := l.due
w.Due = &due
+53
View File
@@ -0,0 +1,53 @@
package gateway
import (
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// 墨雨藏锋 / mycf_711 (#3950): SuperMagic's accounts are prepaid wallets of
// points with no total. Under smart, pace and least used the account with
// 6,291 points left goes before one with 750, whatever their order; the
// Routing page is told each one's figure, not a share. A balance in
// another unit, or another provider's, is never weighed against it.
func TestWalletWithMoreLeftGoesFirst(t *testing.T) {
old := allowances
defer func() { allowances = old }()
share := map[string]provider.Allowance{}
allowances = func(string) map[string]provider.Allowance { return share }
wallet := func(left float64, unit string) provider.Allowance {
return provider.Allowance{{Name: "积分", Balance: &left, Unit: unit}}
}
acct := func(agent, user string) candidate {
return candidate{p: provider.Provider{ID: agent, Account: &provider.Account{Agent: agent, User: user}}, model: "m", rest: agent + "#" + user}
}
for _, routing := range []string{"", provider.Pace, provider.LeastUsed} {
p := provider.Provider{ID: "magicrew", Routing: routing}
order := func(cs ...candidate) (string, weighing, []candidate) {
got, wg := weigh(p, cs, "m", provider.Chat)
var s []string
for _, c := range got {
s = append(s, c.p.Account.User)
}
return strings.Join(s, ","), wg, got
}
share["small"], share["big"] = wallet(750, "积分"), wallet(6291, "积分")
got, wg, cs := order(acct("magicrew", "small"), acct("magicrew", "big"))
if got != "big,small" {
t.Errorf("%q: %s, want big,small", routing, got)
}
if w := weighed(cs[0], p, wg, false, provider.Chat); !w.Known || w.Balance == nil || *w.Balance != 6291 || w.Unit != "积分" || w.Used != 0 {
t.Errorf("%q: the Routing page's row: %+v", routing, w)
}
share["big"] = wallet(6291, "credits")
if got, _, _ := order(acct("magicrew", "small"), acct("magicrew", "big")); got != "small,big" {
t.Errorf("%q, another unit: %s, want their order", routing, got)
}
share["big"] = wallet(6291, "积分")
if got, _, _ := order(acct("magicrew", "small"), acct("othercrew", "big")); got != "small,big" {
t.Errorf("%q, another provider: %s, want their order", routing, got)
}
}
}
+9 -11
View File
@@ -13859,16 +13859,14 @@ async function refreshLanes() {
for (const pill of document.querySelectorAll(".alane")) laneText(pill);
}
// A window reads as how much of it is used, or — as the vendors' own apps
// show it — how much is left, the bar filling with that; one choice for
// every meter and the menu bar, kept in the settings (#122). The vendor's
// own count, where it gives one, stands before the percentage.
// A window reads as used or, as the vendors' apps show it, left, the bar
// filling with that: one setting for every meter and the menu bar (#122).
// The vendor's count, if any, stands before the percentage.
let quotaLeft = false;
function to100(v) { return Math.max(0, Math.min(100, v)); }
// quotaNoShare: the plugin didn't say how much of the window is used. Its
// text is all there is, and no percentage may be read from it: 0 is a
// reading, absent is not (#3650)
function quotaNoShare(w) { return !!w.text || w.used == null; }
// quotaNoShare: no share was said (0 is one, absent is not, #3650), or the
// window is a wallet's balance (#3950): its text or figure is all there is
function quotaNoShare(w) { return !!w.text || w.used == null || w.balance != null; }
function tipLines(...a) { return a.filter(Boolean).join("\n"); }
function quotaFill(w) {
if (w.used == null) return 0;
@@ -13877,6 +13875,7 @@ function quotaFill(w) {
}
function quotaText(w) {
if (w.unlimited) return t("Unlimited");
if (w.balance != null) return t("{n} left", { n: (countFormat.format(w.balance) + " " + t(w.unit || "")).trim() });
if (quotaNoShare(w)) return w.display || t("No allowance reported");
const used = to100(w.used);
const n = quotaLeft ? 100 - used : used;
@@ -13914,9 +13913,8 @@ function paceLine(w) {
: t("Right on an even pace through this window");
return span;
}
// quotaCount: a window's own count, when its vendor counts in amounts
// (WorkBuddy's credits, #659) — "355 / 500 credits" used, or what is left
// of them, as the share beside it says; the vendor's own text otherwise.
// quotaCount: a window's own count in amounts (WorkBuddy's credits, #659),
// "355 / 500 credits" used or left as the share says; else the vendor's text
const countFormat = new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 });
function quotaCount(w) {
if (!(w.limit > 0)) return w.display || "";
+18 -3
View File
@@ -473,7 +473,11 @@ function routingPage(part) {
const share = (w) => quotaLeft ? 100 - Math.max(0, Math.min(100, w.used)) : w.used;
// the account's own count before it, when its vendor counts in amounts
// (WorkBuddy's credits, #659): "355 / 500 credits · 71% used"
const quota = (w, used, left, vars) => (w.limit > 0 ? quotaCount(w) + " · " : "") + t(quotaLeft ? left : used, { n: pct(share(w)), ...vars });
// a prepaid wallet tells what it has left in its unit, no share (#3950):
// "6,291 points left", whichever way the meters read
const balText = (w) => (countFormat.format(w.balance) + " " + t(w.unit || "")).trim();
const quota = (w, used, left, vars) => w.balance != null ? t(left, { n: balText(w), ...vars })
: (w.limit > 0 ? quotaCount(w) + " · " : "") + t(quotaLeft ? left : used, { n: pct(share(w)), ...vars });
const fill = (w) => Math.max(0, Math.min(100, share(w))) + "%";
const FAIL = { rate: "rate limited", credit: "out of credit", quota: "quota used up", other: "failed", auth: "sign-in required", canceled: "canceled", foreign: "another account's reasoning", floor: "reply too short", verify: "needs verification", refused: "refused (safety filter)", shape: "request not understood", proxy: "proxy not reachable", effort: "reasoning effort not in its plan", overflow: "too long for its model", room: "reply asked past the window left", slow: "slow to start", prompt: "agent's prompt turned away", restricted: "account restricted by the vendor" };
const failWord = (why) => t(FAIL[why] || "failed");
@@ -639,6 +643,14 @@ function routingPage(part) {
&& (!(x.fallback || whole) || (y.provider === x.provider && y.model === x.model && (y.fixed || "") === (x.fixed || "") && !!y.fast === !!x.fast)));
}
// walletWhy: f, a prepaid wallet, goes before the next of its
// provider's in its unit as it has more left (routes.byLeft, #3950)
function walletWhy(r, f) {
const o = r.order.find((x) => x !== f && !x.fallback && !x.rest && x.balance != null && x.provider === f.provider && x.unit === f.unit);
return f.balance != null && o && f.balance > o.balance
? t("{who} goes first: of those alike, its wallet has the most left — {n}, where {other} has {m}.", { who: who(f), n: balText(f), other: who(o), m: balText(o) }) : null;
}
// why routing put the first where it did
function firstWhy(r) {
const f = r.order[0];
@@ -696,10 +708,12 @@ function routingPage(part) {
return t("Speed first: none has answered {model} lately, so {who}, first in the list, goes first and its answer measures it.", { who: w, model: f.model });
}
case "usage":
if (f.balance != null) return walletWhy(r, f) || t("{who} goes first.", { who: w });
if (f.known) return t("Least used first: {who} has the most of its allowance left — {n} used.", { who: w, n: pct(f.used) });
if (f.kind === "key" && !someKnown) return t("Least used first: {who} served the fewest tokens lately — {n}.", { who: w, n: tokens(f.tokens || 0) });
return t("Least used first: {who} goes first.", { who: w });
case "pace":
if (f.balance != null) return walletWhy(r, f) || t("{who} goes first.", { who: w });
if (f.known) {
// The allowance window used for pace, which may be shorter than a week.
const left = known0(f.due) ? Math.min(100, Math.round((f.pace || 0) * Math.max(1, (at(f.due) - at(r.time)) / 36e5))) : null;
@@ -732,6 +746,7 @@ function routingPage(part) {
if (c < 0 && k === 0 && known0(f.restarts)) return t("{who} goes first: of those with quota to spare, its allowance starts again soonest — one of its Codex resets about to run out is used by itself in {d}, and what it has left then is lost. {other} renews later and keeps its own.", { who: w, d: dur(at(f.restarts) - at(r.time)), other: who(next) });
if (c < 0 && k === 0) return t("{who} goes first: of those with quota to spare, its allowance renews soonest — in {d} — and what it has left then is lost. {other} renews later and keeps its own.", { who: w, d: dur(renews(f)[0] - at(r.time)), other: who(next) });
if (c < 0) return t("{who} goes first: its allowance renews in the same hour as {other}'s, and its shorter one sooner — in {d}.", { who: w, other: who(next), d: dur(renewsBy(f)[k] - at(r.time)) });
if (c === 0 && walletWhy(r, f)) return walletWhy(r, f);
if (soon) return t("{who} and {other} renew within the same hour, so the order given stays — and the vendor's prompt cache stays warm.", { who: w, other: who(next) });
return t("{who} goes first, in the order given: when its allowance renews isn't known.", { who: w });
}
@@ -2420,7 +2435,7 @@ function routingPage(part) {
// crowd the stage. Live only, as the list's are (winsOf).
const tip = [w.id, ...(day ? [] : winsOf(w))].join("\n");
if (row.li.title !== tip) row.li.title = tip;
const bar = w.known && !w.free;
const bar = w.known && !w.free && w.balance == null;
row.li.classList.toggle("nobar", !bar);
row.bi.style.width = bar ? fill(w) : "0";
// on: the row answers or answered the request shown; flying: a
@@ -3778,7 +3793,7 @@ function routingPage(part) {
fix.append(go);
row.append(fix);
}
if (w.known) {
if (w.known && w.balance == null) {
const bar = el("div", "bar"), bi = el("i");
bi.style.width = fill(w);
bar.append(bi);
@@ -420,6 +420,7 @@ magpie.strings({
"{who} goes first: its allowance renews in the same hour as {other}'s, and its shorter one sooner — in {d}.": "{who} 排第一:它与 {other} 的额度在同一小时重置,而它较短的窗口更早({d}后)。",
"{who} and {other} renew within the same hour, so the order given stays — and the vendor's prompt cache stays warm.": "{who} 和 {other} 在同一小时内重置,保持原顺序,厂商的提示词缓存也保持命中。",
"{who} goes first, in the order given: when its allowance renews isn't known.": "{who} 按原有顺序排第一:不知道它的额度何时重置。",
"{who} goes first: of those alike, its wallet has the most left — {n}, where {other} has {m}.": "{who} 排第一:同类账号里,它的钱包剩得最多——{n},{other} 剩 {m}。",
"{who} is resting — {why}, {when} — so it waits at the back.": "{who} 正在休息({why},{when}),排在最后。",
"{who} is at {n} — all but used up, it answers only when nothing else can.": "{who} 已用 {n},几乎用尽,仅在其他都无法响应时使用。",
"{who} is at {n} — kept for when the others can't.": "{who} 已用 {n},其他账号都无法响应时才用。",
@@ -990,6 +991,7 @@ magpie.strings({
"{who} goes first: its allowance renews in the same hour as {other}'s, and its shorter one sooner — in {d}.": "{who} 排第一:它與 {other} 的額度在同一小時重置,而它較短的時段更早({d}後)。",
"{who} and {other} renew within the same hour, so the order given stays — and the vendor's prompt cache stays warm.": "{who} 和 {other} 在同一小時內重置,保持原順序,廠商的提示詞快取也保持命中。",
"{who} goes first, in the order given: when its allowance renews isn't known.": "{who} 按原有順序排第一:不知道它的額度何時重置。",
"{who} goes first: of those alike, its wallet has the most left — {n}, where {other} has {m}.": "{who} 排第一:同類帳號裡,它的錢包剩得最多——{n},{other} 剩 {m}。",
"{who} is resting — {why}, {when} — so it waits at the back.": "{who} 正在休息({why},{when}),排在最後。",
"{who} is at {n} — all but used up, it answers only when nothing else can.": "{who} 已用 {n},幾乎用盡,僅在其他都無法回應時使用。",
"{who} is at {n} — kept for when the others can't.": "{who} 已用 {n},其他帳號都無法回應時才用。",
@@ -1558,6 +1560,7 @@ magpie.strings({
"{who} goes first: its allowance renews in the same hour as {other}'s, and its shorter one sooner — in {d}.": "{who} が先です:利用枠が {other} と同じ時間帯に更新され、短いほうの枠がより早く — {d} 後に — 更新されます。",
"{who} and {other} renew within the same hour, so the order given stays — and the vendor's prompt cache stays warm.": "{who} と {other} は同じ時間帯に更新されるため、設定順のままです — ベンダーのプロンプトキャッシュも温かいままです。",
"{who} goes first, in the order given: when its allowance renews isn't known.": "{who} が設定順で先です:利用枠がいつ更新されるか不明です。",
"{who} goes first: of those alike, its wallet has the most left — {n}, where {other} has {m}.": "{who} が先です:同じ種類のうち、ウォレットの残りが最も多いため — {n}、{other} は {m}。",
"{who} is resting — {why}, {when} — so it waits at the back.": "{who} は休止中です — {why}、{when} — そのため最後尾で待ちます。",
"{who} is at {n} — all but used up, it answers only when nothing else can.": "{who} は {n} — ほぼ使い切っており、他に応答できる相手がいないときだけ応答します。",
"{who} is at {n} — kept for when the others can't.": "{who} は {n} — 他が応答できないときのために取っておきます。",
@@ -2128,6 +2131,7 @@ magpie.strings({
"{who} goes first: its allowance renews in the same hour as {other}'s, and its shorter one sooner — in {d}.": "{who} kommt zuerst: Sein Kontingent erneuert sich in derselben Stunde wie das von {other}, sein kürzeres aber früher – in {d}.",
"{who} and {other} renew within the same hour, so the order given stays — and the vendor's prompt cache stays warm.": "{who} und {other} erneuern sich in derselben Stunde, daher bleibt die vorgegebene Reihenfolge – und der Prompt-Cache des Anbieters bleibt warm.",
"{who} goes first, in the order given: when its allowance renews isn't known.": "{who} kommt gemäß vorgegebener Reihenfolge zuerst: Wann sich sein Kontingent erneuert, ist unbekannt.",
"{who} goes first: of those alike, its wallet has the most left — {n}, where {other} has {m}.": "{who} kommt zuerst: Unter den gleichartigen hat sein Guthaben am meisten übrig — {n}, {other} hat {m}.",
"{who} is resting — {why}, {when} — so it waits at the back.": "{who} pausiert – {why}, {when} – und wartet daher hinten.",
"{who} is at {n} — all but used up, it answers only when nothing else can.": "{who} liegt bei {n} – fast aufgebraucht, es antwortet nur, wenn nichts anderes kann.",
"{who} is at {n} — kept for when the others can't.": "{who} liegt bei {n} – aufgehoben für den Fall, dass die anderen nicht können.",
@@ -0,0 +1,104 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// #3950 (墨雨藏锋 / mycf_711): prepaid wallets of one provider, in one
// unit, have a balance and no share. On the Routing page each one's row
// says what it has left, "750 积分 left", with no bar (a share it was
// never told), in the live rows and in the accounts listed below; the
// story says the first went first as its wallet has the most left,
// naming both figures, under Smart, Least used and Weekly pace alike.
// Where it said "0% used" and "in the order given". Every language, at a
// window's width and at 420px, in both engines.
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");
const now = new Date();
const ago = (s) => new Date(now.getTime() - s * 1000).toISOString();
// as the gateway sends them (Weighed): known, used 0, the balance and unit
const seat = (who, balance, routing) => ({ id: `magicrew#${who}`, provider: "magicrew", name: "SuperMagic", who, kind: "account", model: "magic-1", plan: "Points",
...(routing ? { routing } : {}), known: true, used: 0, balance, unit: "积分", renews: ["0001-01-01T00:00:00Z"], pace: 100 / 168 });
function serve(lang, routing) {
const order = [seat("big@example.com", 6291, routing), seat("small@example.com", 750, routing)];
const route = {
id: 1, seq: 1, time: ago(1), agent: "codex", model: "magic-1", provider: "magicrew", done: true, status: 200, ms: 900, tokens: 1200, order,
tries: [{ id: order[0].id, model: "magic-1", start: ago(1), done: true, status: 200, ms: 900 }],
};
return async (request) => {
const url = new URL(request.request().url());
const json = (data) => request.fulfill({ json: data });
if (url.pathname === "/boot.js") return request.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return request.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes
return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 1 }, routes: [route] });
}
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json({ providers: [], excluded: [], gateway: { running: true, window: true } });
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)];
await request.fulfill({ body: await fs.readFile(file), contentType });
};
}
const WHY = "{who} goes first: of those alike, its wallet has the most left — {n}, where {other} has {m}.";
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(`${engine}: a wallet's row says its balance, and the story why the fuller went first`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
for (const [routing, width] of [["", 1100], ["usage", 1100], ["pace", 420]]) {
await t.test(`${lang} ${routing || "smart"} at ${width}px`, async () => {
const page = await browser.newPage({ viewport: { width, height: 900 }, reducedMotion: "reduce" });
try {
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (error) => errors.push(error.message));
await page.route("**/*", serve(lang, routing));
await page.goto("http://magpie.test/?view=routing");
const req = page.locator(".rt-req").first();
await req.waitFor();
if (await req.getAttribute("aria-pressed") !== "true") await req.click();
await page.locator(".rt-steps li.why").first().waitFor();
await page.waitForFunction(() => [...document.querySelectorAll(".rt-accts > li")].every((li) => li.querySelector("em")?.textContent.trim()));
const tr = (key, vars) => page.evaluate(([lang, key, vars]) => {
const s = (lang !== "en" && I18N[lang]?.[key]) || key;
return s.replace(/\{(\w+)\}/g, (_, k) => vars[k] ?? `{${k}}`);
}, [lang, key, vars]);
const big = await tr("{n} left", { n: "6,291 积分" }), small = await tr("{n} left", { n: "750 积分" });
const look = (id) => page.locator(`.rt-accts > li[title^="${id}"]`).first().evaluate((li) => ({
st: li.querySelector("em").textContent, bar: getComputedStyle(li.querySelector(".bar")).display !== "none" && li.querySelector(".bar i").style.width !== "0px" && li.querySelector(".bar i").style.width !== "0" }));
const b = await look("magicrew#big@example.com"), s = await look("magicrew#small@example.com");
// the first says it answered; the one behind it, its figure
assert.equal(s.st, small);
assert.equal(b.bar, false, "no bar from a share never told");
assert.equal(s.bar, false);
// the story: the first went first by what its wallet has left
const why = (await page.locator(".rt-steps li.why").first().textContent()).trim();
const tpl = await tr(WHY, { n: "6,291 积分", m: "750 积分" });
const [head, mid, tail] = tpl.split(/\{who\}|\{other\}/);
assert.ok(why.includes(mid.trim()) && why.endsWith(tail.trim()) && (!head || why.startsWith(head)), `the story: ${why}`);
// the accounts below: their figures, no bar
const acts = page.locator(".rt-act");
await acts.filter({ hasText: "6,291" }).first().waitFor();
const list = await acts.evaluateAll((as) => as.map((a) => ({ st: a.querySelector(".st")?.textContent || "", bar: !!a.querySelector(".bar") })));
assert.ok(list.some((a) => a.st.startsWith(big)), JSON.stringify(list));
assert.ok(list.some((a) => a.st.startsWith(small)), JSON.stringify(list));
assert.ok(list.every((a) => !a.bar), "no bar in the list either");
const over = await page.evaluate(() => document.documentElement.scrollWidth - innerWidth);
assert.ok(over <= 1, `${over}px past`);
assert.deepEqual(errors, []);
} finally {
await page.close();
}
});
}
}
});
}
@@ -0,0 +1,86 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// #3950 (墨雨藏锋 / mycf_711): a prepaid wallet (SuperMagic's points) has a
// balance and no total. Its plugin sends the window's balance and unit
// with no used; the usage card says the figure, "6,291 积分 left", with no
// meter and no percentage, whether the meters read used or left, where it
// said "No allowance reported" or a 0% it was never told. A window that
// said its share beside it keeps its percentage and meter. Chromium and
// WebKit, every language, at a window's width and a phone's; no backend,
// the API is faked here.
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(process.env.MAGPIE_ASSETS || path.join(__dirname, "../assets"));
const left = { en: "6,291 积分 left", zh: "剩余 6,291 积分", "zh-TW": "剩餘 6,291 积分", ja: "残り 6,291 积分", de: "6,291 积分 übrig" };
const quotas = [
// as magpie's API sends a wallet's window: its balance and unit, used 0
// and no share (QuotaSpan.Balance)
{ provider: "magicrew-plugin", name: "SuperMagic", user: "wallet@example.com", windows: [
{ name: "Points", used: 0, remaining: 100, balance: 6291, unit: "积分" },
] },
{ provider: "claude", name: "Claude", user: "fine@example.com", windows: [
{ name: "5 hours", used: 40 },
] },
];
function serve(lang) {
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: { lang, theme: "light" } });
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/usage/quotas") return json(quotas);
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
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: "" }); }
};
}
async function windows(card) {
return card.locator(".quota").evaluateAll((qs) => qs.map((q) => ({ n: q.querySelector(".quota-n")?.innerText ?? "", track: !!q.querySelector(".quota-track") })));
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(`${engine}: a wallet's window says its balance, not a percentage`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of Object.keys(left)) {
for (const width of [900, 390]) {
const page = await browser.newPage({ viewport: { width, height: 800 }, reducedMotion: "reduce" });
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang));
await page.goto("http://magpie.test/?view=usage");
const at = `${lang} ${width}px`;
const wallet = page.locator(".subscription-card", { hasText: "SuperMagic" });
const fine = page.locator(".subscription-card", { hasText: "Claude" });
await wallet.locator(".quota-n").first().waitFor();
await fine.locator(".quota-n").first().waitFor();
for (const side of ["used", "left"]) {
const w = await windows(wallet);
assert.equal(w.length, 1, `${at} ${side}: ${JSON.stringify(w)}`);
assert.equal(w[0].n, left[lang], `${at} ${side}: the wallet's figure`);
assert.equal(w[0].track, false, `${at} ${side}: no meter from a share never sent`);
const f = await windows(fine);
assert.match(f[0].n, side === "used" ? /40\s?%/ : /60\s?%/, `${at} ${side}: ${f[0].n}`);
assert.ok(f[0].track, `${at} ${side}: a window that said its share has its meter`);
if (side === "used") await fine.locator(".quota-n").first().click();
}
const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
assert.ok(overflow <= 0, `${at}: the page scrolls sideways by ${overflow}px`);
assert.deepEqual(errors, [], at);
await page.close();
}
}
});
}
+6 -1
View File
@@ -2381,7 +2381,11 @@ async function load({ provider, account, proxy }) {
// count as one), aside? (using it up doesn't
// stop the account), runsOutAt? (ISO or ms: when the soonest
// credits left in it are lost, apart from its reset, as WorkBuddy's
// packages end) / runsOut? (how many are lost then) }],
// packages end) / runsOut? (how many are lost then), balance?
// (how much is left, in unit, of a prepaid wallet with no total:
// sent without used, it is no share, yet routing knows the account
// and puts the one with the most left first among the provider's
// accounts in the same unit, #3950) }],
// signIn?: "expired" | "kept" | "renewed" (what the read means for the
// account's sign-in, as a model request's X-Magpie-Sign-In says;
// without it an error saying to sign in again marks the account and
@@ -2442,6 +2446,7 @@ async function usageOf(provider, account) {
aside: !!w?.aside,
runsOutAt: when(w?.runsOutAt),
runsOut: Math.max(0, num(w?.runsOut)),
balance: typeof w?.balance === "number" && isFinite(w.balance) ? Math.max(0, w.balance) : null, // null: not said
})),
}
}
+3
View File
@@ -1095,6 +1095,9 @@ type UsageWindow struct {
// apart from the window's reset (WorkBuddy's packages)
RunsOutAt string `json:"runsOutAt"`
RunsOut float64 `json:"runsOut"`
// Balance is how much is left in Unit, a prepaid wallet's reading,
// with no share to tell (#3950); nil when the plugin didn't say.
Balance *float64 `json:"balance"`
}
// Checkin is what came of an account's daily check-in, as the plugin's
+7 -2
View File
@@ -158,9 +158,14 @@ func quotaOfPlugin(q SubscriptionQuota, u plugin.Usage) SubscriptionQuota {
w := QuotaWindow{Name: x.Name, ResetSecs: x.ResetSecs, Display: x.Display,
Amount: x.Amount, Limit: x.Limit, Unit: x.Unit,
Span: time.Duration(x.Span * float64(time.Second)), Model: strings.ToLower(x.Model), Aside: x.Aside}
if x.Balance != nil {
// a wallet's balance: a reading, though it tells no share (#3950)
b := *x.Balance
w.Balance = &b
}
if x.Used != nil {
w.Used = *x.Used
} else if !x.Aside {
} else if !x.Aside && x.Balance == nil {
// the plugin didn't say how much of it is used: its text is all
// there is, and routing has no share to count (#3650)
w.Text, w.Aside = true, true
@@ -168,7 +173,7 @@ func quotaOfPlugin(q SubscriptionQuota, u plugin.Usage) SubscriptionQuota {
// a row set aside with text and nothing counted is that text: a
// window that counts nothing yet says 0 with a count, or with no
// text, and one that stops the account is a reading at 0
w.Text = w.Text || x.Aside && x.Display != "" && (x.Used == nil || *x.Used == 0) && x.Amount == 0 && x.Limit == 0
w.Text = w.Text || x.Aside && x.Display != "" && (x.Used == nil || *x.Used == 0) && x.Amount == 0 && x.Limit == 0 && x.Balance == nil
if t, err := time.Parse(time.RFC3339, x.ResetsAt); err == nil {
w.ResetsAt = &t
}
@@ -0,0 +1,129 @@
package provider
import (
"context"
"encoding/json"
"os"
"path/filepath"
"testing"
"time"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/testenv"
)
// A prepaid wallet (SuperMagic's points, #3950) tells how much is left in
// its unit and nothing it is a share of. Its window keeps that figure,
// is no text row and no share, and routing knows the account by it with
// nothing used invented; an empty wallet is used up. Through the decode
// a plugin's reply takes, as host.js hands it on.
func TestPluginWalletBalanceIsAReading(t *testing.T) {
var u plugin.Usage
if err := json.Unmarshal([]byte(`{"windows":[{"name":"积分","balance":6291,"unit":"积分"}]}`), &u); err != nil {
t.Fatal(err)
}
q := quotaOfPlugin(SubscriptionQuota{Provider: "magicrew-plugin", User: "u"}, u)
w := q.Windows[0]
if w.Balance == nil || *w.Balance != 6291 || w.Unit != "积分" {
t.Fatalf("the balance: %+v", w)
}
if w.Text || w.Aside || w.Used != 0 {
t.Errorf("a wallet is a reading with no share invented: Text %v, Aside %v, Used %v", w.Text, w.Aside, w.Used)
}
now := time.Now()
a, ok := routedAllowance("plugin:magicrew", "u", q, now)
if !ok {
t.Fatal("a wallet's account is not known to routing")
}
if used, _ := a.For("", now); used != 0 {
t.Errorf("used invented: %v", used)
}
if left, unit, ok := a.Left(""); !ok || left != 6291 || unit != "积分" {
t.Errorf("Left: %v %q %v", left, unit, ok)
}
var empty plugin.Usage
if err := json.Unmarshal([]byte(`{"windows":[{"name":"积分","balance":0,"unit":"积分"}]}`), &empty); err != nil {
t.Fatal(err)
}
e, ok := routedAllowance("plugin:magicrew", "v", quotaOfPlugin(SubscriptionQuota{Provider: "magicrew-plugin", User: "v"}, empty), now)
if !ok {
t.Fatal("an empty wallet is not known")
}
if used, _ := e.For("", now); used < SpentShare {
t.Errorf("an empty wallet is not used up: %v", used)
}
if left, _, ok := e.Left(""); !ok || left != 0 {
t.Errorf("an empty wallet's Left: %v %v", left, ok)
}
}
// Left is the least balance of the windows that count the model, and
// none when no window told one.
func TestAllowanceLeftIsTheLeastBalance(t *testing.T) {
b := func(f float64) *float64 { return &f }
now := time.Now()
a := allowanceOf([]QuotaWindow{
{Name: "Wallet", Balance: b(800), Unit: "pts"},
{Name: "Opus wallet", Balance: b(30), Unit: "pts", Model: "opus"},
{Name: "Daily", Used: 20, ResetSecs: 3600},
}, now)
if left, _, _ := a.Left("sonnet"); left != 800 {
t.Errorf("sonnet's: %v", left)
}
if left, _, _ := a.Left("opus"); left != 30 {
t.Errorf("opus's: %v", left)
}
if _, _, ok := allowanceOf([]QuotaWindow{{Name: "Daily", Used: 20}}, now).Left(""); ok {
t.Error("no balance told, yet one is left")
}
}
// Through the plugin host: a balance the plugin sends reaches magpie as
// that figure; one that isn't a number is not said.
func TestPluginHostPassesABalanceOn(t *testing.T) {
windows := filepath.Join(t.TempDir(), "windows.json")
if err := os.WriteFile(windows, []byte(`{
"a@fake": [{"name": "积分", "balance": 6291, "unit": "积分"}],
"full@fake": [{"name": "积分", "balance": "lots", "unit": "积分", "display": "lots"}]
}`), 0o600); err != nil {
t.Fatal(err)
}
u := fakePluginUsage(t, windows)
if w := u["a@fake"].Windows; len(w) != 1 || w[0].Balance == nil || *w[0].Balance != 6291 || w[0].Text {
t.Errorf("a balance: %+v", w)
}
if w := u["full@fake"].Windows; len(w) != 1 || w[0].Balance != nil || !w[0].Text {
t.Errorf("not a number: %+v", w)
}
}
// fakePluginUsage signs in the fake plugin's a@fake and full@fake with
// the windows file it reads (FAKE_WINDOWS) and reads their usage.
func fakePluginUsage(t *testing.T, windows string) map[string]SubscriptionQuota {
t.Helper()
bun := testenv.Bun(t)
claudeHome(t)
t.Setenv("MAGPIE_BUN", bun)
t.Setenv("FAKE_WINDOWS", windows)
t.Cleanup(plugin.Settle)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
abs, _ := filepath.Abs("../plugin/testdata/fake/index.js")
if _, err := plugin.Add(ctx, abs); err != nil {
t.Fatal(err)
}
if _, err := plugin.Providers(ctx); err != nil {
t.Fatal(err)
}
for _, team := range []string{"a", "full"} {
st, err := StartPluginSignIn("fakeco", 1, map[string]string{"where": "work", "team": team})
if err != nil {
t.Fatal(err)
}
if err := SubmitSignInCallback(st.ID, "good"); err != nil {
t.Fatal(err)
}
}
return LoginUsage(ctx, "plugin:fakeco")
}
+2 -1
View File
@@ -83,7 +83,8 @@ func TestQuotaSpanCarriesEveryWindowField(t *testing.T) {
// and what is carried is copied: a window with each set says each
at := time.Date(2026, 10, 30, 17, 0, 0, 0, time.UTC)
full := QuotaWindow{Unlimited: true, Name: "Credits", Used: 40, ResetsAt: &at, Display: "1 / 2", Text: true, Amount: 1, Limit: 2, Unit: "credits",
bal := 6291.0
full := QuotaWindow{Balance: &bal, Unlimited: true, Name: "Credits", Used: 40, ResetsAt: &at, Display: "1 / 2", Text: true, Amount: 1, Limit: 2, Unit: "credits",
RunsOutAt: &at, RunsOut: 3, Pool: "P", Holds: &WindowHolds{}, HoldsWhy: "x"}
got := quotaReport([]SubscriptionQuota{{Provider: "p", Windows: []QuotaWindow{full}}}, nil, nil, at)
b, _ := json.Marshal(got[0].Windows[0])
+23 -1
View File
@@ -4,6 +4,8 @@ import (
"context"
"math"
"slices"
"strconv"
"strings"
"time"
)
@@ -139,6 +141,9 @@ type QuotaSpan struct {
// account's have no reset at all (#3762).
RunsOutAt *time.Time `json:"runsOutAt,omitempty"`
RunsOut float64 `json:"runsOut,omitempty"`
// Balance is how much is left in Unit, a prepaid wallet's reading
// (QuotaWindow.Balance, #3950): Used and Remaining are then no share.
Balance *float64 `json:"balance,omitempty"`
// Holds and HoldsWhy are the window's whole as the Usage page's card
// tells it (QuotaWindow.Holds, #2333): reckoned when ReckonHolds is
// set, else left out.
@@ -195,7 +200,7 @@ func quotaReport(subs, plans, balances []SubscriptionQuota, now time.Time) []Quo
// as the usage page shows them
for _, w := range PooledWindows(q.Windows) {
s := QuotaSpan{Unlimited: w.Unlimited, Name: w.Name, Used: w.Used, Remaining: max(0, 100-w.Used), ResetsAt: w.ResetsAt, Display: w.Display, Text: w.Text,
Amount: w.Amount, Limit: w.Limit, Unit: w.Unit, Pool: w.Pool, RunsOutAt: w.RunsOutAt, RunsOut: w.RunsOut, Holds: w.Holds, HoldsWhy: w.HoldsWhy}
Amount: w.Amount, Limit: w.Limit, Unit: w.Unit, Pool: w.Pool, RunsOutAt: w.RunsOutAt, RunsOut: w.RunsOut, Balance: w.Balance, Holds: w.Holds, HoldsWhy: w.HoldsWhy}
if s.ResetsAt == nil && w.ResetSecs > 0 {
t := now.Add(time.Duration(w.ResetSecs) * time.Second)
s.ResetsAt = &t
@@ -208,6 +213,23 @@ func quotaReport(subs, plans, balances []SubscriptionQuota, now time.Time) []Quo
return out
}
// BalanceText is a wallet's balance as told, the figure in its unit:
// "6,291 points left" (QuotaWindow.Balance).
func BalanceText(b float64, unit string) string {
s := strconv.FormatFloat(math.Round(b*100)/100, 'f', -1, 64)
whole, frac, _ := strings.Cut(strings.TrimPrefix(s, "-"), ".")
for i := len(whole) - 3; i > 0; i -= 3 {
whole = whole[:i] + "," + whole[i:]
}
if frac != "" {
whole += "." + frac
}
if b < 0 {
whole = "-" + whole
}
return strings.TrimSpace(whole+" "+unit) + " left"
}
// ResetClock is when a window starts again, on the clock: "14:30" today,
// "tomorrow 09:00", "Wed 14:30" within the week, else "Oct 3 14:30".
func ResetClock(at, now time.Time) string {
+29
View File
@@ -189,6 +189,9 @@ type Limit struct {
// Credits: the account goes on past this window on its credits
// (QuotaWindow.Credits)
Credits bool
// Balance is how much is left in Unit, a wallet's reading with no
// share (QuotaWindow.Balance); nil when not told
Balance *float64
}
// OnCredits says whether the account goes on past its allowance on its
@@ -366,6 +369,23 @@ func (a Allowance) Renewal(model string, now time.Time) []time.Time {
return out
}
// Left is how much a wallet that counts model has left, in unit
// (Limit.Balance): the least of its windows that tell a balance. ok is
// false when none does. Only balances in the same unit of one provider are
// compared (routes.Seat.Left).
func (a Allowance) Left(model string) (left float64, unit string, ok bool) {
model = strings.ToLower(model)
for _, l := range a {
if l.Balance == nil || !l.applies(model) {
continue
}
if !ok || *l.Balance < left {
left, unit, ok = *l.Balance, l.Unit, true
}
}
return left, unit, ok
}
// Lapse is the soonest moment credits left in a window that counts model
// are lost (Limit.RunsOut), zero when none is told or all have passed.
// Smart goes by it when the renewals tie: two WorkBuddy free accounts
@@ -803,6 +823,15 @@ func allowanceOf(ws []QuotaWindow, now time.Time) Allowance {
if w.RunsOutAt != nil {
l.RunsOut = *w.RunsOutAt
}
if w.Balance != nil {
// a wallet is known by its balance, with no share invented:
// one with nothing left is used up, as the vendor refuses it
b := *w.Balance
l.Balance = &b
if b <= 0 {
l.Used = max(l.Used, 100)
}
}
a = append(a, l)
}
return a
+7
View File
@@ -52,6 +52,13 @@ type QuotaWindow struct {
// day. Smart routing takes it for the window's renewal (cdredfox on X).
RunsOutAt *time.Time `json:"runsOutAt,omitempty"`
RunsOut float64 `json:"runsOut,omitempty"`
// Balance is how much is left of the window in Unit, when the vendor
// tells only that: a prepaid wallet, with no total to take a share of
// (SuperMagic's points, #3950). Used is then no reading (0); the GUI
// says the figure left, and routing knows the account by it and puts
// the one with the most left first among a provider's accounts in the
// same unit (Allowance.Left). nil when not told.
Balance *float64 `json:"balance,omitempty"`
// Family is the model family a per-model window belongs to (Antigravity's
// "Gemini 3.1 Pro (High)" is Gemini's), for the GUI to show one figure a
// family, the tightest; each window is still here, and routing reads
+9
View File
@@ -60,6 +60,15 @@ type Seat struct {
// TPS is how fast it wrote them, output tokens a second, 0 when not
// told (a reply let go in a burst tells none). Fastest goes by them.
TTFT, TPS float64
// Left is a prepaid wallet's balance, what it has left in its unit
// (provider.Allowance.Left, #3950), and LeftIn whose wallet that is:
// its provider and unit, empty when no balance was told. A wallet has
// no share and no renewal, so Used and Soon tie; Smart, Pace and
// LeastUsed then put the one with more left first, only among seats
// whose LeftIn is the same (byLeft): points are never weighed against
// another provider's, or another unit.
Left float64
LeftIn string
}
// Strategy orders a pool.
+58 -4
View File
@@ -27,6 +27,42 @@ func tier(share float64) int {
return 0
}
// byLeft is how a pool's wallets go by what they have left (Seat.Left):
// the one with more first, a seat that told none after those that did.
// It orders only a pool whose balances are all in one provider's one unit;
// with two kinds, nothing is weighed by them (nil), since points and
// another vendor's points don't compare.
func byLeft(seats []Seat) func(a, b Seat) int {
in := ""
for _, s := range seats {
switch {
case s.LeftIn == "":
case in == "":
in = s.LeftIn
case in != s.LeftIn:
return nil
}
}
if in == "" {
return nil
}
return func(a, b Seat) int {
ha, hb := a.LeftIn != "", b.LeftIn != ""
switch {
case ha != hb:
if ha {
return -1
}
return 1
case a.Left > b.Left:
return -1
case a.Left < b.Left:
return 1
}
return 0
}
}
func identity(n int) []int {
idx := make([]int, n)
for i := range idx {
@@ -48,7 +84,8 @@ func identity(n int) []int {
// renews, changes nothing. Renewing in the same hours, the one whose
// credits left lapse first (Seat.Lapse) goes first: WorkBuddy's free
// accounts all renew at the month's end, but the credits each was given
// end on their own days (zhaocai_83020 on Discord). Those alike stay in their order, keeping the
// end on their own days (zhaocai_83020 on Discord). Then, of prepaid
// wallets (Seat.Left), the one with more left (#3950). Those alike stay in their order, keeping the
// vendor's prompt cache warm. Past that, whichever has the most left, and
// one all but used up only when nothing else can take it, one that goes
// on on its credits first of those (spentBefore). Only the windows
@@ -59,6 +96,7 @@ func identity(n int) []int {
// once: else, kept after those known, it would never answer and never be
// known (Anthropic's usage endpoint can turn magpie away for hours).
var Smart = Strategy{Order: func(_ string, seats []Seat) []int {
left := byLeft(seats)
var fine, low, spent []int
for i, s := range seats {
switch tier(s.Used) {
@@ -96,7 +134,8 @@ var Smart = Strategy{Order: func(_ string, seats []Seat) []int {
// first, to the hour; one that tells none after those that do
x, y := a.Lapse.Truncate(time.Hour), b.Lapse.Truncate(time.Hour)
if x.Equal(y) {
return false
// then a wallet with more left (#3950)
return left != nil && left(a, b) < 0
}
if x.IsZero() || y.IsZero() {
return y.IsZero()
@@ -137,9 +176,11 @@ var Rotate = Strategy{Order: func(pool string, seats []Seat) []int {
// LeastUsed puts a subscription, or a key that reads its own windows, by the
// share of its allowance used, as the vendor says; then, and for other
// keys, by what magpie sent it lately. Of those all but used up, one that
// keys, by what magpie sent it lately; prepaid wallets, which have no
// share, by what they have left first (Seat.Left). Of those all but used up, one that
// goes on on its credits goes first (spentBefore).
var LeastUsed = Strategy{ByUse: true, Order: func(_ string, seats []Seat) []int {
left := byLeft(seats)
idx := identity(len(seats))
sort.SliceStable(idx, func(a, b int) bool {
sa, sb := seats[idx[a]], seats[idx[b]]
@@ -149,6 +190,11 @@ var LeastUsed = Strategy{ByUse: true, Order: func(_ string, seats []Seat) []int
if sa.Used != sb.Used {
return sa.Used < sb.Used
}
if left != nil {
if c := left(sa, sb); c != 0 {
return c < 0
}
}
return sa.Tokens < sb.Tokens
})
return idx
@@ -166,7 +212,8 @@ var LeastUsed = Strategy{ByUse: true, Order: func(_ string, seats []Seat) []int
// that goes on on its credits first (spentBefore). Among the rest, one
// not known that tells what it has left as it answers goes first while it
// isn't, as in Smart, else it would never be known; then the pace, those
// alike within a tenth by what magpie sent them lately, then in their
// alike within a tenth by what a wallet has left (Seat.Left), then by what
// magpie sent them lately, then in their
// order, keeping the vendor's prompt cache warm. An account not known
// counts as a whole week ahead of it; a key has no week, unless it reads
// its own windows (a sub2api key's limits). A Codex account that spends a
@@ -198,6 +245,7 @@ var Pace = Strategy{ByUse: true, Order: func(_ string, seats []Seat) []int {
band[i] = band[byPace[k-1]]
}
}
left := byLeft(seats)
idx := identity(len(seats))
sort.SliceStable(idx, func(a, b int) bool {
sa, sb := seats[idx[a]], seats[idx[b]]
@@ -213,6 +261,12 @@ var Pace = Strategy{ByUse: true, Order: func(_ string, seats []Seat) []int {
return sa.Learns
} else if band[idx[a]] != band[idx[b]] {
return band[idx[a]] < band[idx[b]]
} else if left != nil {
// a wallet's pace is a whole week's; the one with more left
// first (#3950)
if c := left(sa, sb); c != 0 {
return c < 0
}
}
return sa.Tokens < sb.Tokens
})
+54
View File
@@ -0,0 +1,54 @@
package routes
import (
"slices"
"testing"
)
// Prepaid wallets (Seat.Left, #3950) tie on everything Smart, Pace and
// Least used go by, a wallet having no share and no renewal: the one with
// more left goes first, one that told none after them. Balances in two
// providers' or two units' wallets are never weighed against each other:
// the pool keeps its order.
func TestWalletsGoByWhatTheyHaveLeft(t *testing.T) {
const pts = "magicrew\x00积分"
wallet := func(key string, left float64, in string) Seat {
return Seat{Key: key, Account: true, Known: true, Pace: 100.0 / 168, Left: left, LeftIn: in}
}
for _, st := range []struct {
name string
s Strategy
}{{"smart", Smart}, {"pace", Pace}, {"usage", LeastUsed}} {
s := []Seat{wallet("small", 750, pts), wallet("none", 0, ""), wallet("big", 6291, pts)}
if got, want := keys(s, Apply(st.s, "p", s)), []string{"big", "small", "none"}; !slices.Equal(got, want) {
t.Errorf("%s: %v, want %v", st.name, got, want)
}
// an empty wallet is a reading of nothing left, not one not told
s = []Seat{wallet("empty", 0, pts), wallet("some", 1, pts)}
if got, want := keys(s, Apply(st.s, "p", s)), []string{"some", "empty"}; !slices.Equal(got, want) {
t.Errorf("%s, empty: %v, want %v", st.name, got, want)
}
for _, other := range []string{"magicrew\x00credits", "other\x00积分"} {
s = []Seat{wallet("small", 750, pts), wallet("big", 6291, other)}
if got, want := keys(s, Apply(st.s, "p", s)), []string{"small", "big"}; !slices.Equal(got, want) {
t.Errorf("%s across %q: %v, want %v", st.name, other, got, want)
}
}
}
}
// A wallet's balance never jumps the tiers: one used up (an empty wallet
// counts as all used) or running low waits behind one with room, however
// much it says it has left.
func TestWalletLeftWithinItsTier(t *testing.T) {
const pts = "magicrew\x00积分"
s := []Seat{
{Key: "low", Known: true, Used: 95, Left: 9000, LeftIn: pts},
{Key: "room", Known: true, Used: 0, Left: 10, LeftIn: pts},
}
for _, st := range []Strategy{Smart, Pace, LeastUsed} {
if got := keys(s, Apply(st, "p", s)); got[0] != "room" {
t.Errorf("tier: %v", got)
}
}
}
+1
View File
@@ -534,6 +534,7 @@ magpie quota <span class="c"># acme · Pro · 5h 37%
models: [], notModels: [], <span class="c">// or exactly these ids, or all but these</span>
aside: false, <span class="c">// true: using it up doesn't stop the account</span>
runsOutAt: <span class="s">"2026-10-05T00:00:00Z"</span>, runsOut: 120, <span class="c">// when the soonest credits left are lost, and how many</span>
balance: 6291, <span class="c">// a prepaid wallet: what is left, in unit; no used or limit</span>
}],
resets: { count: 2, until: <span class="s">"…"</span>, byWindow: false, fiveHour: 1, weekly: 1 }, <span class="c">// resets the account may spend</span>
signIn: <span class="s">"kept"</span>, <span class="c">// as X-Magpie-Sign-In</span>
+1
View File
@@ -534,6 +534,7 @@ magpie quota <span class="c"># acme · Pro · 5h 37%
models: [], notModels: [], <span class="c">// or exactly these ids, or all but these</span>
aside: false, <span class="c">// true: using it up doesn't stop the account</span>
runsOutAt: <span class="s">"2026-10-05T00:00:00Z"</span>, runsOut: 120, <span class="c">// when the soonest credits left are lost, and how many</span>
balance: 6291, <span class="c">// a prepaid wallet: what is left, in unit; no used or limit</span>
}],
resets: { count: 2, until: <span class="s">"…"</span>, byWindow: false, fiveHour: 1, weekly: 1 }, <span class="c">// resets the account may spend</span>
signIn: <span class="s">"kept"</span>, <span class="c">// as X-Magpie-Sign-In</span>
+1
View File
@@ -534,6 +534,7 @@ magpie quota <span class="c"># acme · Pro · 5h 37%
models: [], notModels: [], <span class="c">// 或恰好这些 id,或除这些外的全部</span>
aside: false, <span class="c">// true:用完也不影响账号使用</span>
runsOutAt: <span class="s">"2026-10-05T00:00:00Z"</span>, runsOut: 120, <span class="c">// 剩余额度中最早作废的一笔何时作废、作废多少</span>
balance: 6291, <span class="c">// 预付钱包:剩余多少(按 unit 计),不写 used 和 limit</span>
}],
resets: { count: 2, until: <span class="s">"…"</span>, byWindow: false, fiveHour: 1, weekly: 1 }, <span class="c">// 账号可用的重置次数</span>
signIn: <span class="s">"kept"</span>, <span class="c">// 同 X-Magpie-Sign-In</span>