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

lucy on Discord (v0.1.1394, Codex app, signed in in Codex, not in
magpie): on and off, Codex's account menu showed "magpie" instead of the
ChatGPT account, and the model picker listed magpie's catalog ("6.1 Sol
· Codex" ...) instead of Codex's own models.

Cause. codexChatGPT (internal/agent/codex.go:2022 on 0d2a10116) took any
failed read or parse of auth.json as "not signed in to ChatGPT". Codex
rewrites auth.json in place when it refreshes its tokens (codex-rs
login/src/auth/storage.rs FileAuthStorage::save: OpenOptions
truncate(true), then write_all), so a read in that moment finds it empty
or cut off; a keychain read that fails for a moment is the same. Sync
(codex.go:1306, run from every SyncCatalog) then took a Codex on a magpie
model beside its sign-in for one "with no ChatGPT sign-in" and called
set, which (codex.go:1079) made magpie Codex's provider with no codex.out
mark. Nothing put it back: Sync returns it beside the sign-in only from
codex.out, so it stayed until the next pick or group switch. A pick in
that moment (a group switch, the Agents page) did the same, and while
the account was held (codex.out) it forgot the mark.

Fix. provider.CodexSignInKnown says whether the read says anything: no
auth.json, no keychain item, or a store magpie doesn't read is known;
a read error, an auth.json that isn't valid JSON (empty, cut off), or a
keychain read that failed is unknown. codexChatGPTKnown builds on it,
and Codex's chatGPT closure takes an unknown read as magpie last wired
it (joined, beside, or codex.out). A sign-in really gone (codex logout)
or one with no ChatGPT token (an API key) still moves Codex onto magpie
as its provider, as before. codexChatGPT keeps its bool for connectinfo.

Tests (red on the old code, by putting the old answer back by hand in
the closure: every subtest of the first and the second failed):
- TestCodexHalfWrittenAuthKeepsSignIn: beside the sign-in, auth.json
  empty / cut off / not JSON, then Sync and a pick: stays beside; on the
  old code it went to model_provider = "magpie" and stayed there after
  auth.json was whole again and Sync ran.
- TestCodexHalfWrittenAuthKeepsOut: held (codex.out), a pick while
  auth.json is empty keeps the mark, and Sync puts it back beside the
  sign-in once the account has room.
- TestCodexSignInGoneStillKnown: logged out, or an API key: magpie its
  provider, as before.
- TestCodexSignInKnown (provider): signed in, empty, half, removed,
  keyring with no item, keyring refusing, ephemeral.
docs/subsystems/agent-wiring.md says the rule.

Run at the pushed head (this commit on origin/main 761904b5a):
go test -tags nogui -count=1 ./internal/agent -run Codex: ok (26s);
./internal/provider -run Codex: ok (19s); gofmt -l: none; GOOS=linux
and GOOS=windows go vet -tags nogui ./...: ok.
Full suite (go test -tags nogui -timeout 45m ./..., sandbox HOME): still
queued behind other sessions' suites at push time, pushed without
waiting per the owner's rule; a red from this change gets a follow-up,
an unrelated one an issue.

Not tried: the real Codex app through a real token refresh; the race
was reproduced with auth.json written empty / cut off by the test, and
Codex's in-place write was read from codex-rs main's source, not traced
on lucy's machine. Whether lucy's flips were this or the held-account
move (codex.out, CodexUsedUp: allowance out and no credits) isn't known
from the report; this one is the one that sticks after the account is
fine.
This commit is contained in:
yetone
2026-10-25 01:49:13 +08:00
parent 761904b5ab
commit 7b1faf99f2
5 changed files with 214 additions and 7 deletions
+1
View File
@@ -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.
+31 -7
View File
@@ -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
}
return a.Tokens.Access != ""
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 != nil && a.Tokens.Access != "", true
}
// codexReached reads Codex's newest model request since a time — the
+123
View File
@@ -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)
}
})
}
}
+22
View File
@@ -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()) {
+37
View File
@@ -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)
}