Files
magpie/internal/provider/codex_credits_test.go
T
yetone 34a598372c providers, gateway, gui, cli: each usage window of an account can have a cap of its own beside the account's (willz on Discord)
willz asked for a cap per window: a friend's account should stop at 50%
of its five hours, while its week has its own 40%. Until now an account
had one usage cap, the same share of every window.

What the user sees: the account's pill still sets the cap for all its
windows and stays the default. Each window's meter on the account's row
is now a button: a click opens the app's own menu headed "Cap for
<window>" with the account's cap, No cap on this window, 50–90%, and
Other… typed in place. A window with its own cap says it beside its
figure ("Cap 50%", or "No cap"), its mark sits there, and the account's
pill says "Caps by window" when only windows have caps. The account is
held while any window is past its own cap, and the row's note, the
gateway's 429 and the Routing trace name that window's cap. CLI:
magpie provider account-cap <id> <account> --window "5 hours" 50
(none: no cap on that window; default: back to the account's), and
`account-cap <id>` lists the overrides.

How: Provider.AccountWindowCaps (providers.json, by account and the
window's capId, its name in lower case; 1–99, or 100 for none) beside
AccountCaps. provider.WindowCaps gives a window its share (its own, else
the account's); Allowance.CapHeld and capReached judge each window by
its own share and report the fullest holding window's cap.
provider.HoldShare becomes HoldCaps, used by gateway capHeld (plan and
group filtering, cappedError, trace) and codex_backend's route-or-relay
choice; codex_switch's NextLogin moves the agent off at per-window caps.
QuotaWindow carries capId; Limit.name is exported as Limit.Name. A
config with no window caps reads and routes exactly as before
(TestSetWindowCap reads an old one). The meter is a span with
role=button, Enter/Space: a <button> as a flex item of the wrapping
meter line kept WebKit's row at its one-line height until the next
layout, so the row grew under the pointer at the first click.

Verified:
- go test -tags nogui ./... in a sandbox HOME: all ok. New
  TestWindowCapHeld and TestSetWindowCap (provider), TestWindowCapsHoldTheAccount
  through the real gateway (5h 60%/cap 50 goes to the spare; 20/30 under
  50/40 is used; 20/45 with the spare past its own cap is a 429 naming
  "past its 40% cap"), TestAccountCapCmd --window cases.
- Break check: with WindowCaps.Of ignoring the window's own share,
  TestWindowCapHeld fails ("5 hours at 60% of 50%: <nil>") and
  TestWindowCapsHoldTheAccount fails (the request is answered 200 by the
  capped account).
- internal/gui/tests/window-cap.test.cjs: Chromium and WebKit, 420 and
  1100 wide, en, zh, zh-TW, ja, de (60 tests): held note per window,
  marks, menu from the meter with no native select, keyboard, posts of
  50, typed 45, 100 and 0, no page scroll on a click, no sideways scroll,
  no left border stripes, every new string translated. With
  windowOwnCapOf returning 0 it fails.
- account-cap, gui-zh-tw, gui-ja, gui-de, i18n-keys pass; full GUI suite
  in both engines (483 files, concurrency 6): 4315 of 4323
  pass; the 8 that failed (library-servers-bulk, purpose-filter,
  routing-proxy, routing-zcode-blocked) touch no account row and all 32
  of their tests pass when run alone
- gofmt -l clean; go vet -tags nogui ./... on darwin, linux and windows,
  and windows without the tag for ., internal/gui, internal/provider,
  internal/gateway; go build ./...
- Not tried in the real window with a live gateway or real accounts.

Docs: gateway-routing.md (HoldCaps, window caps, tests),
providers-accounts.md (AccountWindowCaps, tests), reference.md.
2026-10-09 12:00:26 +08:00

132 lines
4.7 KiB
Go

package provider
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"slices"
"testing"
"time"
"github.com/yetone/magpie/internal/settings"
)
// The credits a ChatGPT account holds besides its windows are its balance
// (#571), shown when it has some to spend and they are not unlimited.
func TestCodexCreditsBalance(t *testing.T) {
for _, c := range []struct {
name string
credits any
want string
}{
{"none said", nil, ""},
{"held", map[string]any{"has_credits": true, "unlimited": false, "balance": "1234.5"}, "1234.5 credits"},
{"a few", map[string]any{"has_credits": true, "unlimited": false, "balance": "42"}, "42 credits"},
{"none held", map[string]any{"has_credits": false, "unlimited": false, "balance": "0"}, ""},
{"spent", map[string]any{"has_credits": true, "unlimited": false, "balance": "0"}, ""},
{"unlimited", map[string]any{"has_credits": true, "unlimited": true, "balance": ""}, ""},
{"unreadable", map[string]any{"has_credits": true, "balance": "lots"}, ""},
} {
t.Run(c.name, func(t *testing.T) {
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body := map[string]any{"plan_type": "plus", "rate_limit": map[string]any{
"primary_window": map[string]any{"used_percent": 100, "limit_window_seconds": 18000}}}
if c.credits != nil {
body["credits"] = c.credits
}
json.NewEncoder(w).Encode(body)
}))
defer fake.Close()
old := CodexBase
CodexBase = fake.URL + "/backend-api/codex"
defer func() { CodexBase = old }()
plan, windows, _, credits, _, err := codexWindows(context.Background(), "tok", "acct-1")
if err != nil || plan != "plus" || len(windows) != 1 {
t.Fatalf("plan %q, windows %v, err %v", plan, windows, err)
}
if credits != c.want {
t.Errorf("credits %q, want %q", credits, c.want)
}
})
}
}
// Whether an account spends its credits is kept by account, whatever its
// case: on unless turned off. Turned off, a Codex account is held at 100%
// of its windows; a cap holds it sooner, and nothing holds another
// vendor's account for its credits.
func TestCodexCreditsSwitch(t *testing.T) {
signIn(t)
if !CodexCredits("me@example.com") {
t.Fatal("off before it was turned off")
}
if err := SetCodexCredits(" Me@Example.com ", false); err != nil {
t.Fatal(err)
}
if got := settings.Load().CodexNoCredits; !slices.Equal(got, []string{"me@example.com"}) {
t.Fatalf("kept %v", got)
}
if CodexCredits("ME@example.com") || !CodexCredits("other@example.com") {
t.Fatal("read back wrong")
}
p := Provider{ID: "codex", AccountCaps: map[string]int{"capped@example.com": 70}}
for _, c := range []struct {
agent, user string
share int
noCredits bool
}{
{"codex", "me@example.com", 100, true},
{"codex", "other@example.com", 0, false},
{"claude", "me@example.com", 0, false},
{"codex", "capped@example.com", 70, false},
} {
if share, no := HoldCaps(p, c.agent, c.user).Of("5 hours"); share != c.share || no != c.noCredits {
t.Errorf("%s %s: held at %d (credits %v)", c.agent, c.user, share, no)
}
}
if err := SetCodexCredits("me@example.com", true); err != nil {
t.Fatal(err)
}
if !CodexCredits("me@example.com") || len(settings.Load().CodexNoCredits) != 0 {
t.Fatal("still off")
}
}
// A reset spent starts an account's windows again: what was read of them
// before is forgotten, so what holds the account at a share of them (its
// cap, its credits not spent) holds it no more, and they are read again
// at once; the other accounts' readings stay.
func TestRenewedAccountForgetsItsAllowance(t *testing.T) {
signIn(t)
usedCache.Lock()
usedCache.m, usedCache.at, usedCache.loading = map[string]map[string]Allowance{}, map[string]time.Time{}, map[string]chan struct{}{}
usedCache.stale = nil
usedCache.m["codex"] = map[string]Allowance{
"me@example.com": {{Used: 100, Span: 5 * time.Hour}},
"spare@example.com": {{Used: 10, Span: 5 * time.Hour}},
}
usedCache.at["codex"] = time.Now()
handed := usedCache.m["codex"]
usedCache.Unlock()
t.Cleanup(func() {
usedCache.Lock()
usedCache.m, usedCache.at, usedCache.loading = map[string]map[string]Allowance{}, map[string]time.Time{}, map[string]chan struct{}{}
usedCache.stale = nil
usedCache.Unlock()
})
renewedNow("codex", "Me@Example.com")
usedCache.Lock()
m, at := usedCache.m["codex"], usedCache.at["codex"]
usedCache.Unlock()
if _, ok := m["me@example.com"]; ok {
t.Fatalf("still read as before: %v", m["me@example.com"])
}
if _, ok := m["spare@example.com"]; !ok || !at.IsZero() {
t.Fatalf("spare kept %v, read again at once %v", ok, at.IsZero())
}
if _, ok := handed["me@example.com"]; !ok {
t.Fatal("the map handed out before was changed")
}
}