Files
magpie/internal/provider/switch_only_test.go
T
yetone d6fd9b3a36 provider, agent, gui, cli: Codex can switch only its own sign-in between accounts, never through the gateway (#1907, foobra)
foobra wants Codex Desktop and the CLI kept on their own ChatGPT
subscription, moved to the next saved account when the signed-in one is
used up and back when it resets, without magpie's gateway in the way.
magpie already did the switch (codex_switch.go: 98%, 100% In order, back
under 90%, unknown usage never switches), but with more than one Codex
account on it also wrote openai_base_url into config.toml so a refused
request fails over through the gateway (codexFailover). There was no way
to have the first without the second.

Now Codex's subscription has SwitchOnly (providers.json "switchOnly",
opt-in, off by default so nothing changes for anyone who doesn't tick it):
- provider.SetSwitchOnly / provider.SwitchOnly; only Codex's own
  subscription takes it. An unreadable providers.json reads as on, so
  magpie's own failover is never written on a guess.
- agent.codexFailover is false when it is on: no openai_base_url, no
  failover note, no magpie models in Codex's list. A base URL the user
  wrote stays.
- The account Save copy keeps it.
- GUI: "Only switch Codex's sign-in" tick under Providers > Codex's
  accounts (with more than one on), posting provider/switchonly; the
  Agents row's failover title points at it. zh, zh-TW, ja, de.
- CLI: magpie accounts switch-only codex [on|off].
- docs/reference.md and providers-accounts.md say what it does and that
  an open Codex app or app-server stays on its account until reopened.

Run (darwin, sandbox HOME, -tags nogui):
- go test ./internal/provider -run 'TestCodexSwitchOnly|TestCodexSwitchedWhenUsedUp|KeepLogin'
- go test ./internal/agent -run 'TestCodexSwitchOnly|TestCodexFailover|TestCodexOwnModelThroughMagpie|TestCodexHandWritten'
- Broken by hand, each red: codexFailover guard removed (agent test),
  SwitchOnly dropped from the Save copy, SwitchOnly reading false on an
  unreadable file (provider test), the tick drawn unticked (GUI, 16/16).
- GUI: switch-only (new), keep-login, agent-failover, gui-ja, gui-de,
  gui-zh-tw in Chromium and WebKit, en/zh/ja/de at 1100 and 420: 77 pass.
- The built binary's `accounts switch-only` in an empty sandbox HOME:
  reads off, refuses on with no Codex provider, refuses claude.
- gofmt -l clean; darwin go vet.

Reviewed and rerun after rebasing onto eba718736 (darwin, sandbox HOME).
The rebase met #1899's withPicks; SwitchOnly is copied there now.
- gofmt -l clean; go vet -tags nogui on darwin, GOOS=linux and
  GOOS=windows for internal/provider, agent, cli, gui.
- go test -tags nogui -timeout 40m ./internal/provider ./internal/agent
  ./internal/cli ./internal/gui: all ok. (On the base before, provider's
  TestCopilotSecretToolUsername timed out once under load: #1627,
  untouched code, 3 of 3 alone.)
- Broken by hand, each red: the codexFailover guard removed
  (TestCodexSwitchOnlyKeepsCodexOffTheGateway), SwitchOnly dropped from
  the Save copy, from withPicks, and an unreadable providers.json
  reading off (TestCodexSwitchOnlyStillSwitchesTheSignIn).
- GUI: switch-only, keep-login, agent-failover, gui-ja, gui-de, gui-zh-tw
  in Chromium and WebKit at 1100 and 420: 77 of 77 pass.

Rebased again onto 81f587d7b (clean; it touches provider, cli, gui but
not agent): vet on all three OSes again, go test -timeout 40m
./internal/provider ./internal/cli ./internal/gui all ok, -run TestCodex
./internal/agent ok, and the 77 GUI cases above pass again.

Rebased once more onto d45b20757 (clean; no lines of this change touched):
vet on all three OSes, -run 'TestCodex|KeepLogin|SwitchOnly'
./internal/provider ./internal/agent ok, switch-only and agent-failover
in Chromium and WebKit pass.

Not run: not tried with real ChatGPT accounts or the Codex app.
2026-10-13 14:35:08 +08:00

102 lines
3.3 KiB
Go

package provider
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
// #1907 (foobra): Codex Desktop and the CLI on their own ChatGPT
// subscription, two accounts, no gateway in between. Switch-only is kept on
// Codex's subscription; with it on, the account Codex is signed in to
// running out still signs Codex in to the next one with room, in its own
// auth.json, and back once the first has room again. Claude Code's
// subscription has no such setting. A providers.json that can't be read
// says switch-only: the user's choice is unknown, and failover through the
// gateway, magpie's own idea, isn't taken up on it.
func TestCodexSwitchOnlyStillSwitchesTheSignIn(t *testing.T) {
home := signIn(t) // me@example.com, acct-1
rememberLogins(true)
codexSignIn(t, home, "spare@example.com", "r-spare")
rememberLogins(true)
codexSignIn(t, home, "me@example.com", "r-1")
rememberLogins(true)
used := map[string]float64{"acct-me@example.com": 100, "acct-spare@example.com": 20}
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]any{"plan_type": "plus", "rate_limit": map[string]any{
"primary_window": map[string]any{"used_percent": used[r.Header.Get("chatgpt-account-id")], "limit_window_seconds": 18000}}})
}))
defer fake.Close()
old := CodexBase
CodexBase = fake.URL + "/backend-api/codex"
t.Cleanup(func() { CodexBase = old })
switched := func() string {
t.Helper()
loginUsageCache.Lock()
loginUsageCache.m = nil
loginUsageCache.Unlock()
to, err := SwitchWhenSpent(context.Background(), "codex")
if err != nil {
t.Fatal(err)
}
return to
}
signedIn := func() string {
t.Helper()
var live codexAuth
readJSON(filepath.Join(home, ".codex", "auth.json"), &live)
return live.Tokens.RefreshToken
}
if err := SetLoginOn("codex", "spare@example.com", true); err != nil {
t.Fatal(err)
}
if SwitchOnly("codex") {
t.Fatal("switch-only before the user set it")
}
if err := SetSwitchOnly("codex", true); err != nil {
t.Fatal(err)
}
if !SwitchOnly("codex") {
t.Fatal("switch-only not kept")
}
p, err := Find("codex")
if err != nil || !p.SwitchOnly {
t.Fatalf("Find: %+v %v", p, err)
}
if err := SetSwitchOnly("claude", true); err == nil {
t.Error("switch-only set on Claude Code's subscription")
}
// out: on to the spare, in Codex's own auth.json
if to := switched(); to != "spare@example.com" || signedIn() != "r-spare" {
t.Fatalf("switched to %q, Codex signed in with %q", to, signedIn())
}
// the first has room again: back to it
used["acct-me@example.com"] = 10
if to := switched(); !strings.HasPrefix(to, "me@example.com") || signedIn() != "r-1" {
t.Fatalf("back to %q, Codex signed in with %q", to, signedIn())
}
if !SwitchOnly("codex") {
t.Fatal("switch-only lost on a switch")
}
if err := SetSwitchOnly("codex", false); err != nil || SwitchOnly("codex") {
t.Fatalf("off: %v, still %v", err, SwitchOnly("codex"))
}
// neither the file nor its last good generation reads
for _, f := range []string{Path(), Path() + ".bak"} {
if err := os.WriteFile(f, []byte("{not json"), 0o600); err != nil {
t.Fatal(err)
}
}
if !SwitchOnly("codex") {
t.Error("an unreadable providers.json read as switch-only off")
}
}