Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
codex: the Codex app beside the ChatGPT sign-in lists magpie's models too
yetoneadd927e604c4
diff --git a/internal/agent/codex.go b/internal/agent/codex.goindex fb914da03..9a8eed793 100644--- a/internal/agent/codex.go+++ b/internal/agent/codex.go@@ -388,6 +388,97 @@ func codexIn(at place) *Agent {m := get("model")return isMagpie(m) || joined() || beside() || routed() && setAsGroup(cmp.Or(at.id, "codex"), "model", m)}+ // deskList is the list magpie hands Codex beside its ChatGPT sign-in,+ // written to a file of its own (deskPath) and named by+ // model_catalog_json, where the Codex app is installed: the app's+ // picker shows only the models of Codex's list a flag of OpenAI's+ // names while Codex is on its built-in provider, magpie's never among+ // them, unless Codex reads its list from a file (laddieyao on+ // Discord: GPT alone in the app, magpie's in the CLI). It is not+ // magpie's catalog as a provider (catalogPath, ownCatalog): Codex is+ // on its built-in provider, with its own models from the ChatGPT+ // backend's list as the backend sent them (CodexDesktopList).+ deskPath := filepath.Join(dir, "magpie-desktop-models.json")+ deskRef := at.native(deskPath)+ if at.spell == nil && runtime.GOOS == "windows" {+ deskRef = filepath.Base(deskPath)+ }+ deskCatalog := func(c string) bool {+ if c == "" {+ return false+ }+ if c == deskRef || c == at.native(deskPath) {+ return true+ }+ return at.spell == nil && !filepath.IsAbs(c) && filepath.Clean(filepath.Join(dir, c)) == filepath.Clean(deskPath)+ }+ deskGone := func() bool {+ _, err := os.Stat(deskPath)+ return errors.Is(err, fs.ErrNotExist)+ }+ // deskWanted: magpie is connected beside the ChatGPT sign-in (joined,+ // or on one of magpie's models), not as Codex's provider, on this+ // machine's Codex, and the Codex app reads this config. The CLI alone+ // keeps asking the gateway for the list, which follows every change at+ // once; a Codex here for account failover alone has no models of+ // magpie's to show.+ deskWanted := func() bool {+ if at.spell != nil || asProvider() || !viaBase() || !(joined() || beside()) || !chatGPT() {+ return false+ }+ for _, r := range codexReaders(at) {+ if r.Kind == "app" {+ return true+ }+ }+ return false+ }+ // deskList writes the list for the Codex app again, or takes it out+ // where it isn't wanted: the key, and the file. A list not known now+ // (the backend not asked yet, or not answering) leaves the file as it+ // was, never an empty one; a key naming a file that is gone goes, as+ // Codex loads no config then. A model_catalog_json of the user's own+ // stands: theirs is what Codex reads.+ deskList := func() error {+ named := deskCatalog(get("model_catalog_json"))+ if !deskWanted() {+ if named {+ if err := edit.DelTOMLTop(path, "model_catalog_json"); err != nil {+ return err+ }+ }+ if err := os.Remove(deskPath); err != nil && !errors.Is(err, fs.ErrNotExist) {+ return err+ }+ return nil+ }+ if c := get("model_catalog_json"); c != "" && !named {+ if err := os.Remove(deskPath); err != nil && !errors.Is(err, fs.ErrNotExist) {+ return err+ }+ return nil+ }+ var b []byte+ ok := false+ if CodexDesktopList != nil {+ b, ok = CodexDesktopList()+ }+ if !ok {+ if named && deskGone() {+ return edit.DelTOMLTop(path, "model_catalog_json")+ }+ return nil+ }+ if cur, err := edit.Read(deskPath); err != nil || string(cur) != string(b) {+ if err := edit.WriteAtomic(deskPath, b); err != nil {+ return err+ }+ }+ if !named {+ return edit.SetTOMLTop(path, edit.KV{Path: "model_catalog_json", Value: deskRef})+ }+ return nil+ }models := func() []catalog.Model {switch {case asProvider():@@ -409,9 +500,11 @@ func codexIn(at place) *Agent {return writeOwnList(catalogPath, b)}case viaBase():- return codexStaleCache(filepath.Join(dir, "models_cache.json"), provider.CodexListTag())+ if err := codexStaleCache(filepath.Join(dir, "models_cache.json"), provider.CodexListTag()); err != nil {+ return err+ }}- return nil+ return deskList()}var dropSubEffort func() error// keep the effort valid for the model: one set that the model doesn't@@ -440,6 +533,10 @@ func codexIn(at place) *Agent {return err}}+ // the Codex app's list as magpie is wired now, or taken out+ if err := deskList(); err != nil {+ return err+ }return dropSubEffort()}// magpie as a provider Codex can name; its threads started on magpie do@@ -1099,7 +1196,7 @@ func codexIn(at place) *Agent {}// the catalog of the user's own put back while its file is there:// one removed since would keep Codex from loading its config- if c := unstash(at.key("codex.catalog")); c != "" && !ownCatalog(c) && !theirListGone(c) && get("model_catalog_json") == "" {+ if c := unstash(at.key("codex.catalog")); c != "" && !ownCatalog(c) && !deskCatalog(c) && !theirListGone(c) && (get("model_catalog_json") == "" || deskCatalog(get("model_catalog_json"))) {back = append(back, edit.KV{Path: "model_catalog_json", Value: c})}// the effort, where it is still one magpie set: picked on the@@ -1146,7 +1243,7 @@ func codexIn(at place) *Agent {}dropList()forget(at.key("codex.model"), at.key("codex.effort"), at.key("codex.effort_set"), at.key("codex.provider"), at.key("codex.catalog"), at.key("codex.out"), at.key("codex.joined"), at.key("codex.beside"))- return nil+ return deskList()}// magpie API: magpie stays Codex's provider whichever model is the// default, so one of Codex's own goes as magpie serves it, on the@@ -1379,6 +1476,12 @@ func codexIn(at place) *Agent {return err}}+ // the Codex app's list, written again as magpie is wired now+ // (the backend's list or magpie's models changed), or taken out+ // where it is no longer wanted: a hand edit, another tool+ if err := deskList(); err != nil {+ return err+ }if err := asyncCompaction(routed()); err != nil {return err}@@ -2097,6 +2200,12 @@ func EndCodexFailover() error {return nil}+// CodexDesktopList is the list a Codex beside its ChatGPT sign-in is+// handed, as the file the Codex app reads it from (deskList); ok false+// while it isn't known. Set to gateway.CodexDesktopCatalog; nil writes+// none.+var CodexDesktopList func() (b []byte, ok bool)+// CodexOwnOnly reports whether the Codex that asks the gateway for its// model list there (/backend-api/codex/models) reaches magpie for account// failover alone (FailingOver), to be handed only its own models (#1385).diff --git a/internal/agent/codex_desktop_test.go b/internal/agent/codex_desktop_test.gonew file mode 100644index 000000000..8b0ed90ac--- /dev/null+++ b/internal/agent/codex_desktop_test.go@@ -0,0 +1,212 @@+package agent++import (+ "os"+ "path/filepath"+ "strings"+ "testing"+)++// codexAppReads has the Codex app (and a CLI) read every config when app+// is true, the CLI alone when it is false; put back when the test ends.+func codexAppReads(t *testing.T, app *bool) {+ t.Helper()+ was := codexReaders+ t.Cleanup(func() { codexReaders = was })+ codexReaders = func(place) []CodexReader {+ out := []CodexReader{{Kind: "cli", Version: "0.163.0"}}+ if *app {+ out = append(out, CodexReader{Kind: "app", Version: "0.163.0"})+ }+ return out+ }+}++// deskListIs has CodexDesktopList answer list, or not know it while list+// is nil.+func deskListIs(t *testing.T, list *string) {+ t.Helper()+ was := CodexDesktopList+ t.Cleanup(func() { CodexDesktopList = was })+ CodexDesktopList = func() ([]byte, bool) {+ if list == nil || *list == "" {+ return nil, false+ }+ return []byte(*list), true+ }+}++// laddieyao on Discord: Codex joined beside its ChatGPT sign-in, the Codex+// app's picker showed GPT alone while the CLI listed magpie's models. The+// app shows only the models of Codex's list a flag of OpenAI's names,+// unless Codex reads its list from a file: where the app is installed,+// magpie writes the list it hands Codex there and names it; the CLI alone+// keeps the list the gateway hands it.+func TestCodexDesktopListBesideSignIn(t *testing.T) {+ home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, `model = "gpt-5.5"`+"\n")+ dir := filepath.Join(home, ".codex")+ desk := filepath.Join(dir, "magpie-desktop-models.json")+ app := true+ codexAppReads(t, &app)+ list := `{"models":[{"slug":"gpt-6-sol","base_instructions":"theirs"},{"slug":"fake/m1"}]}`+ deskListIs(t, &list)++ cx := codex(home)+ if ok, err := cx.Join(); err != nil || !ok {+ t.Fatalf("join: %v %v", ok, err)+ }+ cfg := read()+ if !strings.Contains(cfg, `model_catalog_json = "`) || !strings.Contains(cfg, "magpie-desktop-models.json") {+ t.Fatalf("joined with the Codex app here, no list named for it:\n%s", cfg)+ }+ if strings.Contains(cfg, "model_provider =") {+ t.Fatalf("Codex's provider changed:\n%s", cfg)+ }+ if b, err := os.ReadFile(desk); err != nil || string(b) != list {+ t.Fatalf("the app's list: %q %v", b, err)+ }+ // connected beside the sign-in, as before: not magpie as its provider+ if !cx.Joined() || cx.AppOut() {+ t.Fatalf("joined %v, app out %v\n%s", cx.Joined(), cx.AppOut(), cfg)+ }+ if msg := cx.Check(); msg != "" {+ t.Fatalf("check: %s", msg)+ }++ // magpie's models changed: written again at the next sync+ list = `{"models":[{"slug":"gpt-6-sol","base_instructions":"theirs"},{"slug":"fake/m2"}]}`+ if err := cx.Sync(); err != nil {+ t.Fatal(err)+ }+ if b, _ := os.ReadFile(desk); string(b) != list {+ t.Fatalf("not written again: %s", b)+ }++ // a list not known now (the backend not answering) is unknown: the+ // file as it was stays, never an empty one+ was := list+ list = ""+ if err := cx.Sync(); err != nil {+ t.Fatal(err)+ }+ if b, _ := os.ReadFile(desk); string(b) != was || !strings.Contains(read(), "magpie-desktop-models.json") {+ t.Fatalf("unknown list: %s\n%s", b, read())+ }+ list = was++ // a magpie model picked beside the sign-in: still Codex's provider,+ // the list still the app's+ if err := cx.Fields[0].Set("fake/m1"); err != nil {+ t.Fatal(err)+ }+ if cfg := read(); !cx.Beside() || !strings.Contains(cfg, "magpie-desktop-models.json") || strings.Contains(cfg, "model_provider =") {+ t.Fatalf("beside: %v\n%s", cx.Beside(), cfg)+ }++ // magpie API: magpie's own catalog, as magpie is Codex's provider, and+ // the app's list gone+ if err := cx.Field("login").Set("api"); err != nil {+ t.Fatal(err)+ }+ if cfg := read(); !strings.Contains(cfg, `model_provider = "magpie"`) || strings.Contains(cfg, "magpie-desktop-models.json") {+ t.Fatalf("api:\n%s", cfg)+ }+ if _, err := os.Stat(desk); !os.IsNotExist(err) {+ t.Fatalf("api: the app's list is still there: %v", err)+ }+ if err := cx.Field("login").Set(""); err != nil {+ t.Fatal(err)+ }+ if cfg := read(); !strings.Contains(cfg, "magpie-desktop-models.json") || strings.Contains(cfg, "model_provider =") {+ t.Fatalf("back beside the sign-in:\n%s", cfg)+ }++ // disconnected: the key and the file go+ if err := cx.Unwire(); err != nil {+ t.Fatal(err)+ }+ if cfg := read(); strings.Contains(cfg, "model_catalog_json") {+ t.Fatalf("unwired:\n%s", cfg)+ }+ if _, err := os.Stat(desk); !os.IsNotExist(err) {+ t.Fatalf("unwired: the app's list is still there: %v", err)+ }+}++// The CLI alone asks the gateway for its list, which follows each change+// as it is made: no file is written for it, and one written while the+// Codex app was installed goes once it isn't.+func TestCodexDesktopListCLIOnly(t *testing.T) {+ home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, `model = "gpt-5.5"`+"\n")+ desk := filepath.Join(home, ".codex", "magpie-desktop-models.json")+ app := false+ codexAppReads(t, &app)+ list := `{"models":[{"slug":"gpt-6-sol"}]}`+ deskListIs(t, &list)+ cx := codex(home)+ if ok, err := cx.Join(); err != nil || !ok {+ t.Fatalf("join: %v %v", ok, err)+ }+ if cfg := read(); strings.Contains(cfg, "model_catalog_json") {+ t.Fatalf("CLI alone:\n%s", cfg)+ }+ if _, err := os.Stat(desk); !os.IsNotExist(err) {+ t.Fatalf("CLI alone: a list written: %v", err)+ }+ app = true+ if err := cx.Sync(); err != nil {+ t.Fatal(err)+ }+ if cfg := read(); !strings.Contains(cfg, "magpie-desktop-models.json") {+ t.Fatalf("the app installed:\n%s", cfg)+ }+ app = false+ if err := cx.Sync(); err != nil {+ t.Fatal(err)+ }+ if cfg := read(); strings.Contains(cfg, "model_catalog_json") {+ t.Fatalf("the app gone:\n%s", cfg)+ }+ if _, err := os.Stat(desk); !os.IsNotExist(err) {+ t.Fatalf("the app gone: the list stays: %v", err)+ }+}++// A model_catalog_json the user set while joined is theirs: it stands, and+// no list of magpie's is written beside it. And a key naming magpie's list+// with the file gone (removed by hand) goes, as Codex loads no config then,+// while the list isn't known to write it again.+func TestCodexDesktopListKeepsTheirs(t *testing.T) {+ home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, `model = "gpt-5.5"`+"\n")+ dir := filepath.Join(home, ".codex")+ desk := filepath.Join(dir, "magpie-desktop-models.json")+ app := true+ codexAppReads(t, &app)+ list := `{"models":[{"slug":"gpt-6-sol"}]}`+ deskListIs(t, &list)+ cx := codex(home)+ if ok, err := cx.Join(); err != nil || !ok {+ t.Fatalf("join: %v %v", ok, err)+ }+ os.Remove(desk)+ list = ""+ if err := cx.Sync(); err != nil {+ t.Fatal(err)+ }+ if cfg := read(); strings.Contains(cfg, "model_catalog_json") {+ t.Fatalf("named with the file gone:\n%s", cfg)+ }+ list = `{"models":[{"slug":"gpt-6-sol"}]}`+ cfg := strings.Replace(read(), `model = "gpt-5.5"`, `model = "gpt-5.5"`+"\n"+`model_catalog_json = "mine.json"`, 1)+ os.WriteFile(filepath.Join(dir, "mine.json"), []byte(`{"models":[]}`), 0o644)+ os.WriteFile(filepath.Join(dir, "config.toml"), []byte(cfg), 0o644)+ if err := cx.Sync(); err != nil {+ t.Fatal(err)+ }+ if cfg := read(); !strings.Contains(cfg, `model_catalog_json = "mine.json"`) {+ t.Fatalf("theirs:\n%s", cfg)+ }+ if _, err := os.Stat(desk); !os.IsNotExist(err) {+ t.Fatalf("written beside theirs: %v", err)+ }+}diff --git a/internal/agent/connectinfo.go b/internal/agent/connectinfo.goindex e44866127..6f636ebaa 100644--- a/internal/agent/connectinfo.go+++ b/internal/agent/connectinfo.go@@ -114,7 +114,9 @@ func (a *Agent) startsWith() (pats []string, files []string, reads func() stringswitch a.ID {case "codex":list := filepath.Join(filepath.Dir(a.Path), "magpie-models.json")- return []string{`(^|/)codex( |$)`}, []string{a.Path, list}, func() string {+ // the list written for the Codex app beside the sign-in (deskList)+ desk := filepath.Join(filepath.Dir(a.Path), "magpie-desktop-models.json")+ return []string{`(^|/)codex( |$)`}, []string{a.Path, list, desk}, func() string {var b strings.Builderfor _, k := range []string{"model_provider", "model_catalog_json", "openai_base_url"} {v, _ := edit.GetTOMLTop(a.Path, k)@@ -125,6 +127,8 @@ func (a *Agent) startsWith() (pats []string, files []string, reads func() stringb.Write(j)c, _ := os.ReadFile(list)b.Write(c)+ d, _ := os.ReadFile(desk)+ b.Write(d)return b.String()}case "claude":diff --git a/internal/cli/main.go b/internal/cli/main.goindex a10f13ef3..478780037 100644--- a/internal/cli/main.go+++ b/internal/cli/main.go@@ -338,6 +338,11 @@ func run(args []string) error {// its ChatGPT sign-in rather than on that account (atom_Ray on X)gateway.CodexSideModel = agent.CodexSideModelgateway.CodexSideSet = agent.CodexSideSet+ // the list the Codex app reads from a file beside the ChatGPT sign-in,+ // its picker showing magpie's models only so (laddieyao on Discord),+ // written again when the backend's list changes+ agent.CodexDesktopList = gateway.CodexDesktopCatalog+ gateway.CodexDesktopChanged = agent.SyncCatalogSoon// the setup kept the same on every computer, by whichever servesgateway.WhileServing = append(gateway.WhileServing, davsync.Run)// and dsh's patch lists, which dsh reads live: a route left behind bydiff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.goindex 7df111d11..9742e3559 100644--- a/internal/gateway/codex_backend.go+++ b/internal/gateway/codex_backend.go@@ -1915,6 +1915,18 @@ func (s *Server) codexModels(w http.ResponseWriter, r *http.Request) {own = append(own, e)}}+ all := codexMerged(own, cached)+ // the list is the backend's and magpie's, and so is its ETag+ w.Header().Set("ETag", codexcat.WithTag(etag, codexListTag()))+ writeJSON(w, 200, map[string]any{"models": all})+}++// codexMerged is the list magpie hands a Codex beside its ChatGPT sign-in:+// own, the backend's entries (cached when they are Codex's last list, not+// the backend's answer), as the user narrowed and set them on the codex+// provider, with magpie's models after them. The entries are written into.+func codexMerged(own []any, cached bool) []any {+ defer provider.Hold()()// the windows the user set on the codex provider, as /v1/models says// them (#674); a cached entry, which keeps what magpie handed Codex// last, takes the account's own list's back when none is set@@ -2015,8 +2027,6 @@ func (s *Server) codexModels(w http.ResponseWriter, r *http.Request) {if !codexOwnOnly() {ms = provider.CodexListed()}- // the list is the backend's and magpie's, and so is its ETag- w.Header().Set("ETag", codexcat.WithTag(etag, codexListTag()))all := append(own, codexcat.Entries(ms, len(own)+100)...)if at, ok := provider.CodexOrder(); ok {codexcat.Order(all, at)@@ -2024,7 +2034,7 @@ func (s *Server) codexModels(w http.ResponseWriter, r *http.Request) {// the Codex app and its VS Code extension read the first 100 alone:// hidden ones go last, and the ones the user uses are among the 100codexcat.Fit(all, usage.CodexUsed())- writeJSON(w, 200, map[string]any{"models": all})+ return all}// modelsEtag is the X-Models-Etag of a backend reply as Codex should readdiff --git a/internal/gateway/codex_desktop.go b/internal/gateway/codex_desktop.gonew file mode 100644index 000000000..160408139--- /dev/null+++ b/internal/gateway/codex_desktop.go@@ -0,0 +1,101 @@+package gateway++import (+ "bytes"+ "context"+ "encoding/json"+ "log"+ "sync"+ "time"++ "github.com/yetone/magpie/internal/provider"+)++// The Codex app's picker shows only the models of Codex's list that a+// flag of OpenAI's names, for Codex on its built-in provider, unless Codex+// reads its list from a file (model_catalog_json): beside the ChatGPT+// sign-in it showed GPT alone, magpie's models in the list it was handed+// all the same (laddieyao on Discord). The CLI shows the whole list. So+// where the Codex app is installed, magpie writes the list it hands Codex+// into a file for Codex to read (agent.CodexDesktopList), and Codex asks+// for no list then: the backend's part of it is asked for here, with+// Codex's sign-in, and kept.++// CodexDesktopChanged is called when the backend's list for the Codex app+// changed, for the file to be written again (agent.SyncCatalogSoon).+var CodexDesktopChanged func()++// codexDeskFetch asks the backend for its list (a test's stands in).+var codexDeskFetch = provider.CodexLiveList++const (+ // codexDeskFor is how long a list the backend gave stands before it+ // is asked for again; codexDeskRetry how long after one it didn't+ codexDeskFor = time.Hour+ codexDeskRetry = 5 * time.Minute+ codexDeskWait = 30 * time.Second+)++var codexDesk struct {+ sync.Mutex+ body []byte+ got, tried time.Time+ asking bool+ done chan struct{} // closed as the ask under way ends+}++// CodexDesktopCatalog is the list a Codex beside its ChatGPT sign-in is+// handed (/backend-api/codex/models), as a file Codex reads with+// model_catalog_json: the backend's entries as it sent them, narrowed and+// set as the codex provider has them, magpie's after them. ok is false+// while the backend's list is not known: none asked for yet, or none it+// gave. That is unknown, never an empty list, and the file as it was+// stands. The backend is asked again in the background when its list is+// old, CodexDesktopChanged told when it changed.+func CodexDesktopCatalog() (b []byte, ok bool) {+ codexDesk.Lock()+ body := codexDesk.body+ stale := body == nil || time.Since(codexDesk.got) >= codexDeskFor+ if stale && !codexDesk.asking && time.Since(codexDesk.tried) >= codexDeskRetry {+ codexDesk.asking, codexDesk.tried = true, time.Now()+ codexDesk.done = make(chan struct{})+ go codexDeskRefresh(codexDesk.done)+ }+ codexDesk.Unlock()+ if body == nil {+ return nil, false+ }+ // each caller's own copy: codexMerged writes into the entries+ var list struct {+ Models []any `json:"models"`+ }+ if json.Unmarshal(body, &list) != nil || len(list.Models) == 0 {+ return nil, false+ }+ b, err := json.MarshalIndent(map[string]any{"models": codexMerged(list.Models, false)}, "", " ")+ if err != nil {+ return nil, false+ }+ return b, true+}++func codexDeskRefresh(done chan struct{}) {+ ctx, cancel := context.WithTimeout(context.Background(), codexDeskWait)+ defer cancel()+ b, err := codexDeskFetch(ctx)+ codexDesk.Lock()+ changed := false+ if err == nil {+ changed = !bytes.Equal(b, codexDesk.body)+ codexDesk.body, codexDesk.got = b, time.Now()+ }+ codexDesk.asking = false+ codexDesk.Unlock()+ if err != nil {+ log.Println("codex: the ChatGPT backend's model list for the Codex app:", err)+ }+ if changed && CodexDesktopChanged != nil {+ CodexDesktopChanged()+ }+ close(done)+}diff --git a/internal/gateway/codex_desktop_test.go b/internal/gateway/codex_desktop_test.gonew file mode 100644index 000000000..990f0a9fd--- /dev/null+++ b/internal/gateway/codex_desktop_test.go@@ -0,0 +1,124 @@+package gateway++import (+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "sync/atomic"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/provider"+)++// codexDeskReset forgets the backend's list for the Codex app, before the+// test and after it.+func codexDeskReset(t *testing.T) {+ t.Helper()+ reset := func() {+ codexDesk.Lock()+ done := codexDesk.done+ codexDesk.Unlock()+ if done != nil {+ <-done+ }+ codexDesk.Lock()+ codexDesk.body, codexDesk.got, codexDesk.tried, codexDesk.asking, codexDesk.done = nil, time.Time{}, time.Time{}, false, nil+ codexDesk.Unlock()+ }+ reset()+ t.Cleanup(reset)+ was := CodexDesktopChanged+ t.Cleanup(func() { CodexDesktopChanged = was })+}++// codexDeskAsked waits for the ask CodexDesktopCatalog started.+func codexDeskAsked(t *testing.T) {+ t.Helper()+ codexDesk.Lock()+ done := codexDesk.done+ codexDesk.Unlock()+ if done == nil {+ t.Fatal("the backend was never asked")+ }+ <-done+}++// The list the Codex app reads from a file beside the ChatGPT sign-in+// (laddieyao on Discord): the backend's entries as it sent them, its+// base_instructions untouched, asked for with Codex's own sign-in, and+// magpie's models after them. Not known until the backend has answered,+// and a failed ask after that keeps the last list it gave: unknown, never+// an empty list.+func TestCodexDesktopCatalog(t *testing.T) {+ codexSignedIn(t)+ codexDeskReset(t)+ if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Anthropic: "http://127.0.0.1:1",+ Models: []string{"claude-opus-5.5"}}); err != nil {+ t.Fatal(err)+ }+ var fail atomic.Bool+ var auth atomic.Value+ up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ auth.Store(r.Header.Get("Authorization"))+ if fail.Load() {+ http.Error(w, "down", http.StatusBadGateway)+ return+ }+ io.WriteString(w, `{"models":[{"slug":"gpt-5.5","priority":1,"base_instructions":"You are Codex, based on GPT-5.","visibility":"list"}]}`)+ }))+ defer up.Close()+ was := provider.CodexBase+ provider.CodexBase = up.URL + "/backend-api/codex"+ defer func() { provider.CodexBase = was }()+ var changed atomic.Int32+ CodexDesktopChanged = func() { changed.Add(1) }++ if b, ok := CodexDesktopCatalog(); ok || b != nil {+ t.Fatalf("known before the backend answered: %s", b)+ }+ codexDeskAsked(t)+ if changed.Load() != 1 {+ t.Fatalf("changed told %d times", changed.Load())+ }+ if a, _ := auth.Load().(string); a == "" {+ t.Fatal("asked without Codex's sign-in")+ }+ b, ok := CodexDesktopCatalog()+ if !ok {+ t.Fatal("not known after the backend answered")+ }+ var got struct {+ Models []map[string]any `json:"models"`+ }+ if err := json.Unmarshal(b, &got); err != nil {+ t.Fatal(err)+ }+ slugs := map[string]map[string]any{}+ for _, m := range got.Models {+ slugs[m["slug"].(string)] = m+ }+ if m := slugs["gpt-5.5"]; m == nil || m["base_instructions"] != "You are Codex, based on GPT-5." {+ t.Fatalf("the backend's entry: %v", m)+ }+ if slugs["relay/claude-opus-5.5"] == nil {+ t.Fatalf("magpie's models missing: %s", b)+ }++ // an ask that fails keeps the list the backend gave last+ fail.Store(true)+ codexDesk.Lock()+ codexDesk.got, codexDesk.tried = time.Time{}, time.Time{}+ codexDesk.Unlock()+ if _, ok := CodexDesktopCatalog(); !ok {+ t.Fatal("the last list forgotten as the backend is asked again")+ }+ codexDeskAsked(t)+ if b2, ok := CodexDesktopCatalog(); !ok || string(b2) != string(b) {+ t.Fatalf("after a failed ask: %v\n%s", ok, b2)+ }+ if changed.Load() != 1 {+ t.Fatalf("a failed ask told as a change")+ }+}diff --git a/internal/provider/codex_models.go b/internal/provider/codex_models.goindex c3ce338da..88b7b3390 100644--- a/internal/provider/codex_models.go+++ b/internal/provider/codex_models.go@@ -60,6 +60,52 @@ func codexModels(ctx context.Context, sign func(context.Context, *http.Request,return ms, nil}+// CodexLiveList is the ChatGPT backend's model list for the account Codex+// is signed in to now, as the backend sends it: its entries, their+// base_instructions among them, untouched. magpie writes it for the Codex+// app beside the sign-in (agent.CodexDesktopList), whose picker shows only+// the models a flag of OpenAI's names unless Codex reads its list from a+// file. An error when Codex is not signed in to ChatGPT, the backend+// doesn't answer 200, or its answer lists no model: never an empty list.+func CodexLiveList(ctx context.Context) ([]byte, error) {+ home, _ := os.UserHomeDir()+ p, ok := codexAccount(home)+ if !ok || p.Account == nil || p.Account.sign == nil {+ return nil, errors.New("Codex is not signed in to ChatGPT")+ }+ ctx = ViaSignedIn(ctx, "codex")+ u := CodexBase + "/models?client_version=" + url.QueryEscape(codexVersion())+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)+ if err != nil {+ return nil, err+ }+ if err := p.Account.sign(ctx, req, nil); err != nil {+ return nil, err+ }+ resp, err := http.DefaultClient.Do(req)+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()+ b, err := io.ReadAll(io.LimitReader(resp.Body, 16<<20))+ if err != nil {+ return nil, err+ }+ if resp.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("ChatGPT models: %s", resp.Status)+ }+ var list struct {+ Models []json.RawMessage `json:"models"`+ }+ if err := json.Unmarshal(b, &list); err != nil {+ return nil, fmt.Errorf("ChatGPT models: %w", err)+ }+ if len(list.Models) == 0 {+ return nil, errors.New("ChatGPT listed no Codex models")+ }+ return b, nil+}+var codexVersionCache struct {sync.Mutexv string