Files
magpie/internal/agent/agentenv_test.go
T
yetone d47c0fea0b 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.
2026-10-10 22:36:28 +08:00

122 lines
4.9 KiB
Go

package agent
import (
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/agentenv"
)
// readsEnv matches the two ways these packages name a variable they read to
// find an agent's folder: as the argument of a Getenv, a LookupEnv or a
// place's getenv, and as the env of a table entry, which is how Qoder's two
// builds are named (read through at.getenv(b.env)).
var readsEnv = regexp.MustCompile(`(?:Getenv|LookupEnv|getenv)\("([A-Z][A-Z_0-9]*)"\)|env:\s*"([A-Z][A-Z_0-9]*)"`)
// notAnAgent are the variables the same sources read that are not an agent's
// folder, so no sandbox clears them through agentenv.Vars.
var notAnAgent = map[string]string{
"APPDATA": "Windows' own folder, which a sandbox sets to one of its own rather than clears",
"LOCALAPPDATA": "the same",
"PATH": "the process' own",
"TZ": "the process' own",
"USER": "the process' own",
"XDG_CONFIG_HOME": "magpie's own folder's, which appdir decides",
"XDG_DATA_HOME": "the same",
"MAGPIE_ADDR": "magpie's own",
"MAGPIE_DEBUG": "magpie's own debug flag",
"MAGPIE_PUBLIC_URL": "magpie's own public URL",
"MAGPIE_TRUST_PROXY": "magpie's own: a proxy here signs its clients in (#1022)",
"MAGPIE_EFFORT_UPDATES": "magpie's own switch for effort updates (#617)",
"MAGPIE_SITE_ORIGIN": "a site origin magpie's Omarchy theme answers, to try the site locally",
"MAGPIE_PARTNERS": "where magpie's own partner list is read from (a URL, or off), not a folder",
"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "Claude Code's behaviour flag, not an agent's folder",
}
// TestFolderVarsAreListed says every variable the packages that find an
// agent's folder read is one a sandbox clears. Nothing said so before, so a
// new agent could take a variable of its own and every sandbox would go on
// 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,
// 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
// test in sessions or provider cannot import this package, which imports
// them; what the walk looks at is what they say, not what they do.
//
// What this cannot see is a variable read through a name the sources build at
// runtime, as omoDir reads OMO_CODING_AGENT_DIR and SENPI_CODING_AGENT_DIR
// out of a slice, or through a constant (const fooEnv = "FOO_HOME" and then
// os.Getenv(fooEnv)). Both are in agentenv.Vars; a third taken either way
// would not be caught here.
func TestFolderVarsAreListed(t *testing.T) {
listed := make(map[string]bool, len(agentenv.Vars))
for _, v := range agentenv.Vars {
listed[v] = true
}
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 {
t.Fatal(err)
}
for _, e := range entries {
n := e.Name()
if e.IsDir() || !strings.HasSuffix(n, ".go") || strings.HasSuffix(n, "_test.go") {
continue
}
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]
}
if _, ok := found[name]; !ok {
found[name] = n
}
}
}
// One name read each way the pattern matches, so that a change in how a
// variable is read empties the scan loudly instead of leaving the test
// nothing to complain of.
for _, canary := range []string{"CODEX_HOME", "QODER_CONFIG_DIR"} {
if _, ok := found[canary]; !ok {
t.Errorf("%s was not found in these sources, so readsEnv no longer matches the way a variable is read", canary)
}
}
// And no excuse outlives the variable it was for.
for n := range notAnAgent {
if _, ok := found[n]; !ok {
t.Errorf("%s is in notAnAgent, but nothing in these sources reads it any more", n)
}
}
names := make([]string, 0, len(found))
for n := range found {
names = append(names, n)
}
slices.Sort(names)
for _, n := range names {
if listed[n] || notAnAgent[n] != "" {
continue
}
t.Errorf("%s, read by %s, is not in agentenv.Vars, so no sandbox clears it and a test meets the agent a developer really has installed: add it to Vars, or to notAnAgent here with a reason if it is not an agent's folder", n, found[n])
}
}