Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
provider, gateway, gui, cli: Claude's accounts can be kept to Claude Code's own sign-in, magpie serving nothing on them (myduso)
yetoneec3dad75ae7d
diff --git a/docs/reference.md b/docs/reference.mdindex 48515ee3f..0657f7e9c 100644--- a/docs/reference.md+++ b/docs/reference.md@@ -1796,6 +1796,16 @@ start, so one already open stays on its account until it is opened again;a new `codex` session takes the new one. Connected to magpie, Codex'srequests go through it as before.+*Only switch Claude Code's sign-in* under Providers › Claude (or `magpie+accounts switch-only claude on`) keeps the Claude accounts to Claude+Code alone, with one account too: magpie still moves Claude Code's own+sign-in as above, and serves no request on them. They leave the model+list, and a request that names them, from any agent, a group, a+fallback or a Claude Code connected to magpie, is refused as kept to+Claude Code, so no turn runs through Claude Code's SDK mode, which+spends more of the allowance than Claude Code used on its own (myduso on+Discord). Their usage is still read and shown.+**How often an allowance is read.** Routing uses what was read last andnever waits for a reading, except the first one after magpie starts (3seconds at most). A reading over a minute old is read again in thediff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.mdindex 0800d6516..241bb97f9 100644--- a/docs/subsystems/providers-accounts.md+++ b/docs/subsystems/providers-accounts.md@@ -44,7 +44,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi| Saved accounts | `logins.json` remembers every Codex and Claude Code account seen signed in. A switch moves the credentials into the agent's own store and saves the ones it replaces. A saved account that is on (`SetLoginOn`) stands behind the agent's own. Its tokens stay in `logins.json`. While Claude Code is signed out, a saved Claude account stands in for its own (`claudeStandIn`); with every saved account's sign-in gone, Claude Code is still listed, on the one seen last, signed out (`claudeListed`), its accounts each saying to sign in again, so it never leaves the Providers list (LeeHom on Discord). Claude Code's own account while still `Held` is never listed that way, since the sign-in it may have left on disk would be served. An account whose every login in use has lapsed is `Provider.SignedOut`: `magpie providers` and the TUI say "<user> is signed out", as the app's row does. | [`logins.go`](../../internal/provider/logins.go), [`logins_on.go`](../../internal/provider/logins_on.go), [`claude_dirs.go`](../../internal/provider/claude_dirs.go) || Sign-in in magpie | `StartSignIn` runs the vendor's own browser OAuth with its client and takes the tokens at a callback on this machine. A browser that can't reach that callback (magpie on a server or in Docker) ends on a page that won't load; its address, pasted (`SubmitSignInCallback`), goes through the same callback handler (`pastedCallback`). ChatGPT's sign-in comes back only to port 1455; when that port can't be opened, the sign-in still starts and waits for the pasted address alone, and says why in `CallbackBlocked` with the port in `CallbackPort`: `reserved` for Windows' WSAEACCES on a port in a range it excludes for Hyper-V, WSL or Docker, `busy` for anything else, such as another program holding it (`callbackBlocked`, #1782). A plugin's browser sign-in (`auto`) whose page names a port on this machine to come back to takes its pasted address too: magpie opens it there on 127.0.0.1, for the plugin's own listener (`pluginCallback`, `loopbackPorts`); Command Code's page posts its key from script, so it offers the API key way instead. A Claude account is signed in by Claude Code itself. Signing in brings back an account removed from magpie (`ShowAccount`). A sign-in started in magpie (`StartSignIn`, `StartPluginSignIn`) reads as done (`SignInStatus`, `WaitSignIn`) only after `finish` has run `ShowAccount` for its account, so the window, which opens the account as soon as it sees done, finds it listed. If providers.json can't be written then, the account stays hidden and the sign-in still ends done. Signing in to a plugin's provider from the command line (`pluginLogin`, with a key or the browser) brings it back too. It also takes off the mark a sign-in its vendor turned away left on the account (`Lapsed`) and shows again the agent's own account removed in magpie (`clearPluginLapse`). The window's plugin sign-in does the same with the browser (`pluginDone`, then `finish`) or with a key (`PluginAPIKey`); a key and the command line share these steps in `PluginSignedIn`. A sign-in leaves through the proxy the account's own requests will use (#1663): `ProxyOfLogin` (the account's, else the subscription's, else the global one) for the account being signed in again, the subscription's for a new one. Every request of the flow goes through `signInFlow.via`, Claude Code's own login gets it as *_PROXY (`netproxy.EnvWith`), and a plugin's sign-in runs its fetch under that proxy (`via` in `host.js`; `plugins_cli.go` for the command line). The window's sign-in box shows it as a "Proxy: …" link (`signInProxyLink`, the app menu, no userinfo shown) with Global, Direct, the subscription's and each account's proxy, or a typed one; picking one starts the sign-in again through it (`SignInOptions.Proxy`), and when it ends the pick is kept as the account's (`keepSignInProxy`: the subscription's own when it is its only account, else the account's entry). Global isn't offered while the subscription has a proxy and other accounts, since nothing could keep it. The browser's own leg goes through the browser's network, not magpie's. Signing out leaves through the same exit: a ChatGPT account's refresh token is revoked through its own proxy, read before the account is forgotten (`forgetSIWCLogin`), and Devin's CLI, asked who is signed in or for its models, runs with the account's proxy (`devinCommand`, `devinProxy`). | [`signin.go`](../../internal/provider/signin.go), [`claude_signin.go`](../../internal/provider/claude_signin.go), [`pluginsignin.go`](../../internal/provider/pluginsignin.go), [`pluginsignin_paste.go`](../../internal/provider/pluginsignin_paste.go), [`proxy.go`](../../internal/provider/proxy.go), [`plugins_cli.go`](../../internal/cli/plugins_cli.go) || Import from files | `ImportLogins` (ChatGPT, Claude), `ImportGoogleAccounts` (Antigravity) and `ImportFactoryKeys` take other tools' files, from the window (`signin/import`) or `magpie accounts import` (#1453). ChatGPT reads Codex's `auth.json`, CLIProxyAPI's and Cockpit Tools' files, Sub2API's export (`sub2apiEntry`) and codexbar's `~/.codexbar/config.json` (`codexbarEntries`: the `openai_oauth` provider's accounts and `openAI.remoteConnectionAccounts`, the workspace from `openAIAccountId`). Each ChatGPT and Google sign-in is refreshed before it is added, so the tool the file came from is signed out of it; both surfaces say so first, and the command imports nothing without `--yes` or a yes. Claude reads CLIProxyAPI's files and Sub2API's export, whose Claude account says its email as Anthropic does, `email_address`, in `credentials` or `extra`, and keeps its `scope`, `account_uuid` and `org_uuid` as Claude Code's scopes, `accountUuid` and `organizationUuid` (#1975); a file with no email is refused, as Claude Code's own `.credentials.json` is. Claude's are kept as the file has them. A refresh token magpie holds already is `exists`, never refreshed; accounts are matched by email and workspace, or for Claude organization (`sameLogin`). An entry with an access token and no refresh token is refused (`accessOnly`). One file of several that holds no account is a failed row with its place (`ImportedAccount.File`), never skipped. The files are only read. | [`login_import.go`](../../internal/provider/login_import.go), [`google_import.go`](../../internal/provider/google_import.go), [`factory_key.go`](../../internal/provider/factory_key.go), [`accounts_cli.go`](../../internal/cli/accounts_cli.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). 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. | [`codex_switch.go`](../../internal/provider/codex_switch.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). 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. | [`codex_switch.go`](../../internal/provider/codex_switch.go) || 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/<id>`); `SaveGroup` refuses loops. A group given another id (`agent.RenameGroup`: the Routing page, `magpie groups rename`, the TUI) moves every agent field on `group/<old>` to `group/<new>`, 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). 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` and said as switched off on the Routing 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 `<remote>/~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=<remote>/~keys&user=<key name>`). 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 <id> 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/cli/accounts_cli.go b/internal/cli/accounts_cli.goindex b7b8d0a8e..b4a6cbb6f 100644--- a/internal/cli/accounts_cli.go+++ b/internal/cli/accounts_cli.go@@ -23,14 +23,14 @@ import (// `magpie accounts switch|forget <agent> <email>`,// `magpie accounts project <gemini|antigravity> <email> <project>`,// `magpie accounts alias <agent> <email> [<name>|--clear]`-// `magpie accounts switch-only codex [on|off]`+// `magpie accounts switch-only <codex|claude> [on|off]`// — the subscriptions magpie remembers, how much of each one's allowance is// used, and switching the agent between them.func accountsCmd(args []string) error {if len(args) > 1 && args[1] == "discovery" {return accountsDiscoveryCmd(args[2:])}- const usage = "usage: magpie accounts [claude|codex|grok|copilot|gemini|antigravity|zed|factory|mimo|<plugin>] [--json] | magpie accounts add <claude|codex|gemini|antigravity|zed|factory|mimo|<plugin>> | magpie accounts add copilot [--host <name>.ghe.com] | magpie accounts import <codex|claude|antigravity|factory> <file>... [--yes] | magpie accounts refresh [--json] | magpie accounts checkin [--json] | magpie accounts switch|forget <claude|codex|gemini|antigravity|zed|factory|mimo|<plugin>> <email> | magpie accounts switch|forget copilot <login>[@<name>.ghe.com] [--host <name>.ghe.com] | magpie accounts project <gemini|antigravity> <email> <gcp-project-id> | magpie accounts alias <agent|<plugin>> <email> [<name>|--clear] | magpie accounts switch-only codex [on|off]"+ const usage = "usage: magpie accounts [claude|codex|grok|copilot|gemini|antigravity|zed|factory|mimo|<plugin>] [--json] | magpie accounts add <claude|codex|gemini|antigravity|zed|factory|mimo|<plugin>> | magpie accounts add copilot [--host <name>.ghe.com] | magpie accounts import <codex|claude|antigravity|factory> <file>... [--yes] | magpie accounts refresh [--json] | magpie accounts checkin [--json] | magpie accounts switch|forget <claude|codex|gemini|antigravity|zed|factory|mimo|<plugin>> <email> | magpie accounts switch|forget copilot <login>[@<name>.ghe.com] [--host <name>.ghe.com] | magpie accounts project <gemini|antigravity> <email> <gcp-project-id> | magpie accounts alias <agent|<plugin>> <email> [<name>|--clear] | magpie accounts switch-only <codex|claude> [on|off]"agentID := func(s string) (string, error) {switch strings.ToLower(s) {case "claude", "cc":@@ -868,20 +868,32 @@ func accountNamed(agent, user string) (string, error) {return "", fmt.Errorf("no saved %s account %q · its accounts: %q", agent, user, names)}-// switchOnlyCmd is `magpie accounts switch-only codex [on|off]`: magpie-// only switches Codex's own sign-in to the next account with room, its-// requests never sent through the gateway for account failover (#1907).-// With no on or off it says which it is.+// switchOnlyCmd is `magpie accounts switch-only <codex|claude> [on|off]`:+// magpie only switches the agent's own sign-in to the next account with+// room. Codex's requests are then never sent through the gateway for+// account failover (#1907); Claude's accounts serve no request through the+// gateway (provider.KeptToAgent, myduso on Discord). With no on or off it+// says which it is.func switchOnlyCmd(args []string) error {- const usage = "usage: magpie accounts switch-only codex [on|off]"- if len(args) < 1 || len(args) > 2 || !strings.EqualFold(args[0], "codex") {+ const usage = "usage: magpie accounts switch-only <codex|claude> [on|off]"+ if len(args) < 1 || len(args) > 2 {+ return fmt.Errorf("%s", usage)+ }+ id := strings.ToLower(args[0])+ if id != "codex" && id != "claude" {return fmt.Errorf("%s", usage)}if len(args) == 1 {- if provider.SwitchOnly("codex") {+ on := provider.SwitchOnly(id)+ switch {+ case id == "codex" && on:fmt.Println("on · magpie only switches Codex's sign-in; its requests go straight to OpenAI")- } else {+ case id == "codex":fmt.Println("off · with more of its accounts on, Codex's requests go through magpie to fail over between them")+ case on:+ fmt.Println("on · magpie only switches Claude Code's sign-in; it serves no requests on the Claude accounts")+ default:+ fmt.Println("off · magpie serves requests on the Claude accounts that are on")}return nil}@@ -893,15 +905,20 @@ func switchOnlyCmd(args []string) error {default:return fmt.Errorf("%s", usage)}- if err := provider.SetSwitchOnly("codex", on); err != nil {+ if err := provider.SetSwitchOnly(id, on); err != nil {return err}- // Codex's config.toml follows now, not at the next start+ // the agents' configs and model lists follow now, not at the next startagent.SyncCatalog()- if on {+ switch {+ case id == "codex" && on:fmt.Println(green.Render("✓"), "magpie only switches Codex's sign-in to an account with room; its requests go straight to OpenAI. A Codex app or session already open stays on its account until it is opened again.")- } else {+ case id == "codex":fmt.Println(green.Render("✓"), "with more of its accounts on, Codex's requests go through magpie to fail over between them again")+ case on:+ fmt.Println(green.Render("✓"), "magpie only switches Claude Code's sign-in to an account with room; it serves no requests on the Claude accounts. A Claude Code session already open stays on its account until it is started again.")+ default:+ fmt.Println(green.Render("✓"), "magpie serves requests on the Claude accounts that are on again")}return nil}diff --git a/internal/cli/main.go b/internal/cli/main.goindex b9ea1484f..29d89d1c3 100644--- a/internal/cli/main.go+++ b/internal/cli/main.go@@ -99,6 +99,7 @@ const usage = `magpie — one place to pick every agent's modelmagpie accounts project <gemini|antigravity> <email> <project> the Google Cloud project a Google account's requests go tomagpie accounts alias <agent> <email> [<name>|--clear] a name of your own for an account, shown on its card, in the menu bar and in magpie quotamagpie accounts switch-only codex [on|off] only switch Codex's own sign-in to an account with room; its requests go straight to OpenAI, never through magpie+ magpie accounts switch-only claude [on|off] only switch Claude Code's own sign-in to an account with room; magpie serves no requests on the Claude accountsmagpie claude-code [install [--yes]|remove] the Claude Code a Claude subscription runs; install downloads Anthropic's own build, checked against its manifest, for a server or container without onemagpie plugin [add <package>|rm|update|on|off|login <provider>|logout <provider>]OpenCode provider plugins and pi packages: subscriptions signed in to, and served, through a plugindiff --git a/internal/gateway/claude_switch_only_test.go b/internal/gateway/claude_switch_only_test.gonew file mode 100644index 000000000..7aa31a83b--- /dev/null+++ b/internal/gateway/claude_switch_only_test.go@@ -0,0 +1,40 @@+package gateway++import (+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/yetone/magpie/internal/provider"+)++// myduso on Discord: Claude's subscription kept to Claude Code, magpie+// only switching its sign-in. A request naming the Claude accounts runs+// no Claude Code through the bridge and is told why, with how to undo it;+// unticked, it is served again.+func TestClaudeKeptToClaudeCodeServesNothing(t *testing.T) {+ claudeMadeFirst(t, false)+ s := New()+ t.Cleanup(s.subscription.abortAll)+ calls := filepath.Join(t.TempDir(), "calls")+ claudeRefuses(t, calls, "tok-none") // no account refused++ if err := provider.SetSwitchOnly("claude", true); err != nil {+ t.Fatal(err)+ }+ rec := askClaudeModel(s, "hi")+ if rec.Code != 404 || !strings.Contains(rec.Body.String(), "kept to Claude Code's own sign-in") {+ t.Fatalf("kept to Claude Code: %d %s", rec.Code, rec.Body.String())+ }+ if b, _ := os.ReadFile(calls); len(b) != 0 {+ t.Fatalf("Claude Code run through the bridge: %q", b)+ }++ if err := provider.SetSwitchOnly("claude", false); err != nil {+ t.Fatal(err)+ }+ if rec := askClaudeModel(s, "again"); rec.Code != 200 || !strings.Contains(rec.Body.String(), "healthy account") {+ t.Fatalf("unticked: %d %s", rec.Code, rec.Body.String())+ }+}diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.goindex b2487221d..da372425b 100644--- a/internal/gateway/gateway.go+++ b/internal/gateway/gateway.go@@ -254,8 +254,12 @@ func namesInCatalog() map[string]bool {}// switchedOff says a request for model went nowhere because p, which-// serves it, is switched off in magpie (provider.Provider.Off).+// serves it, is switched off in magpie (provider.Provider.Off), or kept to+// Claude Code's own sign-in (provider.Provider.KeptToAgent).func switchedOff(p provider.Provider, model string) string {+ if p.KeptToAgent() {+ return fmt.Sprintf("%s's accounts are kept to Claude Code's own sign-in in Magpie, so %q is not served; untick \"Only switch Claude Code's sign-in\" under its accounts in Magpie's Providers to use it", p.Name, model)+ }return fmt.Sprintf("%s is switched off in Magpie, so %q is not served; switch it on again in Magpie's Providers to use it", p.Name, model)}diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.jsindex d52883560..93ae080ad 100644--- a/internal/gui/assets/app.js+++ b/internal/gui/assets/app.js@@ -13083,19 +13083,14 @@ function renderAccounts(a, p) {box.append(keep, as);list.append(box);}- // with more of its accounts on, magpie sends Codex's own requests through- // the gateway to fail over between them (#1385); this has it only switch- // Codex's own sign-in instead, its requests going straight to OpenAI- // (#1907: Codex Desktop and the CLI on their own subscription alone)- if (a.agent === "codex" && several && p) {- const box = el("div", "switch-only");- const [only, cb] = tick(t("Only switch {agent}'s sign-in", { agent: a.agentName }), !!p.switchOnly);- only.title = t("magpie signs {agent} in to the next account with room when the one it is on is used up, and back once that has room again, by writing {agent}'s own sign-in; {agent}'s requests go straight to OpenAI, never through magpie. A {agent} app or session already open stays on its account until it is opened again. Connected to magpie, {agent}'s requests go through it as before.", { agent: a.agentName });- cb.onchange = () => accountAction("provider/switchonly", { id: p.id, switchOnly: cb.checked }, cb.checked- ? t("magpie only switches {agent}'s sign-in; its requests go straight to OpenAI", { agent: a.agentName })- : t("{agent}'s requests go through magpie to fail over to your other accounts again", { agent: a.agentName }));- box.append(only);- list.append(box);+ const cx = a.agent === "codex", ag = { agent: a.agentName };+ if (p && (cx && several || a.agent === "claude")) {+ const [only, cb] = tick(t("Only switch {agent}'s sign-in", ag), p.switchOnly);+ const [tip, on, off] = cx ? [t("magpie signs {agent} in to the next account with room when the one it is on is used up, and back once that has room again, by writing {agent}'s own sign-in; {agent}'s requests go straight to OpenAI, never through magpie. A {agent} app or session already open stays on its account until it is opened again. Connected to magpie, {agent}'s requests go through it as before.", ag), t("magpie only switches {agent}'s sign-in; its requests go straight to OpenAI", ag), t("{agent}'s requests go through magpie to fail over to your other accounts again", ag)]+ : [t("magpie moves {agent}'s own sign-in to the next account with room when one is used up, and back once it has room. Nothing on these accounts is served through magpie.", ag), t("magpie serves no requests on these accounts"), t("magpie serves requests on these accounts again")];+ only.title = tip;+ cb.onchange = () => accountAction("provider/switchonly", { id: p.id, switchOnly: cb.checked }, cb.checked ? on : off);+ list.append(el("div", "switch-only", only));}// how a pool ends at its caps (plugins#349)const capped = (l) => accountCapOf(p, l.user) || windowCapsOf(p, l.user);diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.jsindex dce77b7d2..e1fdf10ad 100644--- a/internal/gui/assets/i18n.js+++ b/internal/gui/assets/i18n.js@@ -1614,6 +1614,9 @@ const I18N = {"No cap on {users}: used to 100% of each window": "{users} 没有上限:每个窗口都会用到 100%","magpie signs {agent} in to the next account with room when the one it is on is used up, and back once that has room again, by writing {agent}'s own sign-in; {agent}'s requests go straight to OpenAI, never through magpie. A {agent} app or session already open stays on its account until it is opened again. Connected to magpie, {agent}'s requests go through it as before.": "当前账号额度用完时,magpie 改写 {agent} 自己的登录,把它切到下一个还有额度的账号,等原账号额度恢复后再切回;{agent} 的请求直接发往 OpenAI,不经过 magpie。已经打开的 {agent} 应用或会话会停留在原账号,直到重新打开。{agent} 接入 magpie 时,请求仍照常经过 magpie。","magpie only switches {agent}'s sign-in; its requests go straight to OpenAI": "magpie 只切换 {agent} 的登录;它的请求直接发往 OpenAI",+ "magpie moves {agent}'s own sign-in to the next account with room when one is used up, and back once it has room. Nothing on these accounts is served through magpie.": "账号用完时,magpie 把 {agent} 自己的登录切到下一个还有额度的账号,有额度后再切回来。这些账号上的请求一概不经 magpie 处理。",+ "magpie serves no requests on these accounts": "magpie 不在这些账号上处理任何请求",+ "magpie serves requests on these accounts again": "magpie 重新在这些账号上处理请求","{agent}'s requests go through magpie to fail over to your other accounts again": "{agent} 的请求重新经过 magpie,以便转到你的其他账号","the first account": "首选账号","Account to stay signed in to": "始终登录的账号",@@ -5659,6 +5662,9 @@ const I18N = {"No cap on {users}: used to 100% of each window": "{users} 沒有上限:每個視窗都會用到 100%","magpie signs {agent} in to the next account with room when the one it is on is used up, and back once that has room again, by writing {agent}'s own sign-in; {agent}'s requests go straight to OpenAI, never through magpie. A {agent} app or session already open stays on its account until it is opened again. Connected to magpie, {agent}'s requests go through it as before.": "目前帳號額度用完時,magpie 改寫 {agent} 自己的登入,把它切到下一個還有額度的帳號,等原帳號額度恢復後再切回;{agent} 的請求直接送往 OpenAI,不經過 magpie。已經開啟的 {agent} 應用程式或工作階段會停留在原帳號,直到重新開啟。{agent} 接入 magpie 時,請求仍照常經過 magpie。","magpie only switches {agent}'s sign-in; its requests go straight to OpenAI": "magpie 只切換 {agent} 的登入;它的請求直接送往 OpenAI",+ "magpie moves {agent}'s own sign-in to the next account with room when one is used up, and back once it has room. Nothing on these accounts is served through magpie.": "帳號用完時,magpie 把 {agent} 自己的登入切到下一個還有額度的帳號,有額度後再切回來。這些帳號上的請求一概不經 magpie 處理。",+ "magpie serves no requests on these accounts": "magpie 不在這些帳號上處理任何請求",+ "magpie serves requests on these accounts again": "magpie 重新在這些帳號上處理請求","{agent}'s requests go through magpie to fail over to your other accounts again": "{agent} 的請求重新經過 magpie,以便轉到你的其他帳號","the first account": "首選帳號","Account to stay signed in to": "始終登入的帳號",@@ -9681,6 +9687,9 @@ const I18N = {"No cap on {users}: used to 100% of each window": "{users} には上限がありません:各ウィンドウを 100% まで使います","magpie signs {agent} in to the next account with room when the one it is on is used up, and back once that has room again, by writing {agent}'s own sign-in; {agent}'s requests go straight to OpenAI, never through magpie. A {agent} app or session already open stays on its account until it is opened again. Connected to magpie, {agent}'s requests go through it as before.": "{agent} がサインイン中のアカウントの利用枠を使い切ると、magpie は {agent} 自身のサインインを書き換えて、枠の残っている次のアカウントに切り替え、元のアカウントの枠が戻ったら切り戻します。{agent} のリクエストは magpie を経由せず、OpenAI に直接送られます。すでに開いている {agent} のアプリやセッションは、開き直すまで元のアカウントのままです。{agent} を magpie に接続している場合、リクエストはこれまでどおり magpie を経由します。","magpie only switches {agent}'s sign-in; its requests go straight to OpenAI": "magpie は {agent} のサインインだけを切り替えます。リクエストは OpenAI に直接送られます",+ "magpie moves {agent}'s own sign-in to the next account with room when one is used up, and back once it has room. Nothing on these accounts is served through magpie.": "アカウントを使い切ると、magpie は {agent} 自身のサインインを空きのある次のアカウントに切り替え、空きが戻ったら切り戻します。これらのアカウントのリクエストは magpie を一切通りません。",+ "magpie serves no requests on these accounts": "magpie はこれらのアカウントでリクエストを処理しません",+ "magpie serves requests on these accounts again": "magpie はこれらのアカウントで再びリクエストを処理します","{agent}'s requests go through magpie to fail over to your other accounts again": "{agent} のリクエストは再び magpie を経由し、他のアカウントへ切り替えられます","the first account": "最初のアカウント","Account to stay signed in to": "サインインしたままにするアカウント",@@ -13733,6 +13742,9 @@ const I18N = {"No cap on {users}: used to 100% of each window": "Kein Limit für {users}: jedes Fenster wird bis 100 % genutzt","magpie signs {agent} in to the next account with room when the one it is on is used up, and back once that has room again, by writing {agent}'s own sign-in; {agent}'s requests go straight to OpenAI, never through magpie. A {agent} app or session already open stays on its account until it is opened again. Connected to magpie, {agent}'s requests go through it as before.": "Ist das Konto, mit dem {agent} angemeldet ist, aufgebraucht, schreibt magpie die eigene Anmeldung von {agent} auf das nächste Konto mit Kontingent um, und zurück, sobald das erste wieder Kontingent hat; die Anfragen von {agent} gehen direkt an OpenAI, nie über magpie. Eine bereits geöffnete {agent}-App oder -Sitzung bleibt beim bisherigen Konto, bis sie neu geöffnet wird. Ist {agent} mit magpie verbunden, laufen seine Anfragen wie bisher über magpie.","magpie only switches {agent}'s sign-in; its requests go straight to OpenAI": "magpie wechselt nur die Anmeldung von {agent}; seine Anfragen gehen direkt an OpenAI",+ "magpie moves {agent}'s own sign-in to the next account with room when one is used up, and back once it has room. Nothing on these accounts is served through magpie.": "Ist ein Konto aufgebraucht, meldet magpie {agent} mit der eigenen Anmeldung beim nächsten Konto mit Kontingent an und wieder zurück, sobald es Kontingent hat. Über diese Konten läuft nichts durch magpie.",+ "magpie serves no requests on these accounts": "magpie bearbeitet keine Anfragen über diese Konten",+ "magpie serves requests on these accounts again": "magpie bearbeitet wieder Anfragen über diese Konten","{agent}'s requests go through magpie to fail over to your other accounts again": "Die Anfragen von {agent} laufen wieder über magpie, um auf deine anderen Konten auszuweichen","the first account": "dem ersten Konto","Account to stay signed in to": "Konto für die dauerhafte Anmeldung",diff --git a/internal/gui/providers.go b/internal/gui/providers.goindex e4f17c54a..4d912e055 100644--- a/internal/gui/providers.go+++ b/internal/gui/providers.go@@ -218,7 +218,9 @@ type providerJSON struct {// first, the gateway still trying them in their orderKeepLoginAs string `json:"keepLoginAs,omitempty"`// SwitchOnly: magpie only moves Codex's own sign-in between its- // accounts, never routing its requests for failover (#1907)+ // accounts, never routing its requests for failover (#1907); on+ // Claude's, the accounts are kept to Claude Code's own sign-in and+ // serve no request through magpie (myduso on Discord)SwitchOnly bool `json:"switchOnly,omitempty"`// CapStop and CapCareful: how its accounts end at their caps// (plugins#349), set on their own with capstop and capcarefuldiff --git a/internal/gui/tests/claude-switch-only.test.cjs b/internal/gui/tests/claude-switch-only.test.cjsnew file mode 100644index 000000000..decbb0eab--- /dev/null+++ b/internal/gui/tests/claude-switch-only.test.cjs@@ -0,0 +1,115 @@+// Run with Node's test runner and Playwright on the module path; see README.md.+// myduso on Discord: under Claude's accounts a tick keeps them to Claude+// Code, magpie only switching its own sign-in and serving no request on+// them. It shows with one account too: what it stops is magpie serving+// them, not a switch between them. Ticking it posts provider/switchonly,+// and the redraw keeps it ticked; unticking posts it off. The page doesn't+// move. In English, Chinese, Japanese and German, Chromium and WebKit, at+// 1100 and 420 wide.+const assert = require("node:assert/strict");+const fs = require("node:fs/promises");+const path = require("node:path");+const { test } = require("node:test");+const { chromium, webkit } = require("playwright");++const assets = path.resolve(__dirname, "../assets");+const claude = ({ switchOnly = false, spare = true } = {}) => ({+ id: "claude", name: "Claude", icon: "claude-color", chat: "", responses: "", anthropic: "", catalog: "", routing: "", switchOnly,+ models: [{ id: "claude-sonnet-5", name: "Claude Sonnet 5", on: true }], agents: [], fallback: [], headers: {}, keyList: [],+ account: {+ agent: "claude", agentName: "Claude Code", user: "[email protected]", plan: "MAX",+ logins: [{ user: "[email protected]", plan: "MAX", active: true, on: true }].concat(spare ? [{ user: "[email protected]", plan: "PRO", on: true }] : []),+ },+});++function serve(lang, first, posts) {+ let list = [first];+ const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };+ const providers = () => ({ providers: list, presets: [], excluded: [], gateway: { running: true, window: true } });+ return async (route) => {+ const url = new URL(route.request().url());+ const json = (data) => route.fulfill({ json: data });+ if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });+ if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });+ if (url.pathname === "/api/state") return json(state);+ if (url.pathname === "/api/providers") return json(providers());+ if (url.pathname === "/api/provider/switchonly") {+ const body = route.request().postDataJSON();+ posts.push(body);+ list = [{ ...list[0], switchOnly: body.switchOnly }];+ return json(providers());+ }+ if (url.pathname === "/api/groups") return json({ groups: [] });+ if (url.pathname === "/api/plugins") return json({ plugins: [] });+ if (url.pathname.startsWith("/api/")) return json({});+ const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);+ const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];+ await route.fulfill({ body: await fs.readFile(file), contentType });+ };+}++const label = {+ en: "Only switch Claude Code's sign-in",+ zh: "只切换 Claude Code 的登录",+ ja: "Claude Code のサインインだけを切り替える",+ de: "Nur die Anmeldung von Claude Code wechseln",+};+const strings = [+ "Only switch {agent}'s sign-in",+ "magpie moves {agent}'s own sign-in to the next account with room when one is used up, and back once it has room. Nothing on these accounts is served through magpie.",+ "magpie serves no requests on these accounts",+ "magpie serves requests on these accounts again",+];++for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {+ for (const width of [1100, 420]) {+ for (const lang of Object.keys(label)) {+ const open = async (t, opts) => {+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));+ t.after(() => browser.close());+ const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();+ page.setDefaultTimeout(5000);+ const errors = [], posts = [];+ page.on("pageerror", (e) => errors.push(e.message));+ await page.route("**/*", serve(lang, claude(opts), posts));+ await page.goto("http://magpie.test/?view=providers");+ await page.locator(".row.provider", { hasText: "Claude" }).first().click();+ await page.locator(".editor .acc").first().waitFor();+ return { page, errors, posts };+ };++ test(`${engine} ${width} ${lang}: a tick keeps Claude's accounts to Claude Code`, async (t) => {+ const { page, errors, posts } = await open(t, {});+ const only = page.locator(".editor .accts .switch-only label");+ assert.equal((await only.textContent()).trim(), label[lang]);+ assert.ok(await only.getAttribute("title"), "it says what it does");+ assert.equal(await only.locator("input").isChecked(), false);+ if (lang === "en") {+ const missing = await page.evaluate((ks) => ["zh", "zh-TW", "ja", "de"].flatMap((l) => ks.filter((k) => !I18N[l][k]).map((k) => `${l}: ${k}`)), strings);+ assert.deepEqual(missing, [], "every string has its translations");+ }+ await only.scrollIntoViewIfNeeded();+ const box = await only.boundingBox();+ assert.ok(box.x >= 0 && box.x + box.width <= width, `the tick fits across ${width}`);+ const scrollers = () => page.evaluate(() => [...document.querySelectorAll("*")].filter((e) => e.scrollTop).map((e) => e.scrollTop).concat(document.scrollingElement.scrollTop));+ const before = await scrollers();+ await only.locator("input").click();+ await page.waitForFunction(() => document.querySelector(".editor .accts .switch-only input")?.checked === true);+ assert.deepEqual(posts, [{ id: "claude", switchOnly: true }]);+ assert.deepEqual(await scrollers(), before, "the page doesn't move");+ await page.locator(".editor .accts .switch-only input").click();+ await page.waitForFunction(() => document.querySelector(".editor .accts .switch-only input")?.checked === false);+ assert.deepEqual(posts, [{ id: "claude", switchOnly: true }, { id: "claude", switchOnly: false }]);+ assert.deepEqual(errors, []);+ });++ test(`${engine} ${width} ${lang}: kept to Claude Code is drawn ticked, and shown with one account`, async (t) => {+ const ticked = await open(t, { switchOnly: true });+ assert.equal(await ticked.page.locator(".editor .accts .switch-only input").isChecked(), true);+ const one = await open(t, { spare: false });+ assert.equal(await one.page.locator(".editor .accts .switch-only").count(), 1);+ assert.deepEqual([...ticked.errors, ...one.errors], []);+ });+ }+ }+}diff --git a/internal/provider/models.go b/internal/provider/models.goindex c64586814..fae543be4 100644--- a/internal/provider/models.go+++ b/internal/provider/models.go@@ -2548,7 +2548,7 @@ func entriesOff(off func(pid, model string) bool) []Entry {func heldOffEntries() []Entry {return heldOf("off entries", func() []Entry {return keptOf("off entries", func() []Entry {- return slices.Clip(entriesOf(func(p Provider) bool { return p.Ready() && p.Off }, disabledNow()))+ return slices.Clip(entriesOf(func(p Provider) bool { return p.Ready() && (p.Off || p.KeptToAgent()) }, disabledNow()))})})}diff --git a/internal/provider/provider.go b/internal/provider/provider.goindex 8ce3eebc0..73942693c 100644--- a/internal/provider/provider.go+++ b/internal/provider/provider.go@@ -151,7 +151,9 @@ type Provider struct {// own sign-in (auth.json) to the next account with room and back:// Codex's requests then go straight to OpenAI, never through the// gateway for account failover, however many of its accounts are on- // (#1907).+ // (#1907). On Claude's subscription it keeps the accounts to Claude+ // Code's own sign-in, which magpie still moves: the gateway serves no+ // request on them (KeptToAgent; myduso on Discord).SwitchOnly bool `json:"switchOnly,omitempty"`// MaxConcurrency is how many requests may be out at the vendor at once@@ -1892,8 +1894,20 @@ func (p Provider) Ready() bool {return p.Account != nil || p.Key != "" || keyOptional(p)}-// On is whether the provider takes requests: ready, and not switched off.-func (p Provider) On() bool { return p.Ready() && !p.Off }+// On is whether the provider takes requests: ready, not switched off and+// not kept to its agent's own sign-in (KeptToAgent).+func (p Provider) On() bool { return p.Ready() && !p.Off && !p.KeptToAgent() }++// KeptToAgent is whether the provider is Claude's subscription with+// SwitchOnly on: its accounts are Claude Code's own sign-in alone, which+// magpie moves to the next account with room and back, and the gateway+// sends no request to them, so none goes through Claude Code's SDK run,+// which spends more of the allowance than Claude Code's own sessions+// (myduso on Discord). Codex's SwitchOnly only keeps failover out of its+// config.+func (p Provider) KeptToAgent() bool {+ return p.SwitchOnly && p.ID == "claude" && p.Account != nil && p.Account.Agent == "claude"+}// SetOff switches a provider off, or on again (see Provider.Off). Saving// it brings the model lists written into agents' files up to date.@@ -1912,12 +1926,12 @@ func SetOff(id string, off bool) error {func SwitchedOff(id string) (Provider, bool) {id = strings.TrimSuffix(strings.TrimSpace(id), "[1m]")if pid, _, ok := strings.Cut(id, "/"); ok {- if p, err := Find(pid); err == nil && p.Off {+ if p, err := Find(pid); err == nil && (p.Off || p.KeptToAgent()) {return *p, true}}for _, p := range All() {- if !p.Off || !p.Ready() {+ if !p.Off && !p.KeptToAgent() || !p.Ready() {continue}if slices.ContainsFunc(p.Exposed(), func(m catalog.Model) bool { return m.ID == id }) {diff --git a/internal/provider/routing.go b/internal/provider/routing.goindex de8e8ae9f..8fd04d0f0 100644--- a/internal/provider/routing.go+++ b/internal/provider/routing.go@@ -117,15 +117,16 @@ func SetKeepLogin(id string, keep bool) error {return nil}-// SetSwitchOnly has magpie only move Codex's own sign-in between its-// accounts (Provider.SwitchOnly), its requests never sent through the-// gateway for account failover, or lets failover go through it again.+// SetSwitchOnly has magpie only move Codex's or Claude Code's own sign-in+// between its accounts (Provider.SwitchOnly): Codex's requests never sent+// through the gateway for account failover, Claude's accounts serving no+// request through the gateway (KeptToAgent). Off, both are as before.func SetSwitchOnly(id string, on bool) error {p, err := Find(id)if err != nil {return err}- if p.Account == nil || p.Account.Agent != p.ID || p.ID != "codex" {+ if p.Account == nil || p.Account.Agent != p.ID || p.ID != "codex" && p.ID != "claude" {return fmt.Errorf("magpie doesn't route %s's own requests for account failover", p.Name)}p.SwitchOnly = ondiff --git a/internal/provider/switch_only_test.go b/internal/provider/switch_only_test.goindex 1f9a4da4e..c50622208 100644--- a/internal/provider/switch_only_test.go+++ b/internal/provider/switch_only_test.go@@ -9,14 +9,17 @@ import ("path/filepath""strings""testing"+ "time"++ "github.com/yetone/magpie/internal/catalog")// #1907 (foobra): Codex Desktop and the CLI on their own ChatGPT// subscription, two accounts, no gateway in between. Switch-only is kept on// Codex's subscription; with it on, the account Codex is signed in to// running out still signs Codex in to the next one with room, in its own-// auth.json, and back once the first has room again. Claude Code's-// subscription has no such setting. A providers.json that can't be read+// auth.json, and back once the first has room again. A providers.json+// that can't be read// says switch-only: the user's choice is unknown, and failover through the// gateway, magpie's own idea, isn't taken up on it.func TestCodexSwitchOnlyStillSwitchesTheSignIn(t *testing.T) {@@ -69,10 +72,6 @@ func TestCodexSwitchOnlyStillSwitchesTheSignIn(t *testing.T) {if err != nil || !p.SwitchOnly {t.Fatalf("Find: %+v %v", p, err)}- if err := SetSwitchOnly("claude", true); err == nil {- t.Error("switch-only set on Claude Code's subscription")- }-// out: on to the spare, in Codex's own auth.jsonif to := switched(); to != "[email protected]" || signedIn() != "r-spare" {t.Fatalf("switched to %q, Codex signed in with %q", to, signedIn())@@ -99,3 +98,104 @@ func TestCodexSwitchOnlyStillSwitchesTheSignIn(t *testing.T) {t.Error("an unreadable providers.json read as switch-only off")}}++// myduso on Discord: Claude's subscription kept to Claude Code alone.+// magpie still signs Claude Code in to the next account with room, by+// writing Claude Code's own sign-in, and serves nothing on the accounts:+// they leave the catalog, a request naming them is refused as switched+// off, and none of it is the raw Off a user's switch writes.+func TestClaudeSwitchOnlyServesNothingAndStillSwitches(t *testing.T) {+ home := claudeHome(t)+ cred := claudeSignIn(t, home, time.Now().Add(time.Hour)) // sk-ant-oat01-old+ writeFile(t, filepath.Join(home, ".claude.json"), map[string]any{"oauthAccount": map[string]any{"emailAddress": "[email protected]", "accountUuid": "u-a"}})+ rememberLogins(true)+ loginsMu.Lock()+ ls := upsertLogin(readLogins(), savedLogin{Agent: "claude", User: "[email protected]", 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": "[email protected]", "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+ os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755)+ if err := os.WriteFile(catalog.CachePath(), []byte(`{"anthropic": {"models": {+ "claude-sonnet-5": {"id":"claude-sonnet-5","name":"Claude Sonnet 5","modalities":{"input":["text"],"output":["text"]}}}}}`), 0o644); err != nil {+ t.Fatal(err)+ }+ catalog.Reset()+ t.Cleanup(catalog.Reset)+ if p, err := Find("claude"); err != nil {+ t.Fatal(err)+ } else if _, err := p.Fetch(context.Background()); err != nil {+ t.Fatal(err)+ }++ served := func() bool {+ t.Helper()+ for _, e := range Catalog() {+ if e.Provider.ID == "claude" {+ return true+ }+ }+ return false+ }+ p, err := Find("claude")+ if err != nil || !p.On() || p.KeptToAgent() || !served() {+ t.Fatalf("before: %+v %v, served %v", p, err, served())+ }+ if err := SetSwitchOnly("claude", true); err != nil {+ t.Fatal(err)+ }+ p, err = Find("claude")+ if err != nil || !p.SwitchOnly || !p.KeptToAgent() || p.On() || p.Off {+ t.Fatalf("kept to Claude Code: %+v %v", p, err)+ }+ if served() {+ t.Error("the catalog still serves the Claude accounts")+ }+ if _, _, ok := Resolve("claude/claude-sonnet-5"); ok {+ t.Error("claude/claude-sonnet-5 resolves kept to Claude Code")+ }+ if _, off := SwitchedOff("claude/claude-sonnet-5"); !off {+ t.Error("a request naming the Claude accounts isn't refused as switched off")+ }+ if leftAlone("claude") {+ t.Fatal("kept to Claude Code reads as left alone: no switching, no usage")+ }++ // spent: Claude Code's own sign-in goes on to b+ for user, u := range map[string]float64{"[email protected]": 99, "[email protected]": 10} {+ NoteClaudeLimits(user, []ClaudeLimit{{Kind: "five_hour", Used: u / 100, ResetsAt: time.Now().Add(time.Hour).Unix()}})+ }+ to, err := SwitchWhenSpent(context.Background(), "claude")+ if err != nil || to != "[email protected]" {+ t.Fatalf("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)+ }+ if p, _ := Find("claude"); !p.KeptToAgent() {+ t.Fatal("kept to Claude Code lost on a switch")+ }++ if err := SetSwitchOnly("claude", false); err != nil {+ t.Fatal(err)+ }+ if p, _ := Find("claude"); !p.On() || !served() {+ t.Fatalf("off again: %+v, served %v", p, served())+ }+ if _, off := SwitchedOff("claude/claude-sonnet-5"); off {+ t.Error("still refused as switched off")+ }+ if _, _, ok := Resolve("claude/claude-sonnet-5"); !ok {+ t.Error("claude/claude-sonnet-5 doesn't resolve unticked")+ }+}