diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index f52579de2..71bfc0802 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -53,7 +53,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | 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. Claude also reads claude-swap's `cswap export` (format 1, claude-swap 0.29; `cswapEntry`, #4532): each account's `credentials.claudeAiOauth` and `config.oauthAccount`, with its organization name, and its alias becomes the account's name when that account has none and no other account is called or signed in as it (`importNames`). An encrypted export, another format, a Codex entry and an API-key entry are refused with what to do; `testdata/cswap_0.29.0_export.json` is claude-swap's own output. A refresh token magpie holds already is `exists`, never refreshed; accounts are matched by email and workspace, or for Claude organization (`sameLogin`). A Claude sign-in for an account magpie has, Claude Code's own or a saved one that can be used, with another refresh token is taken only when the file's `expiresAt` is later than the one magpie has (the account's own config directory counted, `claudeNewerKept`); otherwise it is `exists` with why, and nothing is written: an export made before Claude Code's last refresh holds a spent refresh token, and written over Claude Code's own it signed the account out (#4532, `TestImportCswapKeepsNewerSignIn`). A file that gives no `expiresAt` never replaces one. A sign-in itself imported and never run since is kept with `expiresAt` 1, so any dated file is taken over it. 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) | | Claude setup-token | A Claude account can be added from the long-lived token `claude setup-token` prints (sfss5362 on X), which Claude Code takes in `CLAUDE_CODE_OAUTH_TOKEN` (the window's *Use a setup-token instead…* and *Add an account by setup-token…*, `POST /api/signin/claude-token`). `AddClaudeSetupToken` keeps it in `logins.json` as `{"setupToken":…}`, named `Claude setup-token <6 hex of its hash>` (it tells no email), on beside the others; the same token again is the same account. Such a token has the inference scope only: Claude Code's `auth status` says `oauth_token` with no email or plan, and its `/usage` prints the API cost view, so `/usage` is never run for it and its allowance is unknown (`errClaudeSetupToken`, kept by `passing` as saying nothing about the account) until a reply's rate-limit event tells it. Its config directory (`claudeTokenDir`) holds no `.credentials.json`, which Claude Code could fall back to on a refused token. Claude Code itself is never signed in to it: `addLogin`, `switchLogin`, `putClaudeLogin`, `SetKeepLoginAs`, `NextLogin` and `signInToFirst` pass it over, and the window shows Remove and *magpie only* in place of Use and Make first. Not tried with a real token. | [`claude_setup_token.go`](../../internal/provider/claude_setup_token.go), [`claude_subscription.go`](../../internal/gateway/claude_subscription.go) (`inClaudeDir`), [`providers.go`](../../internal/gui/providers.go) | | Switch accounts only | magpie as a Claude Code (or Codex) account switcher alone, with nothing connected (the owner on X; growaiskills, Rennix7t). In the window, the Agents row of a Claude Code or Codex not connected says the account it is signed in to (`switchEntry` in app.js, from the providers list `prefetchProviders` reads at start, so `/api/state` reads no keychain for it), also when magpie has no models to connect (`switchable`, before the `empty` line). Its menu, headed *Switch accounts only*, lists the agent's saved accounts: a pick goes through `POST /api/login/switch` (`SwitchLogin`), or `provider/keeplogin` with `keepLoginAs` when the agent is kept signed in to an account of the user's choosing, as the account rows do; the button says *Switched* for five seconds and the status line says new sessions use the account, one already open keeps its own until started again. *Only switch {agent}'s sign-in* (`SwitchOnly` above, `provider/switchonly`) is a ticked item there (Codex: with more than one usable account, as under Providers), and the row then says *Not connected · switching accounts only*. *Manage accounts…*, and a pick whose sign-in lapsed, open Providers › the agent. A Codex failing over (#1385) has it in place of the old *ChatGPT accounts* button. In the tray panel (whose Quick panel shortcut opens it from any app, shuizhuyu on X) it is the *account* line of the agent's opened row (`.ag-who`), drawn from the list kept from the last read (`panelAccounts`, `GET /api/providers?last=1`, no keychain read; a fresh read only when none is kept), so opening the panel reads no sign-in. The menu waits for one fresh `/api/providers` read and opens on what it says; *Manage accounts…* and a lapsed pick open the window's Providers (`window/main?view=providers`). The provider and login actions keep their answer as the last list (`keepProviders`), so a switch made anywhere is in the panel's next line at once (`TestKeptProvidersFollowActions`, `panel-switch-accounts.test.cjs`). Not on a WSL twin's row, not on a connected agent's. | [`app.js`](../../internal/gui/assets/app.js), [`logins.go`](../../internal/provider/logins.go) | -| Used-up switch | When the account Codex or Claude Code is signed in to has used its allowance, the agent is signed in to the next account that is on and has room (#208). When every one is past its line too, it goes to the one with the most room left (`roomLeft`: the fullest stopping window's distance below the switch share, or the account's own cap when lower), when that has more than the account it is on by `roomMargin` (1 point), so two all but even accounts don't trade it each look; else it stays (StringKe in #4532, after cswap's `best`; `TestNextLoginTakesTheMostRoomWhenAllArePast`). 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). 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) | | Removing the signed-in account | `ForgetLogin` signs Codex or Claude Code in to another of its accounts first (`nextOnForget`: the first other that is on, else one whose sign-in holds, else any, never a setup-token account or one Codex keeps in another folder: `switchable`), then forgets this one; a switch that fails removes nothing (StringKe, #4532: Claude's was refused while Codex's switched). Codex's only account is signed out as `codex logout` does. Claude Code is never signed out: its last account it can be signed in to is refused with `SignedInError{Only}` (GUI code `signed_in_only`, and that account has no *Remove*). Claude Code's own credential is never deleted; the forgotten account's folder (`forgetClaudeDir`) is its own. `TestForgetLiveClaudeSwitchesFirst`, `TestForgetOnlyClaudeIsKept`, `codex-signout.test.cjs`. | | Claude Code's proxy | Claude Code on its own subscription asks Anthropic itself, through the proxy its env names. While any Claude account has a proxy of its own (`AccountProxies`), the `env` of Claude Code's `settings.json` names the proxy of the account it is signed in to (#1807): `HTTPS_PROXY` and `HTTP_PROXY` set to that account's own, else the subscription's `Proxy` (`ProxyOfLogin`), and `NO_PROXY` to loopback; none for `direct` or a SOCKS proxy, which Claude Code can't use. It is written on every switch (`switchLogin`, the user's or `SwitchWhenSpent`), when the Claude subscription is saved, and at the gateway's look every `loginSwitchEvery` (a sign-in made in Claude Code itself). Claude Code reads its env at start, so only sessions started after the switch take it. A proxy key the user set (in either case) is theirs: magpie then writes none and takes out none of theirs. What magpie wrote is kept in `claude-proxy-env.json`, and a key is magpie's only while it holds that value. A `settings.json` that doesn't parse is left as it is. Its log lines name the proxy through `netproxy.Redact`, without its user and password (#1886); the env gets it whole. | [`claude_proxy_env.go`](../../internal/provider/claude_proxy_env.go) | | Routing groups | User-made groups from the Routing view, and auto-found groups of the same model across providers (derived, never stored). The same model is the same id as vendors agree on it (`sameModel`): lowercase, without a vendor's prefix, a version's dot as `-`, a run of spaces, `_` and `-` as one `-` (a relay listing its display name as the id, `GPT-6 Sol`, joins `gpt-6-sol`, Chill on Discord: `TestSameModelDisplayNameAsID`), and without a YYYYMMDD or Ark YYMMDD snapshot date. Every word still counts (`gpt-6`, `gpt-6-mini` and `gpt-6-sol` stay apart), as do a `:variant`, a four-digit release and OpenAI's dashed date (`gpt-4o-2024-08-06`, a pinned snapshot whose group id agents may already name). A provider kept "Only through routing groups" joins them the same way. Members are `provider/model[:effort]`. A group can nest another (`group/`); `SaveGroup` refuses loops. A group given another id (`agent.RenameGroup`: the Routing page, `magpie groups rename`, the TUI) moves every agent field on `group/` to `group/`, spelled as the agent spells it, through the same `renameRefs` a provider's rename uses, then `SyncCatalog`; before, the agents stayed on a group magpie no longer had (lucis0116 on X, `TestRenameGroupMovesTheAgentsOnIt`). A provider's or group's display name needs no move: `store` and `SaveGroup` drop the catalog, and `SyncCatalog` writes the new labels into every agent's list. `Match` takes a glob or `re:` pattern (#766), both matched in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter). What a pattern matches follows the members named, in the catalog's order, until the user drags it elsewhere (usrname1833 on Discord): `Placed` keeps the whole order, named and matched alike, and the group is read and routed in it (`placedIn`); a model matched since goes last, one no longer matched drops out, a save that sends the named members only leaves the matched where they were (`placedOver`), and a provider's or group's rename carries it (`TestGroupPatternMembersKeepTheirPlace`, `group-member-drag.test.cjs`). A found group follows the providers magpie has: one removed leaves it, while one switched off stays in it (`foundGroups`, `heldOffEntries`; one without a key, such as a plugin not signed in, finds no group), skipped by `membersIn`, left off a found group's card, logos and TUI line with a count of those switched off (XYenon on Discord: `routing-provider-off.test.cjs`, `TestFoundGroupLineLeavesASwitchedOffProviderOut`) and said as switched off in its editor and the TUI's group page, so switching one of two providers off for a while doesn't take the group away from the agents, rules and groups set to it; it is back in its place once on again (#2671: `TestFoundGroupStaysWithAProviderOff`, `TestFoundGroupWithAProviderOff`, `TestReseatKeepsAFoundGroupWithAProviderOff`, `TestFoundGroupMemberOfASwitchedOffProvider`). A found group the user changed (an `auto-…` id stored) is read without the members of providers magpie no longer has (`withoutRemoved`, not written back, so a provider back under its id is back in it), except a manual group's pick, a rule's model, or all of them when none would be left. A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing page says them as switched off (`memberJSON.providerOff`). The user's own groups keep their members. Three templates make a group in one click from the models the user has (`provider.Templates`, `AddTemplate`; the Routing page's cards before a first group and its Templates menu after, `magpie group template [kind] [name]`): `smart` sends a hard turn to the strongest model and an easy one or a compaction to a cheap one, asked by a classifier (the decision API when there is one, else the cheapest priced model that doesn't reason); `thrifty` starts on two cheap models of different providers and sends high reasoning to the strongest; `steady` fails over between the strongest model of up to three providers. A model is weighed by its maker's list price when known, else what its provider charges, else by its id's size words (`sizeOf`); one over `tooDear` (USD 100 a million output tokens) is never picked. A template that can't be made says what is missing (`Need`). It is saved under a name and id no group has (`freeGroupName`, shared with `CopyGroup`), never over one. A group is shared as text (`ShareGroup`, a group row's Copy to share): JSON marked `"magpie": "routing-group"` with a format `version` (`ShareVersion`), holding the group's members as it names them, patterns, routing, rules, classifier and settings. A group holds only `provider/model` ids, never a key, account or address, and the derived matches, found/hidden/off flags and the rules that hold by a folder (a path on the sharer's machine, `Rule.Folders`) stay behind; a pasted one is left out too. `ImportGroup` (the Routing page's Import, `POST /api/groups/import`) reads it with words or a code fence around it, refuses another text, a newer format or none (`ShareError`, said in the reader's language). A member whose provider the importer has is kept; else the same model (`AutoGroupOf`) under the first provider of theirs that serves it (`Instead`); else it is left out and named (`Missing`), with the rules that send to it, its place among the off and fast members, and a classifier gone takes the intent rules and auto effort with it. Nothing is added when no member is left; what is added gets a free name, never replacing a group. A group of patterns only that match nothing now (a plugin's models not listed) has no members: `/api/groups` says them, and an unmakeable template's, as `[]`, never `null`; the Routing page reads the response through `groupsFrom` and draws a group it still can't draw as one row saying so, so one bad group never hides the rest (#1585). | [`group.go`](../../internal/provider/group.go), [`grouptemplate.go`](../../internal/provider/grouptemplate.go), [`group_share.go`](../../internal/provider/group_share.go) | diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 6fbe84f05..f725fbc65 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -11999,7 +11999,11 @@ function renderRouting(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 }) - : routing === "order" || routing === "drain" + : routing === "drain" + // Until used up keeps the requests on the next, and the sign-in + // with them (provider.returnsToFirst; WalterAIBuilder on X) + ? t("Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is used up, and keeps it there till that one is used up too.", { agent: a.agentName }) + : routing === "order" ? t("Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is used up, and back to the first once that has room again.", { agent: a.agentName }) : a.agent === "codex" && !p.switchOnly || p.keepLogin ? t("Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is 98% used, and back to the first once that has room again.", { agent: a.agentName }) diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 28a29b977..2628520aa 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1818,6 +1818,7 @@ const I18N = { "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%。", "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} 直连时始终登录首选账号,无论剩余额度多少。", "Keep {agent} signed in to the first account": "{agent} 始终登录首选账号", "Keep {agent} signed in to": "{agent} 始终登录", @@ -6377,6 +6378,7 @@ const I18N = { "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%。", "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} 直連時始終登入首選帳號,無論剩餘額度多少。", "Keep {agent} signed in to the first account": "{agent} 始終登入首選帳號", "Keep {agent} signed in to": "{agent} 始終登入", @@ -10912,6 +10914,7 @@ const I18N = { "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% 使用されるまでそのまま使います。", "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} 単体では残量にかかわらず最初のアカウントにサインインしたままです。", "Keep {agent} signed in to the first account": "{agent} を最初のアカウントにサインインしたままにする", "Keep {agent} signed in to": "{agent} のサインイン先を固定:", @@ -15478,6 +15481,7 @@ const I18N = { "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.", "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.", "Keep {agent} signed in to the first account": "{agent} beim ersten Konto angemeldet lassen", "Keep {agent} signed in to": "{agent} angemeldet lassen bei", diff --git a/internal/gui/tests/account-return.test.cjs b/internal/gui/tests/account-return.test.cjs index 52d951db6..f5b03ea88 100644 --- a/internal/gui/tests/account-return.test.cjs +++ b/internal/gui/tests/account-return.test.cjs @@ -38,6 +38,10 @@ const claude = () => ({ ], }, }); +// WalterAIBuilder on X: routed Until used up, the gateway keeps the +// requests on the account it went on to, and Codex's or Claude Code's +// sign-in stays there with them (provider.returnsToFirst) +const drains = "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."; const stays = "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."; function serve(lang, list) { @@ -60,8 +64,8 @@ function serve(lang, list) { } const words = { - en: { first: "First", now: "First for now", again: "First again once it has room", note: /and back to the first once that has room again/, why: /work@example\.com was nearly used up/, stays: /keeps it there till that one is 98% used too/ }, - zh: { first: "首选", now: "暂为首选", again: "额度恢复后切回首选", note: /首选账号恢复后切回/, why: /work@example\.com 额度将尽/, stays: /直到它也用到 98%/ }, + en: { first: "First", now: "First for now", again: "First again once it has room", note: /and back to the first once that has room again/, why: /work@example\.com was nearly used up/, stays: /keeps it there till that one is 98% used too/, drains: /once it is used up, and keeps it there till that one is used up too/ }, + zh: { first: "首选", now: "暂为首选", again: "额度恢复后切回首选", note: /首选账号恢复后切回/, why: /work@example\.com 额度将尽/, stays: /直到它也用到 98%/, drains: /该账号额度用完时.*并一直用它,直到它的额度也用完/ }, }; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { @@ -116,6 +120,18 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.deepEqual(errors, []); }); + test(`${engine} ${lang}: routed Until used up, the note says the sign-in stays on the next`, async (t) => { + for (const p of [{ ...codex(false), routing: "drain" }, { ...claude(), routing: "drain" }]) { + const { page, errors } = await open(t, false, p); + const note = await page.locator(".editor").textContent(); + assert.match(note, w.drains, p.id); + assert.doesNotMatch(note, w.note, p.id); + const missing = await page.evaluate((k) => ["zh", "zh-TW", "ja", "de"].filter((l) => !I18N[l][k]), drains); + assert.deepEqual(missing, [], "every language has the note"); + assert.deepEqual(errors, []); + } + }); + test(`${engine} ${lang}: with nothing to go back to, the account Codex is on is first`, async (t) => { const { page, errors } = await open(t, false); const spare = page.locator(".editor .acc", { hasText: "spare@example.com" }); diff --git a/internal/provider/codex_switch.go b/internal/provider/codex_switch.go index 246032642..1cfcc5518 100644 --- a/internal/provider/codex_switch.go +++ b/internal/provider/codex_switch.go @@ -23,8 +23,9 @@ package provider // sign-in follows the gateway it stays that: once it is no longer low // (backShare) the agent is signed back in to it, as Smart gives it // requests again then (#408). Where the sign-in alone spends the accounts -// (returnsToFirst), the agent stays on the one it moved to till that is -// spent too. A switch the user makes meanwhile ends that. With KeepLogin on the subscription, the agent +// (returnsToFirst), or the gateway itself stays on the next (Until used +// up), the agent stays on the one it moved to till that is spent too. A +// switch the user makes meanwhile ends that. With KeepLogin on the subscription, the agent // stays signed in to the first, whatever it has left (#524); with // KeepLoginAs, to that account, wherever it stands in the order. Not while // magpie only switches the sign-in (SwitchOnly): moving it is then all @@ -149,13 +150,17 @@ func loginSwitching(agent string) (share float64, keep bool) { // alone magpie switches (SwitchOnly) — going back at the first's reset // left the account moved to part used and started the first's next // window early, which is not "use one up, then the next" (hxy920830 on -// X): there it stays, unless the user said the first comes first. +// X): there it stays, unless the user said the first comes first. Nor +// does Codex's go back when it is routed Until used up: the gateway then +// keeps its requests on the account it moved to (routes.Drain), so Codex +// signed back in to the first showed that one in use while the other's +// allowance was spent (WalterAIBuilder on X); it stays with the requests. func returnsToFirst(agent string) bool { for _, p := range storedFile().Providers { if p.ID == agent { // kept on the first (KeepLogin), set aside under SwitchOnly, // is still the user's word that the first comes first - return p.Routing == Ordered || p.KeepLogin || agent == "codex" && !p.SwitchOnly + return p.Routing == Ordered || p.KeepLogin || agent == "codex" && !p.SwitchOnly && p.Routing != Drain } } return agent == "codex" diff --git a/internal/provider/drain_signin_test.go b/internal/provider/drain_signin_test.go new file mode 100644 index 000000000..83fd9f99f --- /dev/null +++ b/internal/provider/drain_signin_test.go @@ -0,0 +1,104 @@ +package provider + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" +) + +// WalterAIBuilder on X: Codex's subscription routed Until used up, two +// accounts. The first used up, magpie signed Codex in to the second, and +// signed it back in to the first once that had room again, while the +// gateway, routed Until used up, kept requests on the second as that +// routing says: Codex and the accounts list showed the first in use while +// the second's week was spent. Routed so, Codex's sign-in stays on the +// account it moved to till that is used up too, as the requests do; In +// order still signs it back in to the first. +func TestCodexDrainSignInStaysOnTheNext(t *testing.T) { + for _, c := range []struct { + routing string + back bool // signed back in to the first once it has room + }{ + {Drain, false}, + {Ordered, true}, + } { + t.Run(c.routing, func(t *testing.T) { + home := signIn(t) // me@example.com, acct-1 + rememberLogins(true) + codexSignIn(t, home, "spare@example.com", "r-spare") + rememberLogins(true) + codexSignIn(t, home, "me@example.com", "r-1") + rememberLogins(true) + used := map[string]float64{"acct-me@example.com": 100, "acct-spare@example.com": 20} + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + json.NewEncoder(w).Encode(map[string]any{"plan_type": "plus", "rate_limit": map[string]any{ + "primary_window": map[string]any{"used_percent": used[r.Header.Get("chatgpt-account-id")], "limit_window_seconds": 18000}}}) + })) + defer fake.Close() + old := CodexBase + CodexBase = fake.URL + "/backend-api/codex" + t.Cleanup(func() { CodexBase = old }) + switched := func() string { + t.Helper() + loginUsageCache.Lock() + loginUsageCache.m = nil + loginUsageCache.Unlock() + to, err := SwitchWhenSpent(context.Background(), "codex") + if err != nil { + t.Fatal(err) + } + return to + } + signedIn := func() string { + t.Helper() + var live codexAuth + readJSON(filepath.Join(home, ".codex", "auth.json"), &live) + return live.Tokens.RefreshToken + } + returns := func() bool { + for _, l := range Logins("codex") { + if l.Returns { + return true + } + } + return false + } + if err := SetLoginOn("codex", "spare@example.com", true); err != nil { + t.Fatal(err) + } + if err := SetRouting("codex", c.routing); err != nil { + t.Fatal(err) + } + // the first used up: on to the spare + if to := switched(); to != "spare@example.com" || signedIn() != "r-spare" { + t.Fatalf("switched to %q, Codex signed in with %q", to, signedIn()) + } + // the accounts list marks the first as the one gone back to + // only where magpie goes back to it + if returns() != c.back { + t.Fatalf("first marked to go back to: %v, want %v", returns(), c.back) + } + // the first has room again + used["acct-me@example.com"] = 10 + to := switched() + if c.back { + if !strings.HasPrefix(to, "me@example.com") || signedIn() != "r-1" { + t.Fatalf("In order: back to %q, Codex signed in with %q; want the first", to, signedIn()) + } + return + } + if to != "" || signedIn() != "r-spare" { + t.Fatalf("Until used up: moved off the spare to %q, Codex signed in with %q", to, signedIn()) + } + // the spare used up in turn: on to the first + used["acct-spare@example.com"] = 100 + if to := switched(); !strings.HasPrefix(to, "me@example.com") || signedIn() != "r-1" { + t.Fatalf("spare used up: on to %q, Codex signed in with %q", to, signedIn()) + } + }) + } +}