agent, provider: with CODEX_HOME set, a model picked for Codex goes to $CODEX_HOME/config.toml, the file Codex reads, and its sign-in is read and switched there (#1513, Wakkana, sunxwei)

Wakkana on Discord (macOS, Codex CLI 0.162.1) keeps Codex in a CODEX_HOME
of their own. Picking a model in magpie wrote ~/.codex/config.toml and
~/.codex/magpie-models.json, which Codex never reads, while magpie read the
pick back from the same file and showed it applied.

Checked each claim in the source: codexIn built its folder from
filepath.Join(at.home, ".codex"); so did StandIn, the compact-window tune
and KeepCodexDaemonCurrent; codexAuthPath (logins.go), codexAccount
(account.go) and the Usage card's auth.json (subscription_usage.go) read a
hardcoded ~/.codex, and since the app-server restart takes its home from
codexAuthPath, it restarted ~/.codex's daemon too. sessions.CodexDir,
catalog.CodexHome, library's codexDir and import_codex's config path
already read CODEX_HOME, each with its own copy of the rule.

Now there is one rule, appdir.CodexHome / CodexHomeIn: $CODEX_HOME through
appdir.LookupEnv (so the value proc.UserPath lends the desktop app from the
login shell counts, and a relative one reads as unset), else ~/.codex.
Every place that reads or writes Codex's files goes through it:
config.toml and the catalog (codexIn, so detection, Dir, models_cache,
history, logs, threads too), StandIn, tune, the daemon check, auth.json
read/switch/sign-in/sign-out, the import's own-catalog check, sessions,
the models cache, library targets (AGENTS.md, skills, MCP, rtk). A WSL
distro's Codex keeps ~/.codex (place.codexHome), since magpie can't read
a distro's variables. Left as they are, on purpose: library's project-level
.codex/config.toml (Codex reads that in the project whatever CODEX_HOME
is), sessions/wsl.go and wsl.go's distro probes, cliupdate's standalone
install path, and gateway/prompt.go's "/.codex/" path heuristic for a
Claude Code memory file. Codex itself doesn't expand "~" in CODEX_HOME
(0.162.0: 'CODEX_HOME points to "~/x", but that path does not exist').

Tests:
- TestCodexHomeEnvTakesThePick (agent): CODEX_HOME set, pick fakeup/m1:
  config.toml and magpie-models.json land in CODEX_HOME, Get reads it back,
  StandIn and tune use it, nothing exists under ~/.codex. Old codexIn:
  FAIL "Codex's files at …/001/.codex/config.toml, want under
  …/codex-home"; old tune.go: FAIL "tune didn't write
  $CODEX_HOME/config.toml"; old StandIn: FAIL "stand-in … is """.
- TestCodexHomeEnvSignIn (provider): auth.json, config import path and
  daemon home are CODEX_HOME's; two accounts listed from it; SwitchLogin
  writes it; ~/.codex never created. Old account.go: FAIL "sign-in in
  $CODEX_HOME not read"; old codexAuthPath: FAIL "auth.json at
  …/.codex/auth.json".
- TestRestartCodexDaemon and gui's TestCodexDaemonRestartRoute asserted the
  old ~/.codex daemon under CODEX_HOME=/somewhere/else; they now want
  /somewhere/else. TestFolderVarsAreListed scans appdir/codex.go too, so
  its CODEX_HOME canary still finds the read.

Real use, sandbox HOME + CODEX_HOME=<sb>/custom-codex, MAGPIE_ADDR on a
free port with a stand-in listener: `magpie codex fakeup/m1` (this build)
wrote custom-codex/config.toml + magpie-models.json, no <sb>/home/.codex;
real codex 0.162.0 with that CODEX_HOME: `codex debug models` listed
fakeup/m1, `codex exec` sent POST /v1/responses model=fakeup/m1 to magpie's
address. The origin/main build in the same sandbox wrote
<sb>/home/.codex/{config.toml,magpie-models.json} and left
custom-codex/config.toml at model = "gpt-5.5" (the report). The GUI app
was not run.

#1513 (sunxwei, native Windows 0.1.1157, CODEX_HOME=F:\codex-home) is the
same bug. Windows has no shell to borrow from: a user-level variable is in
the environment Explorer hands the Start-menu app, which is what
appdir.LookupEnv reads, and a drive-letter path is rooted. On the Windows
box: the agent, provider and appdir test binaries (GOOS=windows) pass
TestCodexHomeEnvTakesThePick and TestCodexHomeEnvSignIn with CODEX_HOME a
C:\ temp folder; this build's magpie.exe codex fakeup/m1 in a sandbox
USERPROFILE with CODEX_HOME=D:\codexhome-sb\custom-codex wrote config.toml
(model, magpie provider, catalog) and magpie-models.json there and created
no %USERPROFILE%\.codex. Codex itself isn't installed there, so it was
not run on Windows.

Run: go test -tags nogui ./... in a temp HOME (all ok after the three test
updates above; re-ran agent, provider, gui, catalog, sessions, library,
appdir, usage, codexcat after rebase; gateway after rebase hit the 10m
default timeout at load ~150 and passed with -timeout 25m in 656s),
gofmt -l clean, go vet +
GOOS=linux + GOOS=windows go vet -tags nogui on the touched packages.
This commit is contained in:
yetone
2026-10-10 22:36:28 +08:00
parent cc8eb5a742
commit d47c0fea0b
18 changed files with 192 additions and 54 deletions
+18 -12
View File
@@ -43,7 +43,8 @@ var notAnAgent = map[string]string{
// meeting the agent a developer really has installed — which is how #522 came
// about, four sandboxes clearing lists of their own that had each drifted.
//
// The five packages are this one, sessions, provider, library and gateway:
// The five packages are this one, sessions, provider, library and gateway,
// with appdir's codex.go, where CODEX_HOME is read for all of them:
// every agent's folder variable magpie reads is read in one of them, and the
// rest of the repository reads only magpie's own variables, the process' and
// the desktop's. Their sources are read as files rather than imported, since a
@@ -62,6 +63,7 @@ func TestFolderVarsAreListed(t *testing.T) {
}
dirs := []string{".", filepath.Join("..", "sessions"), filepath.Join("..", "provider"), filepath.Join("..", "library"), filepath.Join("..", "gateway")}
found := map[string]string{}
var files []string
for _, dir := range dirs {
entries, err := os.ReadDir(dir)
if err != nil {
@@ -72,18 +74,22 @@ func TestFolderVarsAreListed(t *testing.T) {
if e.IsDir() || !strings.HasSuffix(n, ".go") || strings.HasSuffix(n, "_test.go") {
continue
}
b, err := os.ReadFile(filepath.Join(dir, n))
if err != nil {
t.Fatal(err)
files = append(files, filepath.Join(dir, n))
}
}
files = append(files, filepath.Join("..", "appdir", "codex.go"))
for _, n := range files {
b, err := os.ReadFile(n)
if err != nil {
t.Fatal(err)
}
for _, m := range readsEnv.FindAllStringSubmatch(string(b), -1) {
name := m[1]
if name == "" {
name = m[2]
}
for _, m := range readsEnv.FindAllStringSubmatch(string(b), -1) {
name := m[1]
if name == "" {
name = m[2]
}
if _, ok := found[name]; !ok {
found[name] = filepath.Join(dir, n)
}
if _, ok := found[name]; !ok {
found[name] = n
}
}
}
+1 -1
View File
@@ -1858,7 +1858,7 @@ func StandIn(agent, model string) string {
return ""
}
if agent == "codex" {
return codexStandIn(filepath.Join(home, ".codex", "config.toml"))
return codexStandIn(filepath.Join(here(home).codexHome(), "config.toml"))
}
if m := claudeStandIn(filepath.Join(home, ".claude", "settings.json"), model); m != "" || runtime.GOOS != "windows" {
return m
+1 -1
View File
@@ -100,7 +100,7 @@ func codexEfforts(ms []catalog.Model, model string) []Option {
}
func codexIn(at place) *Agent {
dir := filepath.Join(at.home, ".codex")
dir := at.codexHome()
path := filepath.Join(dir, "config.toml")
catalogPath := filepath.Join(dir, "magpie-models.json")
get := func(k string) string { v, _ := edit.GetTOMLTop(path, k); return v }
+1 -1
View File
@@ -83,7 +83,7 @@ func KeepCodexDaemonCurrent(ctx context.Context) {
if err != nil {
return
}
path := filepath.Join(home, ".codex", "config.toml")
path := filepath.Join(here(home).codexHome(), "config.toml")
t := time.NewTicker(codexDaemonEvery)
defer t.Stop()
for {
+60
View File
@@ -0,0 +1,60 @@
package agent
import (
"os"
"path/filepath"
"strings"
"testing"
)
// With CODEX_HOME set, a model picked for Codex goes to
// $CODEX_HOME/config.toml, the file Codex reads, and its catalog beside it;
// nothing is written under ~/.codex, and what magpie shows as applied is
// read back from there (Wakkana on Discord, Codex 0.162.1: the pick went to
// ~/.codex/config.toml, Codex never saw it, and magpie showed it applied).
func TestCodexHomeEnvTakesThePick(t *testing.T) {
home, _ := codexHome(t, "", "")
if err := os.RemoveAll(filepath.Join(home, ".codex")); err != nil {
t.Fatal(err)
}
ch := filepath.Join(t.TempDir(), "codex-home")
os.MkdirAll(ch, 0o755)
os.WriteFile(filepath.Join(ch, "config.toml"), []byte("model = \"gpt-5.5\"\n"), 0o644)
t.Setenv("CODEX_HOME", ch)
cx := codex(home)
if cx.Path != filepath.Join(ch, "config.toml") || cx.Dir != ch {
t.Fatalf("Codex's files at %s (%s), want under %s", cx.Path, cx.Dir, ch)
}
if err := cx.Fields[0].Set("fake/m1"); err != nil {
t.Fatal(err)
}
b, _ := os.ReadFile(filepath.Join(ch, "config.toml"))
if cfg := string(b); !strings.Contains(cfg, `model = "fake/m1"`) || !strings.Contains(cfg, "magpie-models.json") {
t.Fatalf("$CODEX_HOME/config.toml doesn't have the pick:\n%s", cfg)
}
if _, err := os.Stat(filepath.Join(ch, "magpie-models.json")); err != nil {
t.Fatalf("the catalog isn't beside it: %v", err)
}
if got := codex(home).Fields[0].Get(); got != "fake/m1" {
t.Fatalf("magpie reads the pick back as %q", got)
}
if m := StandIn("codex", "gpt-5"); m != "fake/m1" {
t.Fatalf("the gateway's stand-in for Codex is %q, read from somewhere else", m)
}
if err := TuneApply(home, "codex", TuneCompact, "", "200000"); err != nil {
t.Fatal(err)
}
b, _ = os.ReadFile(filepath.Join(ch, "config.toml"))
if !strings.Contains(string(b), "model_auto_compact_token_limit = 200000") {
t.Fatalf("tune didn't write $CODEX_HOME/config.toml:\n%s", b)
}
if _, err := os.Stat(filepath.Join(home, ".codex")); !os.IsNotExist(err) {
var names []string
filepath.WalkDir(filepath.Join(home, ".codex"), func(p string, _ os.DirEntry, _ error) error {
names = append(names, p)
return nil
})
t.Fatalf("written under ~/.codex with CODEX_HOME set: %v", names)
}
}
+1 -1
View File
@@ -89,7 +89,7 @@ func tuneWhere(home, agent, knob, model string) (tunePlace, error) {
}
case "codex":
if knob == TuneCompact {
return tunePlace{path: filepath.Join(home, ".codex", "config.toml"), key: "model_auto_compact_token_limit", toml: true, number: true}, nil
return tunePlace{path: filepath.Join(here(home).codexHome(), "config.toml"), key: "model_auto_compact_token_limit", toml: true, number: true}, nil
}
}
return tunePlace{}, fmt.Errorf("%s has no setting %q tune can put in", agent, knob)
+10
View File
@@ -67,6 +67,16 @@ func (p place) getenv(k string) string {
return appdir.Getenv(k)
}
// codexHome is Codex's folder at the place: $CODEX_HOME on this machine
// (appdir.CodexHome), ~/.codex in a distro, whose variables magpie can't
// read.
func (p place) codexHome() string {
if p.spell != nil {
return filepath.Join(p.home, ".codex")
}
return appdir.CodexHomeIn(p.home)
}
// exists is whether there is a file or folder at path, as an agent looks
// for the one it reads; false at a cold place.
func (p place) exists(path string) bool {
+28
View File
@@ -0,0 +1,28 @@
package appdir
import (
"os"
"path/filepath"
)
// CodexHome is the folder Codex CLI keeps its files in: config.toml,
// auth.json, the model catalog magpie writes, sessions, AGENTS.md and
// skills. It is $CODEX_HOME when that is set, as codex-rs's find_codex_home
// reads it, else ~/.codex. Every place magpie reads or writes Codex's files
// goes through here (Wakkana on Discord: with CODEX_HOME set, a model picked
// in magpie went to ~/.codex/config.toml, which Codex never read).
// CODEX_HOME is read through LookupEnv, so the value a login shell lends the
// desktop app (proc.UserPath) counts, and a relative one, which Codex would
// take from whatever folder it runs in, reads as unset.
func CodexHome() string {
home, _ := os.UserHomeDir()
return CodexHomeIn(home)
}
// CodexHomeIn is CodexHome with home as the user's home folder.
func CodexHomeIn(home string) string {
if d := Getenv("CODEX_HOME"); d != "" {
return d
}
return filepath.Join(home, ".codex")
}
+1 -7
View File
@@ -1088,13 +1088,7 @@ func Providers() []string {
}
// CodexHome is where Codex CLI keeps its state: $CODEX_HOME, else ~/.codex.
func CodexHome() string {
if dir := appdir.Getenv("CODEX_HOME"); dir != "" {
return dir
}
home, _ := os.UserHomeDir()
return filepath.Join(home, ".codex")
}
func CodexHome() string { return appdir.CodexHome() }
// CodexModelsCache is the model list Codex CLI keeps, under CodexHome.
func CodexModelsCache() string { return filepath.Join(CodexHome(), "models_cache.json") }
+4 -3
View File
@@ -15,10 +15,11 @@ import (
)
// The Restart button runs `codex app-server daemon restart` with the codex
// magpie finds, for the Codex home it switches; a stand-in codex writes
// magpie finds, for the Codex home it switches, the user's CODEX_HOME when
// that is set; a stand-in codex writes
// down how it was run, since the real one would restart the user's daemon.
func TestCodexDaemonRestartRoute(t *testing.T) {
h := sandboxHome(t)
sandboxHome(t)
bin := t.TempDir()
t.Setenv("PATH", bin)
t.Setenv("CODEX_HOME", "/somewhere/else")
@@ -41,7 +42,7 @@ func TestCodexDaemonRestartRoute(t *testing.T) {
t.Fatalf("state %v %q", err, st.CodexDaemon)
}
b, _ := os.ReadFile(rec)
if got, want := strings.TrimSpace(string(b)), "app-server daemon restart|"+filepath.Join(h, ".codex"); got != want {
if got, want := strings.TrimSpace(string(b)), "app-server daemon restart|/somewhere/else"; got != want {
t.Fatalf("ran %q, want %q", got, want)
}
t.Setenv("FAIL", "1")
+1 -6
View File
@@ -74,12 +74,7 @@ func codebuddyMCP(dir string) string {
return all[0]
}
func codexDir() string {
if d := appdir.Getenv("CODEX_HOME"); d != "" {
return d
}
return filepath.Join(home(), ".codex")
}
func codexDir() string { return appdir.CodexHomeIn(home()) }
// targetOf is where a known agent keeps them, or nil for one magpie can't
// give any of them to.
+1 -1
View File
@@ -879,7 +879,7 @@ type codexAuth struct {
}
func codexAccount(home string) (Provider, bool) {
path := filepath.Join(home, ".codex", "auth.json")
path := filepath.Join(appdir.CodexHomeIn(home), "auth.json")
b, err := os.ReadFile(path)
var a codexAuth
if err != nil || json.Unmarshal(b, &a) != nil || a.Tokens.AccessToken == "" || a.AuthMode == "apikey" {
+3 -2
View File
@@ -204,8 +204,9 @@ func TestRestartCodexDaemon(t *testing.T) {
if got := read(".args"); got != "app-server daemon restart" {
t.Errorf("args %q", got)
}
home, _ := os.UserHomeDir()
if got, want := read(".home"), filepath.Join(home, ".codex"); got != want {
// the daemon of the CODEX_HOME magpie writes auth.json in, which is the
// user's own CODEX_HOME when that is set
if got, want := read(".home"), "/somewhere/else"; got != want || filepath.Clean(got) != filepath.Dir(codexAuthPath()) {
t.Errorf("CODEX_HOME %q, want %q (where magpie writes auth.json)", got, want)
}
if got := read(".stdin"); got != "other" {
+55
View File
@@ -0,0 +1,55 @@
package provider
import (
"os"
"path/filepath"
"testing"
)
// With CODEX_HOME set, Codex's sign-in is read from $CODEX_HOME/auth.json,
// a switch of account writes it there, the config imported from and the
// app-server restarted are that home's, and nothing is written under
// ~/.codex (Wakkana on Discord: magpie read and wrote a ~/.codex Codex
// never looked at).
func TestCodexHomeEnvSignIn(t *testing.T) {
home := signIn(t)
ch := filepath.Join(t.TempDir(), "codex-home")
if err := os.Rename(filepath.Join(home, ".codex"), ch); err != nil {
t.Fatal(err)
}
t.Setenv("CODEX_HOME", ch)
if got := codexAuthPath(); got != filepath.Join(ch, "auth.json") {
t.Fatalf("auth.json at %s", got)
}
if got := codexConfigPath(); got != filepath.Join(ch, "config.toml") {
t.Fatalf("config.toml imported from %s", got)
}
if got := CodexHome(); got != ch {
t.Fatalf("the app-server restarted is %s's", got)
}
if p, ok := codexAccount(home); !ok || p.Account.User != "me@example.com" {
t.Fatalf("Codex's sign-in in $CODEX_HOME not read: %v %+v", ok, p.Account)
}
rememberLogins(true)
codexSignIn(t, home, "work@example.com", "r-work")
// codexSignIn writes as Codex would without CODEX_HOME; put it where
// Codex reads it
if err := os.Rename(filepath.Join(home, ".codex", "auth.json"), filepath.Join(ch, "auth.json")); err != nil {
t.Fatal(err)
}
os.Remove(filepath.Join(home, ".codex"))
rememberLogins(true)
if users, active := loginUsers(Logins("codex")); len(users) != 2 || active != "work@example.com" {
t.Fatalf("accounts %v, in use %q", users, active)
}
if err := SwitchLogin("codex", "me@example.com"); err != nil {
t.Fatal(err)
}
if p, ok := codexAccount(home); !ok || p.Account.User != "me@example.com" {
t.Fatalf("the switch didn't reach $CODEX_HOME/auth.json: %+v", p.Account)
}
if _, err := os.Stat(filepath.Join(home, ".codex")); !os.IsNotExist(err) {
t.Fatalf("written under ~/.codex with CODEX_HOME set: %v", err)
}
}
+2 -7
View File
@@ -11,12 +11,7 @@ import (
)
func codexConfigPath() string {
dir := appdir.Getenv("CODEX_HOME")
if dir == "" {
home, _ := os.UserHomeDir()
dir = filepath.Join(home, ".codex")
}
return filepath.Join(dir, "config.toml")
return filepath.Join(appdir.CodexHome(), "config.toml")
}
func readCodexConfig(path string) ([]AppImport, error) {
@@ -117,7 +112,7 @@ func codexImportModels(configPath, catalogPath string) []string {
} else if !filepath.IsAbs(catalogPath) {
catalogPath = filepath.Join(filepath.Dir(configPath), catalogPath)
}
if filepath.Clean(catalogPath) == filepath.Join(home, ".codex", "magpie-models.json") {
if filepath.Clean(catalogPath) == filepath.Join(appdir.CodexHomeIn(home), "magpie-models.json") {
return nil
}
b, err := os.ReadFile(catalogPath)
+2 -4
View File
@@ -493,10 +493,8 @@ func claudeUser(email, plan string, acct map[string]any) string {
return email + " · " + org
}
func codexAuthPath() string {
home, _ := os.UserHomeDir()
return filepath.Join(home, ".codex", "auth.json")
}
// codexAuthPath is Codex's sign-in, under its home (appdir.CodexHome).
func codexAuthPath() string { return filepath.Join(appdir.CodexHome(), "auth.json") }
// CodexAPIKeySignedIn says Codex itself is signed in with an OpenAI
// API key rather than a ChatGPT account (auth.json's auth_mode): its
+2 -1
View File
@@ -19,6 +19,7 @@ import (
"sync/atomic"
"time"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/plugin"
)
@@ -374,7 +375,7 @@ func fetchSubscriptionUsage(ctx context.Context) []SubscriptionQuota {
if ls := accountsOf("codex"); len(ls) > 1 {
fetches = append(fetches, perLogin(via("codex"), ls, accountCard("codex"))...)
} else {
auth := filepath.Join(home, ".codex", "auth.json")
auth := filepath.Join(appdir.CodexHomeIn(home), "auth.json")
fetches = append(fetches, withUser(ctx, p.Account.User, func() SubscriptionQuota { return codexSubscriptionUsage(viaLogin("codex", p.Account.User), auth) }))
}
}
+1 -7
View File
@@ -368,13 +368,7 @@ func ClaudeDir() string {
}
// CodexDir is Codex's folder: $CODEX_HOME, else ~/.codex.
func CodexDir() string {
if d := appdir.Getenv("CODEX_HOME"); d != "" {
return d
}
home, _ := os.UserHomeDir()
return filepath.Join(home, ".codex")
}
func CodexDir() string { return appdir.CodexHome() }
func stat(f *file) bool {
fi, err := os.Stat(f.path)