From a7b47d57ec79ab1786ea36e39d710e71316fb784 Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 31 Oct 2026 17:51:51 +0800 Subject: [PATCH] accounts: removing the account Claude Code is signed in to switches it to another first (#4532) StringKe (#4532): removing the signed-in Claude account was refused with SignedInError, while Codex's switched away first. ForgetLogin now does the same for Claude Code: nextOnForget picks another account (on first, then one whose sign-in holds), SwitchLogin signs Claude Code in to it, and only then is this one forgotten. If that switch fails, nothing is removed and the error says why. nextOnForget leaves out accounts Claude Code or Codex can't be signed in to (switchable: not a setup-token account, not a Codex account held in another folder). Claude Code is never signed out: when the account is the only one it can be signed in to, it is kept, with SignedInError{Only} (GUI code signed_in_only), which says to add another account first or sign out in Claude Code. The GUI gives the signed-in Claude row a Remove when another account it can use exists, and no Remove or Sign out otherwise. Claude Code's own credential is never deleted; forgetClaudeDir removes only the forgotten account's own folder and its folder's Keychain item, and claudeHolders' check of other records holding the same token is unchanged. Tests: TestForgetLiveClaudeSwitchesFirst, TestForgetOnlyClaudeIsKept (replacing TestClaudeInUseStillRefused, which held the old refusal); codex-signout.test.cjs gets three Claude cases (Remove with another; only + setup-token: no Remove, reason in zh/zh-TW/ja/de; the signed_in_only refusal in en/zh). Run (mote, sandbox HOME through the test helpers): - go test ./internal/provider ./internal/cli, vet and gofmt at the stack head: in the next commit's body (one tree, same run). - Broken by hand, each red: Claude not switched first (TestForgetLiveClaudeSwitchesFirst), Only left false, a setup-token account counted as another, nextOnForget unfiltered (TestForgetOnlyClaudeIsKept). - GUI on Linux (WSL magpie-desktop), Chromium and WebKit: codex-signout, own-signin-remove, saved-signedout-remove, login-import, claude-signin, account-alias and i18n-keys all pass but i18n-keys' "a plugin's words are its own", red on main (#4524). On mote, codex-signout passed in Chromium; its WebKit launches were killed with mote at load ~25 under other sessions' suites (#4125), so WebKit's record is Linux's. CLI in a sandbox HOME (WSL, file credentials): forget of the signed-in account by its name switched Claude Code to the other (.claude.json then says max@x.com); forget of the only one was refused with the message above and left it signed in. Not tried: a real Claude Code switch on removal with real accounts, or in the CLI against a live ~/.claude (sandbox only). --- docs/reference.md | 10 +++ docs/subsystems/providers-accounts.md | 1 + internal/gui/api.go | 3 + internal/gui/assets/app.js | 17 ++-- internal/gui/assets/i18n.js | 12 ++- internal/gui/tests/README.md | 8 +- internal/gui/tests/codex-signout.test.cjs | 67 +++++++++++++-- internal/provider/claude_forget_live_test.go | 86 ++++++++++++++++++++ internal/provider/codex_signout_test.go | 24 ------ internal/provider/logins.go | 68 ++++++++++++---- 10 files changed, 235 insertions(+), 61 deletions(-) create mode 100644 internal/provider/claude_forget_live_test.go diff --git a/docs/reference.md b/docs/reference.md index 4f22813dc..15eee26ed 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1858,6 +1858,16 @@ agent off has every window under 90% again, it signs the agent back in to it. *Keep … signed in to* turns this off: the agent stays on the first account, or on the account you picked, whatever it has left. It changes nothing in the gateway's routing. +Removing the account Codex or Claude Code is signed in to (its *Remove*, +or `magpie accounts forget `) signs the agent +in to another of its accounts first, as that one's *Use* would, then +forgets this one; if that switch fails, nothing is removed. Codex's only +account is signed out instead, as `codex logout` does. Claude Code is +never signed out: when the account is the only one it can be signed in +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 diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 3df81b38b..81de54f62 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -51,6 +51,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Claude setup-token | A Claude account can be added from the long-lived token `claude setup-token` prints (sfss5362 on X), which Claude Code takes in `CLAUDE_CODE_OAUTH_TOKEN` (the window's *Use a setup-token instead…* and *Add an account by setup-token…*, `POST /api/signin/claude-token`). `AddClaudeSetupToken` keeps it in `logins.json` as `{"setupToken":…}`, named `Claude setup-token <6 hex of its hash>` (it tells no email), on beside the others; the same token again is the same account. Such a token has the inference scope only: Claude Code's `auth status` says `oauth_token` with no email or plan, and its `/usage` prints the API cost view, so `/usage` is never run for it and its allowance is unknown (`errClaudeSetupToken`, kept by `passing` as saying nothing about the account) until a reply's rate-limit event tells it. Its config directory (`claudeTokenDir`) holds no `.credentials.json`, which Claude Code could fall back to on a refused token. Claude Code itself is never signed in to it: `addLogin`, `switchLogin`, `putClaudeLogin`, `SetKeepLoginAs`, `NextLogin` and `signInToFirst` pass it over, and the window shows Remove and *magpie only* in place of Use and Make first. Not tried with a real token. | [`claude_setup_token.go`](../../internal/provider/claude_setup_token.go), [`claude_subscription.go`](../../internal/gateway/claude_subscription.go) (`inClaudeDir`), [`providers.go`](../../internal/gui/providers.go) | | Switch accounts only | magpie as a Claude Code (or Codex) account switcher alone, with nothing connected (the owner on X; growaiskills, Rennix7t). In the window, the Agents row of a Claude Code or Codex not connected says the account it is signed in to (`switchEntry` in app.js, from the providers list `prefetchProviders` reads at start, so `/api/state` reads no keychain for it), also when magpie has no models to connect (`switchable`, before the `empty` line). Its menu, headed *Switch accounts only*, lists the agent's saved accounts: a pick goes through `POST /api/login/switch` (`SwitchLogin`), or `provider/keeplogin` with `keepLoginAs` when the agent is kept signed in to an account of the user's choosing, as the account rows do; the button says *Switched* for five seconds and the status line says new sessions use the account, one already open keeps its own until started again. *Only switch {agent}'s sign-in* (`SwitchOnly` above, `provider/switchonly`) is a ticked item there (Codex: with more than one usable account, as under Providers), and the row then says *Not connected · switching accounts only*. *Manage accounts…*, and a pick whose sign-in lapsed, open Providers › the agent. A Codex failing over (#1385) has it in place of the old *ChatGPT accounts* button. In the tray panel (whose Quick panel shortcut opens it from any app, shuizhuyu on X) it is the *account* line of the agent's opened row (`.ag-who`), drawn from the list kept from the last read (`panelAccounts`, `GET /api/providers?last=1`, no keychain read; a fresh read only when none is kept), so opening the panel reads no sign-in. The menu waits for one fresh `/api/providers` read and opens on what it says; *Manage accounts…* and a lapsed pick open the window's Providers (`window/main?view=providers`). The provider and login actions keep their answer as the last list (`keepProviders`), so a switch made anywhere is in the panel's next line at once (`TestKeptProvidersFollowActions`, `panel-switch-accounts.test.cjs`). Not on a WSL twin's row, not on a connected agent's. | [`app.js`](../../internal/gui/assets/app.js), [`logins.go`](../../internal/provider/logins.go) | | Used-up switch | When the account Codex or Claude Code is signed in to has used its allowance, the agent is signed in to the next account that is on and has room (#208). When every one is past its line too, it goes to the one with the most room left (`roomLeft`: the fullest stopping window's distance below the switch share, or the account's own cap when lower), when that has more than the account it is on by `roomMargin` (1 point), so two all but even accounts don't trade it each look; else it stays (StringKe in #4532, after cswap's `best`; `TestNextLoginTakesTheMostRoomWhenAllArePast`). `magpie accounts switch next` (`NextInOrder`) takes the other accounts that are on, from the one after the account the agent is on, wrapping round: the first with room, else the one with the most room left, said to be past its line; with no reading of any, it refuses rather than guess (`TestNextInOrder`). For Codex, *Only switch Codex's sign-in* (`SwitchOnly`, `SetSwitchOnly`) keeps magpie's `openai_base_url` failover out of Codex's config, so the switch is all magpie does (#1907); an unreadable providers.json reads as switch-only, so the failover is not written on a guess. For Claude, the same setting keeps the accounts to Claude Code (`Provider.KeptToAgent`): `On()` is false, so the gateway, catalog and groups serve nothing on them, while switching and usage, gated by `leftAlone` on the raw `Off`, go on. No request of a saved Claude account passes magpie then, so one Claude Code wasn't signed in to since has no reading: once the account Claude Code is on is spent, `NextLogin` reads such a spare (`readSpare`, `spareRead` in `claudeWindows`) by Claude Code's own `/usage` in the account's directory, in order and only till one has room; a spare read once is not read again, and one whose read failed waits `claudeUsageWait` (cn_Vincentzyx on X, `TestClaudeSwitchOnlyReadsUnreadSpares`). Codex's spares are read through their saved tokens and had no such gap. Claude Code on its own login is out long before a five-minute look notices (#4443: 4% left to refused in two minutes): while Claude has an account to move to, `KeepOnAnAccountWithRoom` looks at its sign-in every `claudeLookEvery` (a minute) between its full looks when `claudeLookDue`, that is when the account Claude Code is on is near out (`claudeNearOut`, `codexNearShare`; its `/usage` is then due after `claudeNearOutWait` rather than `claudeUsageWait`), or when Claude Code wrote a `rate_limit` refusal ("You've hit your … limit") into one of its sessions since that account's last `/usage` (`scanClaudeLimits`, which reads only what was appended to each `projects/*/*.jsonl` since the last scan). The refusal names no account, so it only makes the `/usage` read due (and the reading stale, `StaleAllowance`); the read decides (`TestClaudeNearOutIsReadEveryMinute`, `TestClaudeRefusalInSessionReadsAtOnce`, `TestKeepOnAnAccountWithRoomLooksAtClaudeNearOut`). | [`codex_switch.go`](../../internal/provider/codex_switch.go) | +| Removing the signed-in account | `ForgetLogin` signs Codex or Claude Code in to another of its accounts first (`nextOnForget`: the first other that is on, else one whose sign-in holds, else any, never a setup-token account or one Codex keeps in another folder: `switchable`), then forgets this one; a switch that fails removes nothing (StringKe, #4532: Claude's was refused while Codex's switched). Codex's only account is signed out as `codex logout` does. Claude Code is never signed out: its last account it can be signed in to is refused with `SignedInError{Only}` (GUI code `signed_in_only`, and that account has no *Remove*). Claude Code's own credential is never deleted; the forgotten account's folder (`forgetClaudeDir`) is its own. `TestForgetLiveClaudeSwitchesFirst`, `TestForgetOnlyClaudeIsKept`, `codex-signout.test.cjs`. | | Claude Code's proxy | Claude Code on its own subscription asks Anthropic itself, through the proxy its env names. While any Claude account has a proxy of its own (`AccountProxies`), the `env` of Claude Code's `settings.json` names the proxy of the account it is signed in to (#1807): `HTTPS_PROXY` and `HTTP_PROXY` set to that account's own, else the subscription's `Proxy` (`ProxyOfLogin`), and `NO_PROXY` to loopback; none for `direct` or a SOCKS proxy, which Claude Code can't use. It is written on every switch (`switchLogin`, the user's or `SwitchWhenSpent`), when the Claude subscription is saved, and at the gateway's look every `loginSwitchEvery` (a sign-in made in Claude Code itself). Claude Code reads its env at start, so only sessions started after the switch take it. A proxy key the user set (in either case) is theirs: magpie then writes none and takes out none of theirs. What magpie wrote is kept in `claude-proxy-env.json`, and a key is magpie's only while it holds that value. A `settings.json` that doesn't parse is left as it is. Its log lines name the proxy through `netproxy.Redact`, without its user and password (#1886); the env gets it whole. | [`claude_proxy_env.go`](../../internal/provider/claude_proxy_env.go) | | Routing groups | User-made groups from the Routing view, and auto-found groups of the same model across providers (derived, never stored). The same model is the same id as vendors agree on it (`sameModel`): lowercase, without a vendor's prefix, a version's dot as `-`, a run of spaces, `_` and `-` as one `-` (a relay listing its display name as the id, `GPT-6 Sol`, joins `gpt-6-sol`, Chill on Discord: `TestSameModelDisplayNameAsID`), and without a YYYYMMDD or Ark YYMMDD snapshot date. Every word still counts (`gpt-6`, `gpt-6-mini` and `gpt-6-sol` stay apart), as do a `:variant`, a four-digit release and OpenAI's dashed date (`gpt-4o-2024-08-06`, a pinned snapshot whose group id agents may already name). A provider kept "Only through routing groups" joins them the same way. Members are `provider/model[:effort]`. A group can nest another (`group/`); `SaveGroup` refuses loops. A group given another id (`agent.RenameGroup`: the Routing page, `magpie groups rename`, the TUI) moves every agent field on `group/` to `group/`, spelled as the agent spells it, through the same `renameRefs` a provider's rename uses, then `SyncCatalog`; before, the agents stayed on a group magpie no longer had (lucis0116 on X, `TestRenameGroupMovesTheAgentsOnIt`). A provider's or group's display name needs no move: `store` and `SaveGroup` drop the catalog, and `SyncCatalog` writes the new labels into every agent's list. `Match` takes a glob or `re:` pattern (#766), both matched in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter). What a pattern matches follows the members named, in the catalog's order, until the user drags it elsewhere (usrname1833 on Discord): `Placed` keeps the whole order, named and matched alike, and the group is read and routed in it (`placedIn`); a model matched since goes last, one no longer matched drops out, a save that sends the named members only leaves the matched where they were (`placedOver`), and a provider's or group's rename carries it (`TestGroupPatternMembersKeepTheirPlace`, `group-member-drag.test.cjs`). A found group follows the providers magpie has: one removed leaves it, while one switched off stays in it (`foundGroups`, `heldOffEntries`; one without a key, such as a plugin not signed in, finds no group), skipped by `membersIn`, left off a found group's card, logos and TUI line with a count of those switched off (XYenon on Discord: `routing-provider-off.test.cjs`, `TestFoundGroupLineLeavesASwitchedOffProviderOut`) and said as switched off in its editor and the TUI's group page, so switching one of two providers off for a while doesn't take the group away from the agents, rules and groups set to it; it is back in its place once on again (#2671: `TestFoundGroupStaysWithAProviderOff`, `TestFoundGroupWithAProviderOff`, `TestReseatKeepsAFoundGroupWithAProviderOff`, `TestFoundGroupMemberOfASwitchedOffProvider`). A found group the user changed (an `auto-…` id stored) is read without the members of providers magpie no longer has (`withoutRemoved`, not written back, so a provider back under its id is back in it), except a manual group's pick, a rule's model, or all of them when none would be left. A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing page says them as switched off (`memberJSON.providerOff`). The user's own groups keep their members. Three templates make a group in one click from the models the user has (`provider.Templates`, `AddTemplate`; the Routing page's cards before a first group and its Templates menu after, `magpie group template [kind] [name]`): `smart` sends a hard turn to the strongest model and an easy one or a compaction to a cheap one, asked by a classifier (the decision API when there is one, else the cheapest priced model that doesn't reason); `thrifty` starts on two cheap models of different providers and sends high reasoning to the strongest; `steady` fails over between the strongest model of up to three providers. A model is weighed by its maker's list price when known, else what its provider charges, else by its id's size words (`sizeOf`); one over `tooDear` (USD 100 a million output tokens) is never picked. A template that can't be made says what is missing (`Need`). It is saved under a name and id no group has (`freeGroupName`, shared with `CopyGroup`), never over one. A group is shared as text (`ShareGroup`, a group row's Copy to share): JSON marked `"magpie": "routing-group"` with a format `version` (`ShareVersion`), holding the group's members as it names them, patterns, routing, rules, classifier and settings. A group holds only `provider/model` ids, never a key, account or address, and the derived matches, found/hidden/off flags and the rules that hold by a folder (a path on the sharer's machine, `Rule.Folders`) stay behind; a pasted one is left out too. `ImportGroup` (the Routing page's Import, `POST /api/groups/import`) reads it with words or a code fence around it, refuses another text, a newer format or none (`ShareError`, said in the reader's language). A member whose provider the importer has is kept; else the same model (`AutoGroupOf`) under the first provider of theirs that serves it (`Instead`); else it is left out and named (`Missing`), with the rules that send to it, its place among the off and fast members, and a classifier gone takes the intent rules and auto effort with it. Nothing is added when no member is left; what is added gets a free name, never replacing a group. A group of patterns only that match nothing now (a plugin's models not listed) has no members: `/api/groups` says them, and an unmakeable template's, as `[]`, never `null`; the Routing page reads the response through `groupsFrom` and draws a group it still can't draw as one row saying so, so one bad group never hides the rest (#1585). | [`group.go`](../../internal/provider/group.go), [`grouptemplate.go`](../../internal/provider/grouptemplate.go), [`group_share.go`](../../internal/provider/group_share.go) | | Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it, each window with its whole-window estimate (`Holds`/`HoldsWhy`, `usage.WithWindowHolds`, which `quotaReport` reaches through the `ReckonHolds` hook since package provider can't import usage, #2333). A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). Each key of a remote-magpie provider also gets a card of its own, under `/~keys`, one section per key (#1547, `remoteKeyCards` in `remote_key_limits.go`): the gateway key's limit as that magpie holds it, read from `GET /v1/magpie/limit` asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus `GatewayKey` (what is left, calls, a cycle of days, used up); a key held to no limit shows `Unlimited`. It is kept for `remoteCardsFor` like the remote's cards and read again by the card's refresh (`?provider=/~keys&user=`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). A remote that holds the key to a budget, models or accounts answers its cards 403 `gateway_key_held` (#1981, `errKeyHeld`): the cards kept from before are dropped and only the key's own card shows. Its owner can let the key be told the cards of what it may use (#2216, `magpie gateway-key quotas on`); the remote then answers those, and 403 as before when that is none. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, `quotasOpened`, #1588) or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. A plugin's window may carry a prepaid wallet's `balance` in its `unit` and no share (`QuotaWindow.Balance`, #3950): the card and `magpie quota` show the figure (`BalanceText`), and routing reads it through `Allowance.Left`. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`quota_asked.go`](../../internal/provider/quota_asked.go) | diff --git a/internal/gui/api.go b/internal/gui/api.go index 6d4753bc0..3fba60521 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -3150,6 +3150,9 @@ func fail(rw http.ResponseWriter, err error) { var signedIn *provider.SignedInError if errors.As(err, &signedIn) { out["code"], out["agent"], out["user"] = "signed_in", signedIn.Agent, signedIn.User + if signedIn.Only { + out["code"] = "signed_in_only" + } } // a text that isn't a group to import (laincatx on X), said in the // reader's language diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 499c3ae2c..2c132c613 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -162,9 +162,12 @@ async function api(path, body, heads, signal) { if (data?.said) err.message = t(data.said, data); // an i18n.js key (api.go) // an account the agent is signed in to, refused removal while it has // another: said in the reader's language - if (data?.code === "signed_in") { + if (data?.code === "signed_in" || data?.code === "signed_in_only") { err.code = data.code; - err.message = t("{agent} is signed in to {user} now: sign it in to another of its accounts first (Use on that account), then remove this one", { agent: { codex: "Codex", claude: "Claude Code" }[data.agent] || data.agent, user: data.user }); + const v = { agent: { codex: "Codex", claude: "Claude Code" }[data.agent] || data.agent, user: data.user }; + err.message = data.code === "signed_in_only" + ? t("{agent} is signed in to {user}, the only account in magpie it can be signed in to, and magpie doesn't sign it out: add another account first, or sign out in {agent} itself, then remove this one", v) + : t("{agent} is signed in to {user} now: sign it in to another of its accounts first (Use on that account), then remove this one", v); } // a text Import can't add as a routing group (laincatx on X) if (data?.code === "share") { @@ -13142,10 +13145,12 @@ function renderAccounts(a, p) { out.title = t("Signs Codex out of this account, as codex logout does"); out.onclick = () => askSignOutLogin(a, l); line.append(out); - } else if (a.agent === "codex") { - // Codex is signed in to another of its accounts first, then this - // one goes (ForgetLogin), rather than Codex signed out - line.append(forgetOf(t("Codex is signed in to another of its accounts, and magpie forgets this one; the account itself is untouched"))); + } else if (a.agent === "codex" || a.agent === "claude" && ls.some((o) => o !== l && !o.token)) { + // the agent is signed in to another of its accounts first, then + // this one goes (ForgetLogin), rather than Codex signed out or the + // removal refused (#4532); Claude Code's only one it can be signed + // in to has no Remove: magpie never signs it out + line.append(forgetOf(t("{agent} is signed in to another of its accounts, and magpie forgets this one; the account itself is untouched", { agent: a.agentName }))); } } else { const forget = forgetOf(true); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 249cd9374..e169ffbd3 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1397,8 +1397,9 @@ const I18N = { "magpie signs out the accounts it keeps for {name}; adding it again signs in afresh": "退出为 {name} 保存的账号;再次添加需重新登录", "{name} signed out": "已退出 {name}", "{agent} is signed in to {user} now: sign it in to another of its accounts first (Use on that account), then remove this one": "{agent} 当前登录的是 {user}:请先在另一个账号上点「使用」把 {agent} 切过去,再移除这个账号", + "{agent} is signed in to {user}, the only account in magpie it can be signed in to, and magpie doesn't sign it out: add another account first, or sign out in {agent} itself, then remove this one": "{agent} 当前登录的是 {user},这是 magpie 里它唯一能登录的账号,magpie 不会把它登出:请先添加另一个账号,或在 {agent} 里自己登出,再移除这个账号", "Signs Codex out of this account, as codex logout does": "让 Codex 退出这个账号,与 codex logout 相同", - "Codex is signed in to another of its accounts, and magpie forgets this one; the account itself is untouched": "Codex 会先登录到它的另一个账号,magpie 再忘掉这个账号;账号本身不受影响", + "{agent} is signed in to another of its accounts, and magpie forgets this one; the account itself is untouched": "{agent} 会先登录到它的另一个账号,magpie 再忘掉这个账号;账号本身不受影响", "Codex itself is signed out too, as codex logout does.": "Codex 本身也会退出登录,与 codex logout 相同。", "Sign {agent} out of {user}?": "让 {agent} 退出 {user}?", "{agent} is signed out, as codex logout does, and magpie forgets the account. Sign in again to use it; an open {agent} may need quitting and opening again. The account itself is left as it is.": "{agent} 会退出登录(与 codex logout 相同),magpie 也不再保存这个账号。要再用需重新登录;已打开的 {agent} 可能要退出后重新打开。账号本身不受影响。", @@ -5654,8 +5655,9 @@ const I18N = { "magpie signs out the accounts it keeps for {name}; adding it again signs in afresh": "退出為 {name} 儲存的帳號;再次新增需重新登入", "{name} signed out": "已退出 {name}", "{agent} is signed in to {user} now: sign it in to another of its accounts first (Use on that account), then remove this one": "{agent} 目前登入的是 {user}:請先在另一個帳號上點「使用」把 {agent} 切過去,再移除這個帳號", + "{agent} is signed in to {user}, the only account in magpie it can be signed in to, and magpie doesn't sign it out: add another account first, or sign out in {agent} itself, then remove this one": "{agent} 目前登入的是 {user},這是 magpie 裡它唯一能登入的帳號,magpie 不會把它登出:請先新增另一個帳號,或在 {agent} 裡自行登出,再移除這個帳號", "Signs Codex out of this account, as codex logout does": "讓 Codex 退出這個帳號,與 codex logout 相同", - "Codex is signed in to another of its accounts, and magpie forgets this one; the account itself is untouched": "Codex 會先登入到它的另一個帳號,magpie 再忘掉這個帳號;帳號本身不受影響", + "{agent} is signed in to another of its accounts, and magpie forgets this one; the account itself is untouched": "{agent} 會先登入到它的另一個帳號,magpie 再忘掉這個帳號;帳號本身不受影響", "Codex itself is signed out too, as codex logout does.": "Codex 本身也會退出登入,與 codex logout 相同。", "Sign {agent} out of {user}?": "讓 {agent} 退出 {user}?", "{agent} is signed out, as codex logout does, and magpie forgets the account. Sign in again to use it; an open {agent} may need quitting and opening again. The account itself is left as it is.": "{agent} 會退出登入(與 codex logout 相同),magpie 也不再儲存這個帳號。要再用需重新登入;已開啟的 {agent} 可能要退出後重新開啟。帳號本身不受影響。", @@ -9881,8 +9883,9 @@ const I18N = { "magpie signs out the accounts it keeps for {name}; adding it again signs in afresh": "magpie は {name} 用に保存しているアカウントからサインアウトします。再度追加するときは改めてサインインします", "{name} signed out": "{name} からサインアウトしました", "{agent} is signed in to {user} now: sign it in to another of its accounts first (Use on that account), then remove this one": "{agent} は現在 {user} でサインインしています。先に別のアカウントの「使用」で切り替えてから、このアカウントを削除してください", + "{agent} is signed in to {user}, the only account in magpie it can be signed in to, and magpie doesn't sign it out: add another account first, or sign out in {agent} itself, then remove this one": "{agent} は現在 {user} でサインインしています。これは magpie で {agent} がサインインできる唯一のアカウントで、magpie はサインアウトさせません。先に別のアカウントを追加するか、{agent} 自身でサインアウトしてから、このアカウントを削除してください", "Signs Codex out of this account, as codex logout does": "codex logout と同じく、Codex をこのアカウントからサインアウトします", - "Codex is signed in to another of its accounts, and magpie forgets this one; the account itself is untouched": "Codex を別のアカウントにサインインし直してから、magpie はこのアカウントを忘れます。アカウント自体はそのままです", + "{agent} is signed in to another of its accounts, and magpie forgets this one; the account itself is untouched": "{agent} を別のアカウントにサインインし直してから、magpie はこのアカウントを忘れます。アカウント自体はそのままです", "Codex itself is signed out too, as codex logout does.": "codex logout と同じく、Codex 自体もサインアウトします。", "Sign {agent} out of {user}?": "{agent} を {user} からサインアウトしますか?", "{agent} is signed out, as codex logout does, and magpie forgets the account. Sign in again to use it; an open {agent} may need quitting and opening again. The account itself is left as it is.": "codex logout と同じく {agent} はサインアウトし、magpie はこのアカウントを削除します。再び使うにはサインインし直してください。開いている {agent} は終了して開き直す必要があるかもしれません。アカウント自体はそのままです。", @@ -14139,8 +14142,9 @@ const I18N = { "magpie signs out the accounts it keeps for {name}; adding it again signs in afresh": "magpie meldet die für {name} gespeicherten Konten ab; beim erneuten Hinzufügen neu anmelden", "{name} signed out": "{name} abgemeldet", "{agent} is signed in to {user} now: sign it in to another of its accounts first (Use on that account), then remove this one": "{agent} ist gerade bei {user} angemeldet: Melden Sie es zuerst bei einem anderen seiner Konten an (dort „Verwenden“) und entfernen Sie dann dieses", + "{agent} is signed in to {user}, the only account in magpie it can be signed in to, and magpie doesn't sign it out: add another account first, or sign out in {agent} itself, then remove this one": "{agent} ist bei {user} angemeldet, dem einzigen Konto in magpie, bei dem es angemeldet sein kann, und magpie meldet es nicht ab: Fügen Sie zuerst ein anderes Konto hinzu oder melden Sie sich in {agent} selbst ab, und entfernen Sie dann dieses", "Signs Codex out of this account, as codex logout does": "Meldet Codex von diesem Konto ab, wie codex logout", - "Codex is signed in to another of its accounts, and magpie forgets this one; the account itself is untouched": "Codex wird bei einem anderen seiner Konten angemeldet, und magpie vergisst dieses; das Konto selbst bleibt unberührt", + "{agent} is signed in to another of its accounts, and magpie forgets this one; the account itself is untouched": "{agent} wird bei einem anderen seiner Konten angemeldet, und magpie vergisst dieses; das Konto selbst bleibt unberührt", "Codex itself is signed out too, as codex logout does.": "Codex selbst wird ebenfalls abgemeldet, wie mit codex logout.", "Sign {agent} out of {user}?": "{agent} von {user} abmelden?", "{agent} is signed out, as codex logout does, and magpie forgets the account. Sign in again to use it; an open {agent} may need quitting and opening again. The account itself is left as it is.": "{agent} wird abgemeldet, wie mit codex logout, und magpie vergisst das Konto. Zum erneuten Verwenden neu anmelden; ein geöffnetes {agent} muss eventuell beendet und neu geöffnet werden. Das Konto selbst bleibt unverändert.", diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index 59d875c1b..2fe656fd0 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -1021,8 +1021,12 @@ asked in the app's own dialog; Cancel and Escape post nothing and go back to the editor, Sign out posts login/forget and says so. With another account saved the one in use has no Sign out but Remove, which posts login/forget (vincentzhang1_55530 on Discord: magpie signs Codex in to another account -first), and a signed_in refusal is said in the reader's language. No select, no left border, the page doesn't move; in -English and Chinese. +first), and a signed_in refusal is said in the reader's language. Claude Code +signed in to one of two accounts has Remove too (StringKe, #4532); signed in to +its only account it can be signed in to (the other a setup token) it has neither +Remove nor Sign out and says why in zh, zh-TW, ja and de, and a signed_in_only +refusal is said in the reader's language. No select, no left border, the page +doesn't move; in English and Chinese. `nokey-editor.test.cjs` opens two local Ollama providers saved with no key, one from the preset and one custom, as /api/providers gives them: a click diff --git a/internal/gui/tests/codex-signout.test.cjs b/internal/gui/tests/codex-signout.test.cjs index fe3f7df77..35676e991 100644 --- a/internal/gui/tests/codex-signout.test.cjs +++ b/internal/gui/tests/codex-signout.test.cjs @@ -19,11 +19,16 @@ const codex = (logins) => ({ models: [{ id: "gpt-6", name: "GPT-6", on: true }], agents: [], fallback: [], headers: {}, keyList: [], account: { agent: "codex", agentName: "Codex", agentIcon: "codex-color", user: logins[0].user, plan: "PLUS", logins }, }); +const claude = (logins) => ({ + id: "claude", name: "Claude", icon: "claude-color", chat: "", responses: "", anthropic: "", catalog: "", routing: "smart", + models: [{ id: "claude-x", name: "Claude X", on: true }], agents: [], fallback: [], headers: {}, keyList: [], + account: { agent: "claude", agentName: "Claude Code", agentIcon: "claude-color", user: logins[0].user, plan: "MAX", logins }, +}); const one = [{ user: "me@example.com", plan: "PLUS", active: true, on: true }]; const two = [...one, { user: "work@example.com", plan: "PRO", on: true }]; -function serve(lang, logins, posts, refuse) { - const providers = { providers: [codex(logins)], presets: [], excluded: [], gateway: { running: true, window: true } }; +function serve(lang, logins, posts, refuse, of = codex) { + const providers = { providers: [of(logins)], presets: [], excluded: [], gateway: { running: true, window: true } }; const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; return async (route) => { const req = route.request(); @@ -37,6 +42,7 @@ function serve(lang, logins, posts, refuse) { if (url.pathname === "/api/plugins") return json({ plugins: [] }); if (url.pathname === "/api/login/forget") { posts.push(req.postDataJSON()); + if (refuse === "only") return route.fulfill({ status: 400, json: { error: "Claude Code is signed in to me@example.com", code: "signed_in_only", agent: "claude", user: "me@example.com" } }); if (refuse) return route.fulfill({ status: 400, json: { error: "codex is signed in to me@example.com now", code: "signed_in", agent: "codex", user: "me@example.com" } }); return json({ ...providers, providers: [] }); } @@ -48,14 +54,14 @@ function serve(lang, logins, posts, refuse) { } const words = { - en: { out: "Sign out", remove: "Remove", cancel: "Cancel", ask: "Sign Codex out of me@example.com?", text: /Codex is signed out, as codex logout does/, done: "Codex signed out of me@example.com", refused: /Codex is signed in to me@example\.com now: sign it in to another of its accounts first/ }, - zh: { out: "退出登录", remove: "移除", cancel: "取消", ask: "让 Codex 退出 me@example.com?", text: /codex logout/, done: "Codex 已退出 me@example.com", refused: /Codex 当前登录的是 me@example\.com:请先在另一个账号上点「使用」/ }, + en: { out: "Sign out", remove: "Remove", cancel: "Cancel", ask: "Sign Codex out of me@example.com?", text: /Codex is signed out, as codex logout does/, done: "Codex signed out of me@example.com", refused: /Codex is signed in to me@example\.com now: sign it in to another of its accounts first/, only: /Claude Code is signed in to me@example\.com, the only account in magpie it can be signed in to/ }, + zh: { out: "退出登录", remove: "移除", cancel: "取消", ask: "让 Codex 退出 me@example.com?", text: /codex logout/, done: "Codex 已退出 me@example.com", refused: /Codex 当前登录的是 me@example\.com:请先在另一个账号上点「使用」/, only: /Claude Code 当前登录的是 me@example\.com,这是 magpie 里它唯一能登录的账号/ }, }; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { for (const lang of ["en", "zh"]) { const w = words[lang]; - const open = async (t, logins, refuse = false) => { + const open = async (t, logins, refuse = false, of = codex) => { const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); t.after(() => browser.close()); const page = await (await browser.newContext({ viewport: { width: 900, height: 760 }, reducedMotion: "reduce" })).newPage(); @@ -64,9 +70,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; const posts = []; page.on("pageerror", (e) => errors.push(e.message)); - await page.route("**/*", serve(lang, logins, posts, refuse)); + await page.route("**/*", serve(lang, logins, posts, refuse, of)); await page.goto("http://magpie.test/?view=providers"); - await page.locator(".row.provider", { hasText: "Codex" }).first().click(); + await page.locator(".row.provider", { hasText: of === claude ? "Claude" : "Codex" }).first().click(); await page.locator(".editor .acc").first().waitFor(); return { page, errors, posts }; }; @@ -140,12 +146,57 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await confirm.getByRole("button", { name: w.remove, exact: true }).click(); await page.waitForFunction(() => document.querySelector("#status")?.textContent.includes("me@example.com")); assert.deepEqual(posts, [{ agent: "codex", user: "me@example.com" }]); - const missing = await page.evaluate(() => ["Codex is signed in to another of its accounts, and magpie forgets this one; the account itself is untouched"] + const missing = await page.evaluate(() => ["{agent} is signed in to another of its accounts, and magpie forgets this one; the account itself is untouched"] .filter((k) => !I18N.zh[k] || !I18N.ja[k] || !I18N.de[k])); assert.deepEqual(missing, [], "every string has its zh, ja and de"); assert.deepEqual(errors, []); }); + // StringKe (#4532): Claude Code's account in use is removed as Codex's + // is, signed in to another first, while it has another it can be + // signed in to; a setup-token one isn't that, and magpie never signs + // Claude Code out, so its only one has no Remove + test(`${engine} ${lang}: Claude Code's account in use has Remove while another can take its place`, async (t) => { + const { page, errors, posts } = await open(t, [...one, { user: "work@example.com", plan: "MAX", on: true }], false, claude); + const row = page.locator(".editor .acc", { hasText: "me@example.com" }); + await more(row); + const remove = row.getByRole("button", { name: w.remove, exact: true }); + assert.equal(await remove.count(), 1, "the one in use has Remove"); + assert.match(await remove.getAttribute("title"), /Claude Code/); + await remove.click(); + const confirm = page.locator("dialog.action-confirm[open]"); + await confirm.getByRole("button", { name: w.remove, exact: true }).click(); + await page.waitForFunction(() => document.querySelector("#status")?.textContent.includes("me@example.com")); + assert.deepEqual(posts, [{ agent: "claude", user: "me@example.com" }]); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang}: Claude Code's only account it can be signed in to has no Remove`, async (t) => { + const { page, errors } = await open(t, [...one, { user: "ci@example.com", plan: "MAX", on: true, token: true }], false, claude); + const row = page.locator(".editor .acc", { hasText: "me@example.com" }); + await more(row); + assert.equal(await row.getByRole("button", { name: w.remove, exact: true }).count(), 0); + assert.equal(await row.getByRole("button", { name: w.out, exact: true }).count(), 0, "magpie never signs Claude Code out"); + const missing = await page.evaluate(() => ["{agent} is signed in to {user}, the only account in magpie it can be signed in to, and magpie doesn't sign it out: add another account first, or sign out in {agent} itself, then remove this one"] + .filter((k) => !I18N.zh[k] || !I18N["zh-TW"][k] || !I18N.ja[k] || !I18N.de[k])); + assert.deepEqual(missing, [], "every string has its zh, zh-TW, ja and de"); + assert.deepEqual(errors, []); + }); + + // the CLI, or a GUI a step behind the accounts: the refusal of the + // only one says so, not "sign it in to another first" + test(`${engine} ${lang}: the only Claude account's refusal says it is the only one`, async (t) => { + const { page, errors } = await open(t, [...one, { user: "work@example.com", plan: "MAX", on: true }], "only", claude); + const row = page.locator(".editor .acc", { hasText: "me@example.com" }); + await more(row); + await row.getByRole("button", { name: w.remove, exact: true }).click(); + await page.locator("dialog.action-confirm[open]").getByRole("button", { name: w.remove, exact: true }).click(); + await page.waitForFunction(() => /only account|唯一/.test([...document.querySelectorAll(".editor-error, #status")].map((n) => n.textContent).join(" "))); + const said = await page.evaluate(() => [...document.querySelectorAll(".editor-error, #status")].map((n) => n.textContent).join(" ")); + assert.match(said, w.only); + assert.deepEqual(errors, []); + }); + test(`${engine} ${lang}: a refusal says what to do, in the reader's language`, async (t) => { const { page, errors } = await open(t, one, true); await more(page.locator(".editor .acc", { hasText: "me@example.com" })); diff --git a/internal/provider/claude_forget_live_test.go b/internal/provider/claude_forget_live_test.go new file mode 100644 index 000000000..59f92cad0 --- /dev/null +++ b/internal/provider/claude_forget_live_test.go @@ -0,0 +1,86 @@ +package provider + +import ( + "errors" + "os" + "strings" + "testing" + "time" +) + +// StringKe (#4532): removing the account Claude Code is signed in to was +// refused while Codex's switched first. Claude Code is signed in to the +// next account first now, and the removed one's sign-in is left nowhere: +// not in Claude Code, and not in another record. +func TestForgetLiveClaudeSwitchesFirst(t *testing.T) { + _, _ = claudeThree(t) + live, ok := liveLogin("claude") + if !ok || claudeEmail(live.User) != "pro@x.com" { + t.Fatalf("live %+v", live) + } + gone := live + if err := ForgetLogin("claude", live.User); err != nil { + t.Fatal(err) + } + forgetAccountCaches() + now, ok := liveLogin("claude") + if !ok || claudeEmail(now.User) == "pro@x.com" { + t.Fatalf("Claude Code still on %+v", now) + } + if c, ok := parseClaudeCredentials(now.Auth); !ok || c.OAuth.RefreshToken != "r-"+claudeEmail(now.User) { + t.Fatalf("Claude Code's sign-in isn't %s's: %+v", now.User, c) + } + var users []string + for _, l := range Logins("claude") { + users = append(users, l.User) + } + if len(users) != 2 || strings.Contains(strings.Join(users, ","), "pro@x.com") { + t.Fatalf("saved %v", users) + } + if _, others := claudeHolders(readLogins(), gone); len(others) != 0 { + t.Fatalf("the removed sign-in is kept in %+v", others) + } +} + +// Claude Code's account in use is never signed out by a removal, even its +// only one: its sign-in may be in the keychain, and magpie serves its +// saved accounts while it is signed out (claudeStandIn). The refusal says +// it is the only one, not "sign it in to another first", and an account +// added by setup-token, which Claude Code can't be signed in to, doesn't +// count as another. +func TestForgetOnlyClaudeIsKept(t *testing.T) { + home := claudeHome(t) + t.Setenv("CLAUDE_CONFIG_DIR", "") + shellFakes(t) + creds := claudeSignIn(t, home, time.Now().Add(time.Hour)) + writeFile(t, home+"/.claude.json", map[string]any{"oauthAccount": map[string]any{"emailAddress": "cc@example.com"}}) + rememberLogins(true) + live, ok := liveLogin("claude") + if !ok { + t.Fatal("no Claude Code sign-in") + } + loginsMu.Lock() + err := writeLogins(upsertLogin(readLogins(), savedLogin{Agent: "claude", User: "ci@x.com", On: true, Auth: []byte(`{"setupToken":"sk-ant-oat01-x"}`)})) + loginsMu.Unlock() + if err != nil { + t.Fatal(err) + } + var signedIn *SignedInError + err = ForgetLogin("claude", live.User) + if !errors.As(err, &signedIn) || !signedIn.Only || !strings.Contains(err.Error(), "only account") { + t.Fatalf("claude in use: %v", err) + } + if _, err := os.Stat(creds); err != nil { + t.Fatalf("credentials went: %v", err) + } + if now, ok := liveLogin("claude"); !ok || now.User != live.User { + t.Fatalf("Claude Code moved to %+v", now) + } + found := false + for _, l := range Logins("claude") { + found = found || l.User == live.User + } + if !found { + t.Fatal("the account was forgotten") + } +} diff --git a/internal/provider/codex_signout_test.go b/internal/provider/codex_signout_test.go index 6bdb20e41..97d0bdd9f 100644 --- a/internal/provider/codex_signout_test.go +++ b/internal/provider/codex_signout_test.go @@ -6,7 +6,6 @@ import ( "path/filepath" "strings" "testing" - "time" ) // Codex's only account is signed out when it is removed, as codex logout @@ -84,26 +83,3 @@ func TestForgetAccountSignsCodexOut(t *testing.T) { t.Fatalf("saved still: %+v", ls) } } - -// Claude Code's account in use is never signed out by a removal, even its -// only one: its sign-in may be in the keychain, and magpie serves its -// saved accounts while it is signed out (claudeStandIn). -func TestClaudeInUseStillRefused(t *testing.T) { - home := claudeHome(t) - t.Setenv("CLAUDE_CONFIG_DIR", "") - shellFakes(t) - creds := claudeSignIn(t, home, time.Now().Add(time.Hour)) - writeFile(t, filepath.Join(home, ".claude.json"), map[string]any{"oauthAccount": map[string]any{"emailAddress": "cc@example.com"}}) - rememberLogins(true) - live, ok := liveLogin("claude") - if !ok { - t.Fatal("no Claude Code sign-in") - } - var signedIn *SignedInError - if err := ForgetLogin("claude", live.User); !errors.As(err, &signedIn) { - t.Fatalf("claude in use: %v", err) - } - if _, err := os.Stat(creds); err != nil { - t.Fatalf("credentials went: %v", err) - } -} diff --git a/internal/provider/logins.go b/internal/provider/logins.go index 965bb96c6..dbb5c39cd 100644 --- a/internal/provider/logins.go +++ b/internal/provider/logins.go @@ -1335,11 +1335,13 @@ func putClaudeLogin(l savedLogin) error { } // ForgetLogin drops a remembered account. The one an agent is signed in to -// now can't be forgotten while it has another to be signed in to; it would -// only be remembered again (SignedInError). Codex is signed in to another -// of its accounts first (nextOnForget), and its last one is signed out -// instead, as `codex logout` does (mamba on Discord: a single Codex account -// couldn't be removed at all). +// now would only be remembered again, so Codex and Claude Code are signed +// in to another of their accounts first (nextOnForget), as its Use would +// (StringKe, #4532: Claude's was refused while Codex's switched). Codex's +// last one is signed out instead, as `codex logout` does (mamba on +// Discord: a single Codex account couldn't be removed at all). Claude +// Code's last one that it can be signed in to is kept, and the removal +// refused (SignedInError, Only): magpie never signs Claude Code out. func ForgetLogin(agent, user string) error { if settings.AccountDiscoveryOff() { return errAccountDiscoveryOff @@ -1355,15 +1357,16 @@ func ForgetLogin(agent, user string) error { case "gemini", "antigravity": return forgetGoogleLogin(agent, user) } - if agent == "codex" { - // the account Codex is signed in to, with another saved: Codex is - // signed in to that one first, as its Use would, and this one is - // forgotten then, rather than Codex left signed out or the removal - // refused (vincentzhang1_55530 on Discord: a Team account removed - // beside a Plus one, and Codex was at its sign-in screen) + if agent == "codex" || agent == "claude" { + // the account the agent is signed in to, with another saved: the + // agent is signed in to that one first, as its Use would, and this + // one is forgotten then, rather than Codex left signed out or the + // removal refused (vincentzhang1_55530 on Discord: a Team account + // removed beside a Plus one, and Codex was at its sign-in screen). + // A switch that fails removes nothing: the agent is still on user. if next := nextOnForget(agent, user); next != "" { if err := SwitchLogin(agent, next); err != nil { - return err + return fmt.Errorf("%s is signed in to %s now, and signing it in to %s first failed, so %s is kept: %w", loginAgentName(agent), user, next, user, err) } } } @@ -1377,13 +1380,14 @@ func ForgetLogin(agent, user string) error { // nextOnForget is the account an agent is signed in to in place of user, // which is being removed: "" when it isn't signed in to user, or has no -// other saved. The first other in the order that is on, else one whose -// sign-in still holds, else any other. +// other saved that it can be signed in to (switchable). The first other in +// the order that is on, else one whose sign-in still holds, else any other. func nextOnForget(agent, user string) string { ls := Logins(agent) if !slices.ContainsFunc(ls, func(l Login) bool { return l.Active && strings.EqualFold(l.User, user) }) { return "" } + ls = slices.DeleteFunc(ls, func(l Login) bool { return !switchable(l) }) for _, fit := range []func(Login) bool{ func(l Login) bool { return l.On && !l.Paused && l.Lapsed == "" }, func(l Login) bool { return l.Lapsed == "" }, @@ -1398,12 +1402,34 @@ func nextOnForget(agent, user string) string { return "" } +// switchable is an account an agent can be signed in to: not a Claude +// setup-token one (errClaudeTokenSwitch), nor a ChatGPT account Codex +// keeps in another folder (codexHeldIn). +func switchable(l Login) bool { return !l.Token && l.home == "" } + func forgetLogin(agent, user string) (signedOut bool, err error) { loginsMu.Lock() defer loginsMu.Unlock() ls := readLogins() if live, ok := liveLogin(agent); ok && strings.EqualFold(live.User, user) { other := slices.ContainsFunc(ls, func(l savedLogin) bool { return l.Agent == agent && !strings.EqualFold(l.User, user) }) + if agent == "claude" { + // Claude Code is never signed out: its sign-in may be in the + // keychain, and magpie serves its saved accounts while it is + // signed out (claudeStandIn). Still on user, after a switch + // to another (ForgetLogin): that one couldn't be signed in to. + other = slices.ContainsFunc(ls, func(l savedLogin) bool { + return l.Agent == agent && !strings.EqualFold(l.User, user) && claudeSetupToken(l.Auth) == "" + }) + return false, &SignedInError{Agent: agent, User: user, Only: !other} + } + if agent == "codex" { + // nor one Codex keeps in another folder, which ~/.codex + // can't be signed in to (codexHeldIn) + other = slices.ContainsFunc(ls, func(l savedLogin) bool { + return l.Agent == agent && !strings.EqualFold(l.User, user) && codexHeldIn(l) == "" + }) + } if agent != "codex" || other { return false, &SignedInError{Agent: agent, User: user} } @@ -1445,11 +1471,19 @@ func forgetLogin(agent, user string) (signedOut bool, err error) { // SignedInError is ForgetLogin's refusal of the account an agent is // signed in to now while it has another: that one is signed in to first -// (its Use), and this one removed then. The GUI says it in the reader's -// language (code signed_in). -type SignedInError struct{ Agent, User string } +// (its Use), and this one removed then. Only is Claude Code's last account +// it can be signed in to, which magpie keeps rather than sign Claude Code +// out. The GUI says it in the reader's language (codes signed_in and +// signed_in_only). +type SignedInError struct { + Agent, User string + Only bool +} func (e *SignedInError) Error() string { + if e.Only { + return fmt.Sprintf("%s is signed in to %s, the only account in magpie it can be signed in to, and magpie doesn't sign it out: add another account first, or sign out in %s itself, then remove this one", loginAgentName(e.Agent), e.User, loginAgentName(e.Agent)) + } return fmt.Sprintf("%s is signed in to %s now: sign it in to another of its accounts first (Use on that account), then remove this one", loginAgentName(e.Agent), e.User) }