diff --git a/internal/agent/agentenv_test.go b/internal/agent/agentenv_test.go index 8669a7e83..12f13d271 100644 --- a/internal/agent/agentenv_test.go +++ b/internal/agent/agentenv_test.go @@ -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 } } } diff --git a/internal/agent/claude.go b/internal/agent/claude.go index 796784b23..7d721518b 100644 --- a/internal/agent/claude.go +++ b/internal/agent/claude.go @@ -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 diff --git a/internal/agent/codex.go b/internal/agent/codex.go index 19d7034ae..74f6e386a 100644 --- a/internal/agent/codex.go +++ b/internal/agent/codex.go @@ -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 } diff --git a/internal/agent/codex_daemon.go b/internal/agent/codex_daemon.go index 94f7113d3..5674588cc 100644 --- a/internal/agent/codex_daemon.go +++ b/internal/agent/codex_daemon.go @@ -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 { diff --git a/internal/agent/codex_home_env_test.go b/internal/agent/codex_home_env_test.go new file mode 100644 index 000000000..cb22ad22e --- /dev/null +++ b/internal/agent/codex_home_env_test.go @@ -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) + } +} diff --git a/internal/agent/tune.go b/internal/agent/tune.go index eb952ac55..7d933113b 100644 --- a/internal/agent/tune.go +++ b/internal/agent/tune.go @@ -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) diff --git a/internal/agent/wsl.go b/internal/agent/wsl.go index ae62a6cdb..c28df9f95 100644 --- a/internal/agent/wsl.go +++ b/internal/agent/wsl.go @@ -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 { diff --git a/internal/appdir/codex.go b/internal/appdir/codex.go new file mode 100644 index 000000000..433b4c21f --- /dev/null +++ b/internal/appdir/codex.go @@ -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") +} diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index c55bc1a0f..9e806624d 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -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") } diff --git a/internal/gui/codex_daemon_test.go b/internal/gui/codex_daemon_test.go index ef416e8a9..7f23f60ae 100644 --- a/internal/gui/codex_daemon_test.go +++ b/internal/gui/codex_daemon_test.go @@ -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") diff --git a/internal/library/targets.go b/internal/library/targets.go index 906b36b00..1cd09025a 100644 --- a/internal/library/targets.go +++ b/internal/library/targets.go @@ -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. diff --git a/internal/provider/account.go b/internal/provider/account.go index 96a1e7c11..36a383f75 100644 --- a/internal/provider/account.go +++ b/internal/provider/account.go @@ -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" { diff --git a/internal/provider/codex_daemon_test.go b/internal/provider/codex_daemon_test.go index cb05eb6d4..3be3da8bc 100644 --- a/internal/provider/codex_daemon_test.go +++ b/internal/provider/codex_daemon_test.go @@ -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" { diff --git a/internal/provider/codex_home_env_test.go b/internal/provider/codex_home_env_test.go new file mode 100644 index 000000000..519cf5c16 --- /dev/null +++ b/internal/provider/codex_home_env_test.go @@ -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) + } +} diff --git a/internal/provider/import_codex.go b/internal/provider/import_codex.go index 7f5a6c54f..5d55565df 100644 --- a/internal/provider/import_codex.go +++ b/internal/provider/import_codex.go @@ -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) diff --git a/internal/provider/logins.go b/internal/provider/logins.go index f1dabb7d6..df72624e4 100644 --- a/internal/provider/logins.go +++ b/internal/provider/logins.go @@ -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 diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index e997dbf4d..60ea61fa6 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -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) })) } } diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 1ad468808..a6c7f2254 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -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)