gateway, provider: a Codex account's models say Codex's 272K window, not models.dev's 922K (netube on Discord)

netube's Codex Plus account showed a 922K context window on Routing.
922000 is models.dev's input limit for gpt-5.5, which is OpenAI's API's
window. Codex holds a ChatGPT plan's conversation to the context_window
its own list gives (272000).

There were two causes:
- codex_backend.go's end() took catalog.ContextOf(model) (models.dev) as
  the window for a turn Codex sent natively. It now takes
  provider.CodexWindow(user, slug), and falls back to models.dev's window
  only when no list says. CodexWindow checks, in order: the window the
  user set on the codex provider; the account's own live list; magpie's
  Codex subscription's list; Codex CLI's models_cache.json.
- catalog.parseCodex dropped context_window, so until the live list was
  fetched, a Codex subscription's models (catalog.Codex) fell back to
  models.dev's 922K. That reached the Providers page and Routing
  (WindowOf), the Entry.Context agents are told, and siwcWithCodex. It
  now keeps Context.

Only Codex is affected. A provider on OpenAI's API that serves the same
id keeps models.dev's 922K, and both tests check that.

Tests:
- TestCodexNativeTurnTakesCodexWindow (gateway): a native turn's
  Prompt.Window is 272000 from models_cache.json, 258000 from the
  subscription's live list, and 400000 when the user sets it. An "oai"
  provider's gpt-5.5 stays at 922000.
- TestCodexModelsTakeCodexWindow (provider): checks WindowOf, CodexWindow
  (and 0 for an unlisted slug), and the catalog entry's Context, with an
  OpenAI API provider kept at 922000.

Broken by hand:
- codex_backend reverted to ContextOf: the gateway test went red, with
  922000 in all three cases.
- parseCodex's Context removed: the gateway test went red on its first
  case, and the provider test went red on WindowOf 922000, CodexWindow 0
  and the catalog entry 922000.
- Restored: both green.

Run:
- gofmt -l: clean.
- go vet: darwin, GOOS=linux -tags nogui, GOOS=windows -tags nogui.
- go test -tags nogui -timeout 45m ./... at 7660399a1+this: 64 packages
  ok. internal/agent and internal/gateway hit the 45m timeout under a
  load average of ~270. The running tests were 1s and 6s old
  (TestReseatOff, TestClaudeCodeSeenOnAnyRoute), so this was slowness,
  not a hang.
- Rerun at the rebased head with -timeout 90m: EXIT=0, 66 packages ok, none failed (agent 3761s, gateway 3105s), on cb05dc2d1+this.
- Rebased then onto 252bc61ce (84cd686af and 252bc61ce, internal/agent
  only, none of these files): go build ./..., go vet of gateway, provider,
  catalog and agent, and both new tests green there.
This commit is contained in:
yetone
2026-10-17 16:37:09 +08:00
parent 252bc61ce9
commit 9f9bfc1600
5 changed files with 251 additions and 2 deletions
+4 -1
View File
@@ -1504,7 +1504,10 @@ func parseCodex(b []byte) ([]Model, error) {
if m.Visibility == "hide" || MagpieAdded(cache.ETag, m.Slug, m.Description) {
continue
}
mm := Model{ID: m.Slug, Name: m.DisplayName, Provider: "openai", ImageInput: imageInput(m.Input)}
// the window Codex holds a conversation to (272K on a ChatGPT
// plan), which models.dev's input limit for the id, OpenAI's
// API's (gpt-5.5's 922K), would otherwise stand in for
mm := Model{ID: m.Slug, Name: m.DisplayName, Provider: "openai", ImageInput: imageInput(m.Input), Context: Window(m.Context)}
if m.Max > m.Context && m.Context > 0 {
mm.MaxContext = m.Max
}
+12 -1
View File
@@ -756,6 +756,17 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
replyDigest = titleReplyDigest(titleReply.buf.Bytes(), nil)
}
prompt := promptRead() // outside the trace's lock, which reading it takes
// the window Codex holds the conversation to, not models.dev's
// for the id, which is OpenAI's API's (netube on Discord: 922K
// on Routing for a Codex Plus account's 272K)
window := 0
if prompt != nil {
user := ""
if on != nil && on.Account != nil {
user = on.Account.User
}
window = cmp.Or(provider.CodexWindow(user, model), catalog.ContextOf(model))
}
s.trace.update(tr, func(t *Route) {
t.Tries[0].Done, t.Tries[0].Status, t.Tries[0].Millis, t.Tries[0].Error = true, status, ms, msg
t.Tries[0].TTFT, t.Tries[0].FirstText = ttft, text
@@ -772,7 +783,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
t.Flow, t.Tries[0].Flow = flow, flow
t.Usage = routeUsage("openai", model, uu)
if prompt != nil {
t.Prompt = prompt.calibrated(promptCounted(t.Usage), catalog.ContextOf(model))
t.Prompt = prompt.calibrated(promptCounted(t.Usage), window)
}
t.Tries[0].Served, t.Tries[0].Swapped = served, swapped(model, served)
t.Served, t.Swapped = t.Tries[0].Served, t.Tries[0].Swapped
@@ -0,0 +1,130 @@
package gateway
import (
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
// netube on Discord: a Codex Plus account's turn showed a 922K context
// window on Routing, models.dev's input limit for gpt-5.5 (OpenAI's API's),
// where Codex holds the conversation to the 272K its ChatGPT list gives.
// A turn Codex sends through magpie's Codex backend takes Codex's window;
// one the user set on the codex provider comes first; a model of another
// provider, of the same id, keeps models.dev's.
func TestCodexNativeTurnTakesCodexWindow(t *testing.T) {
chatgpt(t, func(w http.ResponseWriter, r *http.Request) {
w.Header()["Content-Type"] = nil // as the ChatGPT backend sends it
io.WriteString(w, sse(
`data: {"type":"response.created","response":{"id":"r1"}}`,
`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":9000,"output_tokens":2}}}`))
})
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cache := t.TempDir()
t.Setenv("XDG_CACHE_HOME", cache)
os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755)
if err := os.WriteFile(catalog.CachePath(), []byte(`{"openai":{"id":"openai","models":{
"gpt-5.5":{"id":"gpt-5.5","limit":{"context":1050000,"input":922000,"output":128000}}}}}`), 0o644); err != nil {
t.Fatal(err)
}
catalog.Reset()
t.Cleanup(catalog.Reset)
// Codex CLI's own list, as the ChatGPT backend gave it for the plan
codexChatGPTAuth(t, "plus@example.com") // the codex subscription, for its window
codexHome := os.Getenv("CODEX_HOME")
if err := os.WriteFile(filepath.Join(codexHome, "models_cache.json"), []byte(`{"etag":"\"e1\"","client_version":"0.159.0","models":[
{"slug":"gpt-5.5","display_name":"GPT-5.5","priority":1,"visibility":"list","context_window":272000,"max_context_window":272000}]}`), 0o644); err != nil {
t.Fatal(err)
}
s := New()
h := s.Handler()
turn := func() *Route {
t.Helper()
before := len(s.Trace(t.Context(), 0, 0).Routes)
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-5.5","stream":true,"input":[
{"type":"message","role":"user","content":[{"type":"input_text","text":"refactor the parser"}]}]}`))
req.Header.Set("Authorization", "Bearer chatgpt-token")
req.Header.Set("chatgpt-account-id", "acct-1")
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
rs := s.Trace(t.Context(), 0, 0).Routes
if len(rs) != before+1 {
t.Fatalf("%d routes, want %d", len(rs), before+1)
}
for i := range rs {
if rs[i].ID == maxRouteID(rs) {
return &rs[i]
}
}
return nil
}
if r := turn(); r.Prompt == nil || r.Prompt.Window != 272000 {
t.Errorf("Codex's own gpt-5.5: prompt %+v, want Codex's window 272000, not models.dev's 922000", r.Prompt)
}
// the window magpie's Codex subscription's list gives comes before
// Codex CLI's cache
if err := catalog.SaveLive("codex", provider.CodexBase, []catalog.Model{{ID: "gpt-5.5", Context: 258000}}); err != nil {
t.Fatal(err)
}
if r := turn(); r.Prompt == nil || r.Prompt.Window != 258000 {
t.Errorf("with the subscription's list: prompt %+v, want 258000", r.Prompt)
}
// the user's own window on the codex provider is the one Codex is told
if err := provider.Save(provider.Provider{ID: "codex", Contexts: map[string]int{"gpt-5.5": 400000}}); err != nil {
t.Fatal(err)
}
if r := turn(); r.Prompt == nil || r.Prompt.Window != 400000 {
t.Errorf("with a window set: prompt %+v, want the user's 400000", r.Prompt)
}
// another provider's gpt-5.5, on OpenAI's API, keeps models.dev's
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(
`data: {"id":"x","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":"ok"}}]}`,
`data: {"id":"x","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`,
`data: {"id":"x","object":"chat.completion.chunk","choices":[],"usage":{"prompt_tokens":9000,"completion_tokens":5}}`,
`data: [DONE]`))
}))
defer up.Close()
if err := provider.Save(provider.Provider{ID: "oai", Name: "OAI", Key: "k", Models: []string{"gpt-5.5"}, Chat: up.URL + "/v1"}); err != nil {
t.Fatal(err)
}
before := len(s.Trace(t.Context(), 0, 0).Routes)
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(`{"model":"oai/gpt-5.5","stream":true,"input":[
{"type":"message","role":"user","content":[{"type":"input_text","text":"refactor the parser"}]}]}`))
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("oai: %d %s", rec.Code, rec.Body)
}
rs := s.Trace(t.Context(), 0, 0).Routes
if len(rs) != before+1 {
t.Fatalf("%d routes, want %d", len(rs), before+1)
}
for _, r := range rs {
if r.ID == maxRouteID(rs) && (r.Prompt == nil || r.Prompt.Window != 922000) {
t.Errorf("another provider's gpt-5.5: prompt %+v, want models.dev's 922000", r.Prompt)
}
}
}
func maxRouteID(rs []Route) int64 {
var n int64
for _, r := range rs {
n = max(n, r.ID)
}
return n
}
+34
View File
@@ -586,6 +586,40 @@ func CodexNativeWindow(restore bool) func(slug string) (n, most int, ok bool) {
}
}
// CodexWindow is the context window Codex works in for one of its own
// models, by the backend's slug, for a request to the ChatGPT backend or
// OpenAI's API that Codex sent through magpie: the window the user set on
// the codex provider, else the one the account's own list gives (user, ""
// for any), else magpie's Codex subscription's, else Codex CLI's
// models_cache.json's; 0 when none says. models.dev's input limit for the
// same id is OpenAI's API's (gpt-5.5's 922K), not the window Codex holds
// a conversation to (272K): netube on Discord saw Routing say 922K for a
// Codex Plus account.
func CodexWindow(user, slug string) int {
p, _ := find(All(), "codex")
if n := p.ContextOf(slug); n > 0 {
return n
}
var lists [][]catalog.Model
if user != "" {
if live, _, ok := catalog.Live(accountModels("codex", user)); ok {
lists = append(lists, live)
}
}
if live, _, ok := catalog.Live("codex"); ok {
lists = append(lists, live)
}
lists = append(lists, catalog.Codex())
for _, ms := range lists {
for _, m := range ms {
if n := catalog.Window(m.Context); m.ID == slug && n > 0 {
return n
}
}
}
return 0
}
// codexWindowsTag is the windows the user set on the codex provider, for
// the ETag of Codex's list: setting one, or taking it away, has Codex ask
// for the list again.
+71
View File
@@ -0,0 +1,71 @@
package provider
import (
"os"
"path/filepath"
"testing"
"github.com/yetone/magpie/internal/catalog"
)
// netube on Discord: a Codex Plus account's gpt-5.5 said 922K, models.dev's
// input limit for the id (OpenAI's API's), where Codex holds it to the 272K
// its ChatGPT list gives. Before the subscription's own list is fetched,
// its models are Codex CLI's models_cache.json's, and their window is that
// list's: on the Providers and Routing pages (WindowOf), in the catalog
// agents are told (Entry.Context) and in CodexWindow. A provider on
// OpenAI's API serving the same id keeps models.dev's.
func TestCodexModelsTakeCodexWindow(t *testing.T) {
home := signIn(t)
cache := catalog.CachePath()
os.MkdirAll(filepath.Dir(cache), 0o755)
if err := os.WriteFile(cache, []byte(`{"openai":{"id":"openai","models":{
"gpt-5.5":{"id":"gpt-5.5","limit":{"context":1050000,"input":922000,"output":128000}}}}}`), 0o644); err != nil {
t.Fatal(err)
}
catalog.Reset()
t.Cleanup(catalog.Reset)
if err := os.WriteFile(filepath.Join(home, ".codex", "models_cache.json"), []byte(`{"etag":"\"e1\"","client_version":"0.159.0","models":[
{"slug":"gpt-5.5","display_name":"GPT-5.5","priority":1,"visibility":"list","context_window":272000,"max_context_window":272000}]}`), 0o644); err != nil {
t.Fatal(err)
}
ForgetAccounts()
t.Cleanup(ForgetAccounts)
p, ok := codexAccount(home)
if !ok {
t.Fatal("no Codex sign-in")
}
var got int
for _, m := range p.Available() {
if m.ID == "gpt-5.5" {
got = p.WindowOf(m)
}
}
if got != 272000 {
t.Errorf("Codex subscription's gpt-5.5 window %d, want Codex's 272000, not models.dev's 922000", got)
}
if n := CodexWindow("", "gpt-5.5"); n != 272000 {
t.Errorf("CodexWindow(gpt-5.5) = %d, want 272000", n)
}
if n := CodexWindow("", "gpt-unlisted"); n != 0 {
t.Errorf("CodexWindow(gpt-unlisted) = %d, want 0: no list says", n)
}
for _, e := range Catalog() {
if e.Provider.ID == "codex" && e.Model == "gpt-5.5" && e.Context != 272000 {
t.Errorf("catalog entry %s told agents %d, want 272000", e.ID, e.Context)
}
}
// the same id on OpenAI's API is models.dev's, as before
oai := Provider{ID: "oai", Name: "OAI", Key: "k", Catalog: "openai", Responses: "https://api.example.invalid/v1"}
got = 0
for _, m := range oai.Available() {
if m.ID == "gpt-5.5" {
got = oai.WindowOf(m)
}
}
if got != 922000 {
t.Errorf("OpenAI API gpt-5.5 window %d, want models.dev's 922000", got)
}
}