From 327da691aec6f01802081ac036e95b8a4479e2dd Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 12 Nov 2026 16:39:14 +0800 Subject: [PATCH] gateway: the Codex app's list stands on Codex's cache while the backend can't be reached (not_4O4 on X) Beside the ChatGPT sign-in the Codex app's picker reads magpie-desktop-models.json, written only once the ChatGPT backend's model list is known. not_4O4 (Windows, Codex App 26.1106.6628.0) had no such file: the backend's ask never succeeded from there, so the file was never written and the picker showed GPT alone while the account had room, magpie's models only (and no GPT) once it was used up and magpie became the provider. After an ask has failed with no list from before for that sign-in, CodexDesktopCatalog now hands Codex's own models_cache.json entries and magpie's models (the revoked sign-in's path), told once through CodexDesktopChanged; the backend's list replaces it when it answers. With no cache the file stays as it was, and a 502 after a revoked sign-in is still no answer. Run (mote): go vet gateway and agent (darwin), GOOS=windows and linux -tags nogui vet of gateway, go test ./internal/gateway ./internal/agent; TestCodexDesktopCatalogBackendUnreachable is new and TestCodexDesktop*, TestCodexDesktopCatalogRevokedSignIn still pass. On the Windows box (win-run) the agent's Codex desktop tests passed and a used-up probe wrote magpie-models.json with relative key as in the report. Broken by hand: the stand-in only for revoked, the new test went red. Not tried: the real Codex app on the reporter's network; the reporter's used-up half (GPT missing from the provider catalog) did not reproduce, the catalog carries codex/ entries in the probe on macOS and Windows. --- docs/subsystems/agent-wiring.md | 1 + internal/gateway/codex_desktop.go | 29 ++++++++++--- internal/gateway/codex_desktop_test.go | 56 +++++++++++++++++++++++++- 3 files changed, 80 insertions(+), 6 deletions(-) diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 980301dfc..d416def40 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -125,6 +125,7 @@ something else shows up as drift. - Every other agent's own models (`ownProvider` in [`agents.go`](../../internal/agent/agents.go), the provider list read from its own auth file or config: Pi, OpenCode, Goose, Crush, Cline, Hermes, the WSL twins and the rest; omp's `ompOwnOptions`) say `Direct` with the provider's name: each is asked of that vendor on the agent's own sign-in or key, so a pick takes the agent off magpie. The picker tags them direct, lists them after magpie's, and asks before such a pick turns 「接入」 off (maxleebeta on Discord: Pi's own OpenCode Go model switched it off with nothing said; `TestOwnModelsSayTheyGoDirect`, `agent-own-direct.test.cjs`). - A line magpie writes into an agent's TOML, YAML or dotenv config gets a comment line of its own just above it, `# magpie: ; ` (`edit.Mark`, set to `agent.lineNote` by the CLI's `run` in [`mark.go`](../../internal/agent/mark.go); the edit side in [`internal/edit/mark.go`](../../internal/edit/mark.go)). Jevik_AI on X deleted magpie's folders by hand, and Codex's `config.toml` kept `openai_base_url` on the gateway with nothing in it naming magpie: every turn was a 502. Only a one-line scalar that points at the gateway or names magpie's model list gets one, and only when the write adds or changes that line, or it had a note already; a line of the user's own that magpie leaves as it is gets none. The note is never on the value's line: Grok App's `providers.rs` reads the rest of a line as the value. Every write takes the notes out first and puts them back over the lines that still need one, so a note goes with its line and a Disconnect leaves none. A YAML note that would change what the file reads as isn't added (`sameYAMLValue`). JSON has no comments and gets none. Tests set no `Mark`, so their exact bytes stay; `TestMarkedLinesEveryAgent` connects every agent with notes on and checks each gateway line has one, a second sync writes nothing, and Disconnect leaves none; `TestCodexMarkedLines`, `internal/edit`'s `TestMark*`. - Codex signed in to ChatGPT stays beside its sign-in (`openai_base_url`) unless the user picks magpie API. magpie becomes its provider only while the Codex app holds the active account, which it sends nothing for: `/wham/usage` says it isn't allowed, and it has no credits and isn't a workspace still within its overage (`codexHeld`, read by `provider.CodexUsedUp`). With Codex switched off or removed in magpie (`leftAlone`), whose allowance magpie otherwise reads nothing of, the active account is still read for this alone while Codex takes magpie's models beside its sign-in or magpie is its provider for the held account (`Agent.HoldMatters`, through the `provider.CodexHoldMatters` hook; `codexHoldReading`): once a minute at most, with the token as Codex keeps it, never renewed or written (`codexTokenAsKept`), and nothing shown on the Usage page. Before, turning Codex off in magpie after its allowance ran out left the Codex app greying Send for magpie's models through restarts, and one already moved was put back on the held account (sherlock_23333 on X; `TestCodexHoldReadLeftAlone`, `TestCodexHoldMatters`). Where the app goes by what usage can't show (an experiment's gate, a reserve, a Team plan's overage under the reserve experiment), it counts as held: a wrong move costs ChatGPT extras, a missed one every turn. A saved reading kept through a failed read stops saying held once its used-up window has started again; a hold with no window used up stays till a fresh read. The app then loses its ChatGPT state (durable threads, remote control), so a window at 100% alone, which credits get past, doesn't move it (with no credits it does when the backend says `allowed` false, and only then: `codexAtLimit`. The app's composer gate greys Send on that alone, in ChatGPT.app 26.1029 as in 26.1021, and keeps a window of an allowed account at 1% or more, so allowed not said or allowed with a window at 100% is an account it still sends for. A used-up 5h window with the week open is held through it: the backend says allowed false there, as the real Team reply in testdata does with its 5h at 100% and its week at 63%; xiaoq6285 on Discord) (`codex.out` marks the move, and Sync undoes it once the account has room). The same holds on one of Codex's own models joined beside the sign-in (MasterYi on Discord: the Codex app greyed Send for every model on a used-up account): Sync makes magpie the provider on that model as magpie serves it (`codexOwnViaMagpie`, `codex/`), keeps the model picked in `codex.out_own`, and once the account has room puts Codex back joined on it; a model the user picked meanwhile stays theirs. With no ChatGPT account in magpie to serve it, Codex is left as it is (`TestCodexOwnModelGoesThroughMagpieWhileUsedUp`, `TestCodexOwnModelKeptOnChatGPT`). Where magpie would serve that model on the same used-up account alone (no fallback on the Codex subscription and no other ChatGPT account not known out: `provider.CodexServesWhileOut` false), every turn on it would be refused too, but the Codex app greys Send for every model while the account is out, so keeping the account's menu costs a grey Send (shamen, chenhan and xiaoq6285 on Discord). Sync then makes magpie the provider on a stand-in model of magpie's that is on no ChatGPT account (`codexOtherModel`, kept in `codex.out_stand` beside `codex.out_own`), once per held/unheld transition: on the stand-in the model is magpie's, so the branch isn't met again and a steady held state writes nothing and ends no app-server. At the reset Codex is put back joined on its own model; another model picked meanwhile stays theirs (the stand-in itself picked can't be told from staying on it, and gives way to the own model). This reverses f37742e14, which left Codex on its sign-in to keep the account's menu and usage (the app-server restarts it cost, #4550, are the two the takeover makes). With nothing else in magpie to offer (no stand-in) Codex stays on its sign-in, as no takeover could send (`TestCodexOwnModelOneSpentAccountStaysOnItsSignIn`, `TestCodexOwnModelOneSpentAccountTakenOverForOtherModels`, `TestCodexServesWhileOut`). The account is read again at once when a reply says it may be out (a `usage_limit_reached` rest, or an `x-codex-*` window heard at 100%; `provider.CodexMayBeUsedUp`, at most every 20s, the active account only), not only on the five-minute look. A turn relayed to Codex's own sign-in, the one account on (`codexUpstreamOn` with no account, the gateway's `codexRelayedAccount`), is heard the same way: its `x-codex-*` windows and `codex.rate_limits` event kept as the sign-in's usage (`heardCodexLimits`), and a `usage_limit_reached` refusal reading it again. Before, only turns served through magpie's accounts were, so with one account magpie learned the account was out only at the next look, minutes on, and the Codex app kept Send greyed until it was restarted (unsplashz on Discord; `TestCodexUsedUpRelayedAsksAtOnce`, `TestCodexRelayedWindowsHeard`). A Codex started before magpie became its provider keeps sending its own model's turns to its built-in provider; while the sign-in is known out (`provider.CodexUsedUpKnown`) and the request signs as it, those go through routing as `codex/` (`codexAccounts`), as a restarted Codex's do (`TestCodexHeldSignInServedWithoutRestart`). The Codex app greys Send for every model, magpie's too, while its `authMethod` is `chatgpt` and its rate limit says not allowed (its composer's gate in ChatGPT.app 26.1013), and reads `authMethod` from its app-server's `account/read` only as the app-server starts; with magpie the provider (`requires_openai_auth` false) that answers no account, so the gate lifts. So the gateway process restarts the app's own app-server each time magpie becomes Codex's provider for the used-up account (`Agent.AppOut`) and again when Codex is put back on the account after its reset, and likewise whenever what the app-server reads as it starts and magpie writes changes, which is where its requests go (`model_provider`, `openai_base_url` and the magpie table's `base_url`, and its `requires_openai_auth` while that table is Codex's `model_provider`: beside the sign-in the app-server reads the built-in provider's account, so the key following the account out and back is nothing it reads; `codexAppRoute`, through the `provider.CodexAppRoute` hook): a Disconnect, a Connect, failover written or taken out. The model list is not part of it: neither `model_catalog_json` nor what the catalog holds. The catalog follows magpie's names and the effort new sessions start at, which the Codex app saves on each pick, and the ChatGPT app takes an ended app-server as a crash and relaunches, so a route that hashed the catalog (from lucis0116 on X until #4550) ended the app every few minutes (indekkusu141209 on X). A new list is read at the app's next launch or on the Agents row's Restart (`StaleCopies`) A list that drops a model and has it back at the next fetch, the same list in another order, and a catalog read half-written leave the route as it was (`TestCodexEffortPickKeepsTheAppRunning`, `TestCodexAppRouteIgnoresARename`, `TestCodexAppRouteKeepsThroughListFlaps`). Before this an app-server started while Codex was connected kept sending to the gateway after Disconnect until the app was restarted (JiangLiuer222 on X). At the watcher's first look only a used-up account's app-servers are ended, since what the others read before magpie started isn't known. What magpie changes by itself that the app works without waits for the user, though, unless they ticked Restart the Codex app when magpie switches its account back (`Provider.RestartApp`, `provider/restartapp`, off by default, this computer's own like KeepLogin): its switch back once the account it moved off has room (`SwitchWhenSpent` → `switchLoginBy(…, true)`, `codexApp.auto`) and giving Codex its account back at the reset. A switch the user makes between accounts with room waits too: the app keeps its sidebar projects per ChatGPT identity, so a restart onto the new account showed none and every thread under Recent (Michael25651150 and ykj5353 on X, `TestCodexAppLeftRunningForMagpiesOwnChanges`). Those leave the app-server running, log why, and the switch notice's Restart is the way to follow; a user's switch off a used-up account (`codexAppSpentSwitch`), a Connect, a Disconnect and failover written or taken out still restart it, and so does the takeover turned off by the user rather than ended by the reset: its sign-in set to Always ChatGPT (the takeover note's Keep on ChatGPT) or Codex disconnected while magpie stood in (`Agent.AppOutOff` through `provider.CodexTakeoverOff`, asked only as `out` goes false). The app-server the takeover started answers `account/read` with no account, so the app kept its ChatGPT projects and chats hidden after the user turned the takeover off to have them back, and the Windows app has no Restart of its own (Herzz____ on X, `TestCodexAppRestartedWhenTheTakeoverIsTurnedOff`). So does whatever leaves the app-server on a used-up account, tick or not: the takeover in, the first look on one, and magpie's switch off one (`needed` in `codexAppStep`), since the app greys Send there and reads the account only as its app-server starts, so with the tick off a takeover at the limit left Send grey and the fallback unreachable (v0.1.2826 to its fix). An app-server left running on the account magpie switched Codex back off is restarted too once that account is read held (`restartCodexAppLeftOnSpent`, on each full look of `KeepOnAnAccountWithRoom`, once per app-server left): it keeps the account it started on (`CodexAppStale`), so when that ran out the app greyed Send for every model while the account Codex is signed in to had room and nothing else read the old one (nb5p on Discord: B first in magpie, the app still on A; `TestCodexAppLeftOnASpentAccountIsRestarted`). atom0964 on Discord had both sign-in ticks off and the ChatGPT app relaunched at every switch between two Plus accounts (`TestCodexAppLeftRunningForMagpiesOwnChanges`, `TestCodexAppFirstLookOnAUsedUpAccountRestarts`, `restart-app.test.cjs`). It runs on every system (`KeepCodexAppOnItsProvider`, every 3s; Ethereal499 and Isdavexxx on X, MasterYi on Discord, #540: the earlier once-only reopen ran on macOS from the GUI process only, so Windows, Linux, a GUI-less magpie and the switch back stayed greyed). It ends only app-servers on magpie's Codex home (`codexAppHomeIs`: the process's `CODEX_HOME`, else `HOME/.codex`, read by `proc.EnvOf`; Windows can't tell and counts every one), only once no Codex request is in flight through the gateway nor ended in the last 10s (`Server.CodexBusy`) and no session under the Codex home has a turn started and not ended (`codexTurnOpen`), and with a clean exit (`proc.End`: SIGTERM, `TerminateProcess` with code 0), since the app shows any other exit as a crash. Each end is logged with what made the app-server stale: the account switched, the route changed, or the used-up takeover (`codex: ended the Codex app's app-server [pid] for the app to start another: `), so a crash a user reports can be put down to one of them (#4550, `TestCodexAppEndSaysWhy`). The app starts another app-server at once and keeps its window, threads and drafts (tried in the real app in a sandbox `CODEX_HOME`, both ways). An app-server that outlives three ends, or may not be ended, leaves the row saying to quit and reopen the app (`CodexAppStuck`). An ended app-server's pid gone doesn't mean the app has another: the Windows app (MSIX `OpenAI.Codex`, stdio) starts one only once the old one's stdout closes, and a child it left (an MCP server, a tool command) holds that pipe open, so the app answered "Codex app-server process is not available" until it was restarted (蛋仔 on Discord). The watcher waits `codexAppBackWait` (30s) for another app-server; when none came and the app is still open (`CodexAppOpen`), it quits and opens the app as the Agents row's Restart does (`CodexAppReopen`, Windows only), else the row says to (`CodexAppStuck`). `RestartCodexApp`, uninstall's `RestartCodexAppWhenIdle` and the switch notice's Restart (`RestartSwitchedCodexApp`) wait for it the same way and reopen or say so alike, and `recheckLeft` keeps the record while the app is open with no app-server. A signed-in ChatGPT app (26.1021) can still fail on the app-server it starts next ("Hosted AppServerManager identity is not ready") and show "ChatGPT hit a snag" until it is quit and opened again (ysm119 on Discord, #4550), a fault in the app the clean end can't avoid. So for `codexAppCrashWait` (60s) after each of these ends ([`codex_app_crash.go`](../../internal/provider/codex_app_crash.go)) the app's own logs are read (`CodexAppCrashed`, [`agent/codex_app_crash.go`](../../internal/agent/codex_app_crash.go): `~/Library/Logs/com.openai.codex`, `%LOCALAPPDATA%\Codex\Logs` and the Store package's, `$XDG_STATE_HOME/codex/logs`) for a whole `fatal_error_broadcasted` line stamped after the end. When the page shows and no request has gone through magpie or been in flight since, and no Codex turn has opened since, the app is quit and opened once (`CodexAppRelaunch`: ⌘Q's quit and `open` on macOS, never forced, ChatGPT.app by its bundle id only; `CodexAppReopen` on Windows), but after an end for a used-up account (a switch off one, or the takeover in: `crashSpent`) at once, and after any other end only with Restart the Codex app ticked (`codexRestartsApp`). The app was greyed on the used-up account already and the page is all its window shows, so RealZeroP27 on X (switch only, "只能通过手动重启 codex 解决", `TestCodexAppReopenedAfterASpentEndUnasked`) was left with a window only a quit clears; unasked, a quit of a working app read as magpie force-restarting it (Michael25651150 on X, `TestCodexAppNotQuitUnasked`, an end for a route change). The tick also gates the Windows reopen when no app-server came back (`codexAppGotNone`). The app-server's own restart at the takeover isn't gated: the app reads its account only as its app-server starts, so without it Send stays grey on the used-up account. Where the tick is off or that can't be done (Linux, an app that didn't quit) the Agents row says to quit and reopen it (`CodexAppSnagged`, `appSnag`) until the app-servers seen then are gone or the app is closed. Logs that can't be read reopen nothing (`TestCodexAppReopenedWhenItShowsItsErrorPage`, `TestCodexAppInUseAfterItsErrorPageIsLeft`, `TestCodexAppCrashedReadsItsOwnLogs`, `TestCodexAppRelaunchOnlyTheCodexApp`, `codex-app-snag.test.cjs`). A turn left open in Codex's sessions holds the restart for up to `codexTurnWindow` (30m), except where the app-server is on a used-up account: after a switch off one (`SwitchWhenSpent` → `codexAppSpentSwitch`, or a switch by hand off an account last read held, `codexHeldKnown` in `noteCodexSwitch`) and when magpie becomes Codex's provider for one (`codexAppStep`'s `into`; xiaoq6285 on Discord: quota out, then another account or provider picked, and Send stayed grey; `TestCodexAppServerRestartedPastATurnStuckWhenMagpieTakesOver`, `TestCodexHandSwitchOffAHeldAccountIsSpent`). There a turn that has written no session file and sent nothing through magpie for `codexTurnStuckAfter` (2m) counts stuck and the app-server is restarted past it, since its next request would be refused on that account (蛋仔 on Discord: quota ran out mid-task and the app hung till restarted; `TestCodexAppServerRestartedPastATurnStuckOnTheSpentAccount`). An account switch restarts nothing, and neither the app nor the background daemon is said to be left on the old account (`CodexAppStale`, `CodexDaemonStale`, the CLI's switch line), while the provider Codex's config.toml names takes no ChatGPT account (`provider.CodexNoAccount`, `codexNoAccount` in [`agents.go`](../../internal/agent/agents.go)): a top-level `model_provider` other than `openai` whose `[model_providers]` table doesn't say `requires_openai_auth = true`, such as magpie's with the user's own `false` (danzi002 on Discord). Codex then sends the table's key and its app-server reads no account (codex-rs `account_state`, `resolve_provider_auth`); tried with codex-cli 0.165.0 in a sandbox `CODEX_HOME`: `account/read` and `getAuthStatus` said no account before and after auth.json was switched, and `codex exec` sent `Bearer` the table's key on both accounts. A route change still restarts it, and so does a switch under a profile, the built-in provider, a provider with no table or a config that can't be read (`TestCodexNoAccountSwitchRestartsNothing`, `TestCodexNoAccountOfEachConfig`, `TestCodexNoAccountFollowsRequiresOpenAIAuth`). Until the reset the app's ChatGPT side is off (cloud tasks, its usage meter, Log out); the Agents row says so with the reset's time (`appOut` in `/api/state`, `CodexOutUntil`), and it all comes back at the reset. While the active account is held or a window is at 90% or more, its usage is read every minute rather than every five (`codexLookEvery`). `TestCodexAppServerRestartedEachWay`, `TestCodexAppServerRestartedOnDisconnect`, `TestCodexAppRouteFollowsConnectAndDisconnect`, `TestCodexEffortPickKeepsTheAppRunning`, `TestCodexAppRouteIgnoresARename`, `TestCodexAppServerUnknown`, `TestCodexAppServerStuck`, `TestCodexAppServersOnHome`, `TestCodexTurnOpen`, `TestCodexBusy`, `codex-app-out.test.cjs`. +- The Codex app's picker beside the sign-in reads `magpie-desktop-models.json` (`deskList`): the ChatGPT backend's list with magpie's models after it (`gateway.CodexDesktopCatalog`). A backend this machine cannot reach (a firewall; not_4O4 on X, Windows) gave no list and the file was never written, GPT alone in the picker. After a failed ask with no list from before, Codex's own `models_cache.json` stands in (`codexDesk.failed`); the real list replaces it when the backend answers. With no cache the file stays as it was, and a 502 after a revoked sign-in is still no answer. - The Codex app (ChatGPT.app 26.1103 and on) keeps its sidebar's projects per ChatGPT identity in `$CODEX_HOME/.codex-global-state.json`, under `electron-account-renderer-state-v1` (`{owner, inactive: {: {atoms, globals}}}`, the hash the sha256 hex of `JSON.stringify([chatgpt_user_id, chatgpt_account_id])`): on an account change it parks the old identity's account-scoped globals and loads the new one's, so a switch to an account that never had the app open showed no projects (Michael25651150 on X; #5497, #5602, #5702, #5874). The app reads the file only as it starts and writes its memory over it, so magpie writes it only while the app is closed ([`codex_projects.go`](../../internal/provider/codex_projects.go)): `codexProjectsStep` in `codexAppStep`, once the file, auth.json or logins.json changed (at most every 30s while the app may be open, since `CodexAppOpen` lists processes), and `CodexAppClosed` between the quit and the open of every reopen (`appQuitDone` in [`apprestart.go`](../../internal/agent/apprestart.go)). Every identity, those of auth.json and magpie's saved Codex logins and those the file has, gets one list (`shareCodexProjects`, Michael25651150 on X again): each identity's `local-projects` together, the signed-in identity's copy first, with the ties the other project keys (`codexProjectKeys`) have to them, one or two levels down (`codexGraft`). A folder is one project (`codexRootKey`): the app gives a project a random id on each account, so a project of a folder an identity has already is that one, its threads renamed to it. What the user removed is remembered: `codex-projects.json` beside logins.json keeps each identity's project ids and folders as the last look left them, and a project a look saw on an identity that the next doesn't have was removed there, so it goes from every identity with every tie to it (`codexPrune`), as do other projects of its folders, unless the user added that project or folder again on some identity since. A record that can't be read or parsed means what was removed is unknown, and nothing is written. The first look, with no record, removes nothing. A ChatGPT project's mirror (`g-p-` ids, and every tie to one) isn't shared, and a backing naming another account is dropped (`projectFor`), since the app refuses to act on a project "belongs to a different ChatGPT account". The record is written only after the state file is, so a look the app's own start overtook is taken again. A file without the key (an older app) or that doesn't parse is left as it is; before its first write the file as it was is kept beside it (`.magpie-before-projects`). Projects added or removed while the app runs reach the other accounts once it is closed. With no account (the takeover, `requires_openai_auth` false) the app shows no projects by its own rule, and they come back with the account (`TestCodexProjectsFollowASwitch`, `TestCodexProjectsShared`, `TestCodexProjectsRemovalRemembered`, `TestCodexProjectsRecordUnreadable`, `TestCodexProjectsUnknownFileLeft`, `TestCodexProjectsStepWaitsForTheAppToClose`). - Moving a field from one of magpie's models to another (the agent's own picker) is not drift. Moving it off magpie is. diff --git a/internal/gateway/codex_desktop.go b/internal/gateway/codex_desktop.go index 69eeb60c8..2849d9329 100644 --- a/internal/gateway/codex_desktop.go +++ b/internal/gateway/codex_desktop.go @@ -49,6 +49,9 @@ var codexDesk struct { // revoked: the last ask had the backend call the sign-in revoked // (provider.CodexListRevoked) revoked 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 // who is the sign-in body and revoked are of (codexDeskWho); asked // the one the last ask was for; want the one a caller last asked about who, asked, want string @@ -80,10 +83,10 @@ func CodexDesktopCatalog() (b []byte, ok bool) { who := codexDeskWho() codexDesk.Lock() codexDesk.want = who - body, revoked := codexDesk.body, codexDesk.revoked + body, revoked, failed := codexDesk.body, codexDesk.revoked, codexDesk.failed mine := codexDesk.who == who if !mine { - body, revoked = nil, false + 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) { @@ -92,11 +95,18 @@ func CodexDesktopCatalog() (b []byte, ok bool) { go codexDeskRefresh(codexDesk.done, who) } codexDesk.Unlock() - if body == nil && revoked { + if body == nil && (revoked || failed) { var own []any for _, e := range codexcat.CacheEntries() { own = append(own, e) } + // the backend can't be asked (not reachable from here: a Windows + // box behind a firewall): Codex's own last list, from its + // models_cache.json, stands in. With none of it, the file stays + // as it was rather than hold magpie's models alone. + if !revoked && len(own) == 0 { + return nil, false + } b, err := json.MarshalIndent(map[string]any{"models": codexMerged(own, true)}, "", " ") return b, err == nil } @@ -124,19 +134,28 @@ func codexDeskRefresh(done chan struct{}, who string) { b, err := codexDeskFetch(ctx) codexDesk.Lock() changed := false + wasRevoked := codexDesk.revoked && codexDesk.who == who if codexDesk.who != who { // another sign-in's list, and what was said of it, is not who's - codexDesk.body, codexDesk.revoked, codexDesk.who = nil, false, who + codexDesk.body, codexDesk.revoked, codexDesk.failed, codexDesk.who = nil, false, false, who } if err == nil { changed = !bytes.Equal(b, codexDesk.body) || codexDesk.revoked - codexDesk.body, codexDesk.got, codexDesk.revoked = b, time.Now(), false + codexDesk.body, codexDesk.got, codexDesk.revoked, codexDesk.failed = b, time.Now(), false, false } else if revoked := provider.CodexListRevoked(err); revoked != codexDesk.revoked { // told only where it changes what is handed out: with no list // from before (CodexDesktopCatalog) changed = codexDesk.body == nil codexDesk.revoked = revoked } + // no list for who from before, and none now: the cached one stands in + // (CodexDesktopCatalog), told once + // (a 502 after the backend called the sign-in revoked is still no + // answer, as before) + if err != nil && codexDesk.body == nil && !codexDesk.failed && !wasRevoked && !codexDesk.revoked { + codexDesk.failed = true + changed = true + } // Codex went on to another sign-in while this one was asked about: // told, for the next look to ask about that one if codexDesk.want != who { diff --git a/internal/gateway/codex_desktop_test.go b/internal/gateway/codex_desktop_test.go index 63b824e7f..f51851d2c 100644 --- a/internal/gateway/codex_desktop_test.go +++ b/internal/gateway/codex_desktop_test.go @@ -15,6 +15,7 @@ import ( "testing" "time" + "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/provider" ) @@ -30,7 +31,7 @@ func codexDeskReset(t *testing.T) { <-done } codexDesk.Lock() - codexDesk.body, codexDesk.got, codexDesk.tried, codexDesk.asking, codexDesk.done, codexDesk.revoked = nil, time.Time{}, time.Time{}, false, nil, false + codexDesk.body, codexDesk.got, codexDesk.tried, codexDesk.asking, codexDesk.done, codexDesk.revoked, codexDesk.failed = nil, time.Time{}, time.Time{}, false, nil, false, false codexDesk.who, codexDesk.asked, codexDesk.want = "", "", "" codexDesk.Unlock() } @@ -264,3 +265,56 @@ func TestCodexDesktopCatalogKeepsNewlyListedBesidePicks(t *testing.T) { t.Errorf("the account's own models beside the picks: %v\n%s", own, b) } } + +// A backend that can't be reached from here (a firewall, a proxy that +// leaves chatgpt.com out; not_4O4 on X, Windows) never gave a list, so the +// file for the Codex app was never written and its picker had GPT alone +// beside the sign-in. Once the ask has failed with no list from before, +// Codex's own last list (models_cache.json) stands in, with magpie's +// models after it; with no such cache the file stays as it was. +func TestCodexDesktopCatalogBackendUnreachable(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) + } + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "down", http.StatusBadGateway) + })) + 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) } + + // no cache either: unknown, the file as it was + if _, ok := CodexDesktopCatalog(); ok { + t.Fatal("known before the backend answered") + } + codexDeskAsked(t) + if b, ok := CodexDesktopCatalog(); ok { + t.Fatalf("no list and no cache, yet known: %s", b) + } + if changed.Load() != 1 { + t.Fatalf("the failed ask told %d times, want once", changed.Load()) + } + + if err := os.WriteFile(catalog.CodexModelsCache(), + []byte(`{"etag":"x","models":[{"slug":"gpt-5.5","priority":1,"base_instructions":"You are Codex, based on GPT-5.","visibility":"list"}]}`), 0o644); err != nil { + t.Fatal(err) + } + codexDesk.Lock() + codexDesk.tried = time.Time{} + codexDesk.Unlock() + CodexDesktopCatalog() + codexDeskAsked(t) + b, ok := CodexDesktopCatalog() + if !ok { + t.Fatal("the cached list does not stand in for a backend that can't be reached") + } + if !strings.Contains(string(b), `"gpt-5.5"`) || !strings.Contains(string(b), "relay/claude-opus-5.5") { + t.Fatalf("want Codex's cached GPT and magpie's models:\n%s", b) + } +}