Files
magpie/internal/gateway/codex_app_list_test.go
T
yetone 2503520f82 codexcat: each Codex model takes official Codex's own instructions for it (#3759, #4008, #4783)
Every magpie model in Codex's catalog (model_catalog_json) carried
gpt-5.2-codex_prompt.md ("You are Codex, based on GPT-5"), so a magpie
GPT-6 model, the auto group's included, ran on a GPT-5.2-era prompt while
official Codex sends GPT-6's own template. magpie still writes no words of
its own into the prompt and leaves the identity line alone: each entry now
takes the text official Codex sends that model, word for word.

- A model's slug (the id's last segment) is matched as Codex 0.166
  matches one (longest prefix of an official slug): first in the entries
  the user's ChatGPT account handed this Codex (models_cache.json), whose
  base_instructions and model_messages go over as sent; then in Codex
  rust-v0.166.0's bundled models.json (instructions_template only, as an
  older Codex may not read 0.166's model_messages), embedded as
  codex_instructions.json.
- Any other model, and a routing group, takes Codex's prompt for a model
  it doesn't know (models-manager/prompt.md, model_info_from_slug), which
  replaces codex_prompt.md: that is what official Codex sends it.
- ownEntry with no base_instructions, and internal/provider's
  codexInstructions fallback, take the same official text.
- testdata holds Codex's models.json and prompt.md at rust-v0.166.0;
  TestBundledIsCodexOwn fails when the embedded copies drift from them.
- GET /v1/codex/models (a remote Codex's model_catalog_url): entries are
  now ~21 KB, so Codex before 0.166's 1 MiB cap holds about 48 of them
  (was ~125). Codex 0.166 reads the catalog whole (models_endpoint.rs
  passes no body limit), and it sends ?client_version=, so the cap now
  applies only to a Codex below 0.166 or one that doesn't say
  (codexReadsWholeCatalog). docs/reference.md says so.
- docs/subsystems/agent-wiring.md: a "Codex instructions" row. The
  Antigravity cloak's comment no longer calls the GPT-5 prompt magpie's.

Run (mote's disk is full, 100% with other sessions' runs, so on WSL
magpie-desktop through wsl-run):
- go test ./internal/codexcat/: ok. go vet -tags nogui ./... and
  GOOS=windows go vet ./...: ok. gofmt -l: clean.
- go test -tags nogui -count=1 -timeout 45m codexcat, provider, agent,
  gui, gateway (every package that imports codexcat): codexcat, provider,
  gui ok. agent: TestGrokInstalled and TestOmpDetectedWithPiDir red, the
  same at origin/main 276c806db on the same box (#3548, #4033: WSL binfmt
  and install detection). gateway: TestCodexCatalogFitsCodexsLimit and
  TestCodexCatalogKeepsTheKeysUsedModelsFirst red from this change (the
  1 MiB cap, fixed above; both ok after, with every TestCodexCatalog*,
  TestCodexListed*, TestCodexApp*), and TestUnroutedHeldReportSaved, red
  only in the full run, ok alone here and at origin/main (#4300).
- Real Codex 0.166.0 (npm) in a sandbox HOME/CODEX_HOME, model_catalog_json
  from this codexcat, against a fake Responses gateway on 127.0.0.1:38611
  capturing each request: 0.166 sends the instructions as the first
  developer message (no top-level instructions). For magpie/gpt-6-astra it
  equals gpt-6-astra's instructions_template in Codex's models.json, byte
  for byte; for magpie/deepseek-v4-pro it equals prompt.md.

- After rebasing on origin/main 9da9bfabd: go vet (linux, windows) of
  codexcat, gateway, provider ok; codexcat ok; -run
  "Codex|Antigravity|Grok" in gateway and provider ok. Then rebased
  onto 546cdbde6 (7 commits in redact, gateway translation and a GUI
  test, none in codexcat or the Codex catalog) and not run again.

Broken by hand:
- The cap held for every client_version: both catalog tests FAIL (47
  listed for 0.166.0, 0.167.0-alpha.1 and 1.0.0).
- Old codex_prompt.md and Prompt everywhere: TestBundledIsCodexOwn,
  TestThirdPartyModelsTakeCodexOwnInstructions (all 7 slugs started "You
  are Codex, based on GPT-5"), TestThirdPartyModelsTakeCachedEntry,
  TestOwnEntryInstructions and TestCodexCatalogKeepsOwnEntries FAIL.
- The same real Codex run on origin/main's codexcat: both models' first
  developer message is the 7.5K GPT-5 prompt, differing from the official
  text at byte 15 (astra) and 8 (deepseek).

Not tried:
- GOOS=darwin go vet (needs mote, full).
- Reading the bundled catalog from the user's installed Codex binary;
  the snapshot is 0.166's, and a Codex release with new templates needs
  testdata and codex_instructions.json refreshed.
- An Antigravity account with Codex's unknown-model prompt ("You are a
  coding agent running in the Codex CLI"): the cloak breaks only the
  GPT-5 identity lines tried before.
- A remote Codex below 0.166 with many models through a gateway key: it
  lists fewer than before; the used ones FitOwn moves into the first 100
  can fall past the 48 that fit.
- A real ChatGPT account's models_cache.json entries (tested with a
  fixture cache).
2026-11-01 22:30:51 +08:00

187 lines
7.5 KiB
Go

package gateway
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"slices"
"testing"
"time"
"github.com/yetone/magpie/internal/codexcat"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// The Codex app and its VS Code extension show the first 100 of Codex's
// model list by priority, hidden ones counted, and never ask for the rest
// (@ZhenLuoTTAWDTT on X: with magpie's models in it, the ones past that
// couldn't be shown or chosen). The list magpie hands Codex puts the
// account's hidden models last and brings the ones the user used into the
// first 100; its ETag changes when Codex uses another, so Codex asks again.
func TestCodexModelListKeepsUsedModelsInTheAppsHundred(t *testing.T) {
codexSignedIn(t)
if err := provider.Save(provider.Provider{ID: "codex", Models: []string{"gpt-5.5"}}); err != nil {
t.Fatal(err)
}
var ms []string
for i := range 130 {
ms = append(ms, fmt.Sprintf("model-%03d", i))
}
if err := provider.Save(provider.Provider{ID: "many", Name: "Many", Key: "k", Chat: "http://127.0.0.1:9/v1", Models: ms}); err != nil {
t.Fatal(err)
}
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("ETag", `"v1"`)
io.WriteString(w, `{"models":[{"slug":"codex-auto-review","priority":0,"visibility":"hide"},{"slug":"gpt-5.5","priority":1,"visibility":"list"}]}`)
}))
defer up.Close()
was := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
defer func() { provider.CodexBase = was }()
list := func() ([]string, string) {
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 []map[string]any `json:"models"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
slices.SortStableFunc(got.Models, func(a, b map[string]any) int {
return int(a["priority"].(float64) - b["priority"].(float64))
})
var out []string
for _, m := range got.Models {
out = append(out, m["slug"].(string))
}
return out, rec.Header().Get("ETag")
}
usage.Append(usage.Record{Time: time.Now().Add(-time.Hour), Agent: "codex", Provider: "many", Requested: "many/model-120", Status: 200})
got, tag := list()
if len(got) != 132 {
t.Fatalf("%d models", len(got))
}
first := got[:codexcat.AppList]
if slices.Contains(first, "codex-auto-review") || got[len(got)-1] != "codex-auto-review" {
t.Errorf("the hidden codex-auto-review is at %d of %d", slices.Index(got, "codex-auto-review")+1, len(got))
}
if !slices.Contains(first, "many/model-120") {
t.Errorf("the used many/model-120 is at %d, past the %d the Codex app reads", slices.Index(got, "many/model-120")+1, codexcat.AppList)
}
if first[0] != "gpt-5.5" || first[1] != "many/model-000" {
t.Errorf("the top is %v", first[:2])
}
usage.Append(usage.Record{Time: time.Now(), Agent: "codex", Provider: "many", Requested: "many/model-125", Status: 200})
got, tag2 := list()
if !slices.Contains(got[:codexcat.AppList], "many/model-125") {
t.Errorf("the newly used many/model-125 is at %d", slices.Index(got, "many/model-125")+1)
}
if tag2 == tag {
t.Errorf("the ETag %q didn't change with the models used", tag)
}
}
// The catalog a Codex on another computer reads puts the models that key's
// Codex used in the first 100, and no other key's. Codex 0.166 reads the
// catalog whole; an older one is held to 1 MiB, about 48 entries
// (TestCodexCatalogFitsCodexsLimit).
func TestCodexCatalogKeepsTheKeysUsedModelsFirst(t *testing.T) {
fresh(t)
var ms []string
for i := range 130 {
ms = append(ms, fmt.Sprintf("model-%03d", i))
}
if err := provider.Save(provider.Provider{ID: "many", Name: "Many", Key: "k", Chat: "http://127.0.0.1:9/v1", Models: ms}); err != nil {
t.Fatal(err)
}
usage.Append(usage.Record{Time: time.Now().Add(-time.Hour), Agent: "codex", Provider: "many", Requested: "many/model-110", Status: 200})
usage.Append(usage.Record{Time: time.Now().Add(-time.Hour), Agent: "codex", Provider: "many", Requested: "many/model-111", CallerKeyID: "someone-else", Status: 200})
w := httptest.NewRecorder()
New().Handler().ServeHTTP(w, httptest.NewRequest("GET", CodexCatalogPath+"?client_version=0.166.0", nil))
var list struct {
Models []map[string]any `json:"models"`
}
if err := json.Unmarshal(w.Body.Bytes(), &list); err != nil {
t.Fatal(err)
}
at := map[string]float64{}
for _, m := range list.Models {
at[m["slug"].(string)] = m["priority"].(float64)
}
if p := at["many/model-110"]; p == 0 || p > codexcat.AppList {
t.Errorf("the used many/model-110's priority is %v", p)
}
if p := at["many/model-111"]; p <= codexcat.AppList {
t.Errorf("another key's many/model-111 was brought up, to %v", p)
}
}
// maiya (Discord): after an update the Codex app showed magpie's models
// and none of Codex's own GPT ones. With an order of Codex's models set on
// the Agents page while its list had no Codex section (the codex provider
// kept for routing groups before a3ee00c05, Codex not signed in yet, or a
// GPT model OpenAI added since), the order names 100 or more of magpie's
// and none of the account's, so Order put every own one after them, past
// the 100 the Codex app reads. The account's own listed models are kept
// in the first 100, wherever the order put them; a hidden one stays last.
func TestCodexModelListKeepsOwnModelsInTheAppsHundred(t *testing.T) {
codexSignedIn(t)
var ms, order []string
for i := range 130 {
ms = append(ms, fmt.Sprintf("model-%03d", i))
order = append(order, fmt.Sprintf("many/model-%03d", i))
}
if err := provider.Save(provider.Provider{ID: "many", Name: "Many", Key: "k", Chat: "http://127.0.0.1:9/v1", Models: ms}); err != nil {
t.Fatal(err)
}
if err := provider.SetModelOrder("codex", order); err != nil {
t.Fatal(err)
}
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("ETag", `"v1"`)
io.WriteString(w, `{"models":[{"slug":"codex-auto-review","priority":0,"visibility":"hide"},{"slug":"gpt-6-sol","priority":1,"visibility":"list"},{"slug":"gpt-5.5","priority":2,"visibility":"list"}]}`)
}))
defer up.Close()
was := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
defer func() { provider.CodexBase = was }()
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 []map[string]any `json:"models"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
slices.SortStableFunc(got.Models, func(a, b map[string]any) int {
return int(a["priority"].(float64) - b["priority"].(float64))
})
var order2 []string
for _, m := range got.Models {
order2 = append(order2, m["slug"].(string))
}
if len(order2) != 133 {
t.Fatalf("%d models", len(order2))
}
first := order2[:codexcat.AppList]
for _, s := range []string{"gpt-6-sol", "gpt-5.5"} {
if !slices.Contains(first, s) {
t.Errorf("Codex's own %s is at %d, past the %d the Codex app reads", s, slices.Index(order2, s)+1, codexcat.AppList)
}
}
if order2[len(order2)-1] != "codex-auto-review" {
t.Errorf("the hidden codex-auto-review is at %d of %d", slices.Index(order2, "codex-auto-review")+1, len(order2))
}
// the user's order holds for the rest: magpie's first 98 as they put them
if !slices.Equal(first[:98], order[:98]) {
t.Errorf("the first 98: %v", first[:98])
}
}