gateway: a ChatGPT account out of its credits rests until they are back, not 30 minutes

PaulT on Discord: ChatGPT plans now come with monthly API credits. An
account on credits only answers 402 once they run out, and magpie rested
it the flat creditRest (30 minutes, a guess) and asked it again, refused
the same, every half hour.

For a Codex account (UsageAgent "codex"; scoped to that vendor, every
other 402 rests as before) the credit rest now takes, in order: a reset
the refusal's body names (resetsAt), one its headers note (resetsNoted),
the time its full window renews from its usage reading (Allowance.Full),
a Retry-After longer than the default, else chatgptCreditRest (5 hours),
capped at longestMonthly and not marked guessed. renewed() also lifts a
Codex account's credit rest, so a reading that finds its window renewed,
or a reset spent, has it back at once.

Test: TestChatGPTOutOfCreditsRestsLong (internal/gateway/
chatgpt_credit_rest_test.go): unread -> 5h, lifted by renewed; window
read full, back in 3h -> rests 3h by "window", lifted by renewed; a key's
402 and a Claude account's 402 still rest creditRest, and renewed
("claude") doesn't lift theirs.

Broken by hand: the Codex branch off -> red ("rests 30m0s ... want
5h0m0s"); the renewed() change off -> red ("still resting after its
window renewed: 5h0m0s by credit").

Not tried: a real ChatGPT 402 from an account out of credits. No real
body is known (not in magpie's code or tests, the plugins repo, logs or
the codex binary's strings), so the test sends a bare 402 and the rest
keys on the account's vendor and status, not on body words. The 5-hour
default is a judgment: credits renew monthly, but the plan's own window
can serve again sooner, and a reading or reset lifts the rest early.
This commit is contained in:
yetone
2026-10-30 11:55:36 +08:00
parent 3f91b98eac
commit 1534474c8e
3 changed files with 115 additions and 7 deletions
File diff suppressed because one or more lines are too long
@@ -0,0 +1,78 @@
package gateway
import (
"net/http"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// PaulT on Discord: a ChatGPT account on the credits its plan gives, the
// credits run out, answered 402 and was asked again every half hour
// (creditRest), each time refused the same. It now sits out until its own
// window renews when its reading has one full, else five hours, and a
// reading finding the window renewed has it back. Another vendor's 402
// rests as it did. No real body of ChatGPT's 402 is known, so the test
// sends none: the status alone is what it rests by.
func TestChatGPTOutOfCreditsRestsLong(t *testing.T) {
fresh(t)
s := New()
old, oldStale := allowances, staleAllowance
t.Cleanup(func() { allowances, staleAllowance = old, oldStale })
staleAllowance = func(string, string) {} // nothing is read again here
var reading provider.Allowance
allowances = func(agent string) map[string]provider.Allowance {
if agent != "codex" || reading == nil {
return nil
}
return map[string]provider.Allowance{"me@example.com": reading}
}
acct := candidate{p: provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: "me@example.com"}}, model: "gpt-5.5", rest: "codex@me@example.com"}
near := func(d, want time.Duration) bool { return d > want-time.Minute && d <= want }
// nothing read: five hours, not thirty minutes
r := s.restAfter(acct, http.StatusPaymentRequired, http.Header{}, nil)
if r.Why != failCredit || !near(time.Until(r.Until), chatgptCreditRest) {
t.Fatalf("unread: rests %v (%s, by %s), want %v", time.Until(r.Until).Round(time.Second), r.Why, r.By, chatgptCreditRest)
}
// its window renewed (a reset spent, a reading): back at once
renewed("codex", "me@example.com")
if r, ok := restOf(acct.restKey()); ok {
t.Fatalf("unread: still resting after its window renewed: %v by %s", time.Until(r.Until).Round(time.Second), r.By)
}
// its five hours read full, back in three: till then, the reading
// saying it holds credits all the same (they are what ran out)
back := time.Now().Add(3 * time.Hour)
reading = provider.Allowance{
{Used: 100, Resets: back, Span: 5 * time.Hour},
{Used: 40, Resets: time.Now().Add(4 * 24 * time.Hour), Span: 7 * 24 * time.Hour},
}
r = s.restAfter(acct, http.StatusPaymentRequired, http.Header{}, nil)
if r.By != "window" || !near(time.Until(r.Until), 3*time.Hour) {
t.Fatalf("window full: rests %v by %s, want 3h by window", time.Until(r.Until).Round(time.Second), r.By)
}
if _, ok := restOf(acct.restKey()); !ok {
t.Fatal("not resting")
}
// a reading finding the window renewed has it back
renewed("codex", "me@example.com")
if r, ok := restOf(acct.restKey()); ok {
t.Fatalf("still resting after its window renewed: %v by %s", time.Until(r.Until).Round(time.Second), r.By)
}
// a key out of credit, any other vendor's account: as before
key := candidate{p: provider.Provider{ID: "relay", Key: "k"}, model: "m", rest: "relay"}
if r := s.restAfter(key, http.StatusPaymentRequired, http.Header{}, nil); r.By != "credit" || !near(time.Until(r.Until), creditRest) {
t.Fatalf("key: rests %v by %s, want %v", time.Until(r.Until).Round(time.Second), r.By, creditRest)
}
other := candidate{p: provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "me@example.com"}}, model: "claude-x", rest: "claude@me@example.com"}
if r := s.restAfter(other, http.StatusPaymentRequired, http.Header{}, nil); r.By != "credit" || !near(time.Until(r.Until), creditRest) {
t.Fatalf("claude account: rests %v by %s, want %v", time.Until(r.Until).Round(time.Second), r.By, creditRest)
}
renewed("claude", "me@example.com")
if _, ok := restOf(other.restKey()); !ok {
t.Fatal("another vendor's credit rest lifted by its window renewing")
}
}
+36 -6
View File
@@ -166,6 +166,12 @@ const (
creditRest = 30 * time.Minute // out of credit: until someone tops it up
quotaRest = 15 * time.Minute // out of quota, with no word of when it resets
longestWait = time.Hour // the most a vendor's own "try again at" is trusted
// chatgptCreditRest is how long a ChatGPT account out of its credits
// sits out when neither the refusal nor its reading says when it can
// answer again: its credits come with the plan, by the month, and its
// own allowance is back as its five hours renew (PaulT on Discord: a
// credits-only account was asked every half hour, 402 each time)
chatgptCreditRest = 5 * time.Hour
// longestQuota is the most an account out of quota, or failing with a
// window full, sits out, when it says when it's back: a week's window,
// and a day over
@@ -608,17 +614,19 @@ func (r Rest) asksAt(now time.Time) time.Time {
// renewed lifts the rests of a subscription account whose windows were
// just started again (a Codex reset spent, or a reading finding a window
// it was full in full no more): out of quota no longer. Only its rests out
// of quota, or failed with a window full ("window"), are lifted; one for a
// rate limit, its credit or a verification stays. Told agent "", it is a
// key (provider.KeyAllowanceID) whose windows a reading found full no
// more — its limit raised, or its usage reset — and its rest out of them
// is lifted; a key's other rests aren't noted by it.
// of quota, or failed with a window full ("window"), are lifted, and a
// ChatGPT account's out of its credits, which it needs no more with its
// window back; one for a rate limit, another's credit or a verification
// stays. Told agent "", it is a key (provider.KeyAllowanceID) whose
// windows a reading found full no more — its limit raised, or its usage
// reset — and its rest out of them is lifted; a key's other rests aren't
// noted by it.
func renewed(agent, user string) {
restingUntil.Lock()
defer restingUntil.Unlock()
now := time.Now()
for k, r := range restingUntil.note {
if r.agent == agent && strings.EqualFold(r.user, user) && (r.Why == failQuota || r.By == "window") {
if r.agent == agent && strings.EqualFold(r.user, user) && (r.Why == failQuota || r.By == "window" || r.Why == failCredit && agent == "codex") {
delete(restingUntil.m, k)
delete(restingUntil.note, k)
liftedLocked(k, now)
@@ -1093,6 +1101,28 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo
switch why {
case failCredit:
d, r.By, guessed = creditRest, "credit", true
if a := c.p.Account; a != nil && a.UsageAgent() == "codex" {
// a ChatGPT account out of the credits its plan gives: they
// come again with the plan, and the account answers again
// once its own window renews, whichever comes first. Until the
// time the refusal names, else the window its reading has
// full (read whatever the credits it said it held: they are
// what ran out), else a while; a reading that finds the window
// renewed lifts it (renewed)
al, _ := c.allowance()
if w := resetsAt(body, now); w > 0 {
d, r.By = w, "resets"
} else if w := resetsNoted(header, now); w > 0 {
d, r.By = w, "resets"
} else if t := al.Full(c.model, provider.SpentShareOf(c.p.Routing), now); !t.IsZero() {
d, r.By = t.Sub(now), "window"
} else if w := retryAfter(header, now); w > chatgptCreditRest {
d, r.By = w, "retry-after"
} else {
d = chatgptCreditRest
}
d, guessed = min(d, longestMonthly), false
}
case failQuota:
if c.onCredits() {
// a Codex account that holds credits refused as out of its