provider, gui: switching only Codex's or Claude Code's sign-in moves it even when it is kept on one account (#1907, foobra; yifengz88611436 on X)

foobra's screenshot on #1907 (v0.1.1224 on) had both "Keep Codex
signed in to [the first account]" and "Only switch Codex's sign-in"
ticked. The account Codex was on had 0% of its five hours left and the
other had 100%. Codex stayed on the spent account, through a restart of
Codex Desktop and the CLI. With KeepLogin on, NextLogin never moves the
sign-in (#524), and switch-only sends nothing through the gateway. So the
pair meant that no account change ever happened, while the switch-only
tick says moving the sign-in is the one thing magpie does. Picking "the
first account" in the keep picker ticks KeepLogin too, so it is easy to
land in this state without meaning to.

Now Provider.keepsLogin() is KeepLogin && !SwitchOnly. loginSwitching,
keptAs (KeepLoginAs) and LoginRanks go by it, so under switch-only the
sign-in moves at the spent share and back once the first has room. That
holds whether the user kept the first account or one of their choosing,
and for Codex and Claude Code alike (switchedAgents). The saved
KeepLogin/KeepLoginAs is left as the user wrote it, and it holds again
once switch-only is unticked. SetKeepLogin(true) and SetKeepLoginAs
refuse while switch-only is on, because there they would do nothing.
GUI: the keep tick and picker are hidden while switch-only is on, and
keptLogin() and the Routing note treat KeepLogin as off then. The
Accounts hint for a switched sign-in said "the gateway moves on to the
next", which isn't true under switch-only. It now says "magpie moves on
to the next", which holds in both modes, in en, zh, zh-TW, ja and de.
app.js ends up 29 bytes smaller than origin/main, so TestCoreScriptBudget
holds without a raise (a first version had been 661 over).

Run (on mote unless said otherwise):
- TestSwitchOnlyMovesASignInKeptOnOne (Codex, kept on the first and on a
  chosen account) and TestClaudeSwitchOnlyMovesASignInKeptOnOne are new.
  With keepsLogin put back to plain KeepLogin by hand, all three cases
  are red ("switched to \"\""). With the change they are green.
- go test -run 'SwitchOnly|KeepLogin|KeptLogin|CodexLoginOrderedAndKept'
  on internal/provider, agent, gateway and davsync: ok at this head
  (rebased on accb951ab).
- keep-login.test.cjs has 4 new cases (switch-only with keep on the
  first or on spare, en and zh). With app.js put back to origin/main,
  4 of 12 are red in Chromium. The GUI files keep-login, switch-only,
  claude-switch-only, i18n-keys, agent-switch-accounts, pool-ends,
  account-return, routing-account-order and account-arrange gave
  185 of 186 in Chromium and WebKit, at base e863f520c. The one red was
  claude-switch-only "chromium 420 ja", where the element was detached
  before the test clicked anything, under load ~90. That file passed
  32 of 32 twice alone. Filed as #4344.
- After the hint and budget change: go test -run 'Budget|I18n'
  ./internal/gui ok; keep-login, i18n-keys and switch-only .test.cjs
  60 of 60 (Chromium and WebKit).
- gofmt -l is clean. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui
  and GOOS=windows go build are ok (at base e863f520c).
- The full go test ./... -timeout 45m follows this push, once mote is
  free; its result goes on #1907.

Not tried: a real ChatGPT or Claude account, and Codex Desktop itself.
Also not covered here: Claude Code not connected and switched by Make
first (cn_Vincentzyx on X). There, a saved Claude account has no usage
reading unless magpie has heard of it, so the switch can find no spare
with known room. That is a separate cause.
This commit is contained in:
yetone
2026-10-30 11:44:40 +08:00
parent 869c4d112d
commit ef2b2d1e3b
7 changed files with 207 additions and 22 deletions
+5 -6
View File
@@ -9475,7 +9475,7 @@ function drawEditor(p, presetID) {
if (subOf(a.agent)) {
// no Claude Code on Windows: the gateway runs the one in WSL
const via = a.wsl ? t("Runs through WSL · {distro}: Claude Code there signs in and answers; Windows has none of its own.", { distro: a.wsl }) + " " : "";
ed.append(...field(t("Accounts"), renderAccounts(a, p), via + (p.routing ? t("Tick every account to use; Routing says how requests spread over them.") : subOf(a.agent).single ? t("{agent} keeps one account; the gateway runs it for every request. Signing in to another replaces it.", { agent: a.agentName }) : subOf(a.agent).own && (a.logins || []).some((l) => l.own) ? t("The gateway uses the first. Tick more and it moves on to the next when the one before it is out of quota. {agent} itself stays signed in as it is.", { agent: a.agentName && a.agentName !== a.agent ? a.agentName : p.name }) : subOf(a.agent).own || subOf(a.agent).plugin ? t("The gateway uses the first. Tick more and it moves on to the next when the one before it is out of quota.") : t("{agent} signs in to the first. Tick more and the gateway moves on to the next when the one before it is out of quota. Sessions already running keep theirs until restarted.", { agent: a.agentName }))));
ed.append(...field(t("Accounts"), renderAccounts(a, p), via + (p.routing ? t("Tick every account to use; Routing says how requests spread over them.") : subOf(a.agent).single ? t("{agent} keeps one account; the gateway runs it for every request. Signing in to another replaces it.", { agent: a.agentName }) : subOf(a.agent).own && (a.logins || []).some((l) => l.own) ? t("The gateway uses the first. Tick more and it moves on to the next when the one before it is out of quota. {agent} itself stays signed in as it is.", { agent: a.agentName && a.agentName !== a.agent ? a.agentName : p.name }) : subOf(a.agent).own || subOf(a.agent).plugin ? t("The gateway uses the first. Tick more and it moves on to the next when the one before it is out of quota.") : t("{agent} signs in to the first. Tick more and magpie moves on to the next when the one before it is out of quota. Sessions already running keep theirs until restarted.", { agent: a.agentName }))));
if ((a.logins || []).filter((l) => l.active || l.on).length > 1) ed.append(...renderRouting(p));
if (p.move) ed.append(...renderMove(p));
} else {
@@ -12061,7 +12061,7 @@ function renderRouting(p) {
const own = (routing) => !a || (a.agent !== "codex" && a.agent !== "claude") ? ""
: " " + (keptLogin(p)
? t("Routing picks the account for each request through magpie, in the accounts' order; {agent} on its own stays signed in to {user}, whatever it has left.", { agent: a.agentName, user: keptLogin(p) })
: p.keepLogin
: p.keepLogin && !p.switchOnly
? t("Routing picks the account for each request through magpie; {agent} on its own stays signed in to the first account, whatever it has left.", { agent: a.agentName })
: routing === "order"
? t("Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is used up, and back to the first once that has room again.", { agent: a.agentName })
@@ -13175,11 +13175,10 @@ function forgetOwnTitle(a) {
}
// keptLogin: the account Codex or Claude Code is kept signed in to in
// place of the first (#524), "" when none — the gateway then tries the
// accounts in their order, the one signed in to at its own place
// place of the first (#524), "" when none or switch-only (#1907)
function keptLogin(p) {
const a = p?.account;
if (!a || (a.agent !== "codex" && a.agent !== "claude") || !p.keepLogin || !p.keepLoginAs) return "";
if (!a || (a.agent !== "codex" && a.agent !== "claude") || !p.keepLogin || p.switchOnly || !p.keepLoginAs) return "";
const as = p.keepLoginAs.toLowerCase();
return (a.logins || []).find((l) => (l.user || "").toLowerCase() === as)?.user || "";
}
@@ -13368,7 +13367,7 @@ function renderAccounts(a, p) {
// first runs low (#209, #408); this keeps it on the first instead, or on
// an account of the user's choosing, the gateway still spreading requests
// over the ticked ones in their order (#524)
if ((a.agent === "codex" || a.agent === "claude") && several && p) {
if ((a.agent === "codex" || a.agent === "claude") && several && p && !p.switchOnly) {
const box = el("div", "keep-login");
const [keep, cb] = tick(t("Keep {agent} signed in to", { agent: a.agentName }), !!p.keepLogin);
keep.title = t("magpie won't sign {agent} in to another account when the first runs low; requests through magpie still go to the other ticked accounts as Routing says", { agent: a.agentName });
+4 -4
View File
@@ -1711,7 +1711,7 @@ const I18N = {
"Weekly pace": "重置前用完",
"Each request goes to the subscription with the most of its week left per hour until it renews — the one with the most to lose at its reset — so less of each week is lost at its reset; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours.": "每个请求发给周剩余额度 ÷ 距重置小时数最高的订阅;用到 90% 以上的,等其他都无法响应时才用。密钥按最近几小时处理的 token 数排序。",
"The gateway now uses {user} first": "网关现在优先使用 {user}",
"{agent} signs in to the first. Tick more and the gateway moves on to the next when the one before it is out of quota. Sessions already running keep theirs until restarted.": "{agent} 登录首选账号;勾选多个时,前一个额度用完网关自动换下一个。已在运行的会话保持原账号,重启后切换。",
"{agent} signs in to the first. Tick more and magpie moves on to the next when the one before it is out of quota. Sessions already running keep theirs until restarted.": "{agent} 登录首选账号;勾选多个时,前一个额度用完 magpie 自动换下一个。已在运行的会话保持原账号,重启后切换。",
"{agent} is signed in to this account": "{agent} 当前登录的就是这个账号",
"Stop using this account": "停用这个账号",
"Use this account too": "同时启用这个账号",
@@ -5840,7 +5840,7 @@ const I18N = {
"Weekly pace": "重置前用完",
"Each request goes to the subscription with the most of its week left per hour until it renews — the one with the most to lose at its reset — so less of each week is lost at its reset; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours.": "每個請求發給週剩餘額度 ÷ 距重置小時數最高的訂閱;用到 90% 以上的,等其他都無法回應時才用。金鑰按最近幾小時處理的 token 數排序。",
"The gateway now uses {user} first": "閘道現在優先使用 {user}",
"{agent} signs in to the first. Tick more and the gateway moves on to the next when the one before it is out of quota. Sessions already running keep theirs until restarted.": "{agent} 登入首選帳號;勾選多個時,前一個額度用完閘道自動換下一個。已在執行的會話保持原帳號,重啟後切換。",
"{agent} signs in to the first. Tick more and magpie moves on to the next when the one before it is out of quota. Sessions already running keep theirs until restarted.": "{agent} 登入首選帳號;勾選多個時,前一個額度用完 magpie 自動換下一個。已在執行的會話保持原帳號,重啟後切換。",
"{agent} is signed in to this account": "{agent} 目前登入的就是這個帳號",
"Stop using this account": "停用這個帳號",
"Use this account too": "同時啟用這個帳號",
@@ -9946,7 +9946,7 @@ const I18N = {
"Weekly pace": "週ペース",
"Each request goes to the subscription with the most of its week left per hour until it renews — the one with the most to lose at its reset — so less of each week is lost at its reset; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours.": "各リクエストは、更新までの1時間あたりの週残量が最も多いサブスクリプション(リセット時に失う分が最も多いもの)に送られ、リセット時に無駄になる週の枠を減らします。90% 以上使用したものは他が応答できないときまで待機します。キーは直近数時間に処理したトークン数で判断します。",
"The gateway now uses {user} first": "ゲートウェイは {user} を最初に使うようになりました",
"{agent} signs in to the first. Tick more and the gateway moves on to the next when the one before it is out of quota. Sessions already running keep theirs until restarted.": "{agent} は最初のアカウントにサインインします。複数チェックすると、前のアカウントのクォータが切れたときにゲートウェイが次へ切り替えます。実行中のセッションは再起動するまで元のアカウントのままです。",
"{agent} signs in to the first. Tick more and magpie moves on to the next when the one before it is out of quota. Sessions already running keep theirs until restarted.": "{agent} は最初のアカウントにサインインします。複数チェックすると、前のアカウントのクォータが切れたときに magpie が次へ切り替えます。実行中のセッションは再起動するまで元のアカウントのままです。",
"{agent} is signed in to this account": "{agent} はこのアカウントにサインインしています",
"Stop using this account": "このアカウントの使用を停止",
"Use this account too": "このアカウントも使用",
@@ -14082,7 +14082,7 @@ const I18N = {
"Weekly pace": "Wochentempo",
"Each request goes to the subscription with the most of its week left per hour until it renews — the one with the most to lose at its reset — so less of each week is lost at its reset; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours.": "Jede Anfrage geht an das Abo, das pro Stunde bis zur Erneuerung am meisten von seiner Woche übrig hat — also das, das beim Reset am meisten verlieren würde —, damit beim Reset weniger von jeder Woche verfällt; eines mit 90 % oder mehr wartet, bis die anderen nicht antworten können. Ein Schlüssel richtet sich nach den Token, die er in den letzten Stunden geliefert hat.",
"The gateway now uses {user} first": "Der Zugangspunkt verwendet jetzt zuerst {user}",
"{agent} signs in to the first. Tick more and the gateway moves on to the next when the one before it is out of quota. Sessions already running keep theirs until restarted.": "{agent} meldet sich beim ersten an. Haken Sie weitere an, wechselt der Zugangspunkt zum nächsten, sobald das vorherige kein Kontingent mehr hat. Laufende Sitzungen behalten ihres bis zum Neustart.",
"{agent} signs in to the first. Tick more and magpie moves on to the next when the one before it is out of quota. Sessions already running keep theirs until restarted.": "{agent} meldet sich beim ersten an. Haken Sie weitere an, wechselt magpie zum nächsten, sobald das vorherige kein Kontingent mehr hat. Laufende Sitzungen behalten ihres bis zum Neustart.",
"{agent} is signed in to this account": "{agent} ist bei diesem Konto angemeldet",
"Stop using this account": "Dieses Konto nicht mehr verwenden",
"Use this account too": "Dieses Konto ebenfalls verwenden",
+25 -6
View File
@@ -7,8 +7,10 @@
// a pick keeps Codex signed in to an account of the user's choosing
// (keepLoginAs) while the first stays first: that row says Signed in, the
// first says First, and Make first on it arranges the order rather than
// signing Codex in. The page doesn't move. In English and Chinese,
// Chromium and WebKit.
// signing Codex in. The page doesn't move. #1907: while magpie only
// switches Codex's sign-in, there is nothing to keep it on (kept on one,
// nothing would move it): no tick, and the notes say magpie moves it. In
// English and Chinese, Chromium and WebKit.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
@@ -16,8 +18,8 @@ const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const codex = ({ keepLogin = false, routing = "", spare = true } = {}) => ({
id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "", routing, keepLogin,
const codex = ({ keepLogin = false, keepLoginAs = "", switchOnly = false, routing = "", spare = true } = {}) => ({
id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "", routing, keepLogin, keepLoginAs, switchOnly,
models: [{ id: "gpt-6", name: "GPT-6", on: true }], agents: [], fallback: [], headers: {}, keyList: [],
account: {
agent: "codex", agentName: "Codex", user: "work@example.com", plan: "PLUS",
@@ -61,8 +63,8 @@ function serve(lang, first, posts) {
}
const words = {
en: { keep: "Keep Codex signed in to", first: "the first account", pickHead: "Account to stay signed in to", signed: "Signed in", firstLabel: "First", makeFirst: "Make first", keptAs: /Codex on its own stays signed in to spare@example.com/, kept: /Codex on its own stays signed in to the first account/, moves: /once it is 98% used/, usedUp: /once it is used up/ },
zh: { keep: "Codex 始终登录", first: "首选账号", pickHead: "始终登录的账号", signed: "已登录", firstLabel: "首选", makeFirst: "设为首选", keptAs: /Codex 直连时始终登录 spare@example.com/, kept: /Codex 直连时始终登录首选账号/, moves: /用到 98% 时/, usedUp: /额度用完时/ },
en: { switchOnly: "Only switch Codex's sign-in", magpieMoves: /Tick more and magpie moves on to the next/, keep: "Keep Codex signed in to", first: "the first account", pickHead: "Account to stay signed in to", signed: "Signed in", firstLabel: "First", makeFirst: "Make first", keptAs: /Codex on its own stays signed in to spare@example.com/, kept: /Codex on its own stays signed in to the first account/, moves: /once it is 98% used/, usedUp: /once it is used up/ },
zh: { switchOnly: "只切换 Codex 的登录", magpieMoves: /前一个额度用完 magpie 自动换下一个/, keep: "Codex 始终登录", first: "首选账号", pickHead: "始终登录的账号", signed: "已登录", firstLabel: "首选", makeFirst: "设为首选", keptAs: /Codex 直连时始终登录 spare@example.com/, kept: /Codex 直连时始终登录首选账号/, moves: /用到 98% 时/, usedUp: /额度用完时/ },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
@@ -177,6 +179,23 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.deepEqual(errors, []);
});
for (const keepLoginAs of ["", "spare@example.com"]) {
test(`${engine} ${lang}: switching only Codex's sign-in, kept on ${keepLoginAs || "the first"}, it is moved on all the same`, async (t) => {
const { page, errors } = await open(t, { switchOnly: true, keepLogin: true, keepLoginAs });
assert.equal(await page.locator(".editor .accts .keep-login").count(), 0, "no keep tick under switch-only");
const only = page.locator(".editor .accts .switch-only label");
assert.equal((await only.textContent()).trim(), w.switchOnly);
assert.equal(await only.locator("input").isChecked(), true);
const text = await page.locator(".editor").textContent();
assert.match(text, w.moves);
assert.doesNotMatch(text, w.kept);
assert.doesNotMatch(text, w.keptAs);
assert.match(text, w.magpieMoves);
assert.equal(await page.evaluate(() => I18N.zh["{agent} signs in to the first. Tick more and magpie moves on to the next when the one before it is out of quota. Sessions already running keep theirs until restarted."] ? "" : "missing"), "");
assert.deepEqual(errors, []);
});
}
test(`${engine} ${lang}: with one account on, there is nothing to keep`, async (t) => {
const { page, errors } = await open(t, { spare: false });
assert.equal(await page.locator(".editor .accts .keep-login label").count(), 0);
+6 -3
View File
@@ -24,7 +24,10 @@ package provider
// to it, as Smart gives it requests again then (#408). A switch the user
// makes meanwhile ends that. With KeepLogin on the subscription, the agent
// stays signed in to the first, whatever it has left (#524); with
// KeepLoginAs, to that account, wherever it stands in the order.
// KeepLoginAs, to that account, wherever it stands in the order. Not while
// magpie only switches the sign-in (SwitchOnly): moving it is then all
// magpie is asked to do, and kept on one account nothing would ever move
// (#1907, keepsLogin).
import (
"context"
@@ -121,11 +124,11 @@ func SpentShareOf(routing string) float64 {
// loginSwitching is how magpie moves agent's sign-in, as its subscription
// says: the share the account it is on is moved off at, and whether it is
// kept on the first instead (KeepLogin).
// kept on the first instead (keepsLogin).
func loginSwitching(agent string) (share float64, keep bool) {
for _, p := range load().Providers {
if p.ID == agent {
return SpentShareOf(p.Routing), p.KeepLogin
return SpentShareOf(p.Routing), p.keepsLogin()
}
}
return SpentShare, false
+20 -2
View File
@@ -25,7 +25,7 @@ func keptAs(agent string) string {
if p.ID != agent {
continue
}
if !p.KeepLogin || p.KeepLoginAs == "" {
if !p.keepsLogin() || p.KeepLoginAs == "" {
return ""
}
for _, l := range Logins(agent) {
@@ -44,7 +44,7 @@ func keptAs(agent string) string {
// signed in to is the first.
func (p Provider) LoginRanks() map[string]int {
if p.Account == nil || p.Account.token != nil && !p.Account.standIn || !slices.Contains(switchedAgents, p.Account.Agent) ||
!p.KeepLogin || p.KeepLoginAs == "" {
!p.keepsLogin() || p.KeepLoginAs == "" {
return nil
}
ranks := map[string]int{}
@@ -70,6 +70,9 @@ func SetKeepLoginAs(id, user string) error {
if p.Account == nil || p.Account.Agent != p.ID || !slices.Contains(switchedAgents, p.ID) {
return fmt.Errorf("magpie doesn't sign %s in to another of its accounts", p.Name)
}
if p.SwitchOnly {
return errSwitchOnly(*p)
}
ls := Logins(p.ID)
i := slices.IndexFunc(ls, func(l Login) bool { return strings.EqualFold(l.User, user) })
if i < 0 {
@@ -107,6 +110,21 @@ func SetKeepLoginAs(id, user string) error {
return SwitchLogin(p.ID, to.User)
}
// keepsLogin reports whether magpie keeps the agent signed in to one
// account (KeepLogin, KeepLoginAs). Not while it only switches the agent's
// sign-in (SwitchOnly): that asks for the sign-in to move to the next
// account with room, and kept on one, nothing would ever move it, nor any
// request fail over through the gateway (#1907: both ticked, Codex stayed
// on an account at 0% left). The choice is kept, and holds again once
// switch-only is unticked.
func (p Provider) keepsLogin() bool { return p.KeepLogin && !p.SwitchOnly }
// errSwitchOnly refuses to keep p's agent on one account while magpie only
// switches its sign-in (keepsLogin).
func errSwitchOnly(p Provider) error {
return fmt.Errorf("magpie only switches %s's sign-in to the next account with room; untick that to keep it signed in to one account", p.Name)
}
// rankLogins writes order as the order of agent's saved accounts.
func rankLogins(agent string, order []string) error {
loginsMu.Lock()
+4 -1
View File
@@ -106,7 +106,10 @@ func SetKeepLogin(id string, keep bool) error {
if p.Account == nil || p.Account.Agent != p.ID || !slices.Contains(switchedAgents, p.ID) {
return fmt.Errorf("magpie doesn't sign %s in to another of its accounts", p.Name)
}
chosen := p.KeepLogin && p.KeepLoginAs != ""
if keep && p.SwitchOnly {
return errSwitchOnly(*p)
}
chosen := p.keepsLogin() && p.KeepLoginAs != ""
p.KeepLogin, p.KeepLoginAs = keep, ""
if err := Save(*p); err != nil {
return err
+143
View File
@@ -3,6 +3,7 @@ package provider
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
@@ -199,3 +200,145 @@ func TestClaudeSwitchOnlyServesNothingAndStillSwitches(t *testing.T) {
t.Error("claude/claude-sonnet-5 doesn't resolve unticked")
}
}
// #1907 (foobra, v0.1.1224 on): "Keep Codex signed in to [the first
// account]" and "Only switch Codex's sign-in" both ticked, the account Codex
// was on at 0% of its five hours left, the other at 100%: Codex stayed on
// the spent one through a restart. Kept on one account, nothing ever moved
// the sign-in, and switch-only sent nothing through the gateway either.
// Switch-only asks for the sign-in to move, so it does, whether kept on the
// first or on an account of the user's choosing; the choice is kept, and
// holds again once switch-only is let go.
func TestSwitchOnlyMovesASignInKeptOnOne(t *testing.T) {
for _, chosen := range []bool{false, true} {
t.Run(fmt.Sprint("kept on one chosen ", chosen), func(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": 0}
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)
}
// the one Codex is signed in to, by the name magpie gives it
as := ""
for _, l := range Logins("codex") {
if l.Active && chosen {
as = l.User
}
}
if !chosen {
if err := SetKeepLogin("codex", true); err != nil {
t.Fatal(err)
}
} else if err := SetKeepLoginAs("codex", as); err != nil {
t.Fatal(err)
}
if to := switched(); to != "" || signedIn() != "r-1" {
t.Fatalf("kept, without switch-only: moved to %q", to)
}
if err := SetSwitchOnly("codex", true); err != nil {
t.Fatal(err)
}
if to := switched(); to != "spare@example.com" || signedIn() != "r-spare" {
t.Fatalf("switch-only, kept on %q: switched to %q, Codex signed in with %q", as, to, signedIn())
}
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())
}
// the user's choice is still theirs
if p, _ := Find("codex"); !p.KeepLogin || p.KeepLoginAs != as {
t.Fatalf("keep login lost: %v %q", p.KeepLogin, p.KeepLoginAs)
}
// it can't be ticked anew under switch-only, where it would
// do nothing
if err := SetKeepLogin("codex", true); err == nil {
t.Error("kept on the first under switch-only")
}
if err := SetKeepLoginAs("codex", "spare@example.com"); err == nil {
t.Error("kept on spare under switch-only")
}
// let go of switch-only, the kept account holds again
used["acct-me@example.com"] = 100
if err := SetSwitchOnly("codex", false); err != nil {
t.Fatal(err)
}
if to := switched(); to != "" || signedIn() != "r-1" {
t.Fatalf("kept again: moved to %q, Codex signed in with %q", to, signedIn())
}
})
}
}
// The same for Claude Code: its accounts kept to its own sign-in
// (switch-only) and Claude Code kept signed in to the first, the first
// spent moves it to the next.
func TestClaudeSwitchOnlyMovesASignInKeptOnOne(t *testing.T) {
home := claudeHome(t)
cred := claudeSignIn(t, home, time.Now().Add(time.Hour))
writeFile(t, filepath.Join(home, ".claude.json"), map[string]any{"oauthAccount": map[string]any{"emailAddress": "a@example.com", "accountUuid": "u-a"}})
rememberLogins(true)
loginsMu.Lock()
ls := upsertLogin(readLogins(), savedLogin{Agent: "claude", User: "b@example.com", Plan: "max", On: true, Seen: time.Now().UTC(),
Auth: mustJSONRaw(t, map[string]any{"claudeAiOauth": map[string]any{"accessToken": "sk-ant-oat01-b", "refreshToken": "sk-ant-ort01-b",
"expiresAt": time.Now().Add(time.Hour).UnixMilli(), "subscriptionType": "max", "scopes": []string{"user:inference", "user:profile"}}}),
Profile: mustJSONRaw(t, map[string]any{"emailAddress": "b@example.com", "accountUuid": "u-b"})})
if err := writeLogins(ls); err != nil {
t.Fatal(err)
}
loginsMu.Unlock()
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Errorf("usage endpoint read: %s", r.URL)
}))
defer fake.Close()
claudeBase = fake.URL // isolate puts it back
for user, u := range map[string]float64{"a@example.com": 100, "b@example.com": 10} {
NoteClaudeLimits(user, []ClaudeLimit{{Kind: "five_hour", Used: u / 100, ResetsAt: time.Now().Add(time.Hour).Unix()}})
}
if err := SetKeepLogin("claude", true); err != nil {
t.Fatal(err)
}
if to, err := SwitchWhenSpent(context.Background(), "claude"); err != nil || to != "" {
t.Fatalf("kept, without switch-only: moved to %q: %v", to, err)
}
if err := SetSwitchOnly("claude", true); err != nil {
t.Fatal(err)
}
to, err := SwitchWhenSpent(context.Background(), "claude")
if err != nil || to != "b@example.com" {
t.Fatalf("switch-only, kept on the first: switched to %q: %v", to, err)
}
var c map[string]any
readJSON(cred, &c)
if o, _ := c["claudeAiOauth"].(map[string]any); o["refreshToken"] != "sk-ant-ort01-b" {
t.Fatalf("Claude Code is signed in with %v", o)
}
}