agent: a Codex not connected is never pointed at magpie for account failover

TylerBai_loveai on X (tweet 2121532671180632290): with several ChatGPT
accounts added in magpie and Codex not connected, Codex's requests went
through magpie anyway; only adding Codex in Agents, then Disconnect,
put it back.

Cause: Sync's `failover` in codex.go wrote
`openai_base_url = "http://127.0.0.1:3425/backend-api/codex"` (stash
codex.failover), or pointed a CC Switch OpenAI mirror's base_url at the
gateway (codex.mirror_failover), for any Codex signed in to ChatGPT with
another of its accounts on (#1385), on every start and Sync, unless the
user had disconnected Codex or turned on "Only switch Codex's sign-in".
The row said not connected while every request went through magpie.

Fix: failover writes nothing any more. A Codex that isn't wired or
using magpie as its provider gets what failover wrote before taken out
by Sync: the marked base URL, or the mirror's base_url. A base URL the
user wrote by hand has no mark and stays (#856). Failover between Codex
accounts comes with connecting Codex. modelOptions no longer counts
failover as through magpie, so a pick of Codex's own model on the
Agents page doesn't go via magpie. codexProxyOK (the proxy probe only
failover waited for) is gone. The CLI's and GUI's switch-only lines,
reference.md and the subsystem pages say failover is for a connected
Codex.

Users already affected: the first Sync after updating (magpie's start)
removes the marked openai_base_url or mirror base_url, and the route
change restarts Codex's app-server; Codex then goes straight to OpenAI
on its own sign-in. A thread opened while it was on magpie keeps its
provider until reopened, as after Disconnect.

Tests:
- TestCodexNotConnectedStaysOffMagpie: two spare accounts on, Codex
  not connected; SyncCatalog, Sync twice and a model pick leave no
  base URL, no model_provider, not Wired/FailingOver/CodexOwnOnly.
- TestCodexFailoverFromBeforeTakenOut: a marked base URL and a marked
  mirror base_url from before are taken out, bytes restored exactly.
- TestCodexSwitchOnlyKeepsCodexOffTheGateway, the CC Switch mirror,
  disconnect-stays and proxy/EndFailover tests reworked to seed the
  old state by hand; TestCodexFailoverHeldWhileProxyDoesNotPassOn
  deleted with codexProxyOK.

Red on the old code (old codex.go + codex_proxy.go, new tests, mote):
TestCodexNotConnectedStaysOffMagpie, TestCodexFailoverFromBeforeTakenOut
and TestCodexSwitchOnlyKeepsCodexOffTheGateway fail with the reporter's
line `openai_base_url = "http://127.0.0.1:3425/backend-api/codex"`;
TestCodexCCSwitchOfficialOpenAIMirror fails with the mirror pointed at
magpie.

Run (mote; mica's disk is full, 100% with other sessions' runs, and
mote's load was ~17-25 of 18):
- At base b592c1fde: go vet ./... (darwin, GOOS=linux, GOOS=windows)
  ok; go test -timeout 45m ./... 98 ok, two reds:
  TestEveryRouteHasACommandOrIsNamed (fixed on main by 69946f43c) and
  TestCoreScriptBudget, mine (+24 bytes) - the GUI string was shortened
  to fit, no raise.
- Rebased on a63923e3d (what main changed since the base: agent, cli,
  gateway, gui, provider, sessions): gofmt -l clean; go test
  ./internal/agent ./internal/cli ./internal/gui ./internal/provider
  ./internal/sessions all ok. Then rebased on 943404477 (GUI tests
  only below run there).
- GUI (chromium + webkit, every language, both widths): switch-only,
  agent-failover, i18n-keys, i18n-en-no-cjk, claude-switch-only,
  panel-switch-accounts: 115 of 116; the red is claude-switch-only
  chromium 1100 en "the page doesn't move" (scrollTop 3), 4 of 12
  alone here, 0 of 9 on origin/main 943404477, on a path this change
  doesn't touch; filed as #6645 with its output. agent-switch-accounts is 20 of 24
  red the same on a fresh origin/main 69946f43c (#5925, Claude Code
  path, untouched here).

Not tried: a real Codex with real ChatGPT accounts across the update
(sandbox HOME tests only), Codex in WSL, Windows.
This commit is contained in:
yetone
2026-11-14 18:40:09 +08:00
parent fc7941ca60
commit 9f4e1120f3
17 changed files with 216 additions and 312 deletions
+7 -7
View File
@@ -2425,13 +2425,13 @@ to (an account added by setup-token doesn't count), magpie keeps it and
says so. Add another account first, or sign out in Claude Code itself,
then remove it.
With more than one Codex account on, magpie also sets `openai_base_url`
in Codex's config.toml, so a request the signed-in account has no
allowance for goes on to the others through the gateway. *Only switch
Codex's sign-in* under Providers › Codex (or `magpie accounts switch-only
codex on`) leaves that out: magpie only moves Codex's own sign-in
(`auth.json`) as above, and Codex's requests go straight to OpenAI, never
through magpie (#1907). An `openai_base_url` you wrote yourself stays. The
A Codex that isn't connected to magpie goes straight to OpenAI on its own
sign-in, however many of its accounts are on: magpie only moves Codex's
sign-in (`auth.json`) as above. Connected, a request the signed-in account
has no allowance for goes on to the others through the gateway. *Only
switch Codex's sign-in* under Providers › Codex (or `magpie accounts
switch-only codex on`) keeps Codex's requests off magpie even then
(#1907). An `openai_base_url` you wrote yourself stays. The
Codex app and a running `codex app-server` read the sign-in when they
start, so one already open stays on its account until it is opened again;
a new `codex` session takes the new one. Connected to magpie, Codex's
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+5 -5
View File
@@ -235,15 +235,15 @@ type Agent struct {
// is that group's (#750).
Routed func() bool
// FailingOver reports an agent that isn't connected whose requests
// still go through magpie's gateway, for account failover alone (Codex
// signed in to ChatGPT with more of its accounts on in magpie, #1385):
// the Agents page says so and what turns it off, and the gateway lists
// it only its own models.
// still go through magpie's gateway, for account failover alone: what
// a magpie from before wrote in Codex's config by itself (#1385), till
// Sync takes it out (TylerBai_loveai on X). The Agents page says so,
// and the gateway lists it only its own models.
FailingOver func() bool
// EndFailover takes out what account failover wrote, for magpie
// quitting: left there, the agent would be pointed at a gateway that
// no longer answers, and retry till magpie is open again (Leon920717
// on X). The next start's Sync writes it again.
// on X).
EndFailover func() error
// TakeLeftovers takes out what magpie wrote that no Disconnect could
// name: an address at magpie's gateway whose marks are gone (magpie's
+19 -60
View File
@@ -1560,69 +1560,28 @@ func codexIn(at place) *Agent {
}
forget(at.key("codex.lent"))
}
// 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, or once the user disconnected Codex,
// it goes straight to OpenAI again
// A Codex that isn't connected goes straight to OpenAI on its own
// sign-in, however many of its ChatGPT accounts are on in magpie.
// magpie once pointed it at the gateway by itself for account failover
// (#1385) while another of its accounts was on, so an unconnected
// Codex's every request went through magpie, the row saying not
// connected, until a Disconnect the user had no reason to look for
// (TylerBai_loveai on X). Failover between the accounts comes with
// connecting Codex. What failover wrote goes as Sync next runs: the
// base URL it marked (codex.failover), or CC Switch's OpenAI mirror it
// pointed at magpie (codex.mirror_failover). A base URL the user wrote
// by hand, unmarked, is theirs and stays (#856).
failover := func() error {
if wired() || asProvider() {
return nil
}
p := get("model_provider")
mirror := isCCSwitchMirror(p)
if !mirror {
_ = dropMirrorFailover()
if err := dropMirrorFailover(); err != nil {
return err
}
if p != "" && p != "openai" && !mirror {
if stashShared()[at.key("codex.failover")] != "1" {
return nil
}
// a Codex that reaches the gateway from another machine is never
// pointed at the Codex path: the gateway takes a named key there,
// so the turn failover handed it came back a 401 (#2145)
on := !disconnected() && codexFailover() && !onAnotherMachine(at.gw())
// failover is magpie's own idea, not the user's: never handed
// Codex's requests while a proxy they'd go through doesn't pass
// them on to magpie, which would have every turn fail with 502
// (codex_proxy.go); one written before goes again
if on && at.spell == nil && !codexProxyOK(path, at.gw()) {
on = false
}
if mirror {
t, _ := edit.GetTOMLTable(path, "model_providers."+p)
hasGateway := t["base_url"] == at.codexURL()
switch {
case on && !hasGateway:
if err := edit.SetTOMLKey(path, "model_providers."+p, "base_url", at.codexURL()); err != nil {
return err
}
stash(map[string]string{at.key("codex.mirror_failover"): p})
case !on && hasGateway:
if err := edit.DelTOMLKey(path, "model_providers."+p, "base_url"); err != nil {
return err
}
forget(at.key("codex.mirror_failover"))
}
return nil
}
// the base URL failover wrote is marked (codex.failover), and only
// that one goes again: one the user wrote in config.toml by hand,
// to have Codex's own models go through magpie, stays (#856: it was
// gone again each time magpie started). One already there while
// failover is on is taken as failover's, as a magpie from before
// the mark wrote it.
owned := stashShared()[at.key("codex.failover")] == "1"
switch {
case on && !viaBase():
if err := edit.SetTOMLTop(path, edit.KV{Path: "openai_base_url", Value: at.codexURL()}); err != nil {
return err
}
stash(map[string]string{at.key("codex.failover"): "1"})
case on && !owned:
stash(map[string]string{at.key("codex.failover"): "1"})
case !on && viaBase() && owned:
return dropBase()
}
return nil
return dropBase()
}
// failingOver: Codex reaches magpie for account failover alone, by the
// base URL failover wrote (codex.failover) or by CC Switch's OpenAI
@@ -1655,12 +1614,12 @@ func codexIn(at place) *Agent {
to, through = p, t["base_url"] == at.codexURL() || t["base_url"] == at.v1()
}
// beside its sign-in on one of magpie's models, not joined, one of
// its own picked here takes magpie out (set, #940) unless failover
// puts the base URL back: it said via magpie, and the pick went
// straight to OpenAI with nothing asked (NancyTom18 on X)
// its own picked here takes magpie out (set, #940): it said via
// magpie, and the pick went straight to OpenAI with nothing asked
// (NancyTom18 on X)
ownThrough := through
if through && (p == "" || p == "openai") && beside() && !asProvider() && !api() &&
!(joined() && chatGPT()) && !(codexFailover() && !disconnected()) {
!(joined() && chatGPT()) {
ownThrough = false
}
say := func(own []Option) []Option {
+14 -30
View File
@@ -112,7 +112,8 @@ func TestCodexKeepsHandPointedCCSwitchTable(t *testing.T) {
// CC Switch's official OpenAI provider mirror writes model_provider = "custom"
// and a [model_providers.custom] table with name = "OpenAI", requires_openai_auth = true
// and no base_url (#504): it is the official provider, so its models are grouped
// under OpenAI and failover moves Codex onto magpie while another account is on.
// under OpenAI, and neither it nor a relay's table is pointed at magpie for a
// Codex not connected while another account is on (TylerBai_loveai on X).
func TestCodexCCSwitchOfficialOpenAIMirror(t *testing.T) {
const ccSwitchOfficialMirror = "model_provider = \"custom\"\nmodel = \"gpt-5.4\"\n\n" +
"[model_providers.custom]\nname = \"OpenAI\"\nrequires_openai_auth = true\nsupports_websockets = true\nwire_api = \"responses\"\n"
@@ -182,29 +183,15 @@ func TestCodexCCSwitchOfficialOpenAIMirror(t *testing.T) {
os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "logins.json"), b, 0o600)
}
logins(true)
if err := cxFailover.Sync(); err != nil {
t.Fatal(err)
}
tb, err := edit.GetTOMLTable(pathFailover, "model_providers.custom")
if err != nil {
t.Fatal(err)
}
codexURL := here(homeFailover).codexURL()
if tb["base_url"] != codexURL {
t.Fatalf("mirror table base_url = %q, want %q", tb["base_url"], codexURL)
}
if strings.Contains(readFailover(), "openai_base_url") {
t.Fatalf("mirror failover wrote openai_base_url:\n%s", readFailover())
}
// When failover turns off, base_url is removed and the file is byte-identical to original
logins(false)
if err := cxFailover.Sync(); err != nil {
t.Fatal(err)
}
if got := readFailover(); got != ccSwitchOfficialMirror {
t.Fatalf("failover off left config not byte-identical:\ngot:\n%s\nwant:\n%s", got, ccSwitchOfficialMirror)
for i := 0; i < 2; i++ {
if err := cxFailover.Sync(); err != nil {
t.Fatal(err)
}
if got := readFailover(); got != ccSwitchOfficialMirror {
t.Fatalf("sync %d with another account on changed CC Switch's mirror:\ngot:\n%s\nwant:\n%s", i, got, ccSwitchOfficialMirror)
}
}
_ = pathFailover
// Real relays with a base_url never get pointed at magpie gateway for failover
homeRelayFailover, readRelayFailover := codexHome(t, string(me), ccSwitchCodex)
@@ -222,20 +209,17 @@ func TestCodexCCSwitchOfficialOpenAIMirror(t *testing.T) {
t.Fatalf("real relay got openai_base_url:\n%s", readRelayFailover())
}
// Switching to a relay while failover was active on the mirror clears the marker
// Switching to a relay while failover from before was on the mirror clears the marker
// without deleting the relay's own base_url on Sync or Set.
homeSwitch, readSwitch := codexHome(t, string(me), ccSwitchOfficialMirror)
cxSwitch := codex(homeSwitch)
pathSwitch := filepath.Join(homeSwitch, ".codex", "config.toml")
logins(true)
if err := cxSwitch.Sync(); err != nil {
// mirror failover as a magpie from before left it, marker and all
if err := edit.SetTOMLKey(pathSwitch, "model_providers.custom", "base_url", here(homeSwitch).codexURL()); err != nil {
t.Fatal(err)
}
// Verify mirror failover was activated and marker was set
tbSwitch, _ := edit.GetTOMLTable(pathSwitch, "model_providers.custom")
if tbSwitch["base_url"] != here(homeSwitch).codexURL() {
t.Fatalf("mirror base_url = %q, want codexURL", tbSwitch["base_url"])
}
stash(map[string]string{"codex.mirror_failover": "custom"})
// User switches CC Switch to a relay, reusing the custom table
if err := os.WriteFile(pathSwitch, []byte(ccSwitchCodex), 0o644); err != nil {
t.Fatal(err)
+2 -1
View File
@@ -17,7 +17,8 @@ import (
// the same to it) is never pointed at the gateway's Codex path for account
// failover either: from there the gateway takes a named key alone, so the
// turn failover handed magpie came back a 401 — the shape #2145 took out
// of the joined case, still written by failover for a Codex not connected.
// of the joined case. No Codex not connected is pointed there now
// (TestCodexNotConnectedStaysOffMagpie); one written before goes.
func TestCodexFailoverBeyondLoopbackNotWritten(t *testing.T) {
claims := func(m map[string]any) string {
b, _ := json.Marshal(m)
+108 -60
View File
@@ -12,68 +12,121 @@ import (
"testing"
"time"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
)
// Codex on one of its own models, signed in to ChatGPT, goes through
// magpie while another of its accounts is on there — so a turn the first
// has no allowance left for goes to the next — and straight to OpenAI
// once none is.
func TestCodexOwnModelThroughMagpieWhileAccountsOn(t *testing.T) {
claims := func(m map[string]any) string {
b, _ := json.Marshal(m)
return "h." + base64.RawURLEncoding.EncodeToString(b) + ".s"
// TylerBai_loveai on X: Codex (the app) signed in to ChatGPT and not
// connected, two more of the user's ChatGPT accounts added and on in
// magpie. magpie pointed Codex at its gateway by itself for account
// failover (#1385), so every Codex request went through magpie while the
// Agents row said not connected, until a Disconnect and cleanup. A Codex
// that isn't connected goes straight to OpenAI: no start, sync or pick of
// one of its own models writes magpie into its config, however many of its
// accounts are on.
func TestCodexNotConnectedStaysOffMagpie(t *testing.T) {
me, _ := json.Marshal(codexChatGPTAuth("me@example.com", "acct-1"))
const own = "model = \"gpt-5.5\"\n"
home, read := codexHome(t, string(me), own)
var saved []map[string]any
for i, u := range []string{"spare1@example.com", "spare2@example.com"} {
saved = append(saved, map[string]any{"agent": "codex", "user": u, "on": true,
"seen": time.Now(), "auth": codexChatGPTAuth(u, "acct-"+string(rune('2'+i)))})
}
auth := func(email, acct string) map[string]any {
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}}
}
me, _ := json.Marshal(auth("me@example.com", "acct-1"))
home, read := codexHome(t, string(me), "model = \"gpt-5.5\"\n")
b, _ := json.Marshal(saved)
os.MkdirAll(filepath.Dir(provider.Path()), 0o755)
os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "logins.json"), b, 0o600)
cx := codex(home)
logins := func(on bool) {
b, _ := json.Marshal([]map[string]any{{"agent": "codex", "user": "spare@example.com", "on": on,
"seen": time.Now(), "auth": auth("spare@example.com", "acct-2")}})
check := func(when string) {
t.Helper()
cfg := read()
if strings.Contains(cfg, "openai_base_url") || strings.Contains(cfg, "model_provider") || strings.Contains(cfg, "127.0.0.1") {
t.Fatalf("%s: an unconnected Codex pointed at magpie:\n%s", when, cfg)
}
if cx.Wired() || cx.FailingOver() || cx.FailoverSaid() != "" || CodexOwnOnly() {
t.Fatalf("%s: wired %v, failing over %v", when, cx.Wired(), cx.FailingOver())
}
if s := stashLoad(); s["codex.failover"] != "" {
t.Fatalf("%s: failover marked: %v", when, s)
}
}
SyncCatalog()
check("magpie's start")
for i := 0; i < 2; i++ {
if err := cx.Sync(); err != nil {
t.Fatal(err)
}
check("sync")
}
if err := cx.Pick("model", "gpt-5.4"); err != nil {
t.Fatal(err)
}
if cfg := read(); !strings.Contains(cfg, `model = "gpt-5.4"`) {
t.Fatalf("pick not written:\n%s", cfg)
}
check("own model picked")
}
// A Codex a magpie from before pointed at the gateway for failover, the
// reporter's config as they upgrade: the base URL it marked goes as Sync
// next runs, the Codex app's app-server restarted for it like any change of
// route, and it stays gone. So does CC Switch's OpenAI mirror that failover
// pointed at magpie (xuxing0727 on X), back to CC Switch's own bytes.
func TestCodexFailoverFromBeforeTakenOut(t *testing.T) {
me, _ := json.Marshal(codexChatGPTAuth("me@example.com", "acct-1"))
accountsOn := func() {
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)
}
logins(false)
if err := cx.Fields[0].Set("gpt-5.4"); err != nil {
home, read := codexHome(t, string(me), "model = \"gpt-5.5\"\n")
accountsOn()
if err := edit.SetTOMLTop(filepath.Join(home, ".codex", "config.toml"), edit.KV{Path: "openai_base_url", Value: here(home).codexURL()}); err != nil {
t.Fatal(err)
}
if cfg := read(); strings.Contains(cfg, "openai_base_url") {
t.Fatalf("one account:\n%s", cfg)
stash(map[string]string{"codex.failover": "1"})
cx := codex(home)
if !cx.FailingOver() {
t.Fatalf("not the reporter's state:\n%s", read())
}
for i := 0; i < 2; i++ {
if err := cx.Sync(); err != nil {
t.Fatal(err)
}
if cfg := read(); cfg != "model = \"gpt-5.5\"\n" {
t.Fatalf("sync %d left failover's base URL:\n%s", i, cfg)
}
if cx.FailingOver() || stashLoad()["codex.failover"] != "" {
t.Fatalf("sync %d: failing over %v", i, cx.FailingOver())
}
}
const unified = "model_provider = \"custom\"\nmodel = \"gpt-5.5\"\n\n" +
"[model_providers.custom]\nname = \"OpenAI\"\nrequires_openai_auth = true\nsupports_websockets = true\nwire_api = \"responses\"\n"
home, read = codexHome(t, string(me), unified)
accountsOn()
if err := edit.SetTOMLKey(filepath.Join(home, ".codex", "config.toml"), "model_providers.custom", "base_url", here(home).codexURL()); err != nil {
t.Fatal(err)
}
stash(map[string]string{"codex.mirror_failover": "custom"})
cx = codex(home)
if !cx.FailingOver() {
t.Fatalf("not the mirror's state:\n%s", read())
}
logins(true)
if err := cx.Sync(); err != nil {
t.Fatal(err)
}
if cfg := read(); !strings.Contains(cfg, `openai_base_url = "http://127.0.0.1:`) || !strings.Contains(cfg, `model = "gpt-5.4"`) {
t.Fatalf("second account on:\n%s", cfg)
}
// picked again, it stays so
if err := cx.Fields[0].Set("gpt-5.5"); err != nil {
t.Fatal(err)
}
if cfg := read(); !strings.Contains(cfg, "openai_base_url") || !strings.Contains(cfg, `model = "gpt-5.5"`) {
t.Fatalf("picked with two accounts on:\n%s", cfg)
}
logins(false)
if err := cx.Sync(); err != nil {
t.Fatal(err)
}
if cfg := read(); strings.Contains(cfg, "openai_base_url") || !strings.Contains(cfg, `model = "gpt-5.5"`) {
t.Fatalf("second account off:\n%s", cfg)
if cfg := read(); cfg != unified || cx.FailingOver() {
t.Fatalf("CC Switch's mirror left on magpie (failing over %v):\n%s", cx.FailingOver(), cfg)
}
}
// A base URL the user wrote in config.toml by hand, to have Codex's own
// models go through magpie, stays when magpie starts (Sync) with no other
// ChatGPT account on to fail over to: failover takes away only the one it
// wrote (#856: it was gone again after every magpie update).
// models go through magpie, stays when magpie starts (Sync): what failover
// wrote is taken away, and only that (#856: it was gone again after every
// magpie update).
func TestCodexHandWrittenBaseURLStays(t *testing.T) {
base := gateway.URL() + gateway.CodexPath
home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`,
@@ -90,10 +143,11 @@ func TestCodexHandWrittenBaseURLStays(t *testing.T) {
}
// #1385 (shenghsi): Codex signed in to ChatGPT, not connected, with two
// more of the user's ChatGPT accounts on in magpie. failover points Codex at
// the gateway; the Agents row says it goes through magpie for that and what
// turns it off, and Codex's model list is its own, not its own and 62 of
// magpie's. Connected, it is magpie's models' again.
// more of the user's ChatGPT accounts on in magpie, pointed at the gateway
// by a magpie from before for failover. Till Sync takes that out, the
// Agents row says it goes through magpie for that, and Codex's model list
// is its own, not its own and 62 of magpie's. Connected, it is magpie's
// models' again.
func TestCodexFailoverOnlyKeepsOwnModels(t *testing.T) {
claims := func(m map[string]any) string {
b, _ := json.Marshal(m)
@@ -115,10 +169,11 @@ func TestCodexFailoverOnlyKeepsOwnModels(t *testing.T) {
b, _ := json.Marshal(saved)
os.MkdirAll(filepath.Dir(provider.Path()), 0o755)
os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "logins.json"), b, 0o600)
// Codex fetched magpie's whole list before
cache := filepath.Join(home, ".codex", "models_cache.json")
now := time.Now().UTC().Format(time.RFC3339)
os.WriteFile(cache, []byte(`{"etag":"\"v1+magpie-`+provider.CodexListTag()+`\"","fetched_at":"`+now+`","models":[]}`), 0o644)
// what a magpie from before wrote for failover
if err := edit.SetTOMLTop(filepath.Join(home, ".codex", "config.toml"), edit.KV{Path: "openai_base_url", Value: here(home).codexURL()}); err != nil {
t.Fatal(err)
}
stash(map[string]string{"codex.failover": "1"})
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, `{"models":[{"slug":"gpt-5.5","priority":1}]}`)
@@ -146,12 +201,8 @@ func TestCodexFailoverOnlyKeepsOwnModels(t *testing.T) {
}
cx := codex(home)
if err := cx.Sync(); err != nil {
t.Fatal(err)
}
s := stashLoad()
if cfg := read(); !strings.Contains(cfg, "openai_base_url") || s["codex.failover"] != "1" || s["codex.joined"] != "" || s["codex.beside"] != "" {
t.Fatalf("not the reporter's state: stash %v\n%s", s, cfg)
if cfg := read(); !strings.Contains(cfg, "openai_base_url") {
t.Fatalf("not the reporter's state:\n%s", cfg)
}
if cx.Wired() || !cx.FailingOver() || !CodexOwnOnly() || !strings.Contains(cx.FailoverSaid(), "Providers › Codex") {
t.Errorf("wired %v, failing over %v, own only %v, said %q", cx.Wired(), cx.FailingOver(), CodexOwnOnly(), cx.FailoverSaid())
@@ -159,9 +210,6 @@ func TestCodexFailoverOnlyKeepsOwnModels(t *testing.T) {
if got := models(); len(got) != 1 || got[0] != "gpt-5.5" {
t.Errorf("failover-only Codex lists %v, want just gpt-5.5", got)
}
if c, _ := os.ReadFile(cache); !strings.Contains(string(c), "1970-01-01") {
t.Errorf("Codex's cached list of magpie's models kept:\n%s", c)
}
// connected, magpie's models are in its list and the row says connected
if ok, err := cx.Join(); !ok || err != nil {
+3 -11
View File
@@ -43,10 +43,9 @@ import (
// magpie opened from the Dock has neither, so the login shell's are asked
// (proc.LoginEnv), over magpie's own.
//
// So before magpie hands Codex's requests to the gateway uninvited (account
// failover), and while it has them, it asks the way Codex would go: through
// which proxy, and whether a request sent through it reaches magpie (Drift
// kind "proxied").
// So while magpie has Codex's requests, it asks the way Codex would go:
// through which proxy, and whether a request sent through it reaches
// magpie (Drift kind "proxied").
// codexProxyEnv, codexSystemProxy and codexProxyOS are what codexProxyFor
// reads, and loginEnv what codexEnv does; vars so tests can say.
@@ -245,13 +244,6 @@ func codexThroughProxy(cfg, base string) (ok, known bool, proxy, from string) {
return ok, known, proxy, from
}
// codexProxyOK is codexThroughProxy waited for: whether Codex gets to the
// gateway at base, a proxy in its way tried now when it hasn't been.
func codexProxyOK(cfg, base string) bool {
proxy, _ := codexProxyFor(cfg, base)
return proxy == "" || probedNow("proxy "+proxy+" "+base, func() bool { return proxyProbe(base, proxy) })
}
// codexProxiedDetail says what keeps Codex off magpie through proxy, and
// how to get it there.
func codexProxiedDetail(base, proxy, from string) string {
+15 -76
View File
@@ -256,53 +256,6 @@ func socksOnly(t *testing.T) string {
return ln.Addr().String()
}
// Muma102kMichael on X: Codex 502 on every project and every new chat once
// magpie took it over, its requests for 127.0.0.1 sent through a proxy that
// didn't pass them on. Failover, which magpie writes uninvited, is never
// written then, and one written before goes again; once the proxy passes
// them on, it is.
func TestCodexFailoverHeldWhileProxyDoesNotPassOn(t *testing.T) {
claims := func(m map[string]any) string {
b, _ := json.Marshal(m)
return "h." + base64.RawURLEncoding.EncodeToString(b) + ".s"
}
auth := func(email, acct string) map[string]any {
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}}
}
me, _ := json.Marshal(auth("me@example.com", "acct-1"))
home, read := codexHome(t, string(me), "model = \"gpt-5.5\"\n")
b, _ := json.Marshal([]map[string]any{{"agent": "codex", "user": "spare@example.com", "on": true,
"seen": time.Now(), "auth": auth("spare@example.com", "acct-2")}})
os.MkdirAll(filepath.Dir(provider.Path()), 0o755)
os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "logins.json"), b, 0o600)
works := false
proxyAs(t, nil, netproxy.Proxy{URL: "http://127.0.0.1:7890", HTTP: "http://127.0.0.1:7890", Bypass: []string{"localhost", "127.*"}}, "windows", &works)
cx := codex(home)
sync := func() string {
t.Helper()
reachForget()
if err := cx.Sync(); err != nil {
t.Fatal(err)
}
return read()
}
if cfg := sync(); strings.Contains(cfg, "openai_base_url") {
t.Fatalf("written while the proxy doesn't pass it on:\n%s", cfg)
}
works = true
if cfg := sync(); !strings.Contains(cfg, `openai_base_url = "`+gateway.URL()) {
t.Fatalf("not written once the proxy passes it on:\n%s", cfg)
}
works = false
if cfg := sync(); strings.Contains(cfg, "openai_base_url") || !strings.Contains(cfg, `model = "gpt-5.5"`) {
t.Fatalf("kept once the proxy stopped passing it on:\n%s", cfg)
}
}
// Connected to magpie, with the gateway up but Codex's way to it through a
// proxy that answers 502: the row says so, which proxy and where it is set,
// rather than connected (kind "proxied"); once the proxy passes it on, or
@@ -370,9 +323,10 @@ func TestCodexProxiedDriftShowsNoCredentials(t *testing.T) {
}
// Leon920717 on X: with magpie quit, Codex CLI kept retrying the gateway
// till magpie was open again. The failover base URL magpie wrote goes as
// the magpie serving the gateway quits (EndCodexFailover), and the next
// start's Sync writes it again; a base URL the user wrote stays.
// till magpie was open again. The failover base URL a magpie from before
// wrote goes as the magpie serving the gateway quits (EndCodexFailover),
// and the next start's Sync doesn't write it again (TylerBai_loveai on X);
// a base URL the user wrote stays.
func TestCodexFailoverEndsWithMagpie(t *testing.T) {
claims := func(m map[string]any) string {
b, _ := json.Marshal(m)
@@ -396,12 +350,10 @@ func TestCodexFailoverEndsWithMagpie(t *testing.T) {
}
logins(true)
cx := codex(home)
if err := cx.Sync(); err != nil {
if err := edit.SetTOMLTop(cx.Path, edit.KV{Path: "openai_base_url", Value: here(home).codexURL()}); err != nil {
t.Fatal(err)
}
if cfg := read(); !strings.Contains(cfg, "openai_base_url") {
t.Fatalf("failover not written:\n%s", cfg)
}
stash(map[string]string{"codex.failover": "1"})
wasKeep := keepCodexDaemon
t.Cleanup(func() { keepCodexDaemon = wasKeep })
var asked []string
@@ -423,8 +375,8 @@ func TestCodexFailoverEndsWithMagpie(t *testing.T) {
if err := cx.Sync(); err != nil {
t.Fatal(err)
}
if cfg := read(); !strings.Contains(cfg, "openai_base_url") {
t.Fatalf("not written again on the next start:\n%s", cfg)
if cfg := read(); strings.Contains(cfg, "openai_base_url") {
t.Fatalf("written again on the next start:\n%s", cfg)
}
// the user's own base URL, with no failover on, stays
@@ -448,10 +400,10 @@ func TestCodexFailoverEndsWithMagpie(t *testing.T) {
}
// CC Switch with "unify Codex session history" on (xuxing0727 on X) runs
// the official sign-in as its "custom" mirror, so failover goes on that
// table's base_url rather than openai_base_url: it too waits for the proxy
// to pass Codex on, and goes as the magpie serving the gateway quits.
func TestCodexMirrorFailoverHeldAndEndsWithMagpie(t *testing.T) {
// the official sign-in as its "custom" mirror, so failover went on that
// table's base_url rather than openai_base_url: one a magpie from before
// wrote goes as the magpie serving the gateway quits.
func TestCodexMirrorFailoverEndsWithMagpie(t *testing.T) {
// CC Switch's own bytes (src-tauri services/provider/mod.rs)
const unified = "model_provider = \"custom\"\nmodel = \"gpt-5.5\"\n\n" +
"[model_providers.custom]\nname = \"OpenAI\"\nrequires_openai_auth = true\nsupports_websockets = true\nwire_api = \"responses\"\n"
@@ -477,24 +429,11 @@ func TestCodexMirrorFailoverHeldAndEndsWithMagpie(t *testing.T) {
t.Cleanup(func() { keepCodexDaemon = wasKeep })
keepCodexDaemon = func(context.Context, string, time.Time) provider.CodexDaemonCheck { return provider.CodexDaemonCheck{} }
works := false
proxyAs(t, map[string]string{"HTTP_PROXY": "http://127.0.0.1:7890"}, netproxy.Proxy{}, "darwin", &works)
cx := codex(home)
sync := func() string {
t.Helper()
reachForget()
if err := cx.Sync(); err != nil {
t.Fatal(err)
}
return read()
}
if cfg := sync(); strings.Contains(cfg, "base_url") {
t.Fatalf("written while the proxy doesn't pass it on:\n%s", cfg)
}
works = true
if cfg := sync(); !strings.Contains(cfg, `base_url = "`+gateway.URL()) {
t.Fatalf("not written once the proxy passes it on:\n%s", cfg)
if err := edit.SetTOMLKey(cx.Path, "model_providers.custom", "base_url", here(home).codexURL()); err != nil {
t.Fatal(err)
}
stash(map[string]string{"codex.mirror_failover": "custom"})
if _, err := EndCodexFailover(); err != nil {
t.Fatal(err)
}
+21 -42
View File
@@ -13,12 +13,10 @@ import (
)
// #1907 (foobra): two ChatGPT accounts, both on in magpie, for Codex
// Desktop and the CLI alone, not for the gateway. With more accounts on,
// magpie points Codex at the gateway to fail over between them (#1385);
// switch-only takes that base URL out, so Codex goes straight to OpenAI and
// magpie only switches its sign-in, and nothing puts it back while it is
// on. Off again, failover writes it back. A base URL the user wrote by hand
// is theirs, and stays either way (#856).
// Desktop and the CLI alone, not for the gateway. Codex isn't connected, so
// it goes straight to OpenAI whether switch-only is on or off, and magpie
// only switches its sign-in; a base URL the user wrote by hand is theirs,
// and stays either way (#856).
func TestCodexSwitchOnlyKeepsCodexOffTheGateway(t *testing.T) {
claims := func(m map[string]any) string {
b, _ := json.Marshal(m)
@@ -38,53 +36,34 @@ func TestCodexSwitchOnlyKeepsCodexOffTheGateway(t *testing.T) {
os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "logins.json"), b, 0o600)
cx := codex(home)
if err := cx.Sync(); err != nil {
t.Fatal(err)
}
if cfg := read(); !strings.Contains(cfg, "openai_base_url") || !cx.FailingOver() {
t.Fatalf("not the reporter's state, failing over %v:\n%s", cx.FailingOver(), cfg)
}
if err := provider.SetSwitchOnly("codex", true); err != nil {
t.Fatal(err)
}
for i := 0; i < 2; i++ {
for _, only := range []bool{false, true, false} {
if err := provider.SetSwitchOnly("codex", only); err != nil {
t.Fatal(err)
}
if err := cx.Sync(); err != nil {
t.Fatal(err)
}
if cfg := read(); strings.Contains(cfg, "openai_base_url") || !strings.Contains(cfg, `model = "gpt-5.5"`) {
t.Fatalf("switch-only, sync %d:\n%s", i, cfg)
t.Fatalf("switch-only %v:\n%s", only, cfg)
}
if cx.FailingOver() || cx.FailoverSaid() != "" || CodexOwnOnly() {
t.Fatalf("switch-only, sync %d: failing over %v, said %q, own only %v", i, cx.FailingOver(), cx.FailoverSaid(), CodexOwnOnly())
t.Fatalf("switch-only %v: failing over %v, said %q, own only %v", only, cx.FailingOver(), cx.FailoverSaid(), CodexOwnOnly())
}
}
if err := provider.SetSwitchOnly("codex", false); err != nil {
t.Fatal(err)
}
if err := cx.Sync(); err != nil {
t.Fatal(err)
}
if cfg := read(); !strings.Contains(cfg, "openai_base_url") || !cx.FailingOver() {
t.Fatalf("switch-only off, failing over %v:\n%s", cx.FailingOver(), cfg)
}
// the user's own base URL, switch-only on: theirs, kept
if err := cx.EndFailover(); err != nil {
t.Fatal(err)
}
forget("codex.failover")
// the user's own base URL: theirs, kept, switch-only on or off
base := codexGatewayURL()
cfg := filepath.Join(home, ".codex", "config.toml")
os.WriteFile(cfg, []byte("model = \"gpt-5.5\"\nopenai_base_url = \""+base+"\"\n"), 0o644)
if err := provider.SetSwitchOnly("codex", true); err != nil {
t.Fatal(err)
}
if err := cx.Sync(); err != nil {
t.Fatal(err)
}
if got := read(); !strings.Contains(got, `openai_base_url = "`+base+`"`) {
t.Fatalf("the user's base URL taken away:\n%s", got)
for _, only := range []bool{true, false} {
if err := provider.SetSwitchOnly("codex", only); err != nil {
t.Fatal(err)
}
if err := cx.Sync(); err != nil {
t.Fatal(err)
}
if got := read(); !strings.Contains(got, `openai_base_url = "`+base+`"`) {
t.Fatalf("switch-only %v: the user's base URL taken away:\n%s", only, got)
}
}
}
+5 -3
View File
@@ -104,7 +104,7 @@ func codexChatGPTAuth(email, acct string) map[string]any {
// 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
// at the gateway for failover then; 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
@@ -120,9 +120,11 @@ func TestCodexDisconnectStaysWithAccountsOn(t *testing.T) {
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
// magpie's first start: a magpie from before pointed Codex at
// the gateway for failover then; Codex not connected stays off
// it now (TylerBai_loveai on X)
SyncCatalog()
if cfg := read(); !strings.Contains(cfg, "openai_base_url") {
if cfg := read(); strings.Contains(cfg, "openai_base_url") {
t.Fatalf("first start, two accounts on:\n%s", cfg)
}
if login != "" {
+1 -1
View File
@@ -187,7 +187,7 @@ func chainsToGateway(v, want string) bool {
}
// magpieAsked is magpieAt waited for, for a write: base, not asked yet, is
// asked now (probedNow, as codexProxyOK asks a proxy), so what the write
// asked now (probedNow), so what the write
// reads after is magpie's answer there. Unasked, surelyMagpie is no, and
// the first write in a magpie just started, the CLI's, took a proxy to
// magpie for the user's own endpoint (#1985). One answered before, at any
+2 -2
View File
@@ -1099,7 +1099,7 @@ func switchOnlyCmd(args []string) error {
case id == "codex" && on:
fmt.Println("on · magpie only switches Codex's sign-in; its requests go straight to OpenAI")
case id == "codex":
fmt.Println("off · with more of its accounts on, Codex's requests go through magpie to fail over between them")
fmt.Println("off · while Codex is connected, its requests go through magpie to fail over between its accounts")
case on:
fmt.Println("on · magpie only switches Claude Code's sign-in; it serves no requests on the Claude accounts")
default:
@@ -1124,7 +1124,7 @@ func switchOnlyCmd(args []string) error {
case id == "codex" && on:
fmt.Println(green.Render("✓"), "magpie only switches Codex's sign-in to an account with room; its requests go straight to OpenAI. A Codex app or session already open stays on its account until it is opened again.")
case id == "codex":
fmt.Println(green.Render("✓"), "with more of its accounts on, Codex's requests go through magpie to fail over between them again")
fmt.Println(green.Render("✓"), "while Codex is connected, its requests go through magpie to fail over between its accounts again")
case on:
fmt.Println(green.Render("✓"), "magpie only switches Claude Code's sign-in to an account with room; it serves no requests on the Claude accounts. A Claude Code session already open stays on its account until it is started again.")
default:
+2 -2
View File
@@ -1655,7 +1655,7 @@ function switchEntry(a) {
openProtoMenu(b, opts, "u:" + cur, (v) => {
const l = ls.find((x) => "u:" + x.user === v);
if (v === "only") accountAction("provider/switchonly", { id: p.id, switchOnly: !p.switchOnly }, !p.switchOnly ? on
: cx ? t("{agent}'s requests go through magpie to fail over to your other accounts again", ag) : t("magpie serves requests on these accounts again"));
: cx ? t("A connected {agent} fails over to your other accounts through magpie again", ag) : t("magpie serves requests on these accounts again"));
else if (v === "manage" || l?.lapsed) pn ? api("window/main?view=providers", {}).catch(statusErr) : openProvider(a.id);
else if (l && l.user !== cur) switchAccountTo(a, p, l.user);
}, "Switch accounts only", "sess-menu", "right");
@@ -13712,7 +13712,7 @@ function renderAccounts(a, p) {
const cx = a.agent === "codex", ag = { agent: a.agentName };
if (p && (cx && several || a.agent === "claude")) {
const [only, cb] = tick(t("Only switch {agent}'s sign-in", ag), p.switchOnly);
const [tip, on, off] = cx ? [t("When an account is used up, magpie signs {agent} in to the next one, and requests go straight to OpenAI. Open {agent} sessions keep their account until reopened.", ag), t("magpie only switches {agent}'s sign-in; its requests go straight to OpenAI", ag), t("{agent}'s requests go through magpie to fail over to your other accounts again", ag)]
const [tip, on, off] = cx ? [t("When an account is used up, magpie signs {agent} in to the next one, and requests go straight to OpenAI. Open {agent} sessions keep their account until reopened.", ag), t("magpie only switches {agent}'s sign-in; its requests go straight to OpenAI", ag), t("A connected {agent} fails over to your other accounts through magpie again", ag)]
: [t("When an account is used up, magpie signs {agent} in to the next one. Requests on these accounts don't go through magpie.", ag), t("magpie serves no requests on these accounts"), t("magpie serves requests on these accounts again")];
only.title = tip;
cb.onchange = () => accountAction("provider/switchonly", { id: p.id, switchOnly: cb.checked }, cb.checked ? on : off);
+4 -4
View File
@@ -2185,7 +2185,7 @@ const I18N = {
"When an account is used up, magpie signs {agent} in to the next one. Requests on these accounts don't go through magpie.": "账号额度用完时,magpie 把 {agent} 切到下一个账号。这些账号的请求都不经过 magpie。",
"magpie serves no requests on these accounts": "magpie 不在这些账号上处理任何请求",
"magpie serves requests on these accounts again": "magpie 重新在这些账号上处理请求",
"{agent}'s requests go through magpie to fail over to your other accounts again": "{agent} 的请求重新经过 magpie,以便转到你的其他账号",
"A connected {agent} fails over to your other accounts through magpie again": "接入后,{agent} 重新经过 magpie 转到你的其他账号",
"the first account": "首选账号",
"Account to stay signed in to": "始终登录的账号",
"The account {agent} stays signed in to": "{agent} 始终登录的账号",
@@ -7445,7 +7445,7 @@ const I18N = {
"When an account is used up, magpie signs {agent} in to the next one. Requests on these accounts don't go through magpie.": "帳號額度用完時,magpie 把 {agent} 切到下一個帳號。這些帳號的請求都不經過 magpie。",
"magpie serves no requests on these accounts": "magpie 不在這些帳號上處理任何請求",
"magpie serves requests on these accounts again": "magpie 重新在這些帳號上處理請求",
"{agent}'s requests go through magpie to fail over to your other accounts again": "{agent} 的請求重新經過 magpie,以便轉到你的其他帳號",
"A connected {agent} fails over to your other accounts through magpie again": "接入後,{agent} 重新經過 magpie 轉到你的其他帳號",
"the first account": "首選帳號",
"Account to stay signed in to": "始終登入的帳號",
"The account {agent} stays signed in to": "{agent} 始終登入的帳號",
@@ -12680,7 +12680,7 @@ const I18N = {
"When an account is used up, magpie signs {agent} in to the next one. Requests on these accounts don't go through magpie.": "アカウントを使い切ると、magpie が {agent} を次のアカウントに切り替えます。これらのアカウントのリクエストは magpie を通りません。",
"magpie serves no requests on these accounts": "magpie はこれらのアカウントでリクエストを処理しません",
"magpie serves requests on these accounts again": "magpie はこれらのアカウントで再びリクエストを処理します",
"{agent}'s requests go through magpie to fail over to your other accounts again": "{agent} のリクエストは再び magpie を経由し、他のアカウントへ切り替えられます",
"A connected {agent} fails over to your other accounts through magpie again": "接続した {agent} は再び magpie を経由して他のアカウントへ切り替わります",
"the first account": "最初のアカウント",
"Account to stay signed in to": "サインインしたままにするアカウント",
"The account {agent} stays signed in to": "{agent} がサインインしたままにするアカウント",
@@ -17946,7 +17946,7 @@ const I18N = {
"When an account is used up, magpie signs {agent} in to the next one. Requests on these accounts don't go through magpie.": "Ist ein Konto aufgebraucht, meldet magpie {agent} beim nächsten an. Anfragen dieser Konten laufen nicht über magpie.",
"magpie serves no requests on these accounts": "magpie bearbeitet keine Anfragen über diese Konten",
"magpie serves requests on these accounts again": "magpie bearbeitet wieder Anfragen über diese Konten",
"{agent}'s requests go through magpie to fail over to your other accounts again": "Die Anfragen von {agent} laufen wieder über magpie, um auf deine anderen Konten auszuweichen",
"A connected {agent} fails over to your other accounts through magpie again": "Ein verbundenes {agent} weicht wieder über magpie auf deine anderen Konten aus",
"the first account": "dem ersten Konto",
"Account to stay signed in to": "Konto für die dauerhafte Anmeldung",
"The account {agent} stays signed in to": "Das Konto, bei dem {agent} angemeldet bleibt",
+1 -1
View File
@@ -61,7 +61,7 @@ const strings = [
"Only switch {agent}'s sign-in",
"When an account is used up, magpie signs {agent} in to the next one, and requests go straight to OpenAI. Open {agent} sessions keep their account until reopened.",
"magpie only switches {agent}'s sign-in; its requests go straight to OpenAI",
"{agent}'s requests go through magpie to fail over to your other accounts again",
"A connected {agent} fails over to your other accounts through magpie again",
];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {