Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

agent: a Codex auth.json caught mid-rewrite leaves Codex beside its ChatGPT sign-in (lucy)

yetone7b1faf99f2a3
diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md
index 18d7b1da6..992aa7eb2 100644
--- a/docs/subsystems/agent-wiring.md
+++ b/docs/subsystems/agent-wiring.md
@@ -107,6 +107,7 @@ something else shows up as drift.
- `proxied` (Muma102kMichael on X: every project and every new chat 502 after magpie took Codex over) is this machine's Codex sending its requests for the gateway through a proxy that doesn't pass them on, while the gateway answers here ([`codex_proxy.go`](../../internal/agent/codex_proxy.go)). Codex's reqwest takes `HTTP_PROXY`, else the system's proxy for `http://` (macOS' HTTP entry alone, never its HTTPS or SOCKS one; Windows' `ProxyServer` only when it is one address for every protocol), else `ALL_PROXY`, and lets only an exact IP or a CIDR in `NO_PROXY` (on Windows, with no `NO_PROXY`, the bypass list with `*.` taken out) keep 127.0.0.1 off it: `127.*` and `localhost` don't, and macOS' exceptions aren't read. With `[features] respect_system_proxy` it asks the system alone, matching its list itself, wildcards and `<local>` included, and goes direct when no proxy is set there; a macOS SOCKS entry alone it can't use, and takes `HTTP_PROXY`/`ALL_PROXY` then (codex-rs `outbound_proxy`; tried with codex-cli 0.162.1). Its reqwest has no SOCKS, so a `socks5://` proxy is spoken to as an HTTP one, and the probe does the same. The environment is Codex's: the login shell's `*_PROXY` (`proc.LoginEnv`, which a terminal's Codex and the ChatGPT app's both have; only exported ones, as the probe asks a child `/bin/sh` for them, so fish's unexported universal `http_proxy` doesn't count, #2627) over magpie's own, which a magpie opened from the Dock lacks (liu_dyj on X: a `NO_PROXY=127.0.0.1` in the profile, or a macOS proxy with no HTTP entry, warned while Codex went direct). `codexProxyFor` works out that proxy the same way, and a `GET /` through it must come back as magpie's (`proxyProbe`), tried as `reachable` is. Its pill says how to fix it, as `unreachable`'s does, naming the proxy and the variable it was read from, `http_proxy` or `HTTP_PROXY` as it is (`Addr`, `Detail`), through `netproxy.Redact`, without its user and password (#1886), while the probe goes through it whole, and the dialog has Disconnect from magpie. Account failover, which magpie writes uninvited, waits for that probe (`codexProxyOK`) and isn't written while the proxy doesn't pass Codex on, and one it wrote goes again. Tests stub the env, the system proxy and `proxyProbe` in `TestMain`.
- Listing never starts a stopped WSL distro. A stopped distro's agent shows what was last seen there (`asleep`, `wsl.json`); setting one of its fields writes its files, which starts the distro.
- Codex's sign-in (`login`) is ChatGPT (`""`, the default), Always ChatGPT (`chatgpt`) or magpie API (`api`). With ChatGPT, magpie's models join Codex's own beside the sign-in (`openai_base_url`), and while the Codex app holds the ChatGPT account Codex is signed in to (`codexUsedUp`, `provider.CodexUsedUp`: OpenAI no longer allows the account and it has no credits left, a workspace still within its overage excepted), magpie is made Codex's provider (`codex.out`): the Codex app sends nothing at all on an account it holds, a magpie model's turn included (#540), and as a provider of its own magpie is past that. A window at 100% with credits left doesn't count, and Codex stays signed in. Sync puts it back beside the sign-in once the account has room. Always ChatGPT never does that: Codex stays in its ChatGPT state, and the Codex app may send nothing till the account has room, while Codex CLI's turns still reach magpie by the base URL, and its routing and other accounts serve them. With magpie API, Codex's `getAuthStatus` returns no token (its provider has no `requires_openai_auth`), so its Chrome control turns away; the option's note says to pick ChatGPT to keep it (#1824). While magpie is Codex's provider (magpie API, or `codex.out`), `Joined` reports false although the `codex.joined` mark stays for Sync's way back: the Agents row said Codex's own models stay in `/model` beside magpie's, the ChatGPT state the Codex app blocks sending in, and the app only leaves that state once it is restarted (#2267, `TestCodexProviderIsNotJoined`). A Codex that reaches the gateway from another machine (a WSL distro under NAT, or `MAGPIE_ADDR` pinned beyond loopback, `onAnotherMachine(at.gw())`) is wired as one with no ChatGPT sign-in (`chatGPT()` is false there): never joined or beside, since beside its sign-in it would send its ChatGPT token to `/backend-api/codex`, and from there the gateway takes a named key alone, so every request was a 401 (#2145, `TestCodexBeyondLoopbackNotJoined`). magpie is its provider and it sends `gwKey()`, the LAN sharing key; one of its own models picked goes straight to OpenAI on its sign-in.
+- Whether Codex is signed in to ChatGPT is read from its auth.json or keychain item (`codexChatGPTKnown`, `provider.CodexSignInKnown`). Codex rewrites auth.json in place when it refreshes its tokens (codex-rs `FileAuthStorage::save` opens it with truncate), so a read in that moment finds it empty or cut off, and a keychain read can fail for a moment. Such a read is unknown, and Codex is taken to be as magpie last wired it (joined, beside, or `codex.out`); only a sign-in that isn't there (no auth.json, no item) or holds no ChatGPT token is "not signed in". Taking an unknown read for "not signed in" made Sync or a pick move Codex from beside its sign-in to magpie as its provider, with no `codex.out` to bring it back, and the Codex app showed "magpie" for its account and magpie's catalog for its models, on and off (lucy on Discord, v0.1.1394; `TestCodexHalfWrittenAuthKeepsSignIn`, `TestCodexHalfWrittenAuthKeepsOut`, `TestCodexSignInKnown`).
- Codex signed in to ChatGPT and not connected still gets `openai_base_url` while more of its ChatGPT accounts are on in magpie (`failover`, stash `codex.failover`; with a CC Switch mirror as its provider, the mirror's `base_url` and `codex.mirror_failover`), so a turn its own account has no allowance for goes on to the next — never for a Codex that reaches the gateway from another machine, where that path takes a named key alone and the failed-over turn came back a 401 (#2145, `TestCodexFailoverBeyondLoopbackNotWritten`); Sync takes one it wrote before off again. That Codex is `FailingOver`: not `Wired`, yet its requests go through magpie. The Agents row says so and what turns it off (`FailoverSaid` in the CLI and TUI, `failover` in `/api/state`, a button to Providers › Codex in the GUI), and the gateway hands it only its own models from `/backend-api/codex/models` (`CodexOwnOnly`, set on `gateway.CodexOwnOnly` by main; its ETag carries `provider.CodexOwnListTag`, and Sync ages a `models_cache.json` without it). A connected WSL Codex shares the gateway path, so while one is connected every Codex gets magpie's models (#1385). A base URL the user wrote by hand (#856) isn't failover's and stays a plain not-connected row. A Codex the user disconnected gets no failover till they connect it again. The app serving the gateway takes failover out as it quits (`EndFailover`, `EndCodexFailover` in `OnShutdown`), so a Codex left on its own goes straight to OpenAI rather than retrying a gateway that's gone (Leon920717 on X); the next start's Sync writes it again. Codex's app-server read the old base URL as it started and keeps it, and `KeepCodexDaemonCurrent` ends with magpie, so `EndCodexFailover` restarts it there when no codex session is on it (`codexDaemonCheck`); with one on it, it stays on the gone gateway until the user restarts it (thisisvainxx on X: "several restarts"). A connected Codex keeps magpie as it quits: its model is one of magpie's, and Disconnect is what puts its own config back. A magpie that ends without quitting (killed, a crash, `magpie serve`) leaves failover in place.
- A Codex thread keeps the provider it was started on. While a magpie model is on, CC Switch's provider tables go through magpie too (`takeTables`), and get their own base URL back when Codex steps off magpie (`giveTables`, stash `codex.tables`). CC Switch's OpenAI mirror (a table of another id, `name = "OpenAI"`, `requires_openai_auth`, no `base_url`) isn't reached by `openai_base_url`, which takes only the built-in provider to magpie: a thread started on it and reopened went straight to ChatGPT, which refused the magpie model picked in it, and magpie never saw the request (#1796). While Codex goes to magpie by the base URL, `takeMirrors` gives each such mirror magpie's ChatGPT backend as its `base_url` (stash `codex.mirrors`), and `giveMirrors` takes it off again; a mirror a profile names, or one whose `base_url` was changed since, stays as it is. Moving the threads onto another provider is the Sessions page's Move (#887).
- An agent's config is written in the form the installed version reads, taken from what that version declares, not the latest one. VSCodium has no Copilot Chat of its own, and the Marketplace's last one (0.48.1) has no Custom Endpoint provider, only OpenAI Compatible (`customoai`, #1014). magpie reads the provider list in the package.json of the `github.copilot-chat` installed under `~/.vscode-oss/extensions` (`vscodeChatOf`). It writes its group for `customendpoint` when that is declared, for `customoai` when only that is, with each model's window as `maxInputTokens` + `maxOutputTokens` and the token as `x-api-key` (that version drops an Authorization in `requestHeaders`). A missing or unreadable extension keeps `customendpoint`. Sync rewrites a group written for the other provider, and Check reports it, as it does a Copilot Chat declaring neither. That Copilot Chat registers its providers only while signed in to GitHub with a personal Copilot plan, which the Notice says.
diff --git a/internal/agent/codex.go b/internal/agent/codex.go
index 0975f7a86..a7c396b7b 100644
--- a/internal/agent/codex.go
+++ b/internal/agent/codex.go
@@ -366,7 +366,15 @@ func codexIn(at place) *Agent {
if settings.AccountDiscoveryOff() {
return joined() || beside()
}
- return codexChatGPT(dir)
+ // a read that says nothing (auth.json caught while Codex rewrites
+ // it) leaves Codex as magpie last wired it: beside its sign-in, or
+ // magpie its provider while the Codex app holds the account
+ // (codex.out), which Sync puts back once it has room
+ signedIn, known := codexChatGPTKnown(dir)
+ if !known {
+ return joined() || beside() || stashLoad()[at.key("codex.out")] == "1"
+ }
+ return signedIn
}
// magpie is in Codex's config: on one of magpie's models, or joined;
// or, routed, on the model of the group magpie set it to as Codex
@@ -2020,21 +2028,37 @@ func CodexSideModel() string {
// its built-in provider then runs and asks for the model list at
// openai_base_url. Signed in with an API key alone, it asks for none.
func codexChatGPT(dir string) bool {
+ signedIn, _ := codexChatGPTKnown(dir)
+ return signedIn
+}
+
+// codexChatGPTKnown is codexChatGPT with whether the read said anything:
+// known is false for an auth.json caught while Codex rewrites it in place
+// (empty, cut off) or a keychain read that failed, which is no answer
+// (provider.CodexSignInKnown). Wiring goes by known alone: taking such a
+// read for "no ChatGPT sign-in" made magpie Codex's provider, and the
+// Codex app showed "magpie" for its account and magpie's catalog for its
+// models, on and off (lucy on Discord, v0.1.1394).
+func codexChatGPTKnown(dir string) (signedIn, known bool) {
if settings.AccountDiscoveryOff() {
- return false
+ return false, true
}
var a struct {
- Tokens struct {
+ Tokens *struct {
Access string `json:"access_token"`
} `json:"tokens"`
}
// auth.json, or the macOS keychain item when Codex's config.toml
// keeps the sign-in there (#2367)
- b, ok := provider.CodexSignIn(dir)
- if !ok || json.Unmarshal(b, &a) != nil {
- return false
+ b, ok, known := provider.CodexSignInKnown(dir)
+ if !ok {
+ return false, known
+ }
+ if json.Unmarshal(b, &a) != nil {
+ // valid JSON that isn't an object: not a sign-in Codex wrote
+ return false, false
}
- return a.Tokens.Access != ""
+ return a.Tokens != nil && a.Tokens.Access != "", true
}
// codexReached reads Codex's newest model request since a time — the
diff --git a/internal/agent/codex_signin_unknown_test.go b/internal/agent/codex_signin_unknown_test.go
new file mode 100644
index 000000000..3a7d8ec38
--- /dev/null
+++ b/internal/agent/codex_signin_unknown_test.go
@@ -0,0 +1,123 @@
+package agent
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// Codex rewrites auth.json in place when it refreshes its tokens
+// (codex-rs FileAuthStorage::save opens it with truncate), so a read in
+// that moment finds it empty or cut off. That says nothing about the
+// sign-in, and must not move Codex off it: Sync took such a read for "no
+// ChatGPT sign-in" and made magpie Codex's provider, and the Codex app
+// then showed "magpie" for its account and magpie's catalog for its
+// models (lucy on Discord, v0.1.1394, on and off). Nothing put it back,
+// as codex.out wasn't marked. A half-written file is unknown, and unknown
+// is the sign-in as last read.
+func TestCodexHalfWrittenAuthKeepsSignIn(t *testing.T) {
+ const signedIn = `{"auth_mode":"chatgpt","tokens":{"access_token":"x","id_token":"x.e30.x","refresh_token":"r"}}`
+ for name, mid := range map[string]string{
+ "empty": "",
+ "cut off": signedIn[:30],
+ "not json": "\x00\x00\x00",
+ "truncated": `{"auth_mode":"chatgpt","tokens":{"access_tok`,
+ } {
+ t.Run(name, func(t *testing.T) {
+ home, read := codexHome(t, signedIn, "")
+ cx := codex(home)
+ if err := cx.Fields[0].Set("fake/m1"); err != nil {
+ t.Fatal(err)
+ }
+ beside := func(when string) {
+ t.Helper()
+ if cfg := read(); strings.Contains(cfg, "model_provider =") || strings.Contains(cfg, "model_catalog_json") ||
+ !strings.Contains(cfg, "openai_base_url") || !strings.Contains(cfg, `model = "fake/m1"`) {
+ t.Fatalf("%s: not beside the sign-in:\n%s", when, cfg)
+ }
+ }
+ beside("picked")
+ auth := filepath.Join(home, ".codex", "auth.json")
+ if err := os.WriteFile(auth, []byte(mid), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := cx.Sync(); err != nil {
+ t.Fatal(err)
+ }
+ beside("synced while Codex rewrites auth.json")
+ // a pick in that moment (a group switch, the Agents page) too
+ if err := cx.Fields[0].Set("fake/m1"); err != nil {
+ t.Fatal(err)
+ }
+ beside("picked while Codex rewrites auth.json")
+ if err := os.WriteFile(auth, []byte(signedIn), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := cx.Sync(); err != nil {
+ t.Fatal(err)
+ }
+ beside("written again")
+ })
+ }
+}
+
+// The same while the Codex app holds the account and magpie is Codex's
+// provider for that (codex.out): a pick in that moment keeps the mark, so
+// Sync puts magpie back beside the sign-in once the account has room. It
+// was forgotten, and Codex stayed on magpie as its provider.
+func TestCodexHalfWrittenAuthKeepsOut(t *testing.T) {
+ const signedIn = `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`
+ home, read := codexHome(t, signedIn, "")
+ cx := codex(home)
+ codexUsedUp = func() bool { return true }
+ if err := cx.Fields[0].Set("fake/m1"); err != nil {
+ t.Fatal(err)
+ }
+ if cfg := read(); !strings.Contains(cfg, `model_provider = "magpie"`) {
+ t.Fatalf("held: magpie its provider:\n%s", cfg)
+ }
+ auth := filepath.Join(home, ".codex", "auth.json")
+ os.WriteFile(auth, nil, 0o600)
+ if err := cx.Fields[0].Set("fake/m1"); err != nil {
+ t.Fatal(err)
+ }
+ os.WriteFile(auth, []byte(signedIn), 0o600)
+ codexUsedUp = func() bool { return false }
+ if err := cx.Sync(); err != nil {
+ t.Fatal(err)
+ }
+ if cfg := read(); strings.Contains(cfg, "model_provider =") || !strings.Contains(cfg, "openai_base_url") {
+ t.Fatalf("room again after a pick mid-rewrite: not back beside the sign-in:\n%s", cfg)
+ }
+}
+
+// A sign-in really gone (auth.json removed: codex logout) or one with no
+// ChatGPT tokens (an API key) is known, and still moves Codex onto magpie
+// as its provider, as before.
+func TestCodexSignInGoneStillKnown(t *testing.T) {
+ for name, after := range map[string]string{
+ "logged out": "",
+ "api key": `{"OPENAI_API_KEY":"sk-x","tokens":null}`,
+ } {
+ t.Run(name, func(t *testing.T) {
+ home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, "")
+ cx := codex(home)
+ if err := cx.Fields[0].Set("fake/m1"); err != nil {
+ t.Fatal(err)
+ }
+ auth := filepath.Join(home, ".codex", "auth.json")
+ if after == "" {
+ os.Remove(auth)
+ } else if err := os.WriteFile(auth, []byte(after), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := cx.Sync(); err != nil {
+ t.Fatal(err)
+ }
+ if cfg := read(); !strings.Contains(cfg, `model_provider = "magpie"`) {
+ t.Fatalf("no ChatGPT sign-in: magpie its provider:\n%s", cfg)
+ }
+ })
+ }
+}
diff --git a/internal/provider/codex_store.go b/internal/provider/codex_store.go
index b60e8537c..493888068 100644
--- a/internal/provider/codex_store.go
+++ b/internal/provider/codex_store.go
@@ -673,6 +673,28 @@ func CodexSignIn(dir string) (b []byte, ok bool) {
return b, err == nil
}
+// CodexSignInKnown is CodexSignIn with whether the read says anything at
+// all. A sign-in that isn't there (no auth.json: codex logout; no keychain
+// item) or is kept where magpie doesn't read is known, ok false. One that
+// couldn't be read, or doesn't parse, is not: Codex rewrites auth.json in
+// place when it refreshes its tokens (codex-rs FileAuthStorage::save
+// opens it with truncate), so a read in that moment finds it empty or cut
+// off, and a keychain read can fail for a moment too. known false says
+// nothing of the sign-in either way.
+func CodexSignInKnown(dir string) (b []byte, ok, known bool) {
+ b, _, err := readCodexLogin(dir, false)
+ if err != nil {
+ var se *codexStoreError
+ gone := errors.Is(err, fs.ErrNotExist) || errors.Is(err, errAccountDiscoveryOff) ||
+ errors.As(err, &se) && se.Cause == nil
+ return nil, false, gone
+ }
+ if !json.Valid(b) {
+ return nil, false, false
+ }
+ return b, true, true
+}
+
// CodexKeychainForTest has Codex's keychain item read through find (no
// item: fs.ErrNotExist) on every system, until restore.
func CodexKeychainForTest(find func(service, account string) ([]byte, error)) (restore func()) {
diff --git a/internal/provider/codex_store_test.go b/internal/provider/codex_store_test.go
index fdeb07c2b..ea8cdaa9d 100644
--- a/internal/provider/codex_store_test.go
+++ b/internal/provider/codex_store_test.go
@@ -553,3 +553,40 @@ func TestCodexKeychainSignOut(t *testing.T) {
t.Fatalf("auth.json left: %v", err)
}
}
+
+// A read of Codex's sign-in that fails, or finds auth.json caught while
+// Codex rewrites it in place (empty, cut off), is unknown; none there
+// (codex logout, keyring with no item) and a store magpie doesn't read
+// are known.
+func TestCodexSignInKnown(t *testing.T) {
+ home := signIn(t)
+ dir := filepath.Join(home, ".codex")
+ auth := filepath.Join(dir, "auth.json")
+ whole, err := os.ReadFile(auth)
+ if err != nil {
+ t.Fatal(err)
+ }
+ check := func(when string, wantOK, wantKnown bool) {
+ t.Helper()
+ if _, ok, known := CodexSignInKnown(dir); ok != wantOK || known != wantKnown {
+ t.Fatalf("%s: ok %v known %v, want %v %v", when, ok, known, wantOK, wantKnown)
+ }
+ }
+ check("signed in", true, true)
+ for _, mid := range []string{"", string(whole[:len(whole)/2])} {
+ os.WriteFile(auth, []byte(mid), 0o600)
+ check("auth.json mid-rewrite: "+mid, false, false)
+ }
+ os.Remove(auth)
+ check("logged out", false, true)
+
+ codexKeychain, codexKeychainHere = &fakeKeychain{}, true
+ os.WriteFile(filepath.Join(dir, "config.toml"), []byte("cli_auth_credentials_store = \"keyring\"\n"), 0o600)
+ resetCodexKeychain()
+ check("keyring, no item", false, true)
+ codexKeychain = &fakeKeychain{findErr: errKeychainRefused, items: map[string][]byte{codexKeychainAccount(dir): []byte(`{}`)}}
+ resetCodexKeychain()
+ check("keyring, the keychain refusing", false, false)
+ os.WriteFile(filepath.Join(dir, "config.toml"), []byte("cli_auth_credentials_store = \"ephemeral\"\n"), 0o600)
+ check("ephemeral", false, true)
+}