Files
magpie/internal/provider/codex_limits.go
T
yetone ef37b6fb76 gateway: an exhausted ChatGPT account no longer greys Codex app's Send while magpie can serve the turn (MasterYi on Discord)
MasterYi (#help, 1563467829687222343): with magpie wired into the Codex
app, a used-up ChatGPT account greys the Send button, so the third-party
models joined in Codex's picker can't be used either.

Cause, as far as the app's bundled code (ChatGPT.app 26.1013.40934,
read-only) shows: Send is gated in the app itself. It needs
authMethod == "chatgpt", the /wham/usage reading (fetched by the app
straight from chatgpt.com, not through magpie) saying not allowed, and
no credits. authMethod is read as the app opens or on account/updated,
which the app-server sends only on login/logout, not on a config change.
So the gate lifts only when model_provider is magpie AND the app has been
opened again. #540 already made magpie the provider while out, but only
when a magpie model was the default; on one of Codex's own models
(joined), nothing changed.

What changed:
- A (agent/codex.go Sync): joined on one of Codex's own models and the
  account out (not Always ChatGPT, not magpie API), magpie becomes the
  provider on that model as magpie serves it (codex/<model>), the model
  kept in codex.out_own. Once the account has room, Codex is put back
  joined on that model. A model picked meanwhile stays the user's. With
  no ChatGPT account in magpie to serve it, nothing changes. New
  Agent.AppOut says magpie is the provider for a used-up sign-in.
- C (provider/codex_app_out.go): a usage_limit_reached rest on the
  active Codex account (gateway routing) or an x-codex-* window heard at
  100% (NoteCodexLimits) has the account read again at once
  (CodexMayBeUsedUp: active account only, at most every 20s, only
  while a KeepOnAnAccountWithRoom loop has made its first reading and
  still runs), not only on the 5-minute look. A first cut turned this
  on for good as the loop started; every gateway test's Serve starts
  it, so later gateway tests had accounts read again behind them, and
  TestCodexOwnModelMovesToNextAccount and
  TestCodexSpentMovesToNextGroupMember went red in the package run
  (green alone 3 of 3). Now a counter, up after the first minute's
  reading, down as the loop ends; the package run is green with it.
- B (gui/codex_app_out.go): the app open when the account ran out is kept
  by its app-server's pid (provider.CodexAppOut; a new pid means it
  reopened and read the provider, standing in for "authMethod is still
  chatgpt"). On macOS, every 10s, magpie reopens it through the Agents
  row's ReopenCodexApp when: AppOut, the account still out, the app is a
  copy from before the config change, no turn in flight through the
  gateway and none ended in the last 30s. At most once per time the
  account runs out, success or not.
  Drafts: the app's code keeps composer drafts in a persisted store
  (composer-prompt-drafts-v2, 250ms debounce, flushed on quit), and
  threads are server-side, so an unsent draft and open threads should
  survive the quit. Not watched in a real app.
- D (GUI): Codex's accounts say "The Codex app can't send on {user}'s
  used-up account": on macOS that magpie reopens it once no turn runs;
  off macOS (no reopen path) or once tried, to quit and reopen it.
  en, zh, zh-TW, ja, de.

Tests (each red on the code without its part, broken by hand):
- TestCodexOwnModelGoesThroughMagpieWhileUsedUp: red at "used up" with
  the out case off, at "allowance back" with the restore off.
  TestCodexOwnModelKeptOnChatGPT: Always ChatGPT stays.
- TestCodexMayBeUsedUpReadsAtOnce: red at "a window full: not read"
  with the NoteCodexLimits hook off. TestCodexAppOutEpisode.
- TestCodexUsedUpReplyAsksAtOnce (gateway): red, asked [], with the
  routing hook off.
- TestCodexAppOutReopenedOnce (gui, reopen stubbed): red at "a turn in
  flight" with the idle check off, and at "again" with the once checks
  off.
- codex-app-out.test.cjs: 40 of 40 (chromium, webkit; 900/480; five
  languages; both texts); 2 of 2 red with the notice's call site off.

What was run, at this tree:
- gofmt -l: none. go vet ./... (darwin), GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: exit 0.
- go test -tags nogui -timeout 45m: internal/agent ok (414s, before a
  comment-only reorder in Sync); internal/gateway ok (534s),
  internal/gui ok (78s), internal/provider ok (137s), after the
  live-check fix, at this tree before the previous commit's JS-only
  move (then with a budget raise since taken back); internal/gui
  again after the move.
- GUI (chromium, webkit), at this tree: codex-app-out, codex-app-stale,
  i18n-keys, gui-de, gui-ja, gui-zh-tw and the files reaching the
  previous commit's move: 164 of 164. Before the trim, every codex-*
  and account-* file: 447 of 448; the red, codex-predictions chromium
  ja 420 "picking a model scrolled the page", is #2624 and is red alone
  on origin/main 5a85a2a91 too (1 of 2); one codex-app-out case timed
  out launching chromium at load ~100 and passed on the rerun.
- TestCoreScriptBudget with the budgets unchanged: ok. The three Codex
  notices now share one box builder (codexNote), and the previous
  commit moved ledSaid out of app.js.

Not tried:
- No real Codex app was quit or reopened (the owner's live app is left
  alone); the reopen path is stubbed. Whether the reopened app's Send
  comes back, and whether a draft survives, is from reading its code.
- No real used-up account; the move was run in a sandbox HOME.
- The full suite: no suite lock on this machine, load ~75.
- A gateway served by another magpie process: the episode lives in the
  process that serves the gateway, so a GUI that doesn't serve it never
  reopens the app or shows the notice.
2026-10-24 17:38:50 +08:00

115 lines
3.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package provider
import (
"slices"
"strings"
"time"
)
// The ChatGPT backend tells what a Codex account has used as it answers:
// its x-codex-primary-* and x-codex-secondary-* headers, and a
// codex.rate_limits event ahead of the reply, which Codex itself reads for
// its /status. Read only from /wham/usage, once a minute, an account near
// its usage cap was sent turn after turn on a reading that said 96% while
// the account went to 100% (#1295): what each reply says is kept at once,
// so the cap holds the account from the next turn on.
// CodexLimit is one of an account's windows as a reply tells it: the
// share used (0–100), how long the window runs, and when it renews (zero
// when not said).
type CodexLimit struct {
Used float64
Span time.Duration
Resets time.Time
}
// NoteCodexLimits keeps what a reply said of agent's account user (agent
// as its usage is read, Account.UsageAgent) in place of the windows of the
// same span last read, for routing (Allowances) and the Usage page alike.
// An account not read yet is left to its reading: a reply names only the
// windows it counts, which isn't the whole of the account.
func NoteCodexLimits(agent, user string, heard []CodexLimit) {
if len(heard) == 0 || user == "" {
return
}
// a window full: Codex's own account may be out, which the Codex app
// is told only as it opens (CodexMayBeUsedUp)
if agent == "codex" && slices.ContainsFunc(heard, func(h CodexLimit) bool { return h.Used >= 100 }) {
CodexMayBeUsedUp(user)
}
key := agent + "/" + strings.ToLower(user)
c := &loginUsageCache
c.Lock()
if e, ok := c.m[key]; ok {
e.q.Windows = heardWindows(e.q.Windows, heard)
if e.read.Error == "" {
e.read.Windows = heardWindows(e.read.Windows, heard)
}
c.m[key] = e
}
c.Unlock()
u := &usedCache
u.Lock()
defer u.Unlock()
m := u.m[agent]
for name, a := range m {
if !strings.EqualFold(name, user) {
continue
}
// new ones: what was handed out is read without the lock
kept := make(map[string]Allowance, len(m))
for k, v := range m {
kept[k] = v
}
kept[name] = heardAllowance(a, heard)
u.m[agent] = kept
return
}
}
// heardWindows is ws, copied, with each window that counts every model
// and runs as long as one heard taking what was heard.
func heardWindows(ws []QuotaWindow, heard []CodexLimit) []QuotaWindow {
out := make([]QuotaWindow, len(ws))
copy(out, ws)
for i, w := range out {
if w.Aside || w.Model != "" || w.Span == 0 {
continue
}
for _, h := range heard {
if h.Span != w.Span {
continue
}
w.Used = h.Used
if !h.Resets.IsZero() {
t := h.Resets
w.ResetsAt, w.ResetSecs = &t, 0
}
out[i] = w
}
}
return out
}
// heardAllowance is heardWindows for an allowance as routing keeps it.
func heardAllowance(a Allowance, heard []CodexLimit) Allowance {
out := make(Allowance, len(a))
copy(out, a)
for i, l := range out {
if l.Model != "" || l.matches != nil || l.Span == 0 {
continue
}
for _, h := range heard {
if h.Span != l.Span {
continue
}
l.Used = h.Used
if !h.Resets.IsZero() {
l.Resets = h.Resets
}
out[i] = l
}
}
return out
}