diff --git a/internal/gateway/codex_desktop.go b/internal/gateway/codex_desktop.go index 2849d9329..1af4934e6 100644 --- a/internal/gateway/codex_desktop.go +++ b/internal/gateway/codex_desktop.go @@ -8,6 +8,7 @@ import ( "sync" "time" + "github.com/yetone/magpie/internal/beat" "github.com/yetone/magpie/internal/codexcat" "github.com/yetone/magpie/internal/provider" ) @@ -33,6 +34,19 @@ var codexDeskFetch = provider.CodexLiveList // gives (a test's stands in). var codexDeskWho = provider.CodexSignInWho +// codexDeskVersion is the Codex version the backend's list is asked for +// now, and codexDeskBehind whether a list asked for one is behind it; the +// backend lists a model only to a client new enough for it (tests' stand +// in). +var ( + codexDeskVersion = provider.CodexClientVersion + codexDeskBehind = provider.CodexVersionBehind +) + +// codexDeskListed is what the sign-in's own list, as magpie keeps it for +// the codex provider, has and when it was asked for (a test's stands in). +var codexDeskListed = provider.CodexSignInListed + 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 @@ -41,6 +55,10 @@ const ( codexDeskWait = 30 * time.Second ) +// codexDeskLook is how often the magpie serving the gateway looks whether +// the list is due (KeepCodexDeskFresh); a var so tests can look sooner. +var codexDeskLook = time.Minute + var codexDesk struct { sync.Mutex body []byte @@ -49,6 +67,9 @@ var codexDesk struct { // revoked: the last ask had the backend call the sign-in revoked // (provider.CodexListRevoked) revoked bool + // ver is the Codex version body was asked for, and slugs its models + ver string + slugs map[string]bool // failed: the last ask got no list (the backend not reachable from // here, or not answering 200), and none is known for who failed bool @@ -58,6 +79,82 @@ var codexDesk struct { done chan struct{} // closed as the ask under way ends } +// codexDeskDue says the list kept for who is to be asked for again: none +// kept, an hour old, asked for an older Codex than magpie asks as now, or +// older than the sign-in's own list magpie keeps for the codex provider +// while that lists a model it lacks. The backend's list is the same for +// both, asked apart: OpenAI listed GPT-6.2 Astra on 11-17, magpie's +// pickers had it, and the Codex app's file didn't (ANAGABRIELRLki on X). +// Called with codexDesk held; behind and listed are read before it is. +func codexDeskDue(who string, behind func(string) bool, listed []string, listedAt time.Time) bool { + c := &codexDesk + if c.who != who || c.body == nil || time.Since(c.got) >= codexDeskFor || behind(c.ver) { + return true + } + if listedAt.After(c.got) { + for _, id := range listed { + if !c.slugs[id] { + return true + } + } + } + return false +} + +// codexDeskAsk starts an ask for who's list when it is due and none is +// under way, not again within codexDeskRetry of the last one for who. +// Called with codexDesk held. +func codexDeskAsk(who string, due bool) { + c := &codexDesk + if due && !c.asking && (c.asked != who || time.Since(c.tried) >= codexDeskRetry) { + c.asking, c.tried, c.asked = true, time.Now(), who + c.done = make(chan struct{}) + go codexDeskRefresh(c.done, who) + } +} + +// codexDeskInputs reads, outside codexDesk's lock, what codexDeskDue weighs. +func codexDeskInputs() (behind func(string) bool, listed []string, listedAt time.Time) { + now := codexDeskVersion() + behind = func(v string) bool { return codexDeskBehind(v, now) } + listed, listedAt, _ = codexDeskListed() + return behind, listed, listedAt +} + +// KeepCodexDeskFresh asks for the Codex app's list again whenever it is +// due (codexDeskDue), once the list was wanted, run by the magpie serving +// the gateway. The list was asked for only as magpie wrote the agents' +// files (CodexDesktopCatalog, from agent.SyncCatalog), which nothing does +// on a quiet magpie: a model OpenAI listed since stayed out of the file, +// and with model_catalog_json named Codex asks for no list of its own. +// A list that changed is told (CodexDesktopChanged), and the file is +// written again. +func KeepCodexDeskFresh(ctx context.Context) { + for { + select { + case <-ctx.Done(): + return + case <-beat.Next(codexDeskLook): + } + codexDesk.Lock() + wanted := codexDesk.want != "" + codexDesk.Unlock() + if !wanted { + continue + } + who := codexDeskWho() + behind, listed, listedAt := codexDeskInputs() + codexDesk.Lock() + if codexDesk.want != "" { + codexDesk.want = who + codexDeskAsk(who, codexDeskDue(who, behind, listed, listedAt)) + } + codexDesk.Unlock() + } +} + +func init() { WhileServing = append(WhileServing, KeepCodexDeskFresh) } + // 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 @@ -81,6 +178,7 @@ var codexDesk struct { // the file kept the other account's list up to an hour). func CodexDesktopCatalog() (b []byte, ok bool) { who := codexDeskWho() + behind, listed, listedAt := codexDeskInputs() codexDesk.Lock() codexDesk.want = who body, revoked, failed := codexDesk.body, codexDesk.revoked, codexDesk.failed @@ -88,12 +186,7 @@ func CodexDesktopCatalog() (b []byte, ok bool) { if !mine { body, revoked, failed = nil, false, false } - stale := body == nil || time.Since(codexDesk.got) >= codexDeskFor - if stale && !codexDesk.asking && (codexDesk.asked != who || time.Since(codexDesk.tried) >= codexDeskRetry) { - codexDesk.asking, codexDesk.tried, codexDesk.asked = true, time.Now(), who - codexDesk.done = make(chan struct{}) - go codexDeskRefresh(codexDesk.done, who) - } + codexDeskAsk(who, codexDeskDue(who, behind, listed, listedAt)) codexDesk.Unlock() if body == nil && (revoked || failed) { var own []any @@ -131,6 +224,7 @@ func CodexDesktopCatalog() (b []byte, ok bool) { func codexDeskRefresh(done chan struct{}, who string) { ctx, cancel := context.WithTimeout(context.Background(), codexDeskWait) defer cancel() + ver := codexDeskVersion() b, err := codexDeskFetch(ctx) codexDesk.Lock() changed := false @@ -142,6 +236,7 @@ func codexDeskRefresh(done chan struct{}, who string) { if err == nil { changed = !bytes.Equal(b, codexDesk.body) || codexDesk.revoked codexDesk.body, codexDesk.got, codexDesk.revoked, codexDesk.failed = b, time.Now(), false, false + codexDesk.ver, codexDesk.slugs = ver, codexDeskSlugs(b) } else if revoked := provider.CodexListRevoked(err); revoked != codexDesk.revoked { // told only where it changes what is handed out: with no list // from before (CodexDesktopCatalog) @@ -171,3 +266,18 @@ func codexDeskRefresh(done chan struct{}, who string) { } close(done) } + +// codexDeskSlugs is the slugs a backend list has. +func codexDeskSlugs(b []byte) map[string]bool { + var list struct { + Models []struct { + Slug string `json:"slug"` + } `json:"models"` + } + _ = json.Unmarshal(b, &list) + out := make(map[string]bool, len(list.Models)) + for _, m := range list.Models { + out[m.Slug] = true + } + return out +} diff --git a/internal/gateway/codex_desktop_test.go b/internal/gateway/codex_desktop_test.go index f51851d2c..2ddda1674 100644 --- a/internal/gateway/codex_desktop_test.go +++ b/internal/gateway/codex_desktop_test.go @@ -318,3 +318,146 @@ func TestCodexDesktopCatalogBackendUnreachable(t *testing.T) { t.Fatalf("want Codex's cached GPT and magpie's models:\n%s", b) } } + +// ANAGABRIELRLki on X: OpenAI listed GPT-6.2 Astra on 11-17, and the Codex +// app beside magpie never showed it. With model_catalog_json named, Codex +// asks for no list of its own, so magpie's file is all the app has. The +// list was asked for again only when magpie wrote the agents' files and +// found it an hour old, which nothing makes it do on a quiet magpie, and a +// list asked for an older Codex, or older than the sign-in's own list +// magpie keeps, stood its hour. Each of those asks again now, and the +// gateway's loop asks with no sync to start it. +func TestCodexDesktopCatalogAskedAgainForANewModel(t *testing.T) { + codexSignedIn(t) + codexDeskReset(t) + var asks atomic.Int32 + var list atomic.Value + list.Store(`{"models":[{"slug":"gpt-6.1-sol","priority":1,"visibility":"list","base_instructions":"You are Codex."}]}`) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + asks.Add(1) + io.WriteString(w, list.Load().(string)) + })) + defer up.Close() + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + defer func() { provider.CodexBase = was }() + ver := atomic.Value{} + ver.Store("0.169.1") + var listed atomic.Value + listed.Store([]string{}) + var listedAt atomic.Int64 + wasVer, wasListed := codexDeskVersion, codexDeskListed + codexDeskVersion = func() string { return ver.Load().(string) } + codexDeskListed = func() ([]string, time.Time, bool) { + return listed.Load().([]string), time.Unix(0, listedAt.Load()), true + } + t.Cleanup(func() { codexDeskVersion, codexDeskListed = wasVer, wasListed }) + var changed atomic.Int32 + CodexDesktopChanged = func() { changed.Add(1) } + has := func(slug string) bool { + b, ok := CodexDesktopCatalog() + return ok && strings.Contains(string(b), `"`+slug+`"`) + } + // the last ask is moments old: past codexDeskRetry for the next + allowRetry := func() { + codexDesk.Lock() + codexDesk.tried = time.Time{} + codexDesk.Unlock() + } + + CodexDesktopCatalog() + codexDeskAsked(t) + if !has("gpt-6.1-sol") || asks.Load() != 1 { + t.Fatalf("the first list: asks %d", asks.Load()) + } + list.Store(`{"models":[{"slug":"gpt-6.2-astra","priority":1,"visibility":"list","base_instructions":"You are Codex."},` + + `{"slug":"gpt-6.1-sol","priority":2,"visibility":"list","base_instructions":"You are Codex."}]}`) + + // minutes old, nothing newer known: not asked again + allowRetry() + if has("gpt-6.2-astra") || asks.Load() != 1 { + t.Fatalf("a fresh list asked for again: asks %d", asks.Load()) + } + + // the sign-in's own list, asked since, has a model this one lacks + listed.Store([]string{"gpt-6.2-astra", "gpt-6.1-sol"}) + listedAt.Store(time.Now().UnixNano()) + told := changed.Load() + CodexDesktopCatalog() + codexDeskAsked(t) + if !has("gpt-6.2-astra") || asks.Load() != 2 { + t.Fatalf("the sign-in's newer list didn't bring the model: asks %d", asks.Load()) + } + if changed.Load() == told { + t.Fatal("the new list not told, so the file isn't written again") + } + // and once asked, that list is not a reason again + allowRetry() + CodexDesktopCatalog() + if asks.Load() != 2 { + t.Fatalf("asked again with nothing newer: asks %d", asks.Load()) + } + + // magpie asks as a newer Codex now: the list asked as the older one + // is asked for again + ver.Store("0.171.0") + allowRetry() + CodexDesktopCatalog() + codexDeskAsked(t) + if asks.Load() != 3 { + t.Fatalf("a list asked for an older Codex not asked again: asks %d", asks.Load()) + } +} + +// The loop of the magpie serving the gateway asks for the list once it is +// due, with no sync to start it, and tells a change, so the file is written +// again. +func TestKeepCodexDeskFreshAsksWhenDue(t *testing.T) { + codexSignedIn(t) + codexDeskReset(t) + var asks atomic.Int32 + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n := asks.Add(1) + slugs := `{"slug":"gpt-6.1-sol","priority":2,"visibility":"list"}` + if n > 1 { + slugs = `{"slug":"gpt-6.2-astra","priority":1,"visibility":"list"},` + slugs + } + io.WriteString(w, `{"models":[`+slugs+`]}`) + })) + defer up.Close() + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + defer func() { provider.CodexBase = was }() + wasListed := codexDeskListed + codexDeskListed = func() ([]string, time.Time, bool) { return nil, time.Time{}, false } + t.Cleanup(func() { codexDeskListed = wasListed }) + changes := make(chan struct{}, 8) + CodexDesktopChanged = func() { changes <- struct{}{} } + waitChange := func(what string) { + t.Helper() + select { + case <-changes: + case <-time.After(30 * time.Second): + t.Fatalf("%s: never told (asks %d)", what, asks.Load()) + } + } + + wasLook := codexDeskLook + codexDeskLook = 20 * time.Millisecond + t.Cleanup(func() { codexDeskLook = wasLook }) + ctx, cancel := context.WithCancel(context.Background()) + ended := make(chan struct{}) + go func() { KeepCodexDeskFresh(ctx); close(ended) }() + t.Cleanup(func() { cancel(); <-ended }) + + CodexDesktopCatalog() + waitChange("the first list") + // an hour on, as the loop sees it + codexDesk.Lock() + codexDesk.got, codexDesk.tried = time.Now().Add(-codexDeskFor), time.Time{} + codexDesk.Unlock() + waitChange("the list an hour old") + if b, ok := CodexDesktopCatalog(); !ok || !strings.Contains(string(b), `"gpt-6.2-astra"`) { + t.Fatalf("the loop's ask: %v\n%s", ok, b) + } +} diff --git a/internal/provider/codex_models.go b/internal/provider/codex_models.go index 0625bd443..8c2956244 100644 --- a/internal/provider/codex_models.go +++ b/internal/provider/codex_models.go @@ -128,6 +128,18 @@ func CodexLiveList(ctx context.Context) ([]byte, error) { return b, nil } +// CodexClientVersion is the Codex client version the backend's model +// list is asked for now (codexVersion): a list asked for an older one may +// lack a model the backend lists only to a newer client. +func CodexClientVersion() string { return codexVersion() } + +// CodexVersionBehind says a list asked for Codex version asked is behind +// now, the version magpie asks as (CodexClientVersion), or its version +// isn't known (codexListBehind). +func CodexVersionBehind(asked, now string) bool { + return asked == "" || asked != now && newerVersion(asked, now) != asked +} + var codexVersionCache struct { sync.Mutex v string @@ -473,10 +485,7 @@ const listRound = 10 * time.Minute // codexListBehind says a ChatGPT account's list asked for Codex version // asked is behind the one magpie asks as now, or its version wasn't kept: // a model the backend lists only to a newer client may be missing from it. -func codexListBehind(asked string) bool { - now := codexVersion() - return asked == "" || asked != now && newerVersion(asked, now) != asked -} +func codexListBehind(asked string) bool { return CodexVersionBehind(asked, codexVersion()) } // Levels are the reasoning levels the account's own list gives the model — // a Free ChatGPT plan's may be fewer than a Plus one's — and ok is false diff --git a/internal/provider/logins.go b/internal/provider/logins.go index 085a9d8e8..433930788 100644 --- a/internal/provider/logins.go +++ b/internal/provider/logins.go @@ -28,6 +28,7 @@ import ( "time" "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/codexcat" "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/filelock" @@ -915,6 +916,28 @@ func CodexSignInWho() string { return l.User + "\x00" + l.Plan } +// CodexSignInListed is the models the account Codex is signed in to listed +// when magpie last asked for its list (KeepAccountsListed), and when that +// was; ok is false while none is kept. The Codex app's list beside the +// sign-in (gateway.CodexDesktopCatalog) is the same backend's list for the +// same account, asked apart: one older than this that lacks a model this +// has is asked for again, or the app's picker went without a model +// magpie's own lists had (ANAGABRIELRLki on X: GPT-6.2 Astra). +func CodexSignInListed() (ids []string, fetched time.Time, ok bool) { + l, found := liveLogin("codex") + if !found { + return nil, time.Time{}, false + } + ms, at, ok := catalog.Live(accountModels("codex", l.User)) + if !ok { + return nil, time.Time{}, false + } + for _, m := range ms { + ids = append(ids, m.ID) + } + return ids, at, true +} + // codexLoginIn is the ChatGPT account Codex is signed in to in its folder // home, as Codex keeps it there (auth.json, or the keychain item named by // the folder).