Files
magpie/internal/gateway/codex_credits_last_test.go
T
yetone 699ddf1524 gateway: a Codex account can spend its credits only after every other account, key and fallback (gokoshiki on Discord)
gokoshiki wants a Codex subscription first, then an OpenAI API key, then
the subscription's credits. Until now an account at 100% that holds
credits either kept its place and spent them there (on) or was held
(off). This adds a third way per account, "last":

- settings: CodexCreditsLast []string, empty by default, so a setting
  saved before it keeps its order. provider.CodexCreditsLast,
  CodexCreditsMode and SetCodexCreditsMode(user, on|last|off);
  SetCodexCredits(on) still means "in its place" and clears last.
- gateway: candidate.creditsLast is true for such an account once a
  window for the model is used up and it is going on its credits (a
  call ChatGPT counts in no window stays in its place). restLast orders
  ready, then resting, then those, and marks Weighed.CreditsLast.
  restLast runs over the asides too, so such an account goes behind a
  provider's reserves (Accounts at once, 2c6b7c063) as well.
  lastBehind keeps In turn's next turn (after), a new conversation's
  spread (leastHeld) and a subagent's lead (readyForNew) from bringing
  it forward, and a kept conversation moves off it to one not on its
  credits (Affinity.Why "credits").
- CLI: magpie quota credits <account> [on|last|off]; alone it lists
  accounts set off and last.
- API: POST /api/settings/codex-credits takes {user, on, last?}.
- GUI: under a Codex account's Use credits, while on, a second switch
  "Only after every other account, key and fallback", in the Usage
  page's card and the tray panel's (both wrap it to its own line at 360
  to 900px), and the panel's folded brief says "On, after everything
  else". The Routing page's trace says why such an account is behind
  (aside, the kept conversation's why, the row tag). zh, zh-TW, ja, de.
  creditsButton and the new switch share creditsSwitch, and the Codex
  options' comments in app.js were cut, so the core budget holds with
  no raise (1,532,664 of 1,533,105).
- docs: reference.md (quota credits) and gateway-routing.md.

Tests:
- gateway: TestCodexCreditsLastAfterTheOthers (two accounts, In order:
  the one at 100% on its credits goes behind, the trace says so, and
  back in place when turned on), TestCodexCreditsLastAfterTheFallback
  (both accounts at 100% and set last: the API key the provider falls
  back to answers before either one's credits; with the credits in
  their place an account answers on them, as before),
  TestCodexCreditsLastNotKept (a kept conversation moves off it).
  All three red with creditsLast and lastBehind forced false.
- provider: TestCodexCreditsLastMode.
- gui: settings_keep_test carries CodexCreditsLast;
  tests/codex-credits-last.test.cjs (Chromium and WebKit, en zh zh-TW
  ja de; Usage at 900 and 440, the panel at 440 and 360, the folded
  brief, the Routing page's aside and why, every key in I18N). Red on
  the old assets (no .ar-credits-last).

Run at this change on origin/main c76bcaea7, on mote (pushed on fd70def82, whose
one commit since, fd70def82, changes only the Providers poll's Go
files in internal/gui):
gofmt clean; go vet of gateway, provider, gui, cli and settings ok;
their tests ok but internal/gui's #4514 and #3949, both on main. The
8 commits between d6aa9cdf6 and c76bcaea7 touch none of this
change's files.

Run at this change on origin/main d6aa9cdf6, Go 1.26.8:
- mote: gofmt -l clean; go vet ./..., and GOOS=linux and GOOS=windows
  go vet -tags nogui ./...: ok. go test -count=1 -timeout 45m ./...:
  85 packages ok; internal/gui red only on TestSettingsSaveKeepsWhatIt
  DoesNotSend's SearchAll (#4514), TestMainWindowCorners (#3949) and
  TestColdTurnsTaken (#4510), all three on main. TestCoreScriptBudget
  passes.
- WSL magpie-desktop, Playwright 1.62.0, both engines: codex-credits*,
  i18n-keys, gui-ja, gui-zh-tw, panel-options-fold, provider-at-once and
  every routing-* file: 2127 tests, 2064 pass. Every codex-credits and
  codex-credits-last test passed (26). The red files (gui-ja, 19 routing
  files) run again at this tree and at d6aa9cdf6, alike: 200 tests, 61
  and 57 red. gui-ja is #4580; the routing reds are timeouts and
  waits, on both. The one file red at this tree only,
  routing-request-model (WebKit 420px "the model is cut"), is 5 of 5
  green alone at both, and with six copies at once red at both (29 and
  27 of 30 here, 28 and 27 of 30 at d6aa9cdf6): a fixed 150ms wait
  after a resize, filed as #4650. Nothing this change adds to Routing
  draws unless an account is set last (fixtures don't).
- Earlier, at 3564eb04b (this change on 7428f3229), WSL: the whole GUI
  suite beside two other sessions' suites, 16944 tests, 16496 pass;
  its 102 red files again at that head and at 7428f3229, 444 and 425
  red. The files red at the head only, run alone: view-open-wheel,
  usage-accounts, add-button, usage-ledger-open-settled 0 red;
  view-wheel-after-click, view-wheel-unheard and context-map (#3488)
  red alone at 7428f3229 too. mote, the credits and i18n files: 172 of
  174, the two #4580 and a click timeout in quota-curve at load 148
  (alone 30 of 30).

Not tried: a real ChatGPT account at 100% with credits beside a real
OpenAI key; the order is shown with the gateway's fake Codex backend.
2026-11-01 09:08:07 +08:00

140 lines
5.7 KiB
Go

package gateway
import (
"net/http"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// gokoshiki on Discord: a Codex subscription, then an OpenAI API key, then
// the subscription's credits. An account at 100% that holds credits keeps
// its place by default (In order: asked first, and spends them); set to
// spend them last, the next account not on its credits is asked first,
// the account behind it, and the trace says why; turned on again it is
// back in its place.
func TestCodexCreditsLastAfterTheOthers(t *testing.T) {
codexSignedIn(t, "spare@example.com")
b := newResetBackend(t) // every account answers: the first on its credits
creditsUsage(t, map[string]float64{"me@example.com": 100, "spare@example.com": 20}, "me@example.com")
if err := provider.SetRouting("codex", provider.Ordered); err != nil {
t.Fatal(err)
}
again := func(want string) *Server {
t.Helper()
b.mu.Lock()
b.tried = nil
b.mu.Unlock()
srv := New()
code, body := resetPost(t, srv)
if tried, _ := b.seen(); code != 200 || !strings.Contains(body, "pong") || tried != want {
t.Fatalf("%d %s tried %q, want %q", code, body, tried, want)
}
return srv
}
again("acct-1") // in its place
if err := provider.SetCodexCreditsMode("Me@Example.com", provider.CreditsLast); err != nil {
t.Fatal(err)
}
srv := again("acct-2")
rs := srv.Trace(t.Context(), 0, 0).Routes
if len(rs) == 0 || len(rs[0].Order) != 2 || rs[0].Order[0].Who != "spare@example.com" || rs[0].Order[0].CreditsLast ||
rs[0].Order[1].Who != "me@example.com" || !rs[0].Order[1].CreditsLast || !rs[0].Order[1].Credits {
t.Fatalf("order %+v", rs)
}
// below its windows' end it isn't on its credits: in its place still
creditsUsage(t, map[string]float64{"me@example.com": 60, "spare@example.com": 20}, "me@example.com")
again("acct-1")
creditsUsage(t, map[string]float64{"me@example.com": 100, "spare@example.com": 20}, "me@example.com")
if err := provider.SetCodexCredits("me@example.com", true); err != nil {
t.Fatal(err)
}
if provider.CodexCreditsLast("me@example.com") {
t.Fatal("on is in its place: last kept")
}
again("acct-1")
}
// The credits come after a provider's fallback too: both accounts at 100%
// on their credits and set to spend them last, an API key the provider
// falls back to answers first; with the credits in their place, an
// account answers on them as before.
func TestCodexCreditsLastAfterTheFallback(t *testing.T) {
codexSignedIn(t, "spare@example.com")
b := newResetBackend(t)
creditsUsage(t, map[string]float64{"me@example.com": 100, "spare@example.com": 100}, "me@example.com", "spare@example.com")
if err := provider.SetRouting("codex", provider.Ordered); err != nil {
t.Fatal(err)
}
fb := &keyed{}
serveOn(t, "spare", "kf", []string{"m2"}, fb)
p, _ := provider.Find("codex")
p.Fallback = []string{"spare/m2"}
if err := provider.Save(*p); err != nil {
t.Fatal(err)
}
post := func() (int, string) {
sticks.Lock()
sticks.m = map[string]stick{}
sticks.Unlock()
return postAs(t, New(), "", `{"model":"codex/gpt-5.5","messages":[{"role":"user","content":"hi"}]}`)
}
code, body := post()
if tried, _ := b.seen(); code != 200 || tried != "acct-1" || len(fb.tried) != 0 {
t.Fatalf("in their place: %d %s, codex tried %q, fallback %v", code, body, tried, fb.tried)
}
for _, u := range []string{"me@example.com", "spare@example.com"} {
if err := provider.SetCodexCreditsMode(u, provider.CreditsLast); err != nil {
t.Fatal(err)
}
}
b.mu.Lock()
b.tried = nil
b.mu.Unlock()
code, body = post()
if tried, _ := b.seen(); code != 200 || !strings.Contains(body, "from kf") || tried != "" {
t.Fatalf("last: %d %s, codex tried %q", code, body, tried)
}
}
// A conversation an account on its credits answered, set to spend them
// last, isn't kept on it by its cache once one not on its credits leads;
// a turn going round, or a new conversation spread, never lands on it
// past that one either.
func TestCodexCreditsLastNotKept(t *testing.T) {
acct := func(u string) candidate {
return candidate{p: provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: u}}, model: "gpt-5.5", rest: "codex/" + u}
}
cs := []candidate{acct("spare@example.com"), acct("me@example.com")}
pl := planned{order: []Weighed{{Who: "spare@example.com"}, {Who: "me@example.com", Credits: true, CreditsLast: true}}}
h := http.Header{}
h.Set("x-claude-code-session-id", "credits-last-kept")
body := []byte(`{"messages":[{"role":"user","content":"hi"}]}`)
_, _, _, key := affine("t", provider.AffinitySession, false, false, false, h, provider.Chat, body, body, cs, pl)
answered(key, cs[1], 1, Usage{CacheRead: 50_000})
t.Cleanup(func() { sticks.Lock(); delete(sticks.m, key); sticks.Unlock() })
got, _, aff, _ := affine("t", provider.AffinitySession, false, false, false, h, provider.Chat, body, body, cs, pl)
if got[0].rest != "codex/spare@example.com" || aff.Kept || aff.Why != "credits" {
t.Fatalf("first %s, kept %v, why %s", got[0].rest, aff.Kept, aff.Why)
}
// every one on its credits and last: kept where it was
both := planned{order: []Weighed{{Who: "spare@example.com", CreditsLast: true}, {Who: "me@example.com", CreditsLast: true}}}
got, _, aff, _ = affine("t", provider.AffinitySession, false, false, false, h, provider.Chat, body, body, cs, both)
if got[0].rest != "codex/me@example.com" || !aff.Kept {
t.Fatalf("all last: first %s, kept %v, why %s", got[0].rest, aff.Kept, aff.Why)
}
// a turn after spare's goes round to spare again, not to me
if got, _ := after(append([]candidate(nil), cs...), planned{order: append([]Weighed(nil), pl.order...)}, 0); got[0].rest != "codex/spare@example.com" {
t.Fatalf("turn went to %s", got[0].rest)
}
if readyForNew(pl.order, 1) {
t.Fatal("a new conversation may go to the one on its credits")
}
}