From 9f7b6bd86c04c67e02160b1fbdfbcfff4ddfb1b2 Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 3 Oct 2026 21:38:19 +0800 Subject: [PATCH] =?UTF-8?q?codex:=20a=20cached=20entry=20keeps=20the=20cac?= =?UTF-8?q?he's=20own=20max=20when=20magpie's=20list=20has=20none,=20and?= =?UTF-8?q?=20Codex's=20models=5Fcache.json=20is=20read=20under=20CODEX=5F?= =?UTF-8?q?HOME=20everywhere=20(follow-up=20to=20#674,=20from=20reviewing?= =?UTF-8?q?=20#679)=20=E2=80=94=20restoring=20a=20cached=20native=20entry?= =?UTF-8?q?=20(backend=20away)=20set=20max=5Fcontext=5Fwindow=20to=20max(M?= =?UTF-8?q?axContext,=20Context)=20from=20magpie's=20live=20list,=20so=20a?= =?UTF-8?q?=20list=20saved=20without=20the=20max=20(before=20magpie=20kept?= =?UTF-8?q?=20it)=20wrote=20the=20window=20over=20the=20cache's=20own=20(8?= =?UTF-8?q?72000=20became=20272000);=20now=20a=20list=20with=20no=20max=20?= =?UTF-8?q?leaves=20the=20cache's,=20and=20codexcat.Window=20still=20raise?= =?UTF-8?q?s=20it=20to=20a=20window=20past=20it.=20codexcat.CacheEntries?= =?UTF-8?q?=20and=20catalog.Codex=20read=20~/.codex/models=5Fcache.json=20?= =?UTF-8?q?even=20with=20CODEX=5FHOME=20set,=20while=20codexVersion=20and?= =?UTF-8?q?=20codexInstructions=20followed=20it;=20all=20four=20now=20take?= =?UTF-8?q?=20catalog.CodexModelsCache()=20(CODEX=5FHOME,=20else=20~/.code?= =?UTF-8?q?x),=20and=20provider's=20codexCLIHome=20and=20the=20copy=20in?= =?UTF-8?q?=20codexInstructions=20are=20gone.=20TestCodexReadsCacheUnderCo?= =?UTF-8?q?dexHome,=20TestCodexCachedListUnderCodexHomeKeepsItsMax=20and?= =?UTF-8?q?=20TestCodexCatalogEntryFromCodexHome=20fail=20on=20the=20old?= =?UTF-8?q?=20code=20(the=20~/.codex=20cache=20read,=20none=20listed=20fro?= =?UTF-8?q?m=20CODEX=5FHOME);=20TestCodexNativeModelsTakeSetWindows=20now?= =?UTF-8?q?=20wants=20a=20cached=20gpt-5.5=20with=20no=20live=20max=20to?= =?UTF-8?q?=20keep=20the=20cache's=20400000=20(old=20code:=20272000).=20go?= =?UTF-8?q?=20vet,=20builds=20(darwin,=20GOOS=3Dlinux,=20GOOS=3Dwindows)?= =?UTF-8?q?=20and=20go=20test=20-tags=20nogui=20-count=3D1=20./...=20under?= =?UTF-8?q?=20a=20temp=20HOME=20pass=20but=20TestProvidersAnswerWhileLists?= =?UTF-8?q?ComeIn,=20a=20timing=20test=20that=20passes=20alone.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/catalog/catalog.go | 15 ++- internal/catalog/codex_home_test.go | 22 +++++ internal/codexcat/codexcat.go | 3 +- internal/gateway/codex_cache_home_test.go | 91 +++++++++++++++++++ internal/gateway/codex_native_context_test.go | 5 +- internal/provider/codex_models.go | 16 +--- internal/provider/codex_request.go | 7 +- 7 files changed, 136 insertions(+), 23 deletions(-) create mode 100644 internal/catalog/codex_home_test.go create mode 100644 internal/gateway/codex_cache_home_test.go diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index 0324d25cf..a62432ab0 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -769,11 +769,22 @@ func Providers() []string { return ids } +// CodexHome is where Codex CLI keeps its state: $CODEX_HOME, else ~/.codex. +func CodexHome() string { + if dir := os.Getenv("CODEX_HOME"); dir != "" { + return dir + } + home, _ := os.UserHomeDir() + return filepath.Join(home, ".codex") +} + +// CodexModelsCache is the model list Codex CLI keeps, under CodexHome. +func CodexModelsCache() string { return filepath.Join(CodexHome(), "models_cache.json") } + // Codex returns the models Codex itself lists, straight from the cache the // Codex CLI writes; there is no compiled-in list to fall back to. func Codex() []Model { - home, _ := os.UserHomeDir() - out, _ := filememo.Read("codex models", filepath.Join(home, ".codex", "models_cache.json"), parseCodex) + out, _ := filememo.Read("codex models", CodexModelsCache(), parseCodex) return slices.Clone(out) } diff --git a/internal/catalog/codex_home_test.go b/internal/catalog/codex_home_test.go new file mode 100644 index 000000000..199961eaa --- /dev/null +++ b/internal/catalog/codex_home_test.go @@ -0,0 +1,22 @@ +package catalog + +import ( + "os" + "path/filepath" + "testing" +) + +// Codex's own models are read from the cache under CODEX_HOME when it is +// set, as Codex CLI writes it there, not from ~/.codex. +func TestCodexReadsCacheUnderCodexHome(t *testing.T) { + home, codexHome := t.TempDir(), t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("CODEX_HOME", codexHome) + os.MkdirAll(filepath.Join(home, ".codex"), 0o755) + os.WriteFile(filepath.Join(home, ".codex", "models_cache.json"), []byte(`{"models":[{"slug":"in-home","visibility":"list"}]}`), 0o644) + os.WriteFile(filepath.Join(codexHome, "models_cache.json"), []byte(`{"models":[{"slug":"in-codex-home","visibility":"list"}]}`), 0o644) + if ms := Codex(); len(ms) != 1 || ms[0].ID != "in-codex-home" { + t.Errorf("Codex() = %+v, want in-codex-home alone", ms) + } +} diff --git a/internal/codexcat/codexcat.go b/internal/codexcat/codexcat.go index a7e9531fb..c76c20251 100644 --- a/internal/codexcat/codexcat.go +++ b/internal/codexcat/codexcat.go @@ -164,8 +164,7 @@ func Entries(ms []catalog.Model, after int) []any { // CacheEntries is Codex's own models, as models_cache.json describes them // for the ChatGPT account it last asked with, by slug. func CacheEntries() map[string]map[string]any { - home, _ := os.UserHomeDir() - b, err := os.ReadFile(filepath.Join(home, ".codex", "models_cache.json")) + b, err := os.ReadFile(catalog.CodexModelsCache()) if err != nil { return nil } diff --git a/internal/gateway/codex_cache_home_test.go b/internal/gateway/codex_cache_home_test.go new file mode 100644 index 000000000..176d8ea20 --- /dev/null +++ b/internal/gateway/codex_cache_home_test.go @@ -0,0 +1,91 @@ +package gateway + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/codexcat" + "github.com/yetone/magpie/internal/provider" +) + +// With the backend away, the list a ChatGPT sign-in is handed is made from +// Codex's cache — the one under CODEX_HOME when it is set, as Codex keeps +// it there. A cached entry restored to the account's own window keeps the +// cache's max when magpie's live list has none (one saved before magpie +// kept the max): 872000 stays, it doesn't fall to the window. +func TestCodexCachedListUnderCodexHomeKeepsItsMax(t *testing.T) { + codexSignedIn(t) + codexHome := t.TempDir() + t.Setenv("CODEX_HOME", codexHome) + // magpie handed Codex 600000 earlier; the window is no longer set + os.WriteFile(filepath.Join(codexHome, "models_cache.json"), []byte(`{"etag":"\"v1\"","models":[ + {"slug":"gpt-6.1-sol","priority":1,"context_window":600000,"max_context_window":872000,"base_instructions":"sol prompt"}, + {"slug":"gpt-6-astra","priority":2,"context_window":272000,"max_context_window":272000}]}`), 0o644) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(500) })) + defer up.Close() + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + defer func() { provider.CodexBase = was }() + // the live list: one without a max, one with a max past the cache's + catalog.SaveLive("codex", provider.CodexBase, []catalog.Model{ + {ID: "gpt-6.1-sol", Context: 272000}, + {ID: "gpt-6-astra", Context: 272000, MaxContext: 872000}, + }) + + rec := httptest.NewRecorder() + req := httptest.NewRequest("GET", CodexPath+"/models", nil) + req.Header.Set("Authorization", "Bearer chatgpt-token") + New().Handler().ServeHTTP(rec, req) + var got struct { + Models []struct { + Slug string `json:"slug"` + Context int `json:"context_window"` + Max int `json:"max_context_window"` + Prompt string `json:"base_instructions"` + } `json:"models"` + } + json.Unmarshal(rec.Body.Bytes(), &got) + want := map[string][2]int{"gpt-6.1-sol": {272000, 872000}, "gpt-6-astra": {272000, 872000}} + seen := 0 + for _, m := range got.Models { + w, ok := want[m.Slug] + if !ok { + continue + } + seen++ + if m.Context != w[0] || m.Max != w[1] { + t.Errorf("cached %s %d/%d, want %d/%d", m.Slug, m.Context, m.Max, w[0], w[1]) + } + if m.Slug == "gpt-6.1-sol" && m.Prompt != "sol prompt" { + t.Errorf("cached gpt-6.1-sol prompt %q, want the cache's", m.Prompt) + } + } + if seen != len(want) { + t.Fatalf("%d of the cache's models listed, want %d (from CODEX_HOME): %s", seen, len(want), rec.Body.String()) + } +} + +// A ChatGPT account's model in a catalog magpie writes takes its entry from +// the cache under CODEX_HOME when it is set. +func TestCodexCatalogEntryFromCodexHome(t *testing.T) { + codexSignedIn(t) + codexHome := t.TempDir() + t.Setenv("CODEX_HOME", codexHome) + os.WriteFile(filepath.Join(codexHome, "models_cache.json"), []byte(`{"etag":"\"v1\"","models":[ + {"slug":"gpt-6.1-sol","context_window":272000,"max_context_window":872000,"base_instructions":"sol prompt"}]}`), 0o644) + es := codexcat.Entries([]catalog.Model{{ID: "codex/gpt-6.1-sol", Name: "Sol", Context: 272000}}, 0) + b, _ := json.Marshal(es[0]) + var e struct { + Max int `json:"max_context_window"` + Prompt string `json:"base_instructions"` + } + json.Unmarshal(b, &e) + if e.Prompt != "sol prompt" || e.Max != 872000 { + t.Errorf("entry max %d, prompt %.20q, want the CODEX_HOME cache's 872000 and \"sol prompt\"", e.Max, e.Prompt) + } +} diff --git a/internal/gateway/codex_native_context_test.go b/internal/gateway/codex_native_context_test.go index 1b41d0426..29b4c51a2 100644 --- a/internal/gateway/codex_native_context_test.go +++ b/internal/gateway/codex_native_context_test.go @@ -112,8 +112,9 @@ func TestCodexNativeModelsTakeSetWindows(t *testing.T) { if c, x := window(got["gpt-6.1-sol"]); c != 272000 || x != 872000 { t.Errorf("cached gpt-6.1-sol %d/%d, want 272000/872000", c, x) } - if c, x := window(got["gpt-5.5"]); c != 272000 || x != 272000 { - t.Errorf("cached gpt-5.5 %d/%d, want 272000/272000", c, x) + // the live list has no max for it: the cache's own stays + if c, x := window(got["gpt-5.5"]); c != 272000 || x != 400000 { + t.Errorf("cached gpt-5.5 %d/%d, want 272000/400000", c, x) } } diff --git a/internal/provider/codex_models.go b/internal/provider/codex_models.go index 6b99a2d94..c03a39531 100644 --- a/internal/provider/codex_models.go +++ b/internal/provider/codex_models.go @@ -85,7 +85,7 @@ func codexVersion() string { var c struct { ClientVersion string `json:"client_version"` } - if b, err := os.ReadFile(filepath.Join(codexCLIHome(), "models_cache.json")); err == nil && json.Unmarshal(b, &c) == nil { + if b, err := os.ReadFile(catalog.CodexModelsCache()); err == nil && json.Unmarshal(b, &c) == nil { newer(c.ClientVersion) } if exe := codexExecutable(); exe != "" { @@ -100,15 +100,6 @@ func codexVersion() string { return newerVersion(codexVersionCache.v, codexSeen.get()) } -// codexCLIHome is where Codex CLI keeps its state: CODEX_HOME, else ~/.codex. -func codexCLIHome() string { - if dir := os.Getenv("CODEX_HOME"); dir != "" { - return dir - } - home, _ := os.UserHomeDir() - return filepath.Join(home, ".codex") -} - // newerVersion is the later of two versions, a when b isn't one. func newerVersion(a, b string) string { if b = claudeSemverRE.FindString(b); b != "" && (a == "" || compareClaudeVersion(b, a) > 0) { @@ -425,7 +416,10 @@ func CodexNativeWindow(restore bool) func(slug string) (n, most int, ok bool) { } for _, m := range live { if m.ID == slug && m.Context > 0 { - return m.Context, max(m.MaxContext, m.Context), true + // a list without the max (saved before magpie kept + // it) leaves the cache's own; Window still raises it to + // the window when it's below + return m.Context, m.MaxContext, true } } return 0, 0, false diff --git a/internal/provider/codex_request.go b/internal/provider/codex_request.go index 511b614df..4509d3240 100644 --- a/internal/provider/codex_request.go +++ b/internal/provider/codex_request.go @@ -227,12 +227,7 @@ func codexInstructions(model string) string { }); ok { return s } - dir := os.Getenv("CODEX_HOME") - if dir == "" { - home, _ := os.UserHomeDir() - dir = filepath.Join(home, ".codex") - } - if s, ok := codexCLIPrompts.get(filepath.Join(dir, "models_cache.json"), model, codexPrompts); ok { + if s, ok := codexCLIPrompts.get(catalog.CodexModelsCache(), model, codexPrompts); ok { return s } return codexcat.Prompt