From 8a3dbf0232f19f700615fcb2f92872cdbaf16a98 Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 11 Nov 2026 03:31:51 +0800 Subject: [PATCH] gui: the accounts list says what magpie does with the agent's sign-in A user with two Claude accounts read the used-up switch as gone. Their "Keep Claude Code signed in to" box was ticked, which turns the switch off, and nothing on the page said so. Under the accounts of a Claude Code or Codex with more than one account, a line now says what the switch does, as NextLogin decides it: - kept: switching is off, the agent stays on the first account (or the one picked) even once it runs out; - gateway: Claude Code's requests go through magpie, which picks an account per request; its own sign-in stays put; - moves: the share it moves at (98%, or used up for In order / Until used up), and whether it comes back to the first (returnsToFirst). provider.SignInMovesOf gives the mode from the same checks NextLogin makes (leftAlone, keep, ClaudeThroughMagpie && !SwitchOnly, SpentShareOf, returnsToFirst). /api/providers carries it as signInMoves on the agent's own provider row. The Routing tab's sign-in note says the gateway case too. Strings in zh, zh-TW, ja and de. Run (mote, through mote-run): - go test -run 'TestSignInMoves|TestClaudeRouted|TestKeepLogin| TestClaudeSwitched|TestNextLogin|TestCodexLogin' ./internal/provider: ok - go test -timeout 45m ./internal/gui ./internal/provider: ok (script size budgets included) - gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows on provider and gui: ok - GUI: sign-in-moves, keep-login, i18n-keys, i18n-en-no-cjk, routing-signin, account-return in chromium and webkit: 60 pass - whole GUI suite (make test-ui): see below - screenshots in WebKit, en and zh: the line sits inside the list at the rows' inset; zh sentences join with no space Broken by hand: dropping NextLogin's keep case from SignInMovesOf turns TestSignInMovesSaysWhatSwitchDoes red; not appending the line turns sign-in-moves.test.cjs red 4 of 4. Not tried: the real app with the owner's accounts; the user's own keepLogin is left as it is. --- docs/subsystems/providers-accounts.md | 2 +- internal/gui/assets/app.css | 1 + internal/gui/assets/app.js | 27 ++++- internal/gui/assets/i18n.js | 28 +++++ internal/gui/providers.go | 6 + internal/gui/tests/sign-in-moves.test.cjs | 128 ++++++++++++++++++++++ internal/provider/sign_in_moves.go | 42 +++++++ internal/provider/sign_in_moves_test.go | 119 ++++++++++++++++++++ 8 files changed, 351 insertions(+), 2 deletions(-) create mode 100644 internal/gui/tests/sign-in-moves.test.cjs create mode 100644 internal/provider/sign_in_moves.go create mode 100644 internal/provider/sign_in_moves_test.go diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 574e50d84..60aa50235 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -59,7 +59,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) | | ChatGPT access token only | A saved ChatGPT account can be kept with only the access token it has (EastonXvii on X: `savedLogin.AccessOnly`, `codex_access_only.go`), from the import (`ImportCodexAccessOnly`; the window's *Access token only* tick, `magpie accounts import codex --access-only`) or on a saved account (`SetLoginAccessOnly`; `POST /api/login/access-only` and `/renewed`, the row's ⋯, `magpie accounts access-only codex on|off`). magpie never refreshes it, which would rotate its refresh token and sign out where it came from: the import sends nothing to ChatGPT's token endpoint and needs an unexpired access token and an id_token (a refresh token is optional, and the import is told apart by its access token); `renewSaved` hands out the token while its own exp is ahead (`accessOnlyToken`), refuses a forced renewal without lapsing, and lapses the account once the token has run out or the backend turned it away (`accessOnlyLapse`, a `refreshRefused`); the keep-alive passes it over. Codex itself is never signed in to it (`switchable`, `switchSavedLogin`, `NextLogin`'s return, keep-as), and the account Codex renews itself, here or in another `CODEX_HOME`, can't be kept so (`errAccessOnlyHeld`). Its row says *magpie only*, and once lapsed *Access expired* with *Import again*. Signing in to it again in magpie, or importing it without the tick, replaces the entry with one magpie renews. | | 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). Claude Code whose requests go to magpie's gateway (`ClaudeThroughMagpie`: its settings' `ANTHROPIC_BASE_URL` is the gateway, either sign-in) is not moved: the gateway already sends its requests to an account with room, and moving the sign-in only took away what the user signed it in for, such as claude.ai connectors (oreoft on Discord set it back more than ten times; `TestClaudeRoutedThroughMagpieKeepsItsSignIn`). Not routed, or with *Only switch Claude Code's sign-in*, it still moves. Codex's sign-in goes back to the account it moved off once that has room again, as the gateway's Smart and In order give it requests again; routed Until used up it doesn't, as the gateway keeps the requests on the next (`routes.Drain`), so it stays with them till that one is used up too, as Claude Code's and a switch-only Codex's do unless routed In order (`returnsToFirst`; WalterAIBuilder on X: Codex signed back in to the first showed that one in use while the second's week was spent, `TestCodexDrainSignInStaysOnTheNext`). 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`). A Claude account on overages (/usage's "You are currently using your overages…" line) is read with its windows and a spent *Extra usage* row of text (`claudeOveragesWindow`: Used 100, ending when the last used-up window renews, else at the next reading), so it is moved off as a used-up one; before, the line made the reading an error, and the switch, which stays on an account it can't read, left Claude Code billing overages (StringKe, #4532; `TestClaudeSwitchOffOverages`). The GUI says the row *In use* in the reader's language. Routing (`Allowances`) skips Text rows, so the gateway's own choice of account doesn't count it. A model's own week (`Current week (Sonnet only)`, `(Fable)`) counts for that model in routing, not for the switch, which moves the sign-in only on windows that count every model (`usedPast`); "Sonnet only" is read as the Sonnet week, `7 days · Sonnet` counting `sonnet`, the window the `seven_day_sonnet` header keeps (#4532, `TestClaudeUsageSonnetOnly`). `magpie accounts switch next` (`NextInOrder`) takes the other accounts the agent can be signed in to (`switchable`, not lapsed), on or off in magpie as the accounts list's *Use* does, so one the agent signed itself in to, which starts off, is in the rotation (StringKe, #4532; `TestNextTakesAccountsThatAreOff`), 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) | +| 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). Claude Code whose requests go to magpie's gateway (`ClaudeThroughMagpie`: its settings' `ANTHROPIC_BASE_URL` is the gateway, either sign-in) is not moved: the gateway already sends its requests to an account with room, and moving the sign-in only took away what the user signed it in for, such as claude.ai connectors (oreoft on Discord set it back more than ten times; `TestClaudeRoutedThroughMagpieKeepsItsSignIn`). Not routed, or with *Only switch Claude Code's sign-in*, it still moves. Codex's sign-in goes back to the account it moved off once that has room again, as the gateway's Smart and In order give it requests again; routed Until used up it doesn't, as the gateway keeps the requests on the next (`routes.Drain`), so it stays with them till that one is used up too, as Claude Code's and a switch-only Codex's do unless routed In order (`returnsToFirst`; WalterAIBuilder on X: Codex signed back in to the first showed that one in use while the second's week was spent, `TestCodexDrainSignInStaysOnTheNext`). 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`). A Claude account on overages (/usage's "You are currently using your overages…" line) is read with its windows and a spent *Extra usage* row of text (`claudeOveragesWindow`: Used 100, ending when the last used-up window renews, else at the next reading), so it is moved off as a used-up one; before, the line made the reading an error, and the switch, which stays on an account it can't read, left Claude Code billing overages (StringKe, #4532; `TestClaudeSwitchOffOverages`). The GUI says the row *In use* in the reader's language. Under the accounts of a Claude Code or Codex with more than one, a line says what the switch does with that agent's sign-in (`SignInMovesOf`, `signInMoves` on its `/api/providers` row, `signInMovesLine` in app.js): off while *Keep {agent} signed in to* is ticked (`kept`), left where the user put it while Claude Code's requests go through the gateway (`gateway`), else the share it moves at and whether it comes back to the first (`moves`), each decided as `NextLogin` decides it. Before, a user whose tick had turned the switch off read it as gone (`TestSignInMovesSaysWhatSwitchDoes`). Routing (`Allowances`) skips Text rows, so the gateway's own choice of account doesn't count it. A model's own week (`Current week (Sonnet only)`, `(Fable)`) counts for that model in routing, not for the switch, which moves the sign-in only on windows that count every model (`usedPast`); "Sonnet only" is read as the Sonnet week, `7 days · Sonnet` counting `sonnet`, the window the `seven_day_sonnet` header keeps (#4532, `TestClaudeUsageSonnetOnly`). `magpie accounts switch next` (`NextInOrder`) takes the other accounts the agent can be signed in to (`switchable`, not lapsed), on or off in magpie as the accounts list's *Use* does, so one the agent signed itself in to, which starts off, is in the rotation (StringKe, #4532; `TestNextTakesAccountsThatAreOff`), 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 groups 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. It keeps following its model as a found group does (Kxsg79bEYFP4 on X: a third provider with the model, a plugin's, had stayed out of a group the user had changed): `SaveGroup` stores, for an `auto-…` id, what it had seen (`Group.Seen`: the models magpie found in it by that save, and those the user named, as `provider/model`), and a provider that serves the model since joins it as it is read, after the user's own members (`joined`, not written back), unless kept out of found groups. A model seen and not a member is one the user took out, and stays out; a provider's rename or a fold carries `Seen` (`mapModelRefs`), and a shared group leaves it behind. A found group changed before `Seen` was kept takes in nothing, as nothing says which of its models the user took out; its next save sees what is found then (`TestChangedFoundGroupTakesInANewProvider`, `TestChangedFoundGroupFromBeforeKeepsItsMembers`, `TestChangedFoundGroupTakesInAPluginProvider`). A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing groups 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 groups 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 groups 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 groups 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) | diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 21f151856..5f4e97e3a 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2864,6 +2864,7 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .accts > :is(.keep-login, .switch-only, .restart-app, .pool-ends) + .acc { border-top: 1px solid var(--line-2); } .editor .accts .keep-login, .editor .accts .switch-only, .editor .accts .restart-app, .editor .accts .pool-ends { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; min-height: 34px; padding: 6px 11px; font-size: 12px; border-top: 1px solid var(--line-2); } .editor .accts .keep-login .keep-as { max-width: 240px; } +.editor .accts .sign-in-moves { margin: 0; padding: 8px 11px; font-size: 12px; line-height: 1.5; color: var(--fg-2); border-top: 1px solid var(--line-2); } /* Claude Code's interactive mode or -p, with why (claudeModeRow) */ .claude-mode { display: contents; } .cc-run { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; min-height: 26px; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index c7cffa710..2578849c6 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -12233,6 +12233,22 @@ function routingOfDraft(p) { if (draft?.sink !== undefined && draft.sink !== !!p.sink) out.sink = draft.sink; return out; } +// signInMovesLine says how magpie moves Codex's or Claude Code's own +// sign-in between its accounts (provider.SignInMovesOf), "" when it +// doesn't: the subscription is off +function signInMovesLine(p, agent) { + const m = p.signInMoves; + if (!m) return ""; + if (m.mode === "kept") return keptLogin(p) + ? t("Automatic switching is off: {agent} stays signed in to {user}, even once it runs out.", { agent, user: keptLogin(p) }) + : t("Automatic switching is off: {agent} stays signed in to the first account, even once it runs out.", { agent }); + if (m.mode === "gateway") return t("{agent}'s requests go through magpie, which sends each one to an account with room; its own sign-in stays where you put it.", { agent }); + if (m.mode !== "moves") return ""; + const on = m.share >= 100 + ? t("When the account {agent} is signed in to is used up, magpie signs it in to the next ticked account with room.", { agent }) + : t("When the account {agent} is signed in to reaches {share}%, magpie signs it in to the next ticked account with room.", { agent, share: m.share }); + return on + (locale === "zh" || locale === "zh-TW" || locale === "ja" ? "" : " ") + (m.back ? t("It goes back to the first once that has room again.") : t("It stays on that one till it runs low too.")); +} function renderRouting(p) { const routingNow = () => draft.routing ?? (p.routing || ""); const affinityNow = () => draft.affinity ?? (p.affinity || ""); @@ -12244,7 +12260,9 @@ function renderRouting(p) { const a = p.account; // — at 98%, In order once used up (#530), never when kept on the first (#524) const own = (routing) => !a || (a.agent !== "codex" && a.agent !== "claude") ? "" - : " " + (keptLogin(p) + : " " + (p.signInMoves?.mode === "gateway" && !keptLogin(p) && !p.keepLogin + ? t("{agent}'s requests go through magpie, which sends each one to an account with room; its own sign-in stays where you put it.", { agent: a.agentName }) + : keptLogin(p) ? t("Routing picks the account for each request through magpie, in the accounts' order; {agent} on its own stays signed in to {user}, whatever it has left.", { agent: a.agentName, user: keptLogin(p) }) : p.keepLogin && !p.switchOnly ? t("Routing picks the account for each request through magpie; {agent} on its own stays signed in to the first account, whatever it has left.", { agent: a.agentName }) @@ -13561,6 +13579,13 @@ function renderAccounts(a, p) { if (amBox) row.append(amBox); list.append(row); } + // what magpie does with the agent's own sign-in, said where the + // accounts are: a tick left on, or Claude Code on the gateway, had it + // never switch with nothing on the page saying so (the owner, 11-11) + if ((a.agent === "codex" || a.agent === "claude") && several && p) { + const say = signInMovesLine(p, a.agentName); + if (say) list.append(el("div", "hint sign-in-moves", say)); + } // one account (#209, #408, #524) if ((a.agent === "codex" || a.agent === "claude") && several && p && !p.switchOnly) { const box = el("div", "keep-login"); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index f96d0911b..ca4a90c85 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2061,6 +2061,13 @@ const I18N = { "Only requests through magpie use them; {agent} itself stays signed in as it is.": "只有经过 magpie 的请求会用这些账号;{agent} 本身的登录不变。", "Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is 98% used, and back to the first once that has room again.": "经 magpie 的请求由路由挑选账号;{agent} 直连时用它登录的账号,该账号用到 98% 时,magpie 把 {agent} 登录到下一个已勾选且有余量的账号,首选账号恢复后切回。", "Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is 98% used, and keeps it there till that one is 98% used too.": "经 magpie 的请求由路由挑选账号;{agent} 直连时用它登录的账号,该账号用到 98% 时,magpie 把 {agent} 登录到下一个已勾选且有余量的账号,并一直用它,直到它也用到 98%。", + "Automatic switching is off: {agent} stays signed in to {user}, even once it runs out.": "自动切换已关闭:{agent} 一直登录 {user},额度用完也不换。", + "Automatic switching is off: {agent} stays signed in to the first account, even once it runs out.": "自动切换已关闭:{agent} 一直登录首选账号,额度用完也不换。", + "{agent}'s requests go through magpie, which sends each one to an account with room; its own sign-in stays where you put it.": "{agent} 的请求经过 magpie,每个请求都发给有额度的账号;{agent} 自己的登录保持你选的账号不变。", + "When the account {agent} is signed in to is used up, magpie signs it in to the next ticked account with room.": "{agent} 登录的账号用完时,magpie 把它登录到下一个已勾选且有额度的账号。", + "When the account {agent} is signed in to reaches {share}%, magpie signs it in to the next ticked account with room.": "{agent} 登录的账号用到 {share}% 时,magpie 把它登录到下一个已勾选且有额度的账号。", + "It goes back to the first once that has room again.": "首选账号恢复额度后再切回去。", + "It stays on that one till it runs low too.": "之后一直用这个账号,直到它的额度也快用完。", "Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is used up, and back to the first once that has room again.": "经 magpie 的请求由路由挑选账号;{agent} 直连时用它登录的账号,该账号额度用完时,magpie 把 {agent} 登录到下一个已勾选且有余量的账号,首选账号恢复后切回。", "Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is used up, and keeps it there till that one is used up too.": "经 magpie 的请求由路由挑选账号;{agent} 直连时用它登录的账号,该账号额度用完时,magpie 把 {agent} 登录到下一个已勾选且有余量的账号,并一直用它,直到它的额度也用完。", "Routing picks the account for each request through magpie; {agent} on its own stays signed in to the first account, whatever it has left.": "经 magpie 的请求由路由挑选账号;{agent} 直连时始终登录首选账号,无论剩余额度多少。", @@ -7076,6 +7083,13 @@ const I18N = { "Only requests through magpie use them; {agent} itself stays signed in as it is.": "只有經過 magpie 的請求會用這些帳號;{agent} 本身的登入不變。", "Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is 98% used, and back to the first once that has room again.": "經 magpie 的請求由路由挑選帳號;{agent} 直連時用它登入的帳號,該帳號用到 98% 時,magpie 把 {agent} 登入到下一個已勾選且有餘量的帳號,首選帳號恢復後切回。", "Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is 98% used, and keeps it there till that one is 98% used too.": "經 magpie 的請求由路由挑選帳號;{agent} 直連時用它登入的帳號,該帳號用到 98% 時,magpie 把 {agent} 登入到下一個已勾選且有餘量的帳號,並一直用它,直到它也用到 98%。", + "Automatic switching is off: {agent} stays signed in to {user}, even once it runs out.": "自動切換已關閉:{agent} 一直登入 {user},額度用完也不換。", + "Automatic switching is off: {agent} stays signed in to the first account, even once it runs out.": "自動切換已關閉:{agent} 一直登入首選帳號,額度用完也不換。", + "{agent}'s requests go through magpie, which sends each one to an account with room; its own sign-in stays where you put it.": "{agent} 的請求經過 magpie,每個請求都發給有額度的帳號;{agent} 自己的登入保持你選的帳號不變。", + "When the account {agent} is signed in to is used up, magpie signs it in to the next ticked account with room.": "{agent} 登入的帳號用完時,magpie 把它登入到下一個已勾選且有額度的帳號。", + "When the account {agent} is signed in to reaches {share}%, magpie signs it in to the next ticked account with room.": "{agent} 登入的帳號用到 {share}% 時,magpie 把它登入到下一個已勾選且有額度的帳號。", + "It goes back to the first once that has room again.": "首選帳號恢復額度後再切回去。", + "It stays on that one till it runs low too.": "之後一直用這個帳號,直到它的額度也快用完。", "Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is used up, and back to the first once that has room again.": "經 magpie 的請求由路由挑選帳號;{agent} 直連時用它登入的帳號,該帳號額度用完時,magpie 把 {agent} 登入到下一個已勾選且有餘量的帳號,首選帳號恢復後切回。", "Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is used up, and keeps it there till that one is used up too.": "經 magpie 的請求由路由挑選帳號;{agent} 直連時用它登入的帳號,該帳號額度用完時,magpie 把 {agent} 登入到下一個已勾選且有餘量的帳號,並一直用它,直到它的額度也用完。", "Routing picks the account for each request through magpie; {agent} on its own stays signed in to the first account, whatever it has left.": "經 magpie 的請求由路由挑選帳號;{agent} 直連時始終登入首選帳號,無論剩餘額度多少。", @@ -12067,6 +12081,13 @@ const I18N = { "Only requests through magpie use them; {agent} itself stays signed in as it is.": "これらのアカウントを使うのは magpie を通るリクエストだけです。{agent} 自身のサインインはそのままです。", "Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is 98% used, and back to the first once that has room again.": "magpie 経由のリクエストはルーティングがアカウントを選びます。{agent} 単体ではサインイン中のアカウントを使い、そのアカウントが 98% 使用されると magpie が残量のある次のチェック済みアカウントに切り替え、最初のアカウントに残量が戻ると元に戻します。", "Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is 98% used, and keeps it there till that one is 98% used too.": "magpie 経由のリクエストはルーティングがアカウントを選びます。{agent} 単体ではサインイン中のアカウントを使い、そのアカウントが 98% 使用されると magpie が残量のある次のチェック済みアカウントに切り替え、そのアカウントも 98% 使用されるまでそのまま使います。", + "Automatic switching is off: {agent} stays signed in to {user}, even once it runs out.": "自動切り替えはオフです:{agent} は使い切っても {user} にサインインしたままです。", + "Automatic switching is off: {agent} stays signed in to the first account, even once it runs out.": "自動切り替えはオフです:{agent} は使い切っても最初のアカウントにサインインしたままです。", + "{agent}'s requests go through magpie, which sends each one to an account with room; its own sign-in stays where you put it.": "{agent} のリクエストは magpie を経由し、各リクエストは残量のあるアカウントに送られます。{agent} 自身のサインインは選んだアカウントのままです。", + "When the account {agent} is signed in to is used up, magpie signs it in to the next ticked account with room.": "{agent} がサインインしているアカウントを使い切ると、magpie は残量のある次のチェック済みアカウントにサインインし直します。", + "When the account {agent} is signed in to reaches {share}%, magpie signs it in to the next ticked account with room.": "{agent} がサインインしているアカウントが {share}% に達すると、magpie は残量のある次のチェック済みアカウントにサインインし直します。", + "It goes back to the first once that has room again.": "最初のアカウントに残量が戻ると、そちらに戻します。", + "It stays on that one till it runs low too.": "そのアカウントも残り少なくなるまで、そのまま使います。", "Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is used up, and back to the first once that has room again.": "magpie 経由のリクエストはルーティングがアカウントを選びます。{agent} 単体ではサインイン中のアカウントを使い、そのアカウントを使い切ると magpie が残量のある次のチェック済みアカウントに切り替え、最初のアカウントに残量が戻ると元に戻します。", "Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is used up, and keeps it there till that one is used up too.": "magpie 経由のリクエストはルーティングがアカウントを選びます。{agent} 単体ではサインイン中のアカウントを使い、そのアカウントを使い切ると magpie が残量のある次のチェック済みアカウントに切り替え、そのアカウントも使い切るまでそのまま使います。", "Routing picks the account for each request through magpie; {agent} on its own stays signed in to the first account, whatever it has left.": "magpie 経由のリクエストはルーティングがアカウントを選びます。{agent} 単体では残量にかかわらず最初のアカウントにサインインしたままです。", @@ -17089,6 +17110,13 @@ const I18N = { "Only requests through magpie use them; {agent} itself stays signed in as it is.": "Nur Anfragen über magpie verwenden diese Konten; {agent} selbst bleibt angemeldet wie bisher.", "Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is 98% used, and back to the first once that has room again.": "Die Weiterleitung wählt für jede Anfrage über magpie das Konto; {agent} selbst nutzt das Konto, bei dem es angemeldet ist; magpie meldet es beim nächsten angehakten Konto mit freiem Kontingent an, sobald das aktuelle zu 98 % verbraucht ist, und wieder beim ersten, sobald dort wieder Kontingent frei ist.", "Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is 98% used, and keeps it there till that one is 98% used too.": "Die Weiterleitung wählt für jede Anfrage über magpie das Konto; {agent} selbst nutzt das Konto, bei dem es angemeldet ist; magpie meldet es beim nächsten angehakten Konto mit freiem Kontingent an, sobald das aktuelle zu 98 % verbraucht ist, und bleibt dort, bis auch dieses zu 98 % verbraucht ist.", + "Automatic switching is off: {agent} stays signed in to {user}, even once it runs out.": "Automatischer Wechsel ist aus: {agent} bleibt bei {user} angemeldet, auch wenn das Kontingent aufgebraucht ist.", + "Automatic switching is off: {agent} stays signed in to the first account, even once it runs out.": "Automatischer Wechsel ist aus: {agent} bleibt beim ersten Konto angemeldet, auch wenn das Kontingent aufgebraucht ist.", + "{agent}'s requests go through magpie, which sends each one to an account with room; its own sign-in stays where you put it.": "Die Anfragen von {agent} laufen über magpie, das jede an ein Konto mit Kontingent schickt; die eigene Anmeldung von {agent} bleibt, wo du sie gesetzt hast.", + "When the account {agent} is signed in to is used up, magpie signs it in to the next ticked account with room.": "Ist das Konto, bei dem {agent} angemeldet ist, aufgebraucht, meldet magpie es beim nächsten angehakten Konto mit Kontingent an.", + "When the account {agent} is signed in to reaches {share}%, magpie signs it in to the next ticked account with room.": "Erreicht das Konto, bei dem {agent} angemeldet ist, {share} %, meldet magpie es beim nächsten angehakten Konto mit Kontingent an.", + "It goes back to the first once that has room again.": "Hat das erste wieder Kontingent, geht es dorthin zurück.", + "It stays on that one till it runs low too.": "Es bleibt dort, bis auch dieses knapp wird.", "Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is used up, and back to the first once that has room again.": "Die Weiterleitung wählt für jede Anfrage über magpie das Konto; {agent} selbst nutzt das Konto, bei dem es angemeldet ist; magpie meldet es beim nächsten angehakten Konto mit freiem Kontingent an, sobald das aktuelle aufgebraucht ist, und wieder beim ersten, sobald dort wieder Kontingent frei ist.", "Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is used up, and keeps it there till that one is used up too.": "Die Weiterleitung wählt für jede Anfrage über magpie das Konto; {agent} selbst nutzt das Konto, bei dem es angemeldet ist; magpie meldet es beim nächsten angehakten Konto mit freiem Kontingent an, sobald das aktuelle aufgebraucht ist, und bleibt dort, bis auch dieses aufgebraucht ist.", "Routing picks the account for each request through magpie; {agent} on its own stays signed in to the first account, whatever it has left.": "Die Weiterleitung wählt für jede Anfrage über magpie das Konto; {agent} selbst bleibt beim ersten Konto angemeldet, egal wie viel dort noch übrig ist.", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index dfb089771..9c8f5128c 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -325,6 +325,9 @@ type providerJSON struct { // 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"` + // SignInMoves: how magpie moves Codex's or Claude Code's own sign-in + // between its accounts (provider.SignInMovesOf), said beside them + SignInMoves *provider.SignInMoves `json:"signInMoves,omitempty"` // RestartApp: magpie restarts the Codex app's app-server for an // account change it makes by itself (provider.Provider.RestartApp) RestartApp bool `json:"restartApp,omitempty"` @@ -846,6 +849,9 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs AccountConcurrency: p.AccountConcurrency, AccountWeights: p.AccountWeights, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, Outputs: provider.OutputsOf(p.ID), Compacts: provider.CompactsOf(p.ID), } + if p.Account != nil && p.Account.Agent == p.ID { + out.SignInMoves = provider.SignInMovesOf(p.ID) + } if p.Account != nil { for _, r := range p.AccountRefs() { if s := provider.SeatNameOf(p.ID, r); s != "" { diff --git a/internal/gui/tests/sign-in-moves.test.cjs b/internal/gui/tests/sign-in-moves.test.cjs new file mode 100644 index 000000000..73a5a4c99 --- /dev/null +++ b/internal/gui/tests/sign-in-moves.test.cjs @@ -0,0 +1,128 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The owner (11-11): Claude Code stopped switching to an account with room, +// and nothing on the page said why: "Keep Claude Code signed in to" was +// ticked. Under the accounts a line now says what magpie does with Claude +// Code's own sign-in, as the server tells it (signInMoves): moved on at 98% +// or once used up, back to the first or not; off while kept on one; left +// alone while its requests go through the gateway. Ticking the keep box +// changes the line. No line with one account. English and Chinese, +// Chromium and WebKit. +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 = ({ signInMoves = { mode: "moves", share: 98 }, keepLogin = false, keepLoginAs = "", spare = true, one = false } = {}) => ({ + id: "claude", name: "Claude Code", icon: "claude-color", chat: "", responses: "", anthropic: "", catalog: "", routing: "", keepLogin, keepLoginAs, signInMoves, + models: [{ id: "claude-opus-5-5", name: "Claude Opus 5.5", on: true }], agents: [], fallback: [], headers: {}, keyList: [], + account: { + agent: "claude", agentName: "Claude Code", user: "a@example.com", plan: "MAX", + logins: [{ user: "a@example.com", plan: "MAX", active: true, on: true }, ...(one ? [] : [{ user: "b@example.com", plan: "MAX", on: spare }])], + }, +}); + +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/keeplogin") { + const body = route.request().postDataJSON(); + posts.push(body); + const as = body.keepLogin && body.keepLoginAs || ""; + const logins = list[0].account.logins.map((l) => ({ ...l, active: as ? l.user === as : l.user === "a@example.com" })); + // the server says what the switch now does (provider.SignInMovesOf) + const signInMoves = body.keepLogin ? { mode: "kept" } : { mode: "moves", share: 98 }; + list = [{ ...list[0], keepLogin: body.keepLogin, keepLoginAs: as, signInMoves, account: { ...list[0].account, logins } }]; + return json(providers()); + } + if (url.pathname === "/api/provider/arrange") { + posts.push({ arrange: route.request().postDataJSON() }); + 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 words = { + en: { + at98: "When the account Claude Code is signed in to reaches 98%, magpie signs it in to the next ticked account with room. It stays on that one till it runs low too.", + usedUpBack: "When the account Claude Code is signed in to is used up, magpie signs it in to the next ticked account with room. It goes back to the first once that has room again.", + kept: "Automatic switching is off: Claude Code stays signed in to the first account, even once it runs out.", + keptAs: "Automatic switching is off: Claude Code stays signed in to b@example.com, even once it runs out.", + gateway: "Claude Code's requests go through magpie, which sends each one to an account with room; its own sign-in stays where you put it.", + }, + zh: { + at98: "Claude Code 登录的账号用到 98% 时,magpie 把它登录到下一个已勾选且有额度的账号。之后一直用这个账号,直到它的额度也快用完。", + usedUpBack: "Claude Code 登录的账号用完时,magpie 把它登录到下一个已勾选且有额度的账号。首选账号恢复额度后再切回去。", + kept: "自动切换已关闭:Claude Code 一直登录首选账号,额度用完也不换。", + keptAs: "自动切换已关闭:Claude Code 一直登录 b@example.com,额度用完也不换。", + gateway: "Claude Code 的请求经过 magpie,每个请求都发给有额度的账号;Claude Code 自己的登录保持你选的账号不变。", + }, +}; + +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, opts) => { + 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(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + 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 Code" }).first().click(); + await page.locator(".editor .acc").first().waitFor(); + return { page, errors, posts }; + }; + const line = (page) => page.locator(".editor .accts .sign-in-moves"); + + test(`${engine} ${lang}: the line says how Claude Code's sign-in moves`, async (t) => { + for (const [opts, want] of [ + [{}, w.at98], + [{ signInMoves: { mode: "moves", share: 100, back: true } }, w.usedUpBack], + [{ signInMoves: { mode: "gateway" } }, w.gateway], + [{ signInMoves: { mode: "kept" }, keepLogin: true, keepLoginAs: "b@example.com" }, w.keptAs], + ]) { + const { page, errors } = await open(t, opts); + assert.equal((await line(page).textContent()).trim(), want); + assert.equal(await line(page).count(), 1); + assert.deepEqual(errors, []); + await page.close(); + } + }); + + test(`${engine} ${lang}: ticking keep changes the line, and none with one account or off`, async (t) => { + const { page, errors, posts } = await open(t, {}); + const top = await page.evaluate(() => document.scrollingElement.scrollTop); + await page.locator(".editor .accts .keep-login input").click(); + await page.waitForFunction((s) => document.querySelector(".editor .accts .sign-in-moves")?.textContent.trim() === s, w.kept); + assert.deepEqual(posts, [{ id: "claude", keepLogin: true }]); + await page.locator(".editor .accts .keep-login input").click(); + await page.waitForFunction((s) => document.querySelector(".editor .accts .sign-in-moves")?.textContent.trim() === s, w.at98); + assert.equal(await page.evaluate(() => document.scrollingElement.scrollTop), top, "the page doesn't move"); + assert.deepEqual(errors, []); + for (const opts of [{ one: true }, { signInMoves: { mode: "off" } }]) { + const o = await open(t, opts); + assert.equal(await line(o.page).count(), 0, JSON.stringify(opts)); + assert.deepEqual(o.errors, []); + } + }); + } +} diff --git a/internal/provider/sign_in_moves.go b/internal/provider/sign_in_moves.go new file mode 100644 index 000000000..62c9bd16e --- /dev/null +++ b/internal/provider/sign_in_moves.go @@ -0,0 +1,42 @@ +package provider + +import "slices" + +// SignInMoves is how magpie moves an agent's own sign-in between its +// accounts, as NextLogin decides it, for the Providers page to say +// beside the accounts: a user who left a "keep signed in" tick on, or +// whose Claude Code went through the gateway, saw no switch and had no +// way to tell why (the owner, 11-11). +type SignInMoves struct { + // Mode: "kept" (stays on one account, KeepLogin / KeepLoginAs), + // "gateway" (Claude Code sends its requests to magpie's gateway, + // which moves each to an account with room, its sign-in left + // where the user put it), "off" (the subscription is off or hidden: + // magpie leaves the sign-in alone) or "moves" (moved on once spent). + Mode string `json:"mode"` + // Share: the share of a window at which the account it is on counts + // spent and is moved off (SpentShareOf); 100 is used up. Only "moves". + Share float64 `json:"share,omitempty"` + // Back: once the account moved off has room again, the agent is + // signed back in to it (returnsToFirst). Only "moves". + Back bool `json:"back,omitempty"` +} + +// SignInMovesOf is SignInMoves for agent; nil for one whose sign-in magpie +// never moves. +func SignInMovesOf(agent string) *SignInMoves { + if !slices.Contains(switchedAgents, agent) { + return nil + } + if leftAlone(agent) { + return &SignInMoves{Mode: "off"} + } + share, keep := loginSwitching(agent) + switch { + case keep: + return &SignInMoves{Mode: "kept"} + case agent == "claude" && ClaudeThroughMagpie() && !SwitchOnly(agent): + return &SignInMoves{Mode: "gateway"} + } + return &SignInMoves{Mode: "moves", Share: share, Back: returnsToFirst(agent)} +} diff --git a/internal/provider/sign_in_moves_test.go b/internal/provider/sign_in_moves_test.go new file mode 100644 index 000000000..d665317ce --- /dev/null +++ b/internal/provider/sign_in_moves_test.go @@ -0,0 +1,119 @@ +package provider + +import ( + "context" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + "time" +) + +// What the Providers page says of Claude Code's sign-in (SignInMovesOf) is +// what the switch does: "moves" exactly when a spent account is moved off, +// at the share it names. The owner's Claude Code went unswitched for days +// under a "keep signed in" tick left on, with nothing on the page saying +// automatic switching was off (11-11). +func TestSignInMovesSaysWhatSwitchDoes(t *testing.T) { + home := claudeHome(t) + cred := claudeSignIn(t, home, time.Now().Add(time.Hour)) // a@example.com, sk-ant-oat01-old + writeFile(t, home+"/.claude.json", map[string]any{"oauthAccount": map[string]any{"emailAddress": "a@example.com", "accountUuid": "u-a"}}) + rememberLogins(true) + loginsMu.Lock() + ls := upsertLogin(readLogins(), savedLogin{Agent: "claude", User: "b@example.com", Plan: "max", On: true, Seen: time.Now().UTC(), + Auth: mustJSONRaw(t, map[string]any{"claudeAiOauth": map[string]any{"accessToken": "sk-ant-oat01-b", "refreshToken": "sk-ant-ort01-b", + "expiresAt": time.Now().Add(time.Hour).UnixMilli(), "subscriptionType": "max", "scopes": []string{"user:inference", "user:profile"}}}), + Profile: mustJSONRaw(t, map[string]any{"emailAddress": "b@example.com", "accountUuid": "u-b"})}) + if err := writeLogins(ls); err != nil { + t.Fatal(err) + } + loginsMu.Unlock() + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Errorf("usage endpoint read: %s", r.URL) + })) + defer fake.Close() + claudeBase = fake.URL // isolate puts it back + + routed := true + old := ClaudeThroughMagpie + ClaudeThroughMagpie = func() bool { return routed } + t.Cleanup(func() { ClaudeThroughMagpie = old }) + + // a used up, b with room + used := map[string]float64{"a@example.com": 100, "b@example.com": 10} + switched := func() string { + t.Helper() + loginUsageCache.Lock() + loginUsageCache.m = nil + loginUsageCache.Unlock() + claudeUsage.Lock() + claudeUsage.m = nil + claudeUsage.Unlock() + for user, u := range used { + 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 { + t.Fatal(err) + } + return to + } + signedInAs := func() string { + t.Helper() + b, err := os.ReadFile(cred) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(b), "sk-ant-ort01-b") { + return "b@example.com" + } + return "a@example.com" + } + + cases := []struct { + name string + routed, only, keep bool + routing string + mode string + share float64 + back bool + }{ + {name: "not routed", mode: "moves", share: SpentShare}, + {name: "not routed, in order", routing: Ordered, mode: "moves", share: 100, back: true}, + {name: "routed", routed: true, mode: "gateway"}, + {name: "routed, switch only", routed: true, only: true, mode: "moves", share: SpentShare}, + {name: "kept on the first", keep: true, mode: "kept"}, + {name: "kept, routed", keep: true, routed: true, mode: "kept"}, + } + for _, c := range cases { + routed = c.routed + if err := SetRouting("claude", c.routing); err != nil { + t.Fatal(err) + } + if err := SetSwitchOnly("claude", c.only); err != nil { + t.Fatal(err) + } + if err := SetKeepLogin("claude", c.keep); err != nil { + t.Fatal(err) + } + if err := SwitchLogin("claude", "a@example.com"); err != nil { + t.Fatal(err) + } + setLoginReturn("claude", loginReturn{}) + m := SignInMovesOf("claude") + if m == nil || m.Mode != c.mode || m.Share != c.share || m.Back != c.back { + t.Fatalf("%s: says %+v, want mode %s share %g back %v", c.name, m, c.mode, c.share, c.back) + } + to := switched() + if moved := to != ""; moved != (c.mode == "moves") { + t.Fatalf("%s: the page says %q but the switch moved to %q", c.name, c.mode, to) + } + if to != "" && signedInAs() != to { + t.Fatalf("%s: switched to %s, signed in as %s", c.name, to, signedInAs()) + } + } + if SignInMovesOf("gemini") != nil { + t.Fatal("an agent whose sign-in magpie never moves has a line") + } +}