agent: a Codex the user disconnected stays disconnected through restarts and updates (paynezhuang)

paynezhuang on Discord: magpie's first start pointed Codex at the gateway
by itself; they switched Codex on, chose "Disconnect from magpie", and after
each update and restart config.toml had openai_base_url again.

Cause: Codex's Sync runs at every start (SyncCatalog) and calls failover(),
which writes openai_base_url whenever Codex is signed in to ChatGPT and
another of the user's ChatGPT accounts is on in magpie. Nothing told it the
user had taken magpie out. The same Sync's #701 branch (sign-in "magpie
API" on one of Codex's own models) wired a disconnected Codex again too, and
with magpie API Disconnect itself left failover's base URL behind (its own
model Set ran failover).

Fix: Disconnect marks the agent disconnected in the stash
(<id>.disconnected) before it writes anything; connect() and an Apply that
leaves the agent wired take the mark out. Codex's failover treats a marked
Codex as having no other account on (and takes out a base URL it owns), and
the #701 re-wire skips it. Failover for a Codex never disconnected, and a
base URL written by hand (#856), are as before.

Siblings: TestDisconnectStaysThroughSync connects and disconnects every
non-WSL agent with fields, then runs SyncCatalog and dsh's KeepDshWired
round twice: none is wired again and no file outside magpie's own changes.
It passes on the old code too (only Codex had the problem); it guards the
class. Cursor, Copilot CLI and Devin can't be connected in the sandbox and
skip; Native (Aside) and Launch agents don't Sync wiring.

Run:
- TestCodexDisconnectStaysWithAccountsOn (ChatGPT and magpie API) and
  TestCodexAPIDisconnectStays fail on the old code ("start 0 after
  Disconnect wired Codex again", "disconnect left magpie in") and pass now.
- go test -tags nogui ./internal/agent ./internal/gui . (sandbox HOME): ok
- gofmt -l, go vet, GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/agent: clean
- Real magpie (nogui build, `magpie web --gateway`) under a scratchpad
  HOME, gateway 127.0.0.1:3481, web 3482, fake ChatGPT auth.json plus a
  second ChatGPT login on: old build re-wrote openai_base_url 2s after a
  restart following Disconnect. New build: first run wires (failover),
  connect, disconnect, restart as 0.1.99998, then start as 0.1.99999
  (last-version moved): config.toml byte-identical to after Disconnect,
  no failover; connecting again wires it and a restart keeps it.
This commit is contained in:
yetone
2026-10-10 19:17:53 +08:00
parent 6d3bc9183d
commit 4e584faa51
4 changed files with 241 additions and 6 deletions
+3 -2
View File
@@ -32,7 +32,7 @@ something else shows up as drift.
2. **Pick.** `Pick` sets a field from the model picker. Picking one of magpie's models on an agent that isn't connected connects it first.
3. **Notice.** After a change the page shows `Notice` when the agent reads its config only at start-up and needs a restart.
4. **Drift.** As the Agents page is drawn, `Drift` compares the config with `applied.json`. It runs `Check` first, then each field. When the config is right and points at an address off loopback (a WSL twin under NAT, or this machine's Codex at an address the user kept, #816), it tries that address ([`reach.go`](../../internal/agent/reach.go)): in the background, at most every 20 s, never waited for. When nothing answers there while the gateway answers on loopback, the drift is `unreachable` (#1013), with what has to listen there: Share on local network, the user's portproxy, Windows' firewall. Then it checks whether the agent's latest use (`LastUsed`, `Reached`) reached the gateway.
5. **Disconnect.** `Disconnect` puts back what the stash kept and forgets the record.
5. **Disconnect.** `Disconnect` puts back what the stash kept and forgets the record. It also marks the agent disconnected (`<id>.disconnected` in the stash, `Disconnected`) until the user connects it again (`connect`, or an `Apply` that leaves it wired): nothing magpie does by itself puts magpie back in meanwhile, neither a start's `Sync` nor Codex's account failover nor #701's magpie API wiring (paynezhuang on Discord: Codex had `openai_base_url` back after every update).
## Constraints and failure behavior
@@ -56,7 +56,7 @@ something else shows up as drift.
- `unreachable` never sets anything: the config is right, and the page's pill only says what has to listen. The exception is an address a WSL distro reached Windows at before (`distro.Was`, kept in `wsl.json`) while it reaches Windows at another now: the pill offers that one, and `Reapply` moves the config there (`Agent.move`, Codex's `codexMoveGateway`). An address no distro was seen at is the user's own and is never moved. An unknown answer (no probe yet) and a gateway down on loopback too are not drift. Tests stub `reachProbe` 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.
- 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. 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.
- 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. 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.
- 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.
- Tuned settings are written only on the user's click, never by Sync or Connect. The value there before is stashed once (`tune.<agent>.<knob>[.<model>]` in `stash.json`), so Undo puts it back, or takes the key out (and a `modelSettings` entry left empty). A value the user changed after the click is theirs: Undo then only forgets the stash. A variable that comes before the setting (`CLAUDE_CODE_AUTO_COMPACT_WINDOW`, `FORCE_PROMPT_CACHING_5M`, `CLAUDE_CODE_PROMPT_CACHE_TTL`, `CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL`, in settings.json's `env` or magpie's own) is shown as `locked` and Apply refuses, since the setting would change nothing. Claude Code compacts at the smaller of the window set and the model's own (its `/autocompact` says "capped to 200k by model"), so advice starts from that, and a model that isn't Claude's has no window here (magpie's own compact wiring serves it). Advice changes a value only when the replay saves 3% or more, and of the windows within 1% of the cheapest takes the largest. Tokens are weighed as billed: cache reads 0.1, 5-minute writes 1.25, hour writes 2, output 5 for Claude; reads 0.1, writes 1, output 8 otherwise.
- A plugin's agent writes each key in place (JSON, YAML or env), the user's comments and other keys kept. What each key held before the first write is stashed under `plugin:<id>:<path>`, typed, and its own model or Disconnect puts every key back and takes out the ones that weren't there; the file is never written whole. A `connect` that throws or takes over a second writes nothing and says why. Its gateway key is `magpie-<id>` (`agentKeyAt`), and usage names its requests by that key or by its `ua` words (`usage.PluginAgents`).
@@ -71,6 +71,7 @@ go test -tags nogui ./internal/agent -run '^TestAir'
go test -tags nogui ./internal/agent -run '^TestAnte'
go test -tags nogui ./internal/agent -run '^TestPlugged'
go test -tags nogui ./internal/agent -run 'TestCodexFailoverOnlyKeepsOwnModels|TestCodexOwnModelThroughMagpieWhileAccountsOn|TestCodexHandWrittenBaseURLStays'
go test -tags nogui ./internal/agent -run 'TestDisconnectStaysThroughSync|TestCodexDisconnectStaysWithAccountsOn|TestCodexAPIDisconnectStays'
go test -tags nogui ./internal/tune ./internal/agent -run 'TestCompact|TestCacheTTL|TestTune'
node --test internal/gui/tests/context-tune.test.cjs
node --test internal/gui/tests/agent-connect.test.cjs internal/gui/tests/agent-disconnect-preview.test.cjs internal/gui/tests/claude-signin.test.cjs internal/gui/tests/agent-failover.test.cjs internal/gui/tests/plugin-agent.test.cjs
+18
View File
@@ -102,6 +102,11 @@ func (a *Agent) Apply(key, v string) error {
}
}
record(a.ID, f.Key, f.Get())
// magpie picked in by the user's own hand (magpie model, a pick in
// the CLI) connects it again
if a.Wired() {
forget(a.ID + disconnectedKey)
}
return nil
}
@@ -479,7 +484,16 @@ func (a *Agent) ConnectHow() (Connection, error) {
return a.connect()
}
// disconnectedKey, after an agent's id, marks in the stash an agent the
// user disconnected: Disconnect sets it, connecting again takes it out.
const disconnectedKey = ".disconnected"
// Disconnected reports whether the user disconnected the agent and hasn't
// connected it since.
func (a *Agent) Disconnected() bool { return stashLoad()[a.ID+disconnectedKey] == "1" }
func (a *Agent) connect() (Connection, error) {
forget(a.ID + disconnectedKey)
// what it is on now, for Disconnect to put back what it can't
// otherwise (Goose's own model)
now := a.Values()
@@ -647,6 +661,10 @@ func (a *Agent) Disconnect() error {
if !a.Wired() {
return nil
}
// the user's say, kept till they connect it again: nothing magpie does
// by itself (a start's Sync, Codex's account failover) puts magpie back
// in, this Disconnect's own writes included (paynezhuang on Discord)
stash(map[string]string{a.ID + disconnectedKey: "1"})
before, rec := a.Values(), appliedOf(a.ID)
if a.Unwire != nil {
if err := a.Unwire(); err != nil {
+10 -4
View File
@@ -480,9 +480,14 @@ func codexIn(at place) *Agent {
}
return nil
}
// the user disconnected Codex and hasn't connected it since: magpie
// writes nothing of its own back (paynezhuang on Discord: the base URL
// was back after every update)
disconnected := func() bool { return stashLoad()[at.key("codex"+disconnectedKey)] == "1" }
// Codex on one of its own models goes through magpie too while more of
// its ChatGPT accounts are on there, so one out of its allowance hands
// the turn to the next; with none, it goes straight to OpenAI again
// the turn to the next; with none, or once the user disconnected Codex,
// it goes straight to OpenAI again
failover := func() error {
if wired() || asProvider() {
return nil
@@ -495,7 +500,7 @@ func codexIn(at place) *Agent {
if p != "" && p != "openai" && !mirror {
return nil
}
on := codexFailover()
on := !disconnected() && codexFailover()
if mirror {
t, _ := edit.GetTOMLTable(path, "model_providers."+p)
hasGateway := t["base_url"] == at.codexURL()
@@ -856,8 +861,9 @@ func codexIn(at place) *Agent {
return err
}
// magpie API on one of Codex's own models, as an older magpie
// left it unwired: wired again, as picking it does now (#701)
if m := get("model"); api() && !isMagpie(m) && !asProvider() && codexOwnViaMagpie(m) != "" {
// left it unwired: wired again, as picking it does now (#701);
// not one the user disconnected, which this left the same
if m := get("model"); api() && !disconnected() && !isMagpie(m) && !asProvider() && codexOwnViaMagpie(m) != "" {
return set(m)
}
// on a magpie model by the base URL alone with no ChatGPT
+210
View File
@@ -0,0 +1,210 @@
package agent
import (
"encoding/base64"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// agentFiles reads every file under home but magpie's own (its settings,
// stash and caches): what an agent reads its config from.
func agentFiles(t *testing.T, home string) map[string]string {
t.Helper()
files := map[string]string{}
filepath.WalkDir(home, func(p string, e os.DirEntry, err error) error {
if err != nil {
return nil
}
rel, _ := filepath.Rel(home, p)
if e.IsDir() {
if rel == filepath.Join(".config", "magpie") || rel == ".cache" {
return filepath.SkipDir
}
return nil
}
b, _ := os.ReadFile(p)
files[rel] = string(b)
return nil
})
return files
}
// A disconnect the user chose stays through magpie's start-up sync, which
// runs at every start and after every update (SyncCatalog): no agent is
// wired again, and none of its files changes (paynezhuang on Discord: Codex
// had magpie's base URL back after each update). So does it through what a
// running gateway keeps up (dsh's routes).
func TestDisconnectStaysThroughSync(t *testing.T) {
home, _ := codexHome(t, "", "")
managed := claudeManaged
claudeManaged = func() string { return filepath.Join(home, "managed-settings.json") }
t.Cleanup(func() { claudeManaged = managed })
startAlma(t) // Alma keeps its providers in the app
os.MkdirAll(filepath.Join(home, ".hanako", "agents", "hana"), 0o755)
os.WriteFile(filepath.Join(home, ".hanako", "agents", "hana", "config.yaml"), []byte("agent:\n name: Hana\n"), 0o644)
for _, a := range All() {
if a.Launch != nil || a.Native != nil || a.WSL != "" || len(a.Fields) == 0 {
continue
}
t.Run(a.ID, func(t *testing.T) {
if _, err := a.ConnectHow(); err != nil {
t.Skip("can't be connected here:", err)
}
if !a.Wired() {
t.Skip("not wired by Connect here")
}
if err := a.Disconnect(); err != nil {
t.Fatal(err)
}
if a.Wired() {
t.Fatal("still wired after Disconnect")
}
before := agentFiles(t, home)
for i := 0; i < 2; i++ {
SyncCatalog()
// and what a running gateway keeps up (KeepDshWired)
dshWiredOnce()
if a.Wired() || a.FailingOver != nil && a.FailingOver() {
t.Fatalf("sync %d wired it again", i)
}
}
after := agentFiles(t, home)
for p, b := range before {
if after[p] != b {
t.Errorf("sync changed %s:\n--- after Disconnect\n%s\n--- after sync\n%s", p, b, after[p])
}
}
for p := range after {
if _, ok := before[p]; !ok {
t.Errorf("sync wrote %s", p)
}
}
})
}
}
// codexChatGPTAuth is a Codex auth.json signed in to ChatGPT as email.
func codexChatGPTAuth(email, acct string) map[string]any {
claims := func(m map[string]any) string {
b, _ := json.Marshal(m)
return "h." + base64.RawURLEncoding.EncodeToString(b) + ".s"
}
return map[string]any{"auth_mode": "chatgpt", "tokens": map[string]any{
"id_token": claims(map[string]any{"email": email}),
"access_token": claims(map[string]any{"exp": time.Now().Add(time.Hour).Unix()}),
"refresh_token": "r-" + acct, "account_id": acct}}
}
// paynezhuang on Discord: Codex signed in to ChatGPT, with another of the
// user's ChatGPT accounts on in magpie. magpie's first start pointed Codex
// at the gateway for failover; the user switched Codex on, then chose
// "Disconnect from magpie", and after each update and restart Codex had
// magpie's base URL in config.toml again. A disconnect is the user's say:
// no start brings it back, with ChatGPT sign-in or magpie API, until the
// user connects Codex again.
func TestCodexDisconnectStaysWithAccountsOn(t *testing.T) {
for _, login := range []string{"", "api"} {
t.Run("login="+login, func(t *testing.T) {
me, _ := json.Marshal(codexChatGPTAuth("me@example.com", "acct-1"))
const own = "model = \"gpt-5.5\"\nmodel_reasoning_effort = \"high\"\n\n[projects.\"/Users/me/code\"]\ntrust_level = \"trusted\"\n"
home, read := codexHome(t, string(me), own)
b, _ := json.Marshal([]map[string]any{{"agent": "codex", "user": "spare@example.com", "on": true,
"seen": time.Now(), "auth": codexChatGPTAuth("spare@example.com", "acct-2")}})
os.MkdirAll(filepath.Dir(provider.Path()), 0o755)
os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "logins.json"), b, 0o600)
cx := codex(home)
// magpie's first start: failover points Codex at the gateway
SyncCatalog()
if cfg := read(); !strings.Contains(cfg, "openai_base_url") {
t.Fatalf("first start, two accounts on:\n%s", cfg)
}
if login != "" {
if err := cx.Apply("login", login); err != nil {
t.Fatal(err)
}
}
if _, err := cx.ConnectHow(); err != nil {
t.Fatal(err)
}
if !cx.Wired() {
t.Fatalf("not connected:\n%s", read())
}
if err := cx.Disconnect(); err != nil {
t.Fatal(err)
}
restored := read()
if strings.Contains(restored, "openai_base_url") || strings.Contains(restored, "model_provider =") {
t.Fatalf("disconnect left magpie in:\n%s", restored)
}
// restarts, an update among them
for i := 0; i < 3; i++ {
SyncCatalog()
if cfg := read(); cfg != restored {
t.Fatalf("start %d after Disconnect wired Codex again:\n--- disconnected\n%s\n--- now\n%s", i, restored, cfg)
}
if cx.Wired() || cx.FailingOver() {
t.Fatalf("start %d: wired %v, failing over %v", i, cx.Wired(), cx.FailingOver())
}
}
// a pick of one of Codex's own models in magpie keeps it so
if login == "" {
if err := cx.Pick("model", "gpt-5.4"); err != nil {
t.Fatal(err)
}
if cfg := read(); strings.Contains(cfg, "openai_base_url") {
t.Fatalf("own model picked after Disconnect:\n%s", cfg)
}
}
// connected again, it is magpie's again, and a start keeps it so
if _, err := cx.ConnectHow(); err != nil {
t.Fatal(err)
}
SyncCatalog()
if !cx.Wired() {
t.Fatalf("connected again, then a start:\n%s", read())
}
})
}
}
// On magpie API, Codex's own model served on its ChatGPT account (#701's
// config): Sync wires a Codex left unwired so, but not one the user
// disconnected.
func TestCodexAPIDisconnectStays(t *testing.T) {
home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, "model = \"gpt-a\"\n")
os.WriteFile(filepath.Join(home, ".codex", "models_cache.json"), []byte(`{"models":[{"slug":"gpt-a","display_name":"A","priority":1}]}`), 0o644)
cx := codex(home)
if err := cx.Field("login").Set("api"); err != nil {
t.Fatal(err)
}
if !cx.Wired() {
t.Fatalf("magpie API not wired:\n%s", read())
}
if err := cx.Disconnect(); err != nil {
t.Fatal(err)
}
restored := read()
if cx.Wired() || strings.Contains(restored, "model_provider =") || strings.Contains(restored, "openai_base_url") {
t.Fatalf("disconnect left magpie in:\n%s", restored)
}
for i := 0; i < 2; i++ {
SyncCatalog()
if cfg := read(); cfg != restored || cx.Wired() {
t.Fatalf("start %d after Disconnect wired Codex again:\n--- disconnected\n%s\n--- now\n%s", i, restored, cfg)
}
}
// connected again by the user, magpie API wires it as before
if _, err := cx.ConnectHow(); err != nil {
t.Fatal(err)
}
SyncCatalog()
if cfg := read(); !cx.Wired() || !strings.Contains(cfg, `model_provider = "magpie"`) {
t.Fatalf("connected again:\n%s", cfg)
}
}