routing: an account's model list older than the model is unknown, not a plan without it

wudao_85256 on Discord: two ChatGPT Plus accounts on the Codex
subscription, each serving gpt-6.1-sol alone. With both on, Routing said
of the second "its plan doesn't list gpt-6.1-sol", and once the first ran
out of its allowance nothing failed over: an unlisted account is asked
only after a listing one refuses the model as unserved, never after a 429.
Re-adding the account and refreshing changed nothing.

Cause: the second account's own list (models/codex@<user>.json) was the
evidence, and it was stale. The ChatGPT backend lists gpt-6.1-sol only to
Codex 0.161.0 and later (dd12c75bf), and a saved account's list is asked
once a day, one account a look, for whatever codexVersion() was then (the
0.159.0 fallback before a Codex client has come through). Codex's own
account is asked every hour, so it gained the model and the saved one kept
a list without it for up to a day, every day the race went that way. A
refresh asks the saved lists only when they are a day old, and removing an
account leaves its list behind, so re-adding found the same list.

Fix, for every subscription that keeps each account's own list in the
catalog (Codex, Antigravity):
- catalog: a kept list records Since, when each model was first in it
  (carried from save to save; a list saved before counts from its fetch),
  and Asked, what it was asked as (LiveSince, LiveAsked, SaveLiveAsked).
- provider.AccountsFor: an account whose list lacks the model is left out
  only when that list can know the model: fetched after, or within
  listRound (10 minutes, one look) before, another account's list first
  had it, and, for ChatGPT, asked for the Codex magpie speaks
  as now (codexListBehind; a list with no version kept is behind). Else
  it is unknown, and routed over at its own place in the order
  (Account.listLags). A Free account's list fetched after the Plus one had
  the model still leaves it out (#520).
- codexFetchSaved asks a behind list at once, as one with no list, and
  one fetched more than listRound before another account's list first
  had a model (catalog.LiveNewest); either waits an hour after a failed
  try. Both Codex lists are kept with the version asked.

Not covered: plugin accounts (pluginLists) and Claude's entitlements keep
their lists elsewhere and are unchanged; API keys' per-key lists
(KeysFor) are unchanged. After the update every Codex list saved before
counts as behind until it is asked again (within the hour), so a Free
account beside a Plus one may be asked a Plus-only model in that time
and refuse it, as an unknown list should be.

Tested: TestStaleAccountListIsNotAPlanWithoutTheModel (two Plus accounts,
the second's list asked for 0.159.0 / with no version / fetched before the
first listed the model / the first's list from before Since: both routed;
fetched since, or in the same look, for this version: left out) is red
on the old AccountsFor, 4 of 6 subtests; its same-look subtest is red
with listRound taken out. TestBehindListAskedAgain is red with the behind
branch of codexFetchSaved taken out by hand, and
TestListOlderThanAnothersModelAskedAgain with the LiveNewest rule taken
out. TestLiveSinceCarriesOver. Without listRound,
TestCodexProviderListsEveryAccountsModels and
TestAntigravityPoolRoutesDiscoveredModels went red (a Free list fetched
moments before the Pro one counted as older than the model).
gofmt -l; go vet ./internal/catalog ./internal/provider ./internal/gateway
for darwin, linux and windows; go test ./internal/catalog ./internal/provider
ok on mote; go test -run 'Unlisted|Codex|Pool|Antigravity|Account'
./internal/gateway ok on mote.
Not tried: a real pair of ChatGPT accounts against the backend; the
version gating is the one dd12c75bf read from the backend's error.

Reported-by: wudao_85256 (Discord)
This commit is contained in:
yetone
2026-11-09 18:13:08 +08:00
parent f5f68b4335
commit 2b8ff0fbeb
6 changed files with 500 additions and 13 deletions
+1 -1
View File
@@ -188,7 +188,7 @@ no decision model was discovered (`Test` in
Account discovery can be turned off (#1535): Settings → Privacy → *Subscription accounts*, `magpie accounts discovery off`, or `MAGPIE_NO_ACCOUNTS=1` for one process. The first two save `noAccountDiscovery: true`, which this computer keeps through a sync or a restored backup (`KeepOwn`); the variable only ever turns discovery off, never on what the user saved off (`settings.AccountDiscoveryOff`). It is on by default. In the GUI, Off asks first and names the subscriptions in use that it stops (`discoveryOffWarning` in `app.js`, #1761: a user turned it off without meaning to and was left with no subscription working). While it is off, magpie reads no agent's sign-in: no credential file (`~/.claude/.credentials.json`, `~/.claude.json`'s account, `~/.codex/auth.json` or Codex's keychain item, Copilot's, Cursor's, Devin's, Kiro's, Gemini's, ZCode's, Command Code's, OpenCode's `auth.json`), no Keychain or Secret Service item (`security`, `secret-tool`), and no agent CLI asked who is signed in. The gates sit at each reader (`readAccountFile`, `discoveryOff` in [`discovery.go`](../../internal/provider/discovery.go)) and at each route that would read or write a sign-in: `Accounts` and `All`, `Logins`, usage, renewal, warm-up, session identities, check-ins, switching, forgetting, `SetLoginOn`, `StartSignIn`, the imports, and moves onto plugins (`MoveCandidates`, `HandOver`, `KeepRetiringMoved`). Those that write refuse with `errAccountDiscoveryOff`, which says how to turn it back on. The agents' side is gated too: the Agents page's *runs on* line (`Agent.Source`), OpenCode's own providers (`readOwnAuth`), and wiring Codex, which goes by magpie's stash instead of `auth.json` (`chatGPT` in [`codex.go`](../../internal/agent/codex.go)). Subscriptions aren't served; API-key providers, middleware plugins and Pi extensions run as before. So does a public plugin, one whose every way in is keyless (`publicPlugin` in [`plugin_accounts.go`](../../internal/provider/plugin_accounts.go), OpenCode Zen Free): it holds no account of the user's, so it stays listed and served, and its sign-in goes through (lileo0668: it signed in, then was listed nowhere). Any other plugin's key is refused in `PluginAPIKey`, as its browser sign-in is, rather than saved and listed nowhere. What magpie kept of its own (`logins.json`, `plugin-auth.json`, `migrations.json`) is left as it is, unread for accounts, and serves again once discovery is on. A change takes effect at once (`ForgetAccounts`); no restart is needed.
A signed-in account's model list exists only at its vendor (the ChatGPT backend's `/models` for a Codex sign-in, …), so `FetchNew` asks for the lists not fetched yet. Every front end calls it at start: the window (`startBackend`, then `FetchNewSoon` behind `/api/state`), the TUI (`fetchModelsCmd` in `Init`) and `magpie serve` (#1789, reyoung: the terminal and a headless gateway had offered the built-in Cursor's fallback `auto` alone until the list was fetched by hand). Listing the accounts asks a CLI who is signed in, and a look waits `firstAsk` (3s) for that; `cursor-agent about` asks Cursor's servers and can take longer, so `FetchNew` waits for each CLI asked for the first time (`awaitIdentities` in [`cli_identity.go`](../../internal/provider/cli_identity.go)) and lists the accounts again. It reports whether an account was left without its list (failed, or waiting `newFetchRetry` after a failure): the TUI then asks again a minute later (`modelsRetry`) and `serve` loops the same way, while the window asks again from its pages. A TUI model picker open when the list arrives is filled in place (`relist`), keeping its filter and the model under the cursor. `TestFetchNewAccount` and the TUI's `TestTUIFetchesSubscriptionModels` / `TestTUIAsksAgainForAMissingList` cover it. A list fetched once is not left as it was: the magpie serving the gateway looks every hour ([`KeepAccountsListed`](../../internal/provider/account_relist.go), first two minutes after it starts) and fetches again each signed-in built-in account's list that is 45 minutes old (`accountListAge`, `relistAccounts`), so a model the vendor adds to the plan is served without Refresh or a magpie release (cliff_26651 on Discord: GPT-6.1 Terra, served to ChatGPT accounts from 10-26, missing from Codex through a magpie whose Codex list was fetched on 10-12). A plugin's accounts are `KeepPluginsListed`'s, one switched off isn't asked, and a fetch that fails keeps the list there was. `TestAccountListFollowsTheVendor` and `TestKeepAccountsListedAsks` cover it. The saved ChatGPT accounts behind the one Codex is signed in to are listed with that fetch (`codexFetchSaved`), but not each time: one with no list yet is asked at once, the others once a day (`codexSavedListAge`) and one a look (`codexSavedAtOnce`), the one asked longest ago first, and one that failed waits its day too (`codexSavedAsked`). Asking every switched-on saved account each hour was a burst of `/codex/models` calls from one address for accounts no Codex used (`TestSavedCodexListsOnceADay`). Every call magpie makes about a ChatGPT account, not only `/codex/models` and `/responses` (`codexSign`), carries Codex's `originator` and User-Agent (`codexClientHeaders`, codex-rs `default_headers`): `/wham/usage`, the reset credits and their use (`codexAccountHeaders`), and the token endpoint's refresh and sign-in exchange. The refresh's body is codex-rs's: `client_id`, `grant_type`, `refresh_token` and a `refresh_reason` (`proactive_expiry`, `scheduled` from the keep-alive, `unauthorized_recovery` after a 401, `forced`), with no `scope` (`TestCodexAccountCallsGoAsCodex`, `TestCodexRefreshSaysWhy`).
A signed-in account's model list exists only at its vendor (the ChatGPT backend's `/models` for a Codex sign-in, …), so `FetchNew` asks for the lists not fetched yet. Every front end calls it at start: the window (`startBackend`, then `FetchNewSoon` behind `/api/state`), the TUI (`fetchModelsCmd` in `Init`) and `magpie serve` (#1789, reyoung: the terminal and a headless gateway had offered the built-in Cursor's fallback `auto` alone until the list was fetched by hand). Listing the accounts asks a CLI who is signed in, and a look waits `firstAsk` (3s) for that; `cursor-agent about` asks Cursor's servers and can take longer, so `FetchNew` waits for each CLI asked for the first time (`awaitIdentities` in [`cli_identity.go`](../../internal/provider/cli_identity.go)) and lists the accounts again. It reports whether an account was left without its list (failed, or waiting `newFetchRetry` after a failure): the TUI then asks again a minute later (`modelsRetry`) and `serve` loops the same way, while the window asks again from its pages. A TUI model picker open when the list arrives is filled in place (`relist`), keeping its filter and the model under the cursor. `TestFetchNewAccount` and the TUI's `TestTUIFetchesSubscriptionModels` / `TestTUIAsksAgainForAMissingList` cover it. A list fetched once is not left as it was: the magpie serving the gateway looks every hour ([`KeepAccountsListed`](../../internal/provider/account_relist.go), first two minutes after it starts) and fetches again each signed-in built-in account's list that is 45 minutes old (`accountListAge`, `relistAccounts`), so a model the vendor adds to the plan is served without Refresh or a magpie release (cliff_26651 on Discord: GPT-6.1 Terra, served to ChatGPT accounts from 10-26, missing from Codex through a magpie whose Codex list was fetched on 10-12). A plugin's accounts are `KeepPluginsListed`'s, one switched off isn't asked, and a fetch that fails keeps the list there was. `TestAccountListFollowsTheVendor` and `TestKeepAccountsListedAsks` cover it. The saved ChatGPT accounts behind the one Codex is signed in to are listed with that fetch (`codexFetchSaved`), but not each time: one with no list yet is asked at once, the others once a day (`codexSavedListAge`) and one a look (`codexSavedAtOnce`), the one asked longest ago first, and one that failed waits its day too (`codexSavedAsked`). Asking every switched-on saved account each hour was a burst of `/codex/models` calls from one address for accounts no Codex used (`TestSavedCodexListsOnceADay`). Each list is kept with the Codex version it was asked for (`catalog.SaveLiveAsked`), as the backend lists a model only to a client new enough for it; a saved account's list asked for an older Codex than magpie speaks as now, or kept with no version, is asked at the next look as one with no list, an hour after a failed try (`codexListBehind`, `codexBehindRetry`, `TestBehindListAskedAgain`); so is one fetched more than `listRound` (10 minutes) before another account's list first had a model (`catalog.LiveNewest`, `TestListOlderThanAnothersModelAskedAgain`). An account's own list (Codex's, Antigravity's) is evidence its plan lacks a model only when it can know the model: `AccountsFor` routes over, as unknown, an account whose list was fetched more than `listRound` before another account's list first had the model (lists fetched in one look are the plans' difference; `catalog.LiveSince`, each model's first save kept from save to save) or, for ChatGPT, was asked for an older Codex (`Account.listLags`; wudao_85256 on Discord: the second of two Plus accounts was "its plan doesn't list gpt-6.1-sol" and never failed over to; `TestStaleAccountListIsNotAPlanWithoutTheModel`). Every call magpie makes about a ChatGPT account, not only `/codex/models` and `/responses` (`codexSign`), carries Codex's `originator` and User-Agent (`codexClientHeaders`, codex-rs `default_headers`): `/wham/usage`, the reset credits and their use (`codexAccountHeaders`), and the token endpoint's refresh and sign-in exchange. The refresh's body is codex-rs's: `client_id`, `grant_type`, `refresh_token` and a `refresh_reason` (`proactive_expiry`, `scheduled` from the keep-alive, `unauthorized_recovery` after a 401, `forced`), with no `scope` (`TestCodexAccountCallsGoAsCodex`, `TestCodexRefreshSaysWhy`).
## Runtime path
+94 -2
View File
@@ -42,6 +42,16 @@ type liveFile struct {
// Kinded is set on a list saved since lists keep the models made for
// another API, tagged (Model.Serves): LiveKinded.
Kinded bool `json:"kinded,omitempty"`
// Since is when each model of the list was first in it, as the saves
// before this one had it: what tells a list fetched before a model
// came (another account's list has had it only since) from one that
// leaves it out (LiveSince).
Since map[string]time.Time `json:"since,omitempty"`
// Asked is what the list was asked as, where the vendor's answer
// depends on it: the Codex client version a ChatGPT account's list
// was asked for (the backend lists a model only to a client new
// enough for it). "" when not said, or saved before it was kept.
Asked string `json:"asked,omitempty"`
// byID is the chat models by their id, in the list's order, made
// once a read: asked for every model of a list, a copy and a scan of
// the list each time cost 2,500 models' /v1/models seconds (K.Liu on
@@ -224,7 +234,59 @@ func Chat(ms []Model) []Model {
// SaveLive stores a fetched list; an empty list forgets it.
func SaveLive(provider, base string, models []Model) error {
return SaveLiveSides(provider, base, models, nil)
return saveLive(provider, base, "", models, nil)
}
// SaveLiveAsked is SaveLive for a list whose answer depends on what it was
// asked as (liveFile.Asked), kept beside it for LiveAsked.
func SaveLiveAsked(provider, base, asked string, models []Model) error {
return saveLive(provider, base, asked, models, nil)
}
// LiveAsked is what the provider's fetched list was asked as
// (SaveLiveAsked): "" when it wasn't said, or there is no list.
func LiveAsked(provider string) string {
f, err := readLive(provider)
if err != nil {
return ""
}
return f.Asked
}
// LiveSince is when the provider's fetched list first had model, as far
// as magpie kept it: since the first save that listed it, or, for a list
// saved before that was kept, since that list's own fetch (no earlier
// one is known). ok is false when the list doesn't have it, or there is
// none.
func LiveSince(provider, model string) (since time.Time, ok bool) {
f, err := readLive(provider)
if err != nil || !slices.ContainsFunc(f.Models, func(m Model) bool { return m.ID == model }) {
return time.Time{}, false
}
if t, ok := f.Since[model]; ok {
return t, true
}
return f.Fetched, true
}
// LiveNewest is when the newest model in provider's list was first in it
// (LiveSince); zero when there is no list.
func LiveNewest(provider string) time.Time {
f, err := readLive(provider)
if err != nil {
return time.Time{}
}
var newest time.Time
for _, m := range f.Models {
t, ok := f.Since[m.ID]
if !ok {
t = f.Fetched
}
if t.After(newest) {
newest = t
}
}
return newest
}
// SaveLiveSides is SaveLive, keeping what each endpoint answered with beside
@@ -232,6 +294,10 @@ func SaveLive(provider, base string, models []Model) error {
// their own asks every base, and a base that can't be asked next time has to
// know which of the models were its own to keep (#904).
func SaveLiveSides(provider, base string, models []Model, sides map[string][]Model) error {
return saveLive(provider, base, "", models, sides)
}
func saveLive(provider, base, asked string, models []Model, sides map[string][]Model) error {
p := LivePath(provider)
if len(models) == 0 {
err := os.Remove(p)
@@ -246,7 +312,9 @@ func SaveLiveSides(provider, base string, models []Model, sides map[string][]Mod
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
return err
}
b, _ := json.MarshalIndent(liveFile{Fetched: time.Now(), Base: base, Models: models, Sides: sides, Kinded: true}, "", " ")
now := time.Now()
b, _ := json.MarshalIndent(liveFile{Fetched: now, Base: base, Models: models, Sides: sides, Kinded: true,
Since: liveSince(provider, models, now), Asked: asked}, "", " ")
if err := os.WriteFile(p, b, 0o644); err != nil {
return err
}
@@ -254,6 +322,30 @@ func SaveLiveSides(provider, base string, models []Model, sides map[string][]Mod
return nil
}
// liveSince is Since for models about to be saved for provider at now:
// what the list saved before said of each model it had too, now for one it
// didn't. A list saved before Since was kept had each of its models since
// its fetch at least.
func liveSince(provider string, models []Model, now time.Time) map[string]time.Time {
prev, err := readLive(provider)
out := make(map[string]time.Time, len(models))
for _, m := range models {
if _, ok := out[m.ID]; ok || m.ID == "" {
continue
}
out[m.ID] = now
if err != nil {
continue
}
if t, ok := prev.Since[m.ID]; ok {
out[m.ID] = t
} else if slices.ContainsFunc(prev.Models, func(o Model) bool { return o.ID == m.ID }) {
out[m.ID] = prev.Fetched
}
}
return out
}
// Changed, when set, is told that the models magpie offers may be others
// now: a provider added, edited or removed, a vendor's list fetched anew.
// The agent package sets it, to bring the model lists agents keep in files
+2 -2
View File
@@ -1074,11 +1074,11 @@ func codexAccount(home string) (Provider, bool) {
acct.models = catalog.Codex
acct.listedOnly = true
acct.fetch = func(ctx context.Context) ([]catalog.Model, error) {
ms, err := codexModels(ctx, acct.sign)
ms, ver, err := codexModelsAsked(ctx, acct.sign)
if err != nil {
return nil, err
}
catalog.SaveLive(accountModels("codex", acct.User), CodexBase, ms)
catalog.SaveLiveAsked(accountModels("codex", acct.User), CodexBase, ver, ms)
codexFetchSaved(ctx)
ms = codexPoolModels(ms)
return ms, catalog.SaveLive("codex", CodexBase, ms)
+280
View File
@@ -0,0 +1,280 @@
package provider
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/catalog"
)
// twoPlusAccounts signs Codex in to work@ and keeps me@ beside it, on: the
// two ChatGPT Plus accounts of wudao_85256 on Discord. Magpie speaks as
// Codex 9.0.0 (a client seen through the gateway), so a list asked for an
// older Codex is behind.
func twoPlusAccounts(t *testing.T) Provider {
t.Helper()
home := signIn(t) // me@example.com
rememberLogins(true)
codexSignIn(t, home, "work@example.com", "r-work")
rememberLogins(true) // Codex on work@, me@ saved
if err := SetLoginOn("codex", "me@example.com", true); err != nil {
t.Fatal(err)
}
ForgetCodexClientsForTest()
codexSeen.saw("9.0.0")
t.Cleanup(ForgetCodexClientsForTest)
p, ok := find(All(), "codex")
if !ok || p.Account == nil || p.Account.User != "work@example.com" {
t.Fatalf("codex provider %+v", p)
}
return p
}
// keepList writes one account's own model list as magpie keeps it: fetched
// at, asked for Codex version asked (none when ""), and since, when each
// model was first in it (none kept when nil).
func keepList(t *testing.T, user string, at time.Time, asked string, since map[string]time.Time, ids ...string) {
t.Helper()
var ms []map[string]any
for _, id := range ids {
ms = append(ms, map[string]any{"id": id, "name": id})
}
f := map[string]any{"fetched": at, "base": CodexBase, "models": ms, "kinded": true}
if asked != "" {
f["asked"] = asked
}
if since != nil {
f["since"] = since
}
b, _ := json.Marshal(f)
path := catalog.LivePath(accountModels("codex", user))
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, b, 0o644); err != nil {
t.Fatal(err)
}
}
func usersOf(as []AccountOn) []string {
var out []string
for _, a := range as {
out = append(out, a.Account.User)
}
return out
}
// An account whose own list leaves a model out is "its plan lacks it"
// only when that list can know the model: fetched after another account's
// list first had it, and asked as the Codex magpie speaks as now. A list
// older than that, or asked for an older Codex (the backend lists
// gpt-6.1-sol only to Codex 0.161.0 and later), or one saved before the
// version was kept, says nothing of it: the account is routed over, not
// left out (wudao_85256 on Discord: Routing said "its plan doesn't list
// gpt-6.1-sol" of the second of two Plus accounts, and nothing failed over
// to it once the first ran out). A Free account's list fetched after the
// Plus one had the model still leaves it out (#520).
func TestStaleAccountListIsNotAPlanWithoutTheModel(t *testing.T) {
p := twoPlusAccounts(t)
now := time.Now()
hourAgo, dayAgo := now.Add(-time.Hour), now.Add(-24*time.Hour)
// work@, Codex's own: asked now, has had gpt-6.1-sol for an hour
work := func() {
keepList(t, "work@example.com", now, "9.0.0",
map[string]time.Time{"gpt-5.5": dayAgo, "gpt-6.1-sol": hourAgo}, "gpt-5.5", "gpt-6.1-sol")
}
for _, c := range []struct {
name string
keep func()
left bool
wantOrder []string
}{
{"asked for an older Codex", func() {
work()
keepList(t, "me@example.com", now, "0.159.0", nil, "gpt-5.5")
}, false, nil},
{"version not kept", func() {
work()
keepList(t, "me@example.com", now, "", nil, "gpt-5.5")
}, false, nil},
{"fetched before the model was listed", func() {
work()
keepList(t, "me@example.com", dayAgo, "9.0.0", nil, "gpt-5.5")
}, false, nil},
{"the other's list saved before since was kept", func() {
keepList(t, "work@example.com", now, "9.0.0", nil, "gpt-5.5", "gpt-6.1-sol")
keepList(t, "me@example.com", hourAgo, "9.0.0", nil, "gpt-5.5")
}, false, nil},
{"fetched in the same look: its plan lacks it", func() {
keepList(t, "work@example.com", now, "9.0.0",
map[string]time.Time{"gpt-5.5": dayAgo, "gpt-6.1-sol": now}, "gpt-5.5", "gpt-6.1-sol")
keepList(t, "me@example.com", now.Add(-time.Minute), "9.0.0", nil, "gpt-5.5")
}, true, nil},
{"fetched since, for this Codex: its plan lacks it", func() {
work()
keepList(t, "me@example.com", now, "9.0.0", nil, "gpt-5.5")
}, true, nil},
} {
t.Run(c.name, func(t *testing.T) {
c.keep()
out, left, barred := p.AccountsFor("gpt-6.1-sol", nil)
if len(barred) != 0 {
t.Fatalf("barred %v", usersOf(barred))
}
if c.left {
if !slices.Equal(usersOf(out), []string{"work@example.com"}) || !slices.Equal(usersOf(left), []string{"me@example.com"}) {
t.Fatalf("out %v, left %v; want me@ left out", usersOf(out), usersOf(left))
}
return
}
if len(left) != 0 || len(out) != 2 {
t.Fatalf("out %v, left %v; want both routed over", usersOf(out), usersOf(left))
}
// at their own places: Codex's account first, as before
if out[0].Account.User != "work@example.com" {
t.Errorf("order %v", usersOf(out))
}
})
}
}
// A saved account's list asked for an older Codex is asked again at the
// next look, for the version magpie speaks as now, and kept with it; one
// asked for this version waits its day, as before.
func TestBehindListAskedAgain(t *testing.T) {
twoPlusAccounts(t)
var mu sync.Mutex
var asked []string
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.HasSuffix(r.URL.Path, "/models") {
http.NotFound(w, r)
return
}
mu.Lock()
asked = append(asked, r.URL.Query().Get("client_version"))
mu.Unlock()
json.NewEncoder(w).Encode(map[string]any{"models": []any{
map[string]any{"slug": "gpt-5.5", "visibility": "list", "priority": 1},
map[string]any{"slug": "gpt-6.1-sol", "visibility": "list", "priority": 2},
}})
}))
defer fake.Close()
old := CodexBase
CodexBase = fake.URL + "/backend-api/codex"
t.Cleanup(func() { CodexBase = old })
codexSavedAsked.Lock()
codexSavedAsked.m = map[string]time.Time{}
codexSavedAsked.Unlock()
t.Cleanup(func() {
codexSavedAsked.Lock()
codexSavedAsked.m = map[string]time.Time{}
codexSavedAsked.Unlock()
})
keepList(t, "me@example.com", time.Now(), "0.159.0", nil, "gpt-5.5")
codexFetchSaved(context.Background())
mu.Lock()
got := slices.Clone(asked)
asked = nil
mu.Unlock()
if !slices.Equal(got, []string{"9.0.0"}) {
t.Fatalf("asked %v, want me@'s list asked once for 9.0.0", got)
}
key := accountModels("codex", "me@example.com")
if v := catalog.LiveAsked(key); v != "9.0.0" {
t.Fatalf("kept as asked for %q", v)
}
if _, ok := catalog.LiveSince(key, "gpt-6.1-sol"); !ok {
t.Fatal("the list asked again lacks gpt-6.1-sol")
}
codexFetchSaved(context.Background())
mu.Lock()
defer mu.Unlock()
if len(asked) != 0 {
t.Fatalf("a list asked for this Codex was asked again at once: %v", asked)
}
}
// A saved account's list fetched before another account's list first had a
// model is asked again at the next look, not at its day's end; one fetched
// in the same look as that list waits its day.
func TestListOlderThanAnothersModelAskedAgain(t *testing.T) {
twoPlusAccounts(t)
var mu sync.Mutex
n := 0
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
n++
mu.Unlock()
json.NewEncoder(w).Encode(map[string]any{"models": []any{
map[string]any{"slug": "gpt-5.5", "visibility": "list", "priority": 1},
}})
}))
defer fake.Close()
old := CodexBase
CodexBase = fake.URL + "/backend-api/codex"
t.Cleanup(func() { CodexBase = old })
forget := func() {
codexSavedAsked.Lock()
codexSavedAsked.m = map[string]time.Time{}
codexSavedAsked.Unlock()
}
t.Cleanup(forget)
now := time.Now()
for _, c := range []struct {
name string
gap time.Duration
want int
}{{"fetched an hour before", time.Hour, 1}, {"fetched in the same look", time.Minute, 0}} {
t.Run(c.name, func(t *testing.T) {
forget()
mu.Lock()
n = 0
mu.Unlock()
keepList(t, "work@example.com", now, "9.0.0",
map[string]time.Time{"gpt-5.5": now.Add(-48 * time.Hour), "gpt-6.1-sol": now}, "gpt-5.5", "gpt-6.1-sol")
keepList(t, "me@example.com", now.Add(-c.gap), "9.0.0", nil, "gpt-5.5")
codexFetchSaved(context.Background())
mu.Lock()
defer mu.Unlock()
if n != c.want {
t.Fatalf("me@'s list asked %d times, want %d", n, c.want)
}
})
}
}
// Since carries over from save to save: a model first listed yesterday
// keeps yesterday through today's save, a new one gets today, and a list
// saved before Since was kept counts from its own fetch.
func TestLiveSinceCarriesOver(t *testing.T) {
twoPlusAccounts(t)
key := accountModels("codex", "me@example.com")
dayAgo := time.Now().Add(-24 * time.Hour).Truncate(time.Second)
keepList(t, "me@example.com", dayAgo, "9.0.0", nil, "gpt-5.5")
if s, ok := catalog.LiveSince(key, "gpt-5.5"); !ok || !s.Equal(dayAgo) {
t.Fatalf("old list: since %v %v, want its fetch %v", s, ok, dayAgo)
}
before := time.Now()
if err := catalog.SaveLiveAsked(key, CodexBase, "9.0.0", []catalog.Model{{ID: "gpt-5.5"}, {ID: "gpt-6.1-sol"}}); err != nil {
t.Fatal(err)
}
if s, _ := catalog.LiveSince(key, "gpt-5.5"); !s.Equal(dayAgo) {
t.Errorf("gpt-5.5 since %v, want %v", s, dayAgo)
}
if s, ok := catalog.LiveSince(key, "gpt-6.1-sol"); !ok || s.Before(before) {
t.Errorf("gpt-6.1-sol since %v %v, want now", s, ok)
}
if _, ok := catalog.LiveSince(key, "gpt-9"); ok {
t.Error("a model the list lacks has a since")
}
}
+102 -6
View File
@@ -33,7 +33,21 @@ const codexClientVersion = "0.159.0"
// models_cache.json, but that one is of whichever account Codex CLI last
// asked with, if it ran at all.
func codexModels(ctx context.Context, sign func(context.Context, *http.Request, []byte) error) ([]catalog.Model, error) {
u := CodexBase + "/models?client_version=" + url.QueryEscape(codexVersion())
ms, _, err := codexModelsAsked(ctx, sign)
return ms, err
}
// codexModelsAsked is codexModels, and the client version the list was
// asked for: the backend lists a model only to a client new enough for
// it, so a list is kept with it (codexListBehind).
func codexModelsAsked(ctx context.Context, sign func(context.Context, *http.Request, []byte) error) ([]catalog.Model, string, error) {
ver := codexVersion()
ms, err := codexModelsAt(ctx, sign, ver)
return ms, ver, err
}
func codexModelsAt(ctx context.Context, sign func(context.Context, *http.Request, []byte) error, ver string) ([]catalog.Model, error) {
u := CodexBase + "/models?client_version=" + url.QueryEscape(ver)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return nil, err
@@ -322,6 +336,67 @@ func (a *Account) Lists(model string) bool {
return slices.ContainsFunc(live, func(m catalog.Model) bool { return m.ID == model })
}
// listLags says the account's own list, which leaves model out
// (Lists), can't say the plan lacks it: the list is older than the model,
// as magpie knows it. That is so when an account in listing (those whose
// lists have it) has had it only since after this one's list was fetched,
// the vendor giving the model since, or when a ChatGPT account's list was
// asked for an older Codex than magpie speaks as now, or for one it didn't
// keep, as the backend lists a model only to a client new enough for it
// (wudao_85256 on Discord: two Plus accounts, the second's list asked
// before gpt-6.1-sol was listed to the Codex asking, and Routing said "its
// plan doesn't list gpt-6.1-sol", never asking it, not even with the
// first out of its allowance). Such a list says nothing of the model:
// unknown, the account asked as one that lists it.
func (a *Account) listLags(model string, listing []AccountOn) bool {
if a == nil || a.plugin != nil || a.Agent == "claude" {
return false // their lists are of another kind (pluginLists, claudeLists)
}
key := accountModels(a.Agent, a.User)
_, fetched, ok := catalog.Live(key)
if !ok {
return false
}
if a.Agent == "codex" && codexListBehind(catalog.LiveAsked(key)) {
return true
}
ids := []string{model}
if a.Agent == "antigravity" {
if variants, family := AntigravityVariants(model); family {
ids = ids[:0]
for _, id := range variants {
ids = append(ids, id)
}
}
}
for _, o := range listing {
if o.Account == nil || o.Account.plugin != nil || o.Account.Agent != a.Agent {
continue
}
for _, id := range ids {
if since, ok := catalog.LiveSince(accountModels(o.Account.Agent, o.Account.User), id); ok && since.After(fetched.Add(listRound)) {
return true
}
}
}
return false
}
// listRound is how far apart two accounts' lists may be fetched and still
// count as one look: lists fetched in one refresh are moments apart, and a
// model one has and the other lacks there is the plans' difference, not
// a list older than the model (TestCodexProviderListsEveryAccountsModels,
// TestAntigravityPoolRoutesDiscoveredModels).
const listRound = 10 * time.Minute
// codexListBehind says a ChatGPT account's list asked for Codex version
// asked is behind the one magpie asks as now, or its version wasn't kept:
// a model the backend lists only to a newer client may be missing from it.
func codexListBehind(asked string) bool {
now := codexVersion()
return asked == "" || asked != now && newerVersion(asked, now) != asked
}
// Levels are the reasoning levels the account's own list gives the model —
// a Free ChatGPT plan's may be fewer than a Plus one's — and ok is false
// when that list wasn't fetched, doesn't have the model or gives it none.
@@ -433,9 +508,14 @@ func levelRank(e string) int {
// /codex/models calls from one address for accounts no Codex was using
// (the audit after owl's deactivated accounts, 10-30). A plan's models
// change seldom: once a day, one account a look, so they drift apart.
// codexBehindRetry is how long a saved account's list asked for an older
// Codex (codexListBehind) waits after a try before it is asked again:
// each such list is asked at once, as one with none, but one that keeps
// failing waits.
const (
codexSavedListAge = 24 * time.Hour
codexSavedAtOnce = 1
codexBehindRetry = time.Hour
)
// codexSavedAsked is when each saved account's list was last asked for,
@@ -469,13 +549,29 @@ func codexFetchSaved(ctx context.Context) {
if l.Active || !l.On {
continue
}
_, at, ok := catalog.Live(accountModels("codex", l.User))
key := accountModels("codex", l.User)
_, at, ok := catalog.Live(key)
if !ok {
fresh = append(fresh, due{l.User, at})
continue
}
if a := codexSavedAsked.m[strings.ToLower(l.User)]; a.After(at) {
at = a
asked := codexSavedAsked.m[strings.ToLower(l.User)]
if codexListBehind(catalog.LiveAsked(key)) && now.Sub(asked) >= codexBehindRetry {
// asked for an older Codex than magpie speaks as now: its
// list may lack what the backend lists to the newer one
fresh = append(fresh, due{l.User, at})
continue
}
if now.Sub(asked) >= codexBehindRetry && slices.ContainsFunc(ls, func(o Login) bool {
return !strings.EqualFold(o.User, l.User) && catalog.LiveNewest(accountModels("codex", o.User)).After(at.Add(listRound))
}) {
// another account's list has had a model only since this one
// was fetched: asked again, so it says whether the plan has it
fresh = append(fresh, due{l.User, at})
continue
}
if asked.After(at) {
at = asked
}
if now.Sub(at) >= codexSavedListAge {
stale = append(stale, due{l.User, at})
@@ -491,8 +587,8 @@ func codexFetchSaved(ctx context.Context) {
user := d.user
sign := codexSign(func(ctx context.Context) (string, string, error) { return savedLoginToken(ctx, "codex", user) })
// through the account's own proxy, if it has one
if ms, err := codexModels(ViaLogin(ctx, "codex", user), sign); err == nil {
catalog.SaveLive(accountModels("codex", user), CodexBase, ms)
if ms, ver, err := codexModelsAsked(ViaLogin(ctx, "codex", user), sign); err == nil {
catalog.SaveLiveAsked(accountModels("codex", user), CodexBase, ver, ms)
}
}
}
+21 -2
View File
@@ -58,7 +58,9 @@ func (p Provider) AccountsOn() []AccountOn {
// back (the gateway's usage caps; nil holds none). An account whose list
// lacks the model would only answer 400, so it is in out only when no
// account lists it (by the vendor's own id: an account's list names its
// models by theirs, not by one the user lists one by).
// models by theirs, not by one the user lists one by). A list older than
// the model, as magpie knows it (Account.listLags), is unknown, not a
// plan without it: that account is in out.
func (p Provider) AccountsFor(model string, held func(AccountOn) bool) (out, left, barred []AccountOn) {
all := slices.DeleteFunc(p.AccountsOn(), func(a AccountOn) bool {
if p.AccountServes(a.Account.User, model) {
@@ -77,16 +79,33 @@ func (p Provider) AccountsFor(model string, held func(AccountOn) bool) (out, lef
})
}
own := p.OwnModelID(model)
var lacking []AccountOn
for _, a := range all {
if a.Account.Lists(own) {
out = append(out, a)
} else {
left = append(left, a)
lacking = append(lacking, a)
}
}
if len(out) == 0 {
return all, nil, barred
}
// a list older than the model says nothing of it (listLags): such an
// account is asked as one that lists it, at its own place in the order
listing := slices.Clone(out)
lags := map[int]bool{}
for _, a := range lacking {
if a.Account.listLags(own, listing) {
lags[a.Rank] = true
} else {
left = append(left, a)
}
}
if len(lags) > 0 {
out = slices.DeleteFunc(slices.Clone(all), func(a AccountOn) bool {
return !lags[a.Rank] && !slices.ContainsFunc(listing, func(o AccountOn) bool { return o.Rank == a.Rank })
})
}
return out, left, barred
}