codex: the Codex app beside the ChatGPT sign-in lists magpie's models too
laddieyao (Discord #general, 10-27): with Codex joined to magpie beside its ChatGPT sign-in, the Codex desktop app's model picker showed OpenAI's GPT models alone, while the Codex CLI listed magpie's. The /models request does reach magpie's gateway and its answer holds magpie's models. ChatGPT.app 26.1013's picker then narrows app-server model/list to the models a Statsig config (107580212, use_hidden_models / available_models) names, while Codex is on its built-in provider, unless Codex reads its list from a file (model_catalog_json, hasConfiguredModelCatalog) or names a provider of its own. The CLI has no such filter. Where the Codex app is installed (codexReaders has an "app"), and only joined/beside the sign-in (not magpie as Codex's provider, not account failover alone), magpie writes the list it hands Codex at /backend-api/codex/models to ~/.codex/magpie-desktop-models.json and names it with model_catalog_json. Codex is still on its built-in provider. With a catalog named Codex asks for no list, so magpie asks the backend itself, with Codex's live sign-in (provider.CodexLiveList): its entries go in verbatim, base_instructions and all, merged as the gateway merges them (codexMerged, factored out of codexModels: picked, hidden, window, V1, AutoReview edits), magpie's models after them. - A list not known (not asked yet, or the backend failing) is unknown: the file as it was stays, never an empty list; a key naming a file that is gone goes, as Codex loads no config then. - Written via temp+rename at Join, set, settle and every Sync (so a change of magpie's models, picks or hidden models rewrites it, as SyncCatalog runs on them); the backend list is asked again hourly (5 min after a failure) and a change syncs again. - A model_catalog_json of the user's own stands; none is written beside. - magpie API, the app gone, or unwire take the key and the file out; unroute never restores the desk file as the user's catalog. - connectinfo counts the file, so a running app on an old list reads as needing a restart. - CLI-only machines: unchanged, the live /models path as before. Run: - Real account, sandbox HOME (copy of auth.json, chatgpt Pro; live ~/.codex untouched): Join wrote model_catalog_json and the file with the real backend's 10 entries (gpt-6.1-sol ... codex-auto-review, each with base_instructions) plus relay/claude-opus-5.5 and relay/claude-sonnet-4-5. Then the real app-server bundled in ChatGPT.app (codex 0.163.0-alpha.10.2, CODEX_HOME sandbox, base URL pointed at a dead port) model/list returned all 12, relay models visible, and config/read showed model_catalog_json set, which is what the app's picker checks to skip its filter. - New tests: TestCodexDesktopListBesideSignIn, ...CLIOnly, ...KeepsTheirs (internal/agent), TestCodexDesktopCatalog (internal/gateway). - Broken by hand, each went red: deskList a no-op (all three agent tests), the user's-own branch removed (KeepsTheirs), the gone-file branch removed (KeepsTheirs), the keep-last-good rule broken in codexDeskRefresh (TestCodexDesktopCatalog). - go test -tags nogui -timeout 45m ./internal/agent ./internal/gateway ./internal/provider ./internal/cli at bc0a99bb6 (on68bbcc01c): agent, gateway, cli ok; provider red on TestUnreadLogins... (synctest crash, #3632) and three TestFetch* tests (#3854), both red the same at origin/main68bbcc01c/5a3292354run alone, both filed. - Rebased overe7f21dba5(Disconnect keeps a hand-set catalog): the conflict in unroute merged (the desk key counts as no catalog of the user's), and -run 'CodexDesktop|Disconnect|Unwire|Catalog' ./internal/agent ok. The packages' run at the final head could not build: the machine's disk was full (other sessions). - gofmt -l clean; go vet ./... on darwin, GOOS=linux, GOOS=windows ok. Not tried: clicking the real desktop app's picker (the app-server answer and config were checked, not the GUI); the Windows Store app (its readers get no version but count as the app; not run there); a backend list change rewriting the file while the app runs (the app needs reopening to read a new file, which connectinfo's restart notice covers).
This commit is contained in:
+113
-4
@@ -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).
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -114,7 +114,9 @@ func (a *Agent) startsWith() (pats []string, files []string, reads func() string
|
||||
switch 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.Builder
|
||||
for _, 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() string
|
||||
b.Write(j)
|
||||
c, _ := os.ReadFile(list)
|
||||
b.Write(c)
|
||||
d, _ := os.ReadFile(desk)
|
||||
b.Write(d)
|
||||
return b.String()
|
||||
}
|
||||
case "claude":
|
||||
|
||||
@@ -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.CodexSideModel
|
||||
gateway.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 serves
|
||||
gateway.WhileServing = append(gateway.WhileServing, davsync.Run)
|
||||
// and dsh's patch lists, which dsh reads live: a route left behind by
|
||||
|
||||
@@ -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 100
|
||||
codexcat.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 read
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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.Mutex
|
||||
v string
|
||||
|
||||
Reference in New Issue
Block a user