diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 482a2e968..b3f46f9bd 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -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 }); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 7714ac8d7..48f01d112 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -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", diff --git a/internal/gui/tests/keep-login.test.cjs b/internal/gui/tests/keep-login.test.cjs index f4278e09a..9ab54a460 100644 --- a/internal/gui/tests/keep-login.test.cjs +++ b/internal/gui/tests/keep-login.test.cjs @@ -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); diff --git a/internal/provider/codex_switch.go b/internal/provider/codex_switch.go index d4f915893..820e6ca8f 100644 --- a/internal/provider/codex_switch.go +++ b/internal/provider/codex_switch.go @@ -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 diff --git a/internal/provider/keep_login_as.go b/internal/provider/keep_login_as.go index 6f87bfaf0..23cd20775 100644 --- a/internal/provider/keep_login_as.go +++ b/internal/provider/keep_login_as.go @@ -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() diff --git a/internal/provider/routing.go b/internal/provider/routing.go index 49de3640a..4e711b4c8 100644 --- a/internal/provider/routing.go +++ b/internal/provider/routing.go @@ -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 diff --git a/internal/provider/switch_only_test.go b/internal/provider/switch_only_test.go index c50622208..f2fa4204a 100644 --- a/internal/provider/switch_only_test.go +++ b/internal/provider/switch_only_test.go @@ -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) + } +}