alanwalk asked for "自动使用重置卡" to be split: they want a reset that is
about to expire used rather than lost, but a used-up week waited out rather
than spending a reset on it (and the other way round for others).
What changed:
- settings: codexAutoResetOnly narrows an account in codexAutoReset to
"week" or "expiring". An account with no entry keeps both, so every
existing config means what it meant: nothing to migrate, and no user
value is rewritten. Load drops entries for accounts not in the list or
with an unknown value.
- provider: CodexAutoResetWhen(user) reads both times. AutoUseCodexReset
(the week used up, called from the gateway's autoReset and
autoResetSignedIn through AutoResetsWeek) only acts when the week is on;
SpendExpiringCodexResets and routing's resetRunsOut only count on the
expiring reset when that is on. SetCodexAutoResetCase(user, when, on)
sets one time and keeps the other; SetCodexAutoReset still sets both.
Both off removes the account.
- gateway: POST /api/settings/codex-auto-reset takes an optional "when";
POST /api/settings keeps codexAutoResetOnly, which the page doesn't send.
- GUI: the account's card (Usage page and the menu bar panel) says
"Auto-use resets:" with each time on its own line and its own switch;
the brief account's one switch still sets both, its title naming each
time; Settings › Usage gives each account an Off/On per time. The status
line says which times are on now. "· auto-used before it expires" on
the resets held follows the expiring switch alone. Strings in zh, zh-TW,
ja and de.
- CLI/TUI: `magpie quota auto-reset <account> week|expiring on|off`; the
quota and accounts tables and the TUI say "auto", "auto when the week
runs out" or "auto before one expires".
What was run (worktree on origin/main 2fbbd1694):
- gofmt -l on the changed Go files: clean. go vet ./... (darwin),
GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: clean.
- go test -tags nogui ./internal/provider ./internal/gateway ./internal/cli
./internal/tui ./internal/gui ./internal/settings: ok. The gateway
package hit go test's 10m default once while ~15 sibling sessions were
building on this machine (no test failed; TestRemoteMagpieModels was
merely running); with -timeout 30m it passed in 967s.
- New Go tests: TestCodexAutoResetCases (provider), a week-only step in
TestSpendExpiringCodexResets, an "only before one expires" case in
TestCodexAutoResetNot (gateway), CodexAutoResetOnly in
TestSettingsSaveKeepsWhatItDoesNotSend. Broken by hand: making
CodexAutoResetWhen ignore the narrowing turned all three reset tests
red (the gateway case answered 200, a week-only account read 2 and
spent 1); dropping the keep line in api.go turned the settings test red.
- GUI (Playwright, chromium and webkit): codex-auto-reset.test.cjs, now in
en, zh, zh-TW, ja and de at 1100 and 420 wide, flips each time's switch
on the card and the panel and checks posts carry "when", the other time
is kept, the status, the resets-held line, the brief switch, fit at 420,
no left border, no select; codex-auto-reset-settings.test.cjs does the
same for Settings › Usage. Both, with codex-resets-used, routing-auto-reset,
quota-curve (its class list now holds ar-split) and i18n-keys: 56 + 18
pass. Broken by hand: posting without "when" turned 20 of 21 red.
quota-curve failed 2 of 18 once while a go test build ran beside it; it
passed 15/15 serially and 18/18 again at concurrency 4 just after.
Not tried: a real ChatGPT account using or keeping a reset; the times are
driven with the faked usage reads the existing tests use.
217 lines
7.8 KiB
Go
217 lines
7.8 KiB
Go
package gateway
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// resetBackend stands in for the ChatGPT backend of accounts that are out
|
|
// of their allowance: their usage (the week's and five hours'), the
|
|
// resets each holds, and spending one, which lets the account answer again.
|
|
type resetBackend struct {
|
|
mu sync.Mutex
|
|
week map[string]float64 // used, by account id; the five hours are full
|
|
held map[string]int // resets held
|
|
out map[string]bool // out of its allowance
|
|
spent []string // accounts a reset was spent on
|
|
gone bool // every reset spent elsewhere since the usage was read
|
|
tried []string // accounts asked for a turn
|
|
}
|
|
|
|
func newResetBackend(t *testing.T, accounts ...string) *resetBackend {
|
|
t.Helper()
|
|
b := &resetBackend{week: map[string]float64{}, held: map[string]int{}, out: map[string]bool{}}
|
|
for _, a := range accounts {
|
|
b.week[a], b.held[a], b.out[a] = 100, 1, true
|
|
}
|
|
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
acct := r.Header.Get("chatgpt-account-id")
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
now := time.Now()
|
|
switch r.URL.Path {
|
|
case "/backend-api/codex/responses":
|
|
io.ReadAll(r.Body)
|
|
b.tried = append(b.tried, acct)
|
|
if b.out[acct] {
|
|
w.WriteHeader(429)
|
|
io.WriteString(w, `{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached","plan_type":"plus","resets_in_seconds":7200}}`)
|
|
return
|
|
}
|
|
io.WriteString(w, sse(
|
|
`data: {"type":"response.created","response":{"id":"r1","model":"gpt-5.5"}}`,
|
|
`data: {"type":"response.output_text.delta","delta":"pong"}`,
|
|
`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":7,"output_tokens":1}}}`))
|
|
case "/backend-api/wham/usage":
|
|
five := 100.0
|
|
if !b.out[acct] {
|
|
five = 0
|
|
}
|
|
json.NewEncoder(w).Encode(map[string]any{"plan_type": "plus",
|
|
"rate_limit": map[string]any{
|
|
"primary_window": map[string]any{"used_percent": five, "limit_window_seconds": 18000, "reset_at": now.Add(2 * time.Hour).Unix()},
|
|
"secondary_window": map[string]any{"used_percent": b.week[acct], "limit_window_seconds": 604800, "reset_at": now.Add(3 * 24 * time.Hour).Unix()}},
|
|
"rate_limit_reset_credits": map[string]any{"available_count": b.held[acct]}})
|
|
case "/backend-api/wham/rate-limit-reset-credits":
|
|
var credits []any
|
|
for i := range b.held[acct] {
|
|
credits = append(credits, map[string]any{"id": acct + "-" + string(rune('a'+i)), "reset_type": "codex_rate_limits",
|
|
"status": "available", "granted_at": "2026-09-01T00:00:00Z", "expires_at": now.Add(20 * 24 * time.Hour).Format(time.RFC3339)})
|
|
}
|
|
json.NewEncoder(w).Encode(map[string]any{"available_count": b.held[acct], "credits": credits})
|
|
case "/backend-api/wham/rate-limit-reset-credits/consume":
|
|
if b.held[acct] == 0 || b.gone {
|
|
io.WriteString(w, `{"code":"no_credit","windows_reset":0}`)
|
|
return
|
|
}
|
|
b.held[acct]--
|
|
b.spent = append(b.spent, acct)
|
|
b.out[acct], b.week[acct] = false, 0
|
|
io.WriteString(w, `{"code":"reset","windows_reset":2}`)
|
|
default:
|
|
w.WriteHeader(404)
|
|
}
|
|
}))
|
|
t.Cleanup(up.Close)
|
|
was := provider.CodexBase
|
|
provider.CodexBase = up.URL + "/backend-api/codex"
|
|
t.Cleanup(func() { provider.CodexBase = was })
|
|
return b
|
|
}
|
|
|
|
func (b *resetBackend) seen() (tried, spent string) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
return strings.Join(b.tried, ","), strings.Join(b.spent, ",")
|
|
}
|
|
|
|
// resetPost posts a Codex turn to srv as codexPost does.
|
|
func resetPost(t *testing.T, srv *Server) (int, string) {
|
|
t.Helper()
|
|
rec := httptest.NewRecorder()
|
|
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-5.5","stream":true,"input":"ping"}`))
|
|
req.Header.Set("Authorization", "Bearer chatgpt-token")
|
|
req.Header.Set("chatgpt-account-id", "acct-1")
|
|
srv.Handler().ServeHTTP(rec, req)
|
|
return rec.Code, rec.Body.String()
|
|
}
|
|
|
|
// resetsTraced is the resets the routing trace says were spent by
|
|
// themselves, as who: what.
|
|
func resetsTraced(srv *Server) []string {
|
|
var out []string
|
|
for _, r := range srv.Trace(context.Background(), 0, 0).Routes {
|
|
for _, t := range r.Tries {
|
|
if t.Reset != nil {
|
|
out = append(out, t.Reset.Who+": "+t.Reset.Text)
|
|
}
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Codex's one account, its week used up, with the user's leave to spend
|
|
// its resets by itself: one is spent and the turn goes through (StringKe
|
|
// on Discord: resets gifted to the account, used once the week is out).
|
|
func TestCodexAutoResetOneAccount(t *testing.T) {
|
|
codexSignedIn(t)
|
|
b := newResetBackend(t, "acct-1")
|
|
if err := provider.SetCodexAutoReset("Me@example.com", true); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
srv := New()
|
|
code, body := resetPost(t, srv)
|
|
tried, spent := b.seen()
|
|
if code != 200 || !strings.Contains(body, "pong") || tried != "acct-1,acct-1" || spent != "acct-1" {
|
|
t.Fatalf("%d %s tried %s spent %s", code, body, tried, spent)
|
|
}
|
|
if got := resetsTraced(srv); len(got) != 1 || got[0] != "me@example.com: 2 windows started again" {
|
|
t.Fatalf("traced %v", got)
|
|
}
|
|
if calls := srv.Recent(); len(calls) == 0 || !strings.Contains(calls[0].Fallback, "used one of its resets") {
|
|
t.Fatalf("request log %+v", calls)
|
|
}
|
|
// out again in the same week: no second reset spent
|
|
b.mu.Lock()
|
|
b.out["acct-1"], b.week["acct-1"], b.held["acct-1"] = true, 100, 1
|
|
b.mu.Unlock()
|
|
code, _ = resetPost(t, srv)
|
|
if _, spent := b.seen(); code != 429 || spent != "acct-1" {
|
|
t.Fatalf("second time in the week %d, spent %s", code, spent)
|
|
}
|
|
}
|
|
|
|
// Two accounts out, the one Codex is signed in to spending its resets by
|
|
// itself: tried both, it spends one and answers.
|
|
func TestCodexAutoResetAfterEveryAccount(t *testing.T) {
|
|
codexSignedIn(t, "spare@example.com")
|
|
b := newResetBackend(t, "acct-1", "acct-2")
|
|
if err := provider.SetCodexAutoReset("me@example.com", true); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
srv := New()
|
|
code, body := resetPost(t, srv)
|
|
tried, spent := b.seen()
|
|
if code != 200 || !strings.Contains(body, "pong") || spent != "acct-1" || !strings.HasSuffix(tried, ",acct-1") || strings.Count(tried, ",") != 2 {
|
|
t.Fatalf("%d %s tried %s spent %s", code, body, tried, spent)
|
|
}
|
|
if got := resetsTraced(srv); len(got) != 1 || !strings.HasPrefix(got[0], "me@example.com: ") {
|
|
t.Fatalf("traced %v", got)
|
|
}
|
|
}
|
|
|
|
// No reset is spent when the user didn't say so, when they kept it to
|
|
// the one about to expire (#2078), when only the five hours are used up,
|
|
// or when the account holds none: ChatGPT's refusal goes back as it came.
|
|
func TestCodexAutoResetNot(t *testing.T) {
|
|
for _, c := range []struct {
|
|
name string
|
|
on bool
|
|
week float64
|
|
held int
|
|
gone bool
|
|
// expiringOnly: on before one expires, off when the week runs out
|
|
expiringOnly bool
|
|
}{
|
|
{"not turned on", false, 100, 1, false, false},
|
|
{"only before one expires", true, 100, 1, false, true},
|
|
{"only the five hours", true, 60, 1, false, false},
|
|
{"none held", true, 100, 0, false, false},
|
|
{"no credit when spent", true, 100, 1, true, false},
|
|
} {
|
|
t.Run(c.name, func(t *testing.T) {
|
|
codexSignedIn(t)
|
|
b := newResetBackend(t, "acct-1")
|
|
b.week["acct-1"], b.held["acct-1"], b.gone = c.week, c.held, c.gone
|
|
if c.on {
|
|
if err := provider.SetCodexAutoReset("me@example.com", true); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if c.expiringOnly {
|
|
if err := provider.SetCodexAutoResetCase("me@example.com", provider.ResetCaseWeek, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
srv := New()
|
|
code, body := resetPost(t, srv)
|
|
tried, spent := b.seen()
|
|
if code != 429 || !strings.Contains(body, "usage_limit_reached") || tried != "acct-1" || spent != "" {
|
|
t.Fatalf("%d %s tried %s spent %s", code, body, tried, spent)
|
|
}
|
|
if got := resetsTraced(srv); len(got) != 0 {
|
|
t.Fatalf("traced %v", got)
|
|
}
|
|
})
|
|
}
|
|
}
|