Files
magpie/internal/provider/codex_resets_used.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

126 lines
3.9 KiB
Go

package provider
// What magpie spent of a Codex account's rate-limit resets, kept so the
// user can see it afterwards (foobra12 on Discord: "magpie会自动使用codex
// 重置卡吗 我发现刚才好像不小心自动给我使用了一张"). Auto-use spends one
// in the background — its week used up, or one about to run out — and
// before this only the gateway's log said so; a reset gone from the card
// read the same whether magpie spent it, the user did, or it ran out. Each
// use is kept in codex-resets-used.json, by account, and shown on the
// account's card and by `magpie quota auto-reset`.
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"slices"
"strings"
"time"
"github.com/yetone/magpie/internal/filelock"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/steady"
)
// Why a reset was used: by itself as the account's week was used up and no
// other account could answer (AutoUseCodexReset), by itself as it was about
// to run out unused (SpendExpiringCodexResets), or by hand from the Usage
// page, the panel or the CLI (UseCodexReset).
const (
ResetUsedWeek = "week"
ResetUsedExpiring = "expiring"
ResetUsedByHand = "hand"
)
// ResetUse is one reset magpie spent on an account.
type ResetUse struct {
User string `json:"user"`
At time.Time `json:"at"`
Why string `json:"why"`
Windows int `json:"windows,omitempty"` // how many windows started again
}
var (
// resetsUsedKeep is how long a use is kept, and resetsUsedMost how many
// at most: enough to answer "did magpie use one?" a while later
resetsUsedKeep = 90 * 24 * time.Hour
resetsUsedMost = 200
// resetsUsedShown is how many of an account's uses its card gets
resetsUsedShown = 5
)
func resetsUsedPath() string { return filepath.Join(settings.Dir(), "codex-resets-used.json") }
// resetsUsedMu keeps the file to one writer at a time, across the magpies
// on the computer too: the gateway spends by itself, a terminal's magpie
// by hand.
var resetsUsedMu = filelock.Mutex{Path: func() string { return resetsUsedPath() + ".lock" }}
// readResetsUsed reads the file: none yet is no uses; one that can't be
// read or parsed is an error, never taken for none.
func readResetsUsed() ([]ResetUse, error) {
b, err := os.ReadFile(resetsUsedPath())
if errors.Is(err, fs.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
var us []ResetUse
if err := json.Unmarshal(b, &us); err != nil {
return nil, fmt.Errorf("%s: %w", resetsUsedPath(), err)
}
return us, nil
}
// noteResetUsed keeps that a reset of user's was used, for why, when out
// says one was. A file that doesn't parse is copied aside first, not
// written over unread.
func noteResetUsed(user, why string, out ResetOutcome) {
if user == "" || out.Code != "reset" {
return
}
resetsUsedMu.Lock()
defer resetsUsedMu.Unlock()
us, err := readResetsUsed()
if err != nil {
p := resetsUsedPath()
if b, rerr := os.ReadFile(p); rerr == nil {
_ = os.WriteFile(p+".bad-"+time.Now().UTC().Format("20060102T150405.000000000"), b, 0o600)
}
us = nil
}
now := time.Now().UTC()
us = slices.DeleteFunc(us, func(u ResetUse) bool { return now.Sub(u.At) > resetsUsedKeep })
us = append(us, ResetUse{User: user, At: now, Why: why, Windows: out.Windows})
if len(us) > resetsUsedMost {
us = us[len(us)-resetsUsedMost:]
}
b, _ := json.MarshalIndent(us, "", " ")
_ = os.MkdirAll(settings.Dir(), 0o755)
_ = steady.WriteFile(resetsUsedPath(), append(b, '\n'), 0o600)
}
// ResetsUsed is what magpie spent of the Codex account user's resets,
// newest first, resetsUsedShown at most; nil when none, or when the file
// can't be read.
func ResetsUsed(user string) []ResetUse {
if user == "" {
return nil
}
us, err := readResetsUsed()
if err != nil {
return nil
}
var out []ResetUse
for i := len(us) - 1; i >= 0 && len(out) < resetsUsedShown; i-- {
if strings.EqualFold(us[i].User, user) {
out = append(out, us[i])
}
}
return out
}