Files
magpie/internal/provider/codex_resets_used_test.go
T
yetone 4795f56469 provider, gui, cli: a Codex account's card says the last reset magpie used, when and why (foobra12 on Discord)
foobra12: "magpie会自动使用codex重置卡吗 我发现刚才好像不小心自动给我使用了
一张". Auto-use is off by default and spends only for accounts switched on
(the week used up with no other account to answer, or a reset ~30 min
before it expires), but a reset magpie spent was said only in the gateway's
log. A reset gone from the card read the same whether magpie used it, the
user did, or it ran out.

Each reset magpie spends is now kept in codex-resets-used.json (by account,
when, why: week / expiring / hand, windows started again; 90 days, 200 at
most, under a cross-process filelock, written with steady.WriteFile; a file
that doesn't parse is copied aside to .bad-<ts>, never read as empty). Only
a consume whose outcome is "reset" is kept. useCodexReset carries why:
AutoUseCodexReset passes week, SpendExpiringCodexResets expiring, and
UseCodexReset (Usage page, panel, CLI) hand.

loginReading, the choke point for LoginUsage and the Usage page, attaches
an account's last 5 uses to its reading (cached readings too, so a reading
kept from before a use still says it), and Quota/SubscriptionQuota carry
resetsUsed. The auto-use row on the Usage page's and the panel's card adds
a line "Last reset used: {when} · {why}" (zh 上次用卡:… · 自动,重置卡到期前),
every kept use in its title; an account in brief has it in its switch's
title. `magpie quota auto-reset <account>` lists them. en, zh, zh-TW, ja, de.

The default (off) and the expiry rule are unchanged: both are documented in
the switch's title and only reach accounts the user turned on.

Run:
- go test -tags nogui -count=10 -run TestResetUse ./internal/provider/
- break by hand: noteResetUsed call removed -> TestResetUsesKept red
  ("kept [], want [week hand expiring]"); loginReading attach removed ->
  red ("the card's reading has []")
- node --test codex-resets-used.test.cjs: chromium+webkit, 1100 and 420,
  en zh zh-TW ja de, the Usage page card, brief title, the panel card; 3
  runs green; with the say.append removed, 5/5 red
- codex-auto-reset, routing-auto-reset, quota-curve, click-scroll,
  tray-usages, i18n-keys, gui-ja, gui-de, gui-zh-tw: green.
  old-webkit is red on "Safari 15.0 styles" at app.css .prefs
  .val:has(> .side-effort), from dc2f0da82, the same on origin/main
  692a779d3; not this change's.
- gofmt -l, go vet (darwin, linux -tags nogui, windows), full tests of
  internal/provider, internal/cli, internal/gui, internal/gateway

Not tried: no real Codex account and no real reset spent (the ChatGPT
endpoints are faked); no notification when magpie spends one.
2026-10-13 17:32:39 +08:00

145 lines
5.4 KiB
Go

package provider
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/settings"
)
// foobra12 on Discord: "magpie会自动使用codex重置卡吗 我发现刚才好像不小心
// 自动给我使用了一张". A reset magpie spent by itself was said only in the
// gateway's log, so a reset gone from the card read the same whether magpie
// used it, the user did, or it ran out. Each one magpie spends is kept, with
// why, and the account's reading carries them, newest first: one spent as
// it was about to run out, one by hand, and one as the week was used up.
func TestResetUsesKept(t *testing.T) {
signIn(t)
rememberLogins(true) // the account kept, as the Usage page lists it
old, oldUntil := expiring.next, expiring.until
expiring.next, expiring.until = map[string]time.Time{}, map[string]time.Time{}
t.Cleanup(func() { expiring.next, expiring.until = old, oldUntil })
soon := time.Now().Add(20 * time.Minute).UTC().Format(time.RFC3339)
var weekUsed atomic.Int32
weekUsed.Store(35)
var consumed atomic.Int32
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/backend-api/wham/usage":
json.NewEncoder(w).Encode(map[string]any{"plan_type": "pro",
"rate_limit": map[string]any{
"primary_window": map[string]any{"used_percent": 10, "limit_window_seconds": 18000},
"secondary_window": map[string]any{"used_percent": weekUsed.Load(), "limit_window_seconds": 604800, "reset_at": time.Now().Add(72 * time.Hour).Unix()}},
"rate_limit_reset_credits": map[string]any{"available_count": 3}})
case "/backend-api/wham/rate-limit-reset-credits":
json.NewEncoder(w).Encode(map[string]any{"available_count": 3, "credits": []any{
map[string]any{"id": "soon", "status": "available", "expires_at": soon},
}})
case "/backend-api/wham/rate-limit-reset-credits/consume":
consumed.Add(1)
json.NewEncoder(w).Encode(map[string]any{"code": "reset", "windows_reset": 2})
default:
w.WriteHeader(404)
}
}))
t.Cleanup(fake.Close)
oldBase := CodexBase
CodexBase = fake.URL + "/backend-api/codex"
t.Cleanup(func() { CodexBase = oldBase })
const who = "me@example.com"
if got := ResetsUsed(who); len(got) != 0 {
t.Fatalf("none used yet, got %+v", got)
}
if err := SetCodexAutoReset(who, true); err != nil {
t.Fatal(err)
}
// about to run out, the account used: spent by itself
SpendExpiringCodexResets(t.Context())
if consumed.Load() != 1 {
t.Fatalf("spent %d, want the one about to run out", consumed.Load())
}
// by hand, from the Usage page or the CLI
if out, err := UseCodexReset(t.Context(), who); err != nil || out.Code != "reset" {
t.Fatalf("by hand: %+v %v", out, err)
}
// the week used up, no other account
weekUsed.Store(100)
if out, err := AutoUseCodexReset(t.Context(), who); err != nil || out.Code != "reset" {
t.Fatalf("week used up: %+v %v", out, err)
}
got := ResetsUsed(who)
want := []string{ResetUsedWeek, ResetUsedByHand, ResetUsedExpiring}
if len(got) != len(want) {
t.Fatalf("kept %+v, want %v", got, want)
}
for i, u := range got {
if u.Why != want[i] || u.User != who || u.At.IsZero() || u.Windows != 2 {
t.Fatalf("use %d: %+v, want why %q", i, u, want[i])
}
}
// the account's card says so: its reading carries them
q := LoginUsage(t.Context(), "codex")[who]
if len(q.ResetsUsed) != 3 || q.ResetsUsed[0].Why != ResetUsedWeek {
t.Fatalf("the card's reading has %+v", q.ResetsUsed)
}
// another account's are its own
if other := ResetsUsed("other@example.com"); len(other) != 0 {
t.Fatalf("another account got %+v", other)
}
// kept on disk: a restart still says it
if _, err := os.Stat(filepath.Join(settings.Dir(), "codex-resets-used.json")); err != nil {
t.Fatal(err)
}
}
// A use that didn't start anything again isn't one: nothing kept.
func TestResetUseNotKeptWhenNothingSpent(t *testing.T) {
signIn(t)
noteResetUsed("me@example.com", ResetUsedByHand, ResetOutcome{Code: "nothing_to_reset"})
noteResetUsed("me@example.com", ResetUsedByHand, ResetOutcome{Code: "no_credit"})
if got := ResetsUsed("me@example.com"); len(got) != 0 {
t.Fatalf("kept %+v", got)
}
}
// A file that doesn't parse is copied aside before a new use is written,
// never taken for none and written over; a use older than resetsUsedKeep
// is let go.
func TestResetUsesUnreadableKeptAside(t *testing.T) {
signIn(t)
p := resetsUsedPath()
os.MkdirAll(filepath.Dir(p), 0o755)
if err := os.WriteFile(p, []byte("{not json"), 0o600); err != nil {
t.Fatal(err)
}
if got := ResetsUsed("me@example.com"); got != nil {
t.Fatalf("unreadable read as %+v", got)
}
noteResetUsed("me@example.com", ResetUsedByHand, ResetOutcome{Code: "reset", Windows: 1})
aside, _ := filepath.Glob(p + ".bad-*")
if len(aside) != 1 {
t.Fatalf("copied aside: %v", aside)
}
if b, _ := os.ReadFile(aside[0]); string(b) != "{not json" {
t.Fatalf("aside holds %q", b)
}
if got := ResetsUsed("me@example.com"); len(got) != 1 {
t.Fatalf("after a use: %+v", got)
}
// an old one goes on the next write
old := []ResetUse{{User: "me@example.com", At: time.Now().Add(-resetsUsedKeep - time.Hour), Why: ResetUsedWeek}}
b, _ := json.Marshal(old)
os.WriteFile(p, b, 0o600)
noteResetUsed("me@example.com", ResetUsedExpiring, ResetOutcome{Code: "reset", Windows: 1})
if got := ResetsUsed("me@example.com"); len(got) != 1 || got[0].Why != ResetUsedExpiring {
t.Fatalf("kept %+v", got)
}
}