From 2f25728ddfc7dbaf287a18d9bbaf2e3b00ad1f86 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 17 Nov 2026 10:05:34 +0800 Subject: [PATCH] claude: Use switches Claude Code itself to a setup-token account (liukaybee on X) liukaybee adds Claude accounts with `claude setup-token` and wants magpie to switch only which one Claude Code itself uses, without connecting it to magpie. Such an account has no sign-in to put in Claude Code's keychain or .credentials.json, so Use was refused ("magpie only"). Claude Code takes CLAUDE_CODE_OAUTH_TOKEN from the env of its user settings.json ahead of its stored sign-in. Use on a setup-token account now writes the token there (claude_token_env.go). Claude Code's stored sign-in stays as it is and stays Active; the token account is listed with Uses. A switch to a signed-in account, Use on the signed-in row, or removing the token's account takes the token out again. - A value the user set is theirs: magpie keeps only the sha256 of what it wrote (claude-token-env.json), never writes over another value and never removes one whose hash differs, even if it once wrote it. - An unreadable settings.json is "unknown": nothing is written, the record is kept, and the switch fails without moving the sign-in. - NextLogin (Switch accounts only) leaves Claude Code on a token in use, as its allowance can't be read. - magpie's own runs pass --setting-sources "" and are unaffected. - GUI: the token row's Use and In use; the signed-in row says Signed in with a Use back. Every new string in zh, zh-TW, ja and de. - app.js +864 bytes over its budget, raised with the reason in core_budget_test.go: one swUse helper shared by both buttons, packed; renderAccounts draws every account row, so no page to move it to. Real use: real Claude Code 2.1.316 in a sandbox HOME/CLAUDE_CONFIG_DIR (never the live ~/.claude) with a deliberately broken .credentials.json access token. The settings.json magpie's switch writes (dumped from a test) gave a PONG with a real account's token; the file after switching back gave "401 OAuth access token is invalid", i.e. Claude Code was on its stored sign-in again. Sandbox homes holding real tokens deleted. Run (mote/mica, at f00e2059d rebased on 593517bf0, then this head): - Rebased on effdd1beb (internal/gui and internal/provider untouched since, but for this): TestCoreScriptBudget and the provider TestClaude*, NextLogin and Forget tests rerun at the pushed head, ok. - go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: ok. gofmt -l: clean. - go test ./... -timeout 45m on mote: 102 packages ok, internal/gui FAIL: TestCoreScriptBudget (fixed above, then green) and TestQuitKeepsTheMenuBarIconsPlace, killed at its 30s AppKit bar under load; passes alone in 1.1s here and on origin/main 00b2c11a6. Filed #6919. - GUI, both engines, every language, on mica: the 45 account, Claude, switch, sign-in and i18n files (1275 tests, 68 red). The same 9 red files on origin/main effdd1beb give 67 of the same reds (#5925, #6660, #6179, #6424, #6010, #5998, #5814, #6877). The one red only at this head, accounts-own-signin webkit zh (access-control on /api/autobackup) is #6038 and passes 20/20 alone. claude-setup-token: green in all 10 engine x language runs. Broken by hand, each red, then restored: the own-value check (TestClaudeOwnEnvTokenLeftAlone), clearing on an OAuth switch (TestClaudeCodeSwitchedToSetupToken, ...UnreadableSettings), clearing on Use back (Switched, InUseNotMovedOff), clearing on remove (TestClaudeSetupTokenRemovedLeavesSettings), the NextLogin guard (InUseNotMovedOff), unreadable settings read as empty (TestClaudeEnvTokenUnreadableSettings). Not tried: the whole GUI suite (both machines were running other sessions' full suites for hours); a magpie GUI build clicking Use against the real binary (the switch's file was checked instead); Windows and Linux Claude Code. --- docs/subsystems/providers-accounts.md | 2 +- internal/gui/assets/app.js | 18 +- internal/gui/assets/i18n.js | 24 +- internal/gui/core_budget_test.go | 4 +- .../gui/tests/claude-setup-token.test.cjs | 50 +++- internal/provider/claude_proxy_env.go | 3 +- internal/provider/claude_setup_token.go | 13 +- internal/provider/claude_setup_token_test.go | 5 +- internal/provider/claude_token_env.go | 228 +++++++++++++++ internal/provider/claude_token_env_test.go | 270 ++++++++++++++++++ internal/provider/codex_switch.go | 5 + internal/provider/logins.go | 77 ++++- 12 files changed, 662 insertions(+), 37 deletions(-) create mode 100644 internal/provider/claude_token_env.go create mode 100644 internal/provider/claude_token_env_test.go diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index e90968d45..94f22dbde 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -61,7 +61,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`). A line (or a JSON string) holding a setup-token (`sk-ant-oat…`, as `claude setup-token` prints it, bare, as `CLAUDE_CODE_OAUTH_TOKEN=…` or `export …`) is added as one by `AddClaudeSetupToken`, never taken for a refresh token (`bareImport`, `importSetupToken`, liukaybee on X); one magpie has is `exists`, an API key pasted there is refused, and in the ChatGPT import it is refused as Claude's, nothing sent (`TestImportClaudeSetupToken`). 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) | | Antigravity to agy | The withdrawn Antigravity plugin (`antigravity`) signed in with Antigravity's own Google OAuth client, the one `agy` signs in with, so its accounts move to Antigravity (local agy CLI) as they are (@tongzhenbao on X). `AgyMoveUsers` names the plugin's sign-ins (then the built-in's never moved) whose email agy-cli doesn't have, as `agyMove` in `/api/providers`; the line over the list (`agymove.js`, imported only when there are any) has Move and Not now. `MoveToAgy` (`provider/toagy`) installs agy-cli at `agyCLIMin` (0.1.68, whose `auth.import` takes them; from the plugins repo's dist branch while npm has none), agy when it is missing, and hands every sign-in to its import, which writes each into an agy home of its own and keeps it only once `agy models` runs with it; one agy refuses is said by name (`agyMoved`). The token goes only where it went (Google, through agy), and the old sign-ins are left where they are. `TestAgyMoveUsersAreTheOldPluginsNotInAgyCLI`, `TestMoveToAgyImportsTheOldSignIns`, `TestToAgyMovesAndSaysEachAccount`, `agy-move.test.cjs`. | [`agy_move.go`](../../internal/provider/agy_move.go), [`providers.go`](../../internal/gui/providers.go), [`agymove.js`](../../internal/gui/assets/agymove.js) | | Export to files | `ExportLogins` (ChatGPT, Claude) writes the saved accounts in the two formats `ImportLogins` reads (heyiwei5 and Rk1ngggg on X): Sub2API's `sub2api-data` (one file, `sub2apiAccount`: `platform` openai or anthropic, as Sub2API's `account_data.go` has it) or CLIProxyAPI's auth files (one an account, `cliproxyAuth`, named `-[-].json`), so a round trip into magpie, Sub2API or CLIProxyAPI works (`TestExportClaudeRoundTrip`, `TestExportCodexRoundTrip`). A CLIProxyAPI Claude file also carries `account_uuid` and `org_uuid`, which its own readers ignore and `loginEntry` keeps, so two seats of one email stay two accounts. The file holds live sign-ins: it is written 0600 and never over a file (`WriteExport`), no surface prints a token, and each says first (`ExportRisk`) that whoever has the file is signed in as the account, and that a ChatGPT refresh token renews in one place only, so the first tool to renew it signs the other out. An account with no refresh token (access-only, a setup-token) is skipped and named with why. The window's *Export accounts to a file…* row on a ChatGPT or Claude account list (`acctexport.js`, `POST /api/signin/export`) saves into Downloads (a folder of its own for CLIProxyAPI's) and shows the path; `magpie accounts export [...] [--format sub2api\|cliproxyapi] [--to ] [--yes]` asks first without `--yes`. | [`login_export.go`](../../internal/provider/login_export.go), [`accounts_cli.go`](../../internal/cli/accounts_cli.go), [`gui/providers.go`](../../internal/gui/providers.go), [`acctexport.js`](../../internal/gui/assets/acctexport.js) | -| 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) | +| 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. Nothing of it goes in Claude Code's keychain or `.credentials.json`: `addLogin`, `putClaudeLogin`, `SetKeepLoginAs` (`errClaudeTokenSwitch`), `NextLogin`'s spares and `signInToFirst` pass it over. Claude Code itself is switched to it by hand only (liukaybee on X, `claude_token_env.go`): its row's *Use* (`SwitchLogin`) writes the token as `env.CLAUDE_CODE_OAUTH_TOKEN` in Claude Code's user `settings.json`, which Claude Code takes over its stored sign-in, and keeps the token's sha256 in `claude-token-env.json`; the stored sign-in is left as it is, and stays the Active account the gateway and magpie's own runs use (they read no user settings: `--setting-sources ""`). `Login.Uses` marks the token Claude Code uses; the window says *In use* on it, and *Signed in* with a *Use* that switches back on the account signed in to. A switch to any signed-in account takes magpie's token out first (a `settings.json` that can't be read refuses the switch and keeps the record), and so does removing the token's account (`claudeTokenGone`). A value the user set there, or changed from magpie's, is theirs: never written over (`errClaudeOwnToken`) nor taken out. While the token is in use `NextLogin` moves Claude Code nowhere, as its allowance can't be read. Claude Code reads its env as it starts, so sessions started after the switch are on the new account. Tried with Claude Code 2.1.316 in a sandbox: a token there is used over a valid stored sign-in, and with it taken out the stored sign-in is used again. `TestClaudeCodeSwitchedToSetupToken`, `TestClaudeOwnEnvTokenLeftAlone`, `TestClaudeEnvTokenUnreadableSettings`, `TestClaudeSetupTokenRemovedLeavesSettings`, `TestClaudeSetupTokenInUseNotMovedOff`, `claude-setup-token.test.cjs`. | [`claude_setup_token.go`](../../internal/provider/claude_setup_token.go), [`claude_token_env.go`](../../internal/provider/claude_token_env.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 still failing over from a magpie before (#1385, until the next Sync takes it out) 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. Under the accounts of a Claude Code or Codex with more than one, the switch is a switch of its own, *Switch {agent}'s account automatically* (the `auto-switch` box in app.js; off is `KeepLogin`, posted to `provider/keeplogin`; before 11-11 a *Keep {agent} signed in to* tick that turned it off, which a user read as the switch gone). On, a line under it says what the switch does with that agent's sign-in (`SignInMovesOf`, `signInMoves` on its `/api/providers` row, `signInMovesLine`): 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 (`TestSignInMovesSaysWhatSwitchDoes`). Off, it names the account the agent stays on, with a pick of another (`keepLoginAs`). Switch-only always moves the sign-in, so the switch is held on there (sign-in-moves.test.cjs). Beside the switch, an ⓘ mark whose hover card (settingshints.js, the box a `.hint-row` with its `.hint` lines out of sight) says how the switch works and why it is the agent's own use of the account: the sign-in written where the agent keeps its own, as `/login` or `codex login` does; usage read by Claude Code's own `/usage` or where Codex's `/status` reads it; for Claude Code, every request still sent by Claude Code itself straight to Anthropic; and that sharing an account is against the vendor's terms. It promises nothing about bans (autoswitchtip.js, loaded when the switch is drawn). Only where the sign-in moves: `moves`, or `kept` without `routed`, which `SignInMovesOf` sets when Claude Code goes through the gateway, so turning the switch on would move its requests, not its sign-in. 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) | diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 6fbdc9ae8..3af6131cb 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -13566,9 +13566,13 @@ function renderAccounts(a, p) { const quota = loginUsageOf(a.agent); // signed out while spent, back once it has room (#408) const back = ls.find((l) => l.returns && !l.active); + // the setup-token Claude Code itself uses over its sign-in + const tokenUsed = ls.find((l) => l.uses); for (const l of ls) { const on = isOn(l); const row = el("div", "acc" + (on ? " in-use" : " off") + (l.user === justAdded ? " new" : "")); + // Use that switches Claude Code itself + const swUse = (title, b = el("button", "text", t("Use"))) => (b.title = title, b.onclick = () => (b.classList.add("busy"), accountAction("login/switch", { agent: a.agent, user: l.user }, t("{agent} now uses {user}", { agent: a.agentName, user: l.user }))), b); // its Remove, titled as given; true: the own account's, else the plain one const forgetOf = (title) => { const f = el("button", "text quiet", t("Remove")); @@ -13661,6 +13665,11 @@ function renderAccounts(a, p) { signed.title = t("{agent} is kept signed in to this account; requests through magpie go to the accounts in their order", { agent: a.agentName }); line.append(signed); if (on) line.append(makeFirst(l)); + } else if (l.active && tokenUsed) { + // its sign-in still, under the setup-token Claude Code uses over it + const signed = el("span", "using", l.paused ? t("Paused") : t("Signed in")); + signed.title = t("{agent} is signed in to this account, but uses {user}'s setup-token over it", { agent: a.agentName, user: tokenUsed.user }); + line.append(signed, swUse(t("Switch {agent} itself back to this account", { agent: a.agentName }))); } else if (l.active) { const using = el("span", "using", l.paused ? t("Paused") : back ? t("First for now") : several ? t("First") : t("In use")); if (back && !l.paused) using.title = t("{user} was nearly used up, so magpie signed {agent} in to this one; it goes back to {user} once that has room again", { user: back.user, agent: a.agentName }); @@ -13689,10 +13698,13 @@ function renderAccounts(a, p) { line.append(forget); if (l.user === firstUser) line.append(el("span", "using", t("First"))); else if (on) line.append(makeFirst(l)); + } else if (l.token && l.uses) { + const using = el("span", "using", t("In use")); + using.title = t("{agent} itself uses this setup-token, set in its settings.json", { agent: a.agentName }); + line.append(forget, using); } else if (l.token) { - const only = el("span", "using", t("magpie only")); - only.title = t("Added by a setup-token: requests through magpie use it; Claude Code itself can't be signed in to it"); - line.append(forget, only); + // Claude Code itself switched to it in its settings.json (liukaybee on X) + line.append(forget, swUse(t("Switch {agent} itself to this setup-token, in its settings.json; its own sign-in stays", { agent: a.agentName }))); } else if (l.accessOnly) { const only = el("span", "using", t("magpie only")); only.title = t("Kept access token only: requests through magpie use it until it expires; Codex itself isn't signed in to it, as Codex would renew it"); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index e29316534..832fb0eb8 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2487,7 +2487,11 @@ const I18N = { "Add an account by setup-token…": "用 setup-token 添加账号…", "Sign in on another computer…": "在另一台电脑上登录…", "magpie only": "仅 magpie", - "Added by a setup-token: requests through magpie use it; Claude Code itself can't be signed in to it": "由 setup-token 添加:经 magpie 的请求会使用它;Claude Code 本身无法登录到这个账号", + "{agent} is signed in to this account, but uses {user}'s setup-token over it": "{agent} 登录的是这个账号,但优先使用 {user} 的 setup-token", + "Switch {agent} itself back to this account": "把 {agent} 本身切回这个账号", + "{agent} now uses {user}": "{agent} 现在使用 {user}", + "{agent} itself uses this setup-token, set in its settings.json": "{agent} 本身正在使用这个 setup-token,写在它的 settings.json 里", + "Switch {agent} itself to this setup-token, in its settings.json; its own sign-in stays": "把 {agent} 本身切换到这个 setup-token(写入它的 settings.json);它原有的登录保持不变", "Bring in accounts exported from Antigravity Cockpit, Antigravity Manager or CLIProxyAPI": "导入从 Antigravity Cockpit、Antigravity Manager 或 CLIProxyAPI 导出的账号", "Import accounts from a file…": "从文件导入账号…", "Import {name} accounts": "导入 {name} 账号", @@ -7842,7 +7846,11 @@ const I18N = { "Add an account by setup-token…": "用 setup-token 新增帳號…", "Sign in on another computer…": "在另一台電腦上登入…", "magpie only": "僅 magpie", - "Added by a setup-token: requests through magpie use it; Claude Code itself can't be signed in to it": "由 setup-token 新增:經 magpie 的請求會使用它;Claude Code 本身無法登入到這個帳號", + "{agent} is signed in to this account, but uses {user}'s setup-token over it": "{agent} 登入的是這個帳號,但優先使用 {user} 的 setup-token", + "Switch {agent} itself back to this account": "把 {agent} 本身切回這個帳號", + "{agent} now uses {user}": "{agent} 現在使用 {user}", + "{agent} itself uses this setup-token, set in its settings.json": "{agent} 本身正在使用這個 setup-token,寫在它的 settings.json 裡", + "Switch {agent} itself to this setup-token, in its settings.json; its own sign-in stays": "把 {agent} 本身切換到這個 setup-token(寫入它的 settings.json);它原有的登入保持不變", "Bring in accounts exported from Antigravity Cockpit, Antigravity Manager or CLIProxyAPI": "匯入從 Antigravity Cockpit、Antigravity Manager 或 CLIProxyAPI 匯出的帳號", "Import accounts from a file…": "從檔案匯入帳號…", "Import {name} accounts": "匯入 {name} 帳號", @@ -13172,7 +13180,11 @@ const I18N = { "Add an account by setup-token…": "setup-token でアカウントを追加…", "Sign in on another computer…": "別のコンピュータでサインイン…", "magpie only": "magpie のみ", - "Added by a setup-token: requests through magpie use it; Claude Code itself can't be signed in to it": "setup-token で追加:magpie 経由のリクエストはこれを使いますが、Claude Code 自体をこのアカウントにサインインさせることはできません", + "{agent} is signed in to this account, but uses {user}'s setup-token over it": "{agent} はこのアカウントにサインインしていますが、{user} の setup-token を優先して使っています", + "Switch {agent} itself back to this account": "{agent} 自体をこのアカウントに戻します", + "{agent} now uses {user}": "{agent} は {user} を使うようになりました", + "{agent} itself uses this setup-token, set in its settings.json": "{agent} 自体がこの setup-token を使っています(settings.json に設定)", + "Switch {agent} itself to this setup-token, in its settings.json; its own sign-in stays": "{agent} 自体をこの setup-token に切り替えます(settings.json に設定)。元のサインインはそのままです", "Bring in accounts exported from Antigravity Cockpit, Antigravity Manager or CLIProxyAPI": "Antigravity Cockpit、Antigravity Manager、CLIProxyAPI からエクスポートしたアカウントを取り込みます", "Import accounts from a file…": "ファイルからアカウントをインポート…", "Import {name} accounts": "{name} アカウントをインポート", @@ -18533,7 +18545,11 @@ const I18N = { "Add an account by setup-token…": "Konto per setup-token hinzufügen…", "Sign in on another computer…": "Auf einem anderen Computer anmelden…", "magpie only": "Nur magpie", - "Added by a setup-token: requests through magpie use it; Claude Code itself can't be signed in to it": "Per setup-token hinzugefügt: Anfragen über magpie nutzen es; Claude Code selbst kann sich damit nicht anmelden", + "{agent} is signed in to this account, but uses {user}'s setup-token over it": "{agent} ist bei diesem Konto angemeldet, nutzt aber vorrangig das Setup-Token von {user}", + "Switch {agent} itself back to this account": "{agent} selbst wieder auf dieses Konto umstellen", + "{agent} now uses {user}": "{agent} nutzt jetzt {user}", + "{agent} itself uses this setup-token, set in its settings.json": "{agent} selbst nutzt dieses Setup-Token, eingetragen in seiner settings.json", + "Switch {agent} itself to this setup-token, in its settings.json; its own sign-in stays": "{agent} selbst auf dieses Setup-Token umstellen, in seiner settings.json; seine eigene Anmeldung bleibt", "Bring in accounts exported from Antigravity Cockpit, Antigravity Manager or CLIProxyAPI": "Konten übernehmen, die aus Antigravity Cockpit, Antigravity Manager oder CLIProxyAPI exportiert wurden", "Import accounts from a file…": "Konten aus Datei importieren…", "Import {name} accounts": "{name}-Konten importieren", diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index 0a1563bab..5a465070b 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -17,8 +17,8 @@ import ( // never what pays for a change (#5918); the history of each number is in // `git log -L` of this file. const ( - appScriptBudget = 1_087_447 // app.js: 1,080,614 at 8016205e3, with the 5,653 of room it had; +123 for a sidebar list folded from its page's row (hkwok06 on X), its chevron and fold in navicons.js, imported with the first list; +57 for each account of a provider's Usage card in a card of its own (normalcoder_ on X), past the 24 of room left; +17 for an allowance card's wallet line under its rings (apple_test_src on X), the one filter shared with its text line; +338 for the Daily update channel (fishmagic80 on X): its segment, its line under Update channel and the version row's two Up to date on Daily words, packed to the shortest form (one t() per choice); Settings › About and renderUpdate draw them on every window, so there is no page to move them to; +35 for Baidu Qianfan's Token Plan sign-in (yuushabu_buyinn on X, #5860): its field in qianfanplan.js, imported when such a provider's editor opens, drawn by renderStepPlan now told whose sign-in it brings, and what is left is the import and two quotaError lines, past the room there was; quotaError reads every card's error, so there is no page to move it to; +27 for Windows' title bar (258a14 on X): the caption buttons, their clicks, the bar's double click and what keeps them over a dialog in wincap.js, imported in Windows' window alone, the header's room for them in app.css, and what is left is the one line that imports it, past the 29 of room there was; that window's frame is drawn on every start, so there is no page to move it to; +107 for the pages in the reader's own order (chet030714 on X): the order, the sidebar and tab bar put in it, and the menu's drag and keys in navorder.js and navpages.js, imported once an order is kept or Settings draws, and what is left is the one line in navHides that imports it; navHides runs on every start, so there is no page to move it to; +275 for the grants Alibaba's Token Plan asks of a RAM user's AccessKey in the reader's language (MetalHqa on X): one string (ALI_RAM) shown under the editor's AccessKey ID and on the card that names them, less the 48 of the wrong "a RAM user that may use Model Studio is enough" it replaces; the editor and quotaError draw them on every window, so there is no page to move them to; +135 for a model test its vendor queued shown queued and not green (sufeng1894 on X): queuedSaid, one string shared by the chip's title, Test models' and Test this model's status, and the chip's amber dot; renderModels draws the provider editor's chips, so there is no page to move it to; +66 for AstrLink Guard's row saying an x64 magpie runs it under Windows on Arm's emulation until the next update installs the Arm build (EV_John_Liu on X), the Rosetta line's sibling, one line in pmSub; the Privacy rows draw it, so there is no page to move it to - coreScriptBudget = 1_271_726 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to; +168 for Discover's long lists drawn in part (the owner, 11-13), after the rest of its hook moved into plugingrid.js, imported when Plugins first draws; +296 for the cap toggle and Smart sentences that say what they do and the Sign in on another computer row (Wing8Aqua on X), packed to the shortest form, no page left to move them to; +333 for In turn's figure in a provider's editor and its words naming the message that goes round (Wing8Aqua on X), the figure itself in rotfig.js, imported when In turn is first shown, the hook packed to the shortest form; +236 for a lone capped Codex account's row saying its turns go to the fallbacks when Codex is connected (not_4O4 on X), the two helpers inlined, no page left to move it to; +717 for omp's advisor (Awad_Yoo on X, #6408): its three rows moved into ompadvisor.js, imported when an omp's settings show, and what is left is the import, the role's " · off" and the Settings line's name, packed to the shortest form; +468 for a plugin's own file import (auth.import) in the import sheet, in the plugin's words (marchen_cc on X), packed to one statement; importSay is read as the Providers rows draw, so it has no lazy page to go to, and nothing else was moved out; +180 for Claude Magpie's own Claude Code folder (xMopf7RF on X, #6459): its Advanced fold in claudemagpie.js, imported when it first shows, and what is left is the import and the fold's place in the Separate app line, 216 bytes packed to the shortest form, less the 36 of room there was; +81 for the Use Claude Magpie button on Claude Desktop's row (xMopf7RF on X), drawn by claudemagpie.js too, what is left the one line that places it (#2710); +225 for the Hermes row's Other profiles lines (Norethcy on X), which 1d60b165c took out while each profile had a row and c96f33d65 left with no place at all, packed to the shortest form; the dead hermes# Default note went with it, and the Agents rows draw it, so there is no page to move it to; +397 for a key's own price rate (tnt12231 on X): its lines, check and placeholder in keyrates.js, imported when a provider with two or more keys opens, and what is left is the import, the draft's copy, Advanced opening for it, the save's one line and proxyLines drawing another kind of line; +316 for an image or video model's chip saying what it makes from its right-click (iceloon on X): the chat chip's Makes… now shared with it, and the media chip's Copy model ID left out, packed to the shortest form; the provider's editor draws it, so there is no page to move it to; +67 for the Claude Code · Claude Magpie row saying it is on magpie through Claude Magpie (xMopf7RF on X), one line in connectLine with the shortest words that say it; the Agents rows draw it, so there is no page to move it to; +12 for AIGoCode's logo in pngIcons (MindfulReturn on X), the list every drawn icon is looked up in; +491 for each cost in the tray panel's and Requests' chart and ranking in its own provider's currency (onkashiko on X): ledProv and the provider passed through, packed to the shortest form; drawLedColumns and drawLedRank are shared by the panel, so there is no page to move it to; +326 for the Qwen AI platform's Token Plan sign-in (imthe99galaxy on X): its field, sign-in and wait in qianwenplan.js, imported when such a provider's editor opens, and what is left is the import and one quotaError line for its two refusals, packed to the shortest form; quotaError reads every card's error, so there is no page to move it to; +72 for Copy all keys (emilochen on X): its row in keyrates.js, imported when a provider with two or more keys opens through keyRateField, now told which of its parts to draw, and what is left is the one line that places it; +83 for the page saying it has gone from view, so what its Sessions and Usage pages keep goes in 30 s and not 7 minutes (P0 memory): folded into the visibilitychange listener every window has, packed to the shortest form, so there is no page to move it to; +270 for Providers' Select, to remove several at once (eiyuuzaki2333 on X): its rows, bar, removal and keys in pvpick.js, imported when Select is first clicked, and what is left is pvSel, the button's click and two lines in renderProviders, which draws the list, so there is no page to move it to; +81 for each account of a provider's Usage card in a card of its own (normalcoder_ on X): one line that makes the box, its brief look left to CSS, and renderQuotas, which draws every card, so there is no page to move it to; +17 for Kimi Code's booster balance under an allowance card's rings in the tray panel (apple_test_src on X): the card's text line and the wallet line share one filter, packed to the shortest form; panelQuotaCard draws every card, so there is no page to move it to; +51 for what a failed plugin install left in plugins/, listed under Installed with a Remove (CHENGJIAHEGOXIS on X): its section in plugininstalled.js as pmLeftovers, imported when Plugins first draws, and what is left is the one call after drawInstalled; draw is what draws the page, so there is no page to move it to; +123 for a sidebar list folded from its page's row (hkwok06 on X): the chevron, its click and the fold kept per page in navicons.js, imported with the first list, and what is left is the folded list read beside the hidden pages' (navList, which navMine now shares) and the two rows' clicks asking navFold first; navSubs draws every list, so there is no page to move it to; +338 for the Daily update channel (fishmagic80 on X): its segment, its line under Update channel and the version row's two Up to date on Daily words, packed to the shortest form (one t() per choice); Settings › About and renderUpdate draw them on every window, so there is no page to move them to; +35 for Baidu Qianfan's Token Plan sign-in (yuushabu_buyinn on X, #5860): its field in qianfanplan.js, imported when such a provider's editor opens, drawn by renderStepPlan now told whose sign-in it brings, and what is left is the import and two quotaError lines, past the room there was; quotaError reads every card's error, so there is no page to move it to; +27 for Windows' title bar (258a14 on X): the caption buttons, their clicks, the bar's double click and what keeps them over a dialog in wincap.js, imported in Windows' window alone, the header's room for them in app.css, and what is left is the one line that imports it, past the 29 of room there was; that window's frame is drawn on every start, so there is no page to move it to; +107 for the pages in the reader's own order (chet030714 on X): the order, the sidebar and tab bar put in it, and the menu's drag and keys in navorder.js and navpages.js, imported once an order is kept or Settings draws, and what is left is the one line in navHides that imports it; navHides runs on every start, so there is no page to move it to; +275 for the grants Alibaba's Token Plan asks of a RAM user's AccessKey in the reader's language (MetalHqa on X): one string (ALI_RAM) shown under the editor's AccessKey ID and on the card that names them, less the 48 of the wrong "a RAM user that may use Model Studio is enough" it replaces; the editor and quotaError draw them on every window, so there is no page to move them to; +135 for a model test its vendor queued shown queued and not green (sufeng1894 on X): queuedSaid, one string shared by the chip's title, Test models' and Test this model's status, and the chip's amber dot; renderModels draws the provider editor's chips, so there is no page to move it to; +66 for AstrLink Guard's row saying an x64 magpie runs it under Windows on Arm's emulation until the next update installs the Arm build (EV_John_Liu on X), the Rosetta line's sibling, one line in pmSub; the Privacy rows draw it, so there is no page to move it to; +189 for Let magpie set it on a Codex card locked by config.toml's own compact limit or background threshold (sufeng1894 on X), and Undo for a background share taken over: the shared send posts it, packed to the shortest form; adviceRow draws every card, so there is no page to move it to + appScriptBudget = 1_088_311 // app.js: 1,080,614 at 8016205e3, with the 5,653 of room it had; +123 for a sidebar list folded from its page's row (hkwok06 on X), its chevron and fold in navicons.js, imported with the first list; +57 for each account of a provider's Usage card in a card of its own (normalcoder_ on X), past the 24 of room left; +17 for an allowance card's wallet line under its rings (apple_test_src on X), the one filter shared with its text line; +338 for the Daily update channel (fishmagic80 on X): its segment, its line under Update channel and the version row's two Up to date on Daily words, packed to the shortest form (one t() per choice); Settings › About and renderUpdate draw them on every window, so there is no page to move them to; +35 for Baidu Qianfan's Token Plan sign-in (yuushabu_buyinn on X, #5860): its field in qianfanplan.js, imported when such a provider's editor opens, drawn by renderStepPlan now told whose sign-in it brings, and what is left is the import and two quotaError lines, past the room there was; quotaError reads every card's error, so there is no page to move it to; +27 for Windows' title bar (258a14 on X): the caption buttons, their clicks, the bar's double click and what keeps them over a dialog in wincap.js, imported in Windows' window alone, the header's room for them in app.css, and what is left is the one line that imports it, past the 29 of room there was; that window's frame is drawn on every start, so there is no page to move it to; +107 for the pages in the reader's own order (chet030714 on X): the order, the sidebar and tab bar put in it, and the menu's drag and keys in navorder.js and navpages.js, imported once an order is kept or Settings draws, and what is left is the one line in navHides that imports it; navHides runs on every start, so there is no page to move it to; +275 for the grants Alibaba's Token Plan asks of a RAM user's AccessKey in the reader's language (MetalHqa on X): one string (ALI_RAM) shown under the editor's AccessKey ID and on the card that names them, less the 48 of the wrong "a RAM user that may use Model Studio is enough" it replaces; the editor and quotaError draw them on every window, so there is no page to move them to; +135 for a model test its vendor queued shown queued and not green (sufeng1894 on X): queuedSaid, one string shared by the chip's title, Test models' and Test this model's status, and the chip's amber dot; renderModels draws the provider editor's chips, so there is no page to move it to; +66 for AstrLink Guard's row saying an x64 magpie runs it under Windows on Arm's emulation until the next update installs the Arm build (EV_John_Liu on X), the Rosetta line's sibling, one line in pmSub; the Privacy rows draw it, so there is no page to move it to; +864 for Use on a Claude setup-token account, which switches Claude Code itself to it in its settings.json, and Use back on its signed-in account (liukaybee on X): one swUse helper shared by both buttons, packed to the shortest form; renderAccounts draws every account row, so there is no page to move it to + coreScriptBudget = 1_272_590 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to; +168 for Discover's long lists drawn in part (the owner, 11-13), after the rest of its hook moved into plugingrid.js, imported when Plugins first draws; +296 for the cap toggle and Smart sentences that say what they do and the Sign in on another computer row (Wing8Aqua on X), packed to the shortest form, no page left to move them to; +333 for In turn's figure in a provider's editor and its words naming the message that goes round (Wing8Aqua on X), the figure itself in rotfig.js, imported when In turn is first shown, the hook packed to the shortest form; +236 for a lone capped Codex account's row saying its turns go to the fallbacks when Codex is connected (not_4O4 on X), the two helpers inlined, no page left to move it to; +717 for omp's advisor (Awad_Yoo on X, #6408): its three rows moved into ompadvisor.js, imported when an omp's settings show, and what is left is the import, the role's " · off" and the Settings line's name, packed to the shortest form; +468 for a plugin's own file import (auth.import) in the import sheet, in the plugin's words (marchen_cc on X), packed to one statement; importSay is read as the Providers rows draw, so it has no lazy page to go to, and nothing else was moved out; +180 for Claude Magpie's own Claude Code folder (xMopf7RF on X, #6459): its Advanced fold in claudemagpie.js, imported when it first shows, and what is left is the import and the fold's place in the Separate app line, 216 bytes packed to the shortest form, less the 36 of room there was; +81 for the Use Claude Magpie button on Claude Desktop's row (xMopf7RF on X), drawn by claudemagpie.js too, what is left the one line that places it (#2710); +225 for the Hermes row's Other profiles lines (Norethcy on X), which 1d60b165c took out while each profile had a row and c96f33d65 left with no place at all, packed to the shortest form; the dead hermes# Default note went with it, and the Agents rows draw it, so there is no page to move it to; +397 for a key's own price rate (tnt12231 on X): its lines, check and placeholder in keyrates.js, imported when a provider with two or more keys opens, and what is left is the import, the draft's copy, Advanced opening for it, the save's one line and proxyLines drawing another kind of line; +316 for an image or video model's chip saying what it makes from its right-click (iceloon on X): the chat chip's Makes… now shared with it, and the media chip's Copy model ID left out, packed to the shortest form; the provider's editor draws it, so there is no page to move it to; +67 for the Claude Code · Claude Magpie row saying it is on magpie through Claude Magpie (xMopf7RF on X), one line in connectLine with the shortest words that say it; the Agents rows draw it, so there is no page to move it to; +12 for AIGoCode's logo in pngIcons (MindfulReturn on X), the list every drawn icon is looked up in; +491 for each cost in the tray panel's and Requests' chart and ranking in its own provider's currency (onkashiko on X): ledProv and the provider passed through, packed to the shortest form; drawLedColumns and drawLedRank are shared by the panel, so there is no page to move it to; +326 for the Qwen AI platform's Token Plan sign-in (imthe99galaxy on X): its field, sign-in and wait in qianwenplan.js, imported when such a provider's editor opens, and what is left is the import and one quotaError line for its two refusals, packed to the shortest form; quotaError reads every card's error, so there is no page to move it to; +72 for Copy all keys (emilochen on X): its row in keyrates.js, imported when a provider with two or more keys opens through keyRateField, now told which of its parts to draw, and what is left is the one line that places it; +83 for the page saying it has gone from view, so what its Sessions and Usage pages keep goes in 30 s and not 7 minutes (P0 memory): folded into the visibilitychange listener every window has, packed to the shortest form, so there is no page to move it to; +270 for Providers' Select, to remove several at once (eiyuuzaki2333 on X): its rows, bar, removal and keys in pvpick.js, imported when Select is first clicked, and what is left is pvSel, the button's click and two lines in renderProviders, which draws the list, so there is no page to move it to; +81 for each account of a provider's Usage card in a card of its own (normalcoder_ on X): one line that makes the box, its brief look left to CSS, and renderQuotas, which draws every card, so there is no page to move it to; +17 for Kimi Code's booster balance under an allowance card's rings in the tray panel (apple_test_src on X): the card's text line and the wallet line share one filter, packed to the shortest form; panelQuotaCard draws every card, so there is no page to move it to; +51 for what a failed plugin install left in plugins/, listed under Installed with a Remove (CHENGJIAHEGOXIS on X): its section in plugininstalled.js as pmLeftovers, imported when Plugins first draws, and what is left is the one call after drawInstalled; draw is what draws the page, so there is no page to move it to; +123 for a sidebar list folded from its page's row (hkwok06 on X): the chevron, its click and the fold kept per page in navicons.js, imported with the first list, and what is left is the folded list read beside the hidden pages' (navList, which navMine now shares) and the two rows' clicks asking navFold first; navSubs draws every list, so there is no page to move it to; +338 for the Daily update channel (fishmagic80 on X): its segment, its line under Update channel and the version row's two Up to date on Daily words, packed to the shortest form (one t() per choice); Settings › About and renderUpdate draw them on every window, so there is no page to move them to; +35 for Baidu Qianfan's Token Plan sign-in (yuushabu_buyinn on X, #5860): its field in qianfanplan.js, imported when such a provider's editor opens, drawn by renderStepPlan now told whose sign-in it brings, and what is left is the import and two quotaError lines, past the room there was; quotaError reads every card's error, so there is no page to move it to; +27 for Windows' title bar (258a14 on X): the caption buttons, their clicks, the bar's double click and what keeps them over a dialog in wincap.js, imported in Windows' window alone, the header's room for them in app.css, and what is left is the one line that imports it, past the 29 of room there was; that window's frame is drawn on every start, so there is no page to move it to; +107 for the pages in the reader's own order (chet030714 on X): the order, the sidebar and tab bar put in it, and the menu's drag and keys in navorder.js and navpages.js, imported once an order is kept or Settings draws, and what is left is the one line in navHides that imports it; navHides runs on every start, so there is no page to move it to; +275 for the grants Alibaba's Token Plan asks of a RAM user's AccessKey in the reader's language (MetalHqa on X): one string (ALI_RAM) shown under the editor's AccessKey ID and on the card that names them, less the 48 of the wrong "a RAM user that may use Model Studio is enough" it replaces; the editor and quotaError draw them on every window, so there is no page to move them to; +135 for a model test its vendor queued shown queued and not green (sufeng1894 on X): queuedSaid, one string shared by the chip's title, Test models' and Test this model's status, and the chip's amber dot; renderModels draws the provider editor's chips, so there is no page to move it to; +66 for AstrLink Guard's row saying an x64 magpie runs it under Windows on Arm's emulation until the next update installs the Arm build (EV_John_Liu on X), the Rosetta line's sibling, one line in pmSub; the Privacy rows draw it, so there is no page to move it to; +189 for Let magpie set it on a Codex card locked by config.toml's own compact limit or background threshold (sufeng1894 on X), and Undo for a background share taken over: the shared send posts it, packed to the shortest form; adviceRow draws every card, so there is no page to move it to; +864 for Use on a Claude setup-token account, which switches Claude Code itself to it in its settings.json, and Use back on its signed-in account (liukaybee on X): one swUse helper shared by both buttons, packed to the shortest form; renderAccounts draws every account row, so there is no page to move it to ) // codeBytes is how many bytes of b are code: its blank lines, its lines diff --git a/internal/gui/tests/claude-setup-token.test.cjs b/internal/gui/tests/claude-setup-token.test.cjs index 84f20c292..aeaca9e3c 100644 --- a/internal/gui/tests/claude-setup-token.test.cjs +++ b/internal/gui/tests/claude-setup-token.test.cjs @@ -3,8 +3,9 @@ // "Use a setup-token instead…", which ends the browser sign-in and asks for // the token `claude setup-token` printed, said whole in the page's // language. A refused token says why and stays to be fixed; one taken is -// added. The account it makes is magpie's only: Remove and "magpie only", -// no Use or Make first. +// added. Its row's Use switches Claude Code itself to it (in its +// settings.json, liukaybee on X); in use, the signed-in account's Use +// switches back. // Chromium and WebKit, English, Chinese (both), Japanese and German, at // 420px; no backend, the API is faked here. const assert = require("node:assert/strict"); @@ -107,19 +108,44 @@ for (const engine of engines) for (const lang of ["en", "zh", "zh-TW", "ja", "de assert.deepEqual(await page.evaluate(() => window.signedInWith), [{ agent: "claude", user: "Claude setup-token 3204d0", token: true }]); assert.equal(await box.innerText().then((s) => s.includes(TOKEN)), false); - // its row is magpie's only - const row = await page.evaluate(() => { - const ls = [{ user: "pro@x.com", active: true, plan: "max" }, { user: "Claude setup-token 3204d0", on: true, token: true }]; + // its row's Use switches Claude Code itself to it (liukaybee on X) + const rowsOf = (uses) => page.evaluate((uses) => { + document.getElementById("accts-under-test")?.remove(); + const ls = [{ user: "pro@x.com", active: true, plan: "max" }, { user: "Claude setup-token 3204d0", on: true, token: true, uses }]; const a = { agent: "claude", agentName: "Claude Code", logins: ls }; const list = renderAccounts(a, { id: "claude", account: { agent: "claude", user: "pro@x.com" } }); + list.id = "accts-under-test"; document.body.append(list); - const rows = [...list.querySelectorAll("*")].filter((e) => e.textContent.includes("Claude setup-token 3204d0") && !e.textContent.includes("pro@x.com") && e.querySelector("button")); - const r = rows[0]; - return r ? { text: r.innerText, buttons: [...r.querySelectorAll("button")].map((b) => b.textContent) } : null; - }).catch((e) => ({ error: e.message })); - assert.ok(row && !row.error, JSON.stringify(row)); - assert.ok(row.text.includes(await translated("magpie only")), row.text); - assert.ok(!row.buttons.includes(await said("Make first")) && !row.buttons.includes(await said("Use")), row.buttons.join(",")); + const of = (u) => { + const r = list.querySelector(`[data-account-id="${u}"] .acc-line`); + return { text: r.innerText, buttons: [...r.querySelectorAll("button.text")].map((b) => ({ text: b.textContent, title: b.title })), spans: [...r.querySelectorAll(".using")].map((x) => ({ text: x.textContent, title: x.title })) }; + }; + return { pro: of("pro@x.com"), tok: of("Claude setup-token 3204d0") }; + }, uses); + const use = await said("Use"); + let rows = await rowsOf(false); + const tokUse = rows.tok.buttons.find((b) => b.text === use); + assert.ok(tokUse, JSON.stringify(rows.tok)); + assert.equal(tokUse.title, await translated("Switch {agent} itself to this setup-token, in its settings.json; its own sign-in stays", { agent: "Claude Code" })); + assert.ok(!rows.tok.text.includes(await said("magpie only")), rows.tok.text); + assert.ok(!rows.pro.buttons.some((b) => b.text === use), JSON.stringify(rows.pro)); + const posted = page.waitForRequest((r) => new URL(r.url()).pathname === "/api/login/switch"); + await page.locator('#accts-under-test [data-account-id="Claude setup-token 3204d0"] button.text', { hasText: use }).click(); + assert.deepEqual((await posted).postDataJSON(), { agent: "claude", user: "Claude setup-token 3204d0" }); + + // in use: said on it, and the signed-in account's Use switches back + rows = await rowsOf(true); + assert.deepEqual(rows.tok.spans.map((x) => x.text), [await said("In use")]); + assert.equal(rows.tok.spans[0].title, await translated("{agent} itself uses this setup-token, set in its settings.json", { agent: "Claude Code" })); + assert.ok(!rows.tok.buttons.some((b) => b.text === use), JSON.stringify(rows.tok)); + assert.deepEqual(rows.pro.spans.map((x) => x.text), [await said("Signed in")]); + assert.equal(rows.pro.spans[0].title, await translated("{agent} is signed in to this account, but uses {user}'s setup-token over it", { agent: "Claude Code", user: "Claude setup-token 3204d0" })); + const back = rows.pro.buttons.find((b) => b.text === use); + assert.ok(back, JSON.stringify(rows.pro)); + assert.equal(back.title, await translated("Switch {agent} itself back to this account", { agent: "Claude Code" })); + await translated("{agent} now uses {user}", { agent: "Claude Code", user: "pro@x.com" }); + const w2 = await page.evaluate(() => Math.max(...[...document.querySelectorAll("#accts-under-test *")].map((e) => e.getBoundingClientRect().right))); + assert.ok(w2 <= 420, `accounts reach ${w2}px`); assert.deepEqual(errors, []); }); } diff --git a/internal/provider/claude_proxy_env.go b/internal/provider/claude_proxy_env.go index 63faf6f64..00b784bfc 100644 --- a/internal/provider/claude_proxy_env.go +++ b/internal/provider/claude_proxy_env.go @@ -240,7 +240,8 @@ func syncClaudeProxyEnvNow() { } user := "" for _, l := range Logins("claude") { - if l.Active { + if l.Active && user == "" || l.Uses { + // the setup-token it uses over its sign-in, if any user = l.User } } diff --git a/internal/provider/claude_setup_token.go b/internal/provider/claude_setup_token.go index 1d90bf471..de779ecd6 100644 --- a/internal/provider/claude_setup_token.go +++ b/internal/provider/claude_setup_token.go @@ -11,8 +11,9 @@ package provider // "oauth_token" and no more), and its /usage shows the API cost view, not // the subscription's windows. The account is named by the token's own // short hash, and its allowance is unknown (errClaudeSetupToken) until a -// reply's rate-limit headers tell it. Claude Code itself can't be signed in -// to it: there is nothing to put in its keychain or .credentials.json. +// reply's rate-limit headers tell it. There is nothing to put in Claude +// Code's keychain or .credentials.json for it: Claude Code itself is +// switched to it through its settings.json (claude_token_env.go). import ( "crypto/sha256" @@ -65,9 +66,11 @@ func claudeTokenName(token string) string { // zero. Its words must not read as a refusal (claudeUsageDenied). var errClaudeSetupToken = errors.New("unknown: a setup-token can't read the allowance (Claude Code's /usage needs a full sign-in); it shows once a reply tells it") -// errClaudeTokenSwitch is the answer to signing Claude Code in to a -// setup-token account. -const errClaudeTokenSwitch = "%s was added by a setup-token: magpie's requests use it, but Claude Code itself can't be signed in to it" +// errClaudeTokenSwitch is the answer to keeping Claude Code signed in to a +// setup-token account (SetKeepLoginAs), or to putting one in its sign-in +// store: Claude Code is switched to it in its settings.json alone +// (claude_token_env.go), when the user picks it. +const errClaudeTokenSwitch = "%s was added by a setup-token: Use switches Claude Code itself to it, but magpie can't keep Claude Code on it, as it can't read its allowance" // checkClaudeSetupToken is token trimmed, or why it isn't a setup-token. func checkClaudeSetupToken(token string) (string, error) { diff --git a/internal/provider/claude_setup_token_test.go b/internal/provider/claude_setup_token_test.go index 1dad56d55..5a472f32f 100644 --- a/internal/provider/claude_setup_token_test.go +++ b/internal/provider/claude_setup_token_test.go @@ -87,8 +87,9 @@ func TestClaudeSetupTokenAccount(t *testing.T) { t.Fatal("Claude Code's own run was given the token") } - // Claude Code can't be signed in to it - if err := SwitchLogin("claude", user); err == nil || !strings.Contains(err.Error(), "setup-token") { + // Claude Code's own sign-in isn't written with it: a switch to it + // goes in settings.json (claude_token_env_test.go) + if err := SwitchLogin("claude", user); err != nil { t.Fatalf("switch onto a setup-token account: %v", err) } if after, _ := os.ReadFile(cred); string(after) != string(before) { diff --git a/internal/provider/claude_token_env.go b/internal/provider/claude_token_env.go new file mode 100644 index 000000000..37fa265ab --- /dev/null +++ b/internal/provider/claude_token_env.go @@ -0,0 +1,228 @@ +package provider + +// Claude Code itself on an account added by a setup-token (liukaybee on X). +// There is no sign-in to put in Claude Code's keychain or +// .credentials.json for such an account, but Claude Code takes the token +// in CLAUDE_CODE_OAUTH_TOKEN, and reads that from the env of its user +// settings.json too, ahead of its stored sign-in (its docs' authentication +// order; tried with Claude Code 2.1.316: a token there is used over a +// valid stored sign-in, and with it taken out the stored sign-in is used +// again). So a switch to such an account writes the token there, and a +// switch to a signed-in account takes it out again. +// +// Claude Code's stored sign-in is left as it is meanwhile: it is still +// the account magpie's own runs of Claude Code are on, since those read +// no settings of the user's (--setting-sources ""), and the account +// Logins calls Active. A setup-token in use is said beside it (Login.Uses). +// +// A token the user set there is theirs: magpie writes none over it and +// never takes it out. magpie keeps the hash of the token it wrote +// (claude-token-env.json), and the value counts as its own only while it +// still has that hash. Claude Code reads its env as it starts, so it is +// the sessions started after a switch that are on the new account. + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "sync" + + "github.com/tidwall/gjson" + "github.com/tidwall/jsonc" + "github.com/yetone/magpie/internal/edit" +) + +const claudeTokenEnvKey = "CLAUDE_CODE_OAUTH_TOKEN" + +var claudeTokenEnvMu sync.Mutex + +func claudeTokenRecordPath() string { + return filepath.Join(filepath.Dir(Path()), "claude-token-env.json") +} + +// claudeTokenRecord is what magpie last wrote to Claude Code's env: the +// token's hash, never the token. +type claudeTokenRecord struct { + Hash string `json:"hash"` +} + +func claudeTokenHash(token string) string { + sum := sha256.Sum256([]byte(token)) + return hex.EncodeToString(sum[:]) +} + +// readClaudeTokenRecord is the hash magpie wrote, "" for none. One that +// can't be read is an error, never "nothing written": that would make +// magpie's own token look like the user's for good. +func readClaudeTokenRecord() (string, error) { + b, err := os.ReadFile(claudeTokenRecordPath()) + if errors.Is(err, os.ErrNotExist) { + return "", nil + } + if err != nil { + return "", err + } + var r claudeTokenRecord + if err := json.Unmarshal(b, &r); err != nil { + return "", fmt.Errorf("%s: %w", claudeTokenRecordPath(), err) + } + return r.Hash, nil +} + +func writeClaudeTokenRecord(hash string) error { + if hash == "" { + if err := os.Remove(claudeTokenRecordPath()); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + return nil + } + b, err := json.MarshalIndent(claudeTokenRecord{Hash: hash}, "", " ") + if err != nil { + return err + } + return writePrivate(claudeTokenRecordPath(), append(b, '\n')) +} + +// claudeEnvToken is CLAUDE_CODE_OAUTH_TOKEN in the env of Claude Code's +// settings.json, and whether it is set there. A file that can't be read +// is an error: what it holds is unknown. +func claudeEnvToken() (string, bool, error) { + path := claudeSettingsFile() + raw, err := edit.Read(path) + if err != nil { + return "", false, err + } + if len(bytes.TrimSpace(raw)) == 0 { + return "", false, nil + } + stripped := jsonc.ToJSON(raw) + if !json.Valid(stripped) { + return "", false, fmt.Errorf("%s can't be read", path) + } + v := gjson.GetBytes(stripped, "env."+claudeTokenEnvKey) + return v.String(), v.Exists(), nil +} + +// claudeTokenInUse is the setup-token magpie has Claude Code use, "" +// when there is none of magpie's in its settings.json (none, the user's +// own, or one that can't be read). +func claudeTokenInUse() string { + claudeTokenEnvMu.Lock() + defer claudeTokenEnvMu.Unlock() + return claudeTokenOursLocked() +} + +func claudeTokenOursLocked() string { + hash, err := readClaudeTokenRecord() + if err != nil || hash == "" { + return "" + } + v, ok, err := claudeEnvToken() + if err != nil || !ok || v == "" || claudeTokenHash(v) != hash { + return "" + } + return v +} + +// ClaudeTokenUser is the saved setup-token account Claude Code itself +// uses now (magpie's token in its settings.json), "" for none. +func ClaudeTokenUser() string { + tok := claudeTokenInUse() + if tok == "" { + return "" + } + loginsMu.Lock() + defer loginsMu.Unlock() + return claudeTokenUserIn(readLogins(), tok) +} + +func claudeTokenUserIn(ls []savedLogin, tok string) string { + if tok == "" { + return "" + } + for _, l := range ls { + if l.Agent == "claude" && claudeSetupToken(l.Auth) == tok { + return l.User + } + } + return "" +} + +// errClaudeOwnToken: the user set CLAUDE_CODE_OAUTH_TOKEN in Claude +// Code's settings.json themselves. +const errClaudeOwnToken = "Claude Code's %s sets CLAUDE_CODE_OAUTH_TOKEN of your own, which Claude Code uses over any account magpie switches it to; magpie leaves it as it is. Take it out there to switch Claude Code here." + +// setClaudeEnvToken has Claude Code use token (setClaudeEnvToken("") +// takes magpie's out again), leaving a value the user set alone: putting +// one in over it is an error, taking magpie's out leaves it. +func setClaudeEnvToken(token string) error { + claudeTokenEnvMu.Lock() + defer claudeTokenEnvMu.Unlock() + return setClaudeEnvTokenLocked(token) +} + +func setClaudeEnvTokenLocked(token string) error { + hash, err := readClaudeTokenRecord() + if err != nil { + return err + } + if token == "" && hash == "" { + return nil // nothing of magpie's there, nor to be + } + path := claudeSettingsFile() + cur, has, err := claudeEnvToken() + if err != nil { + if token == "" { + // what it holds is unknown: magpie's token may be there yet, + // and the record is kept to take it out once it can be read + return err + } + return fmt.Errorf("%w; Claude Code is left on the account it is on", err) + } + ours := has && hash != "" && claudeTokenHash(cur) == hash + if token == "" { + if ours { + if err := edit.DelJSON(path, "env."+claudeTokenEnvKey); err != nil { + return err + } + } + return writeClaudeTokenRecord("") + } + if has && !ours && cur != "" { + return fmt.Errorf(errClaudeOwnToken, path) + } + // what is about to be written is kept first: a crash between the two + // then leaves a record of a value that isn't there, never a value of + // magpie's that looks like the user's + if err := writeClaudeTokenRecord(claudeTokenHash(token)); err != nil { + return err + } + if has && cur == token { + return nil + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + return edit.SetJSON(path, edit.KV{Path: "env." + claudeTokenEnvKey, Value: token}) +} + +// claudeTokenGone takes magpie's token for the removed account l out of +// Claude Code's settings.json, so Claude Code goes back to its own +// sign-in; another account's, or the user's own, stays. +func claudeTokenGone(l savedLogin) error { + tok := claudeSetupToken(l.Auth) + if tok == "" || l.Agent != "claude" { + return nil + } + claudeTokenEnvMu.Lock() + defer claudeTokenEnvMu.Unlock() + if claudeTokenOursLocked() != tok { + return nil + } + return setClaudeEnvTokenLocked("") +} diff --git a/internal/provider/claude_token_env_test.go b/internal/provider/claude_token_env_test.go new file mode 100644 index 000000000..a03b9a9c4 --- /dev/null +++ b/internal/provider/claude_token_env_test.go @@ -0,0 +1,270 @@ +package provider + +import ( + "context" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + + "github.com/tidwall/gjson" +) + +// envTokenOf is CLAUDE_CODE_OAUTH_TOKEN in Claude Code's settings.json. +func envTokenOf(t *testing.T) (string, bool) { + t.Helper() + b, err := os.ReadFile(claudeSettingsFile()) + if os.IsNotExist(err) { + return "", false + } + if err != nil { + t.Fatal(err) + } + v := gjson.GetBytes(b, "env."+claudeTokenEnvKey) + return v.String(), v.Exists() +} + +func claudeLoginOf(t *testing.T, user string) Login { + t.Helper() + for _, l := range Logins("claude") { + if l.User == user { + return l + } + } + t.Fatalf("%q isn't listed: %+v", user, Logins("claude")) + return Login{} +} + +// liukaybee on X: accounts added by `claude setup-token`, and Claude Code +// itself switched among them, never connected to magpie. Use on such an +// account puts its token in Claude Code's settings.json env, which Claude +// Code takes over its stored sign-in; that sign-in is left as it is, and a +// switch to a signed-in account takes the token out again. +func TestClaudeCodeSwitchedToSetupToken(t *testing.T) { + claudeThree(t) // Claude Code on the Pro, the Team and Max saved + pro, team := "pro@x.com", "team@x.com · Acme" + cred := claudeSettingsFile() + cred = filepath.Join(filepath.Dir(cred), ".credentials.json") + before, err := os.ReadFile(cred) + if err != nil { + t.Fatal(err) + } + // the user's own env stays beside magpie's token + writeFile(t, claudeSettingsFile(), map[string]any{"env": map[string]any{"FOO": "bar"}, "model": "opus"}) + tok, err := AddClaudeSetupToken(testSetupToken) + if err != nil { + t.Fatal(err) + } + + if err := SwitchLogin("claude", tok); err != nil { + t.Fatal(err) + } + if v, _ := envTokenOf(t); v != testSetupToken { + t.Fatalf("settings.json's %s = %q, want the setup-token", claudeTokenEnvKey, v) + } + if after, _ := os.ReadFile(cred); string(after) != string(before) { + t.Fatal("a switch to a setup-token wrote Claude Code's stored sign-in") + } + b, _ := os.ReadFile(claudeSettingsFile()) + if gjson.GetBytes(b, "env.FOO").String() != "bar" || gjson.GetBytes(b, "model").String() != "opus" { + t.Fatalf("the user's settings were lost: %s", b) + } + if b, _ := os.ReadFile(claudeTokenRecordPath()); strings.Contains(string(b), testSetupToken) { + t.Fatal("the record keeps the token, not its hash") + } + if l := claudeLoginOf(t, tok); !l.Uses || l.Active { + t.Fatalf("setup-token listed as %+v, want Uses and not Active", l) + } + if l := claudeLoginOf(t, pro); !l.Active || l.Uses { + t.Fatalf("Claude Code's sign-in listed as %+v, want Active", l) + } + if err := SwitchLogin("claude", tok); err != nil { // again: nothing to do + t.Fatal(err) + } + + // back to the account it is signed in to: the token goes + if err := SwitchLogin("claude", pro); err != nil { + t.Fatal(err) + } + if _, has := envTokenOf(t); has { + t.Fatal("a switch back to the sign-in left the setup-token in settings.json") + } + if _, err := os.Stat(claudeTokenRecordPath()); !os.IsNotExist(err) { + t.Fatalf("the record stayed: %v", err) + } + if b, _ := os.ReadFile(claudeSettingsFile()); gjson.GetBytes(b, "env.FOO").String() != "bar" { + t.Fatalf("the user's env was lost: %s", b) + } + if l := claudeLoginOf(t, tok); l.Uses { + t.Fatal("still listed as used") + } + + // to another signed-in account: that one's sign-in, and the token goes + if err := SwitchLogin("claude", tok); err != nil { + t.Fatal(err) + } + if err := SwitchLogin("claude", team); err != nil { + t.Fatal(err) + } + if _, has := envTokenOf(t); has { + t.Fatal("a switch to another account left the setup-token in settings.json") + } + if l := claudeLoginOf(t, team); !l.Active { + t.Fatalf("%s listed as %+v, want Active", team, l) + } +} + +// A CLAUDE_CODE_OAUTH_TOKEN the user set in settings.json themselves is +// theirs: magpie writes none over it, and takes it out on no switch. +func TestClaudeOwnEnvTokenLeftAlone(t *testing.T) { + claudeThree(t) + team := "team@x.com · Acme" + writeFile(t, claudeSettingsFile(), map[string]any{"env": map[string]any{claudeTokenEnvKey: "sk-ant-oat01-users-own"}}) + tok, err := AddClaudeSetupToken(testSetupToken) + if err != nil { + t.Fatal(err) + } + if err := SwitchLogin("claude", tok); err == nil || !strings.Contains(err.Error(), "of your own") { + t.Fatalf("switch over the user's own token: %v", err) + } + if err := SwitchLogin("claude", team); err != nil { + t.Fatal(err) + } + if v, _ := envTokenOf(t); v != "sk-ant-oat01-users-own" { + t.Fatalf("the user's own token became %q", v) + } + if claudeLoginOf(t, tok).Uses { + t.Fatal("the user's own token was taken for magpie's") + } + + // magpie's, then changed by the user: theirs from then on + writeFile(t, claudeSettingsFile(), map[string]any{}) + if err := SwitchLogin("claude", tok); err != nil { + t.Fatal(err) + } + writeFile(t, claudeSettingsFile(), map[string]any{"env": map[string]any{claudeTokenEnvKey: "sk-ant-oat01-users-later"}}) + if err := SwitchLogin("claude", "max@x.com"); err != nil { + t.Fatal(err) + } + if v, _ := envTokenOf(t); v != "sk-ant-oat01-users-later" { + t.Fatalf("the user's later token became %q", v) + } +} + +// A settings.json that can't be read holds what it holds: no token is +// written into it, and the record of magpie's stays until it can be read. +func TestClaudeEnvTokenUnreadableSettings(t *testing.T) { + claudeThree(t) + tok, err := AddClaudeSetupToken(testSetupToken) + if err != nil { + t.Fatal(err) + } + if err := SwitchLogin("claude", tok); err != nil { + t.Fatal(err) + } + broken := []byte(`{"env": {"` + claudeTokenEnvKey + `": "` + testSetupToken + `",`) + if err := os.WriteFile(claudeSettingsFile(), broken, 0o600); err != nil { + t.Fatal(err) + } + if err := SwitchLogin("claude", "team@x.com · Acme"); err == nil { + t.Fatal("a switch past an unreadable settings.json said it took the token out") + } + if b, _ := os.ReadFile(claudeSettingsFile()); string(b) != string(broken) { + t.Fatalf("an unreadable settings.json was written: %s", b) + } + if claudeLoginOf(t, "team@x.com · Acme").Active { + t.Fatal("Claude Code's sign-in was switched under a token that couldn't be taken out") + } + if _, err := os.Stat(claudeTokenRecordPath()); err != nil { + t.Fatalf("the record went with the token still there: %v", err) + } + // readable again: the token goes on the next switch + writeFile(t, claudeSettingsFile(), map[string]any{"env": map[string]any{claudeTokenEnvKey: testSetupToken}}) + if err := SwitchLogin("claude", "team@x.com · Acme"); err != nil { + t.Fatal(err) + } + if _, has := envTokenOf(t); has { + t.Fatal("the token stayed") + } +} + +// Removing the setup-token Claude Code uses takes it out of settings.json: +// Claude Code is on its own sign-in again. +func TestClaudeSetupTokenRemovedLeavesSettings(t *testing.T) { + claudeThree(t) + tok, err := AddClaudeSetupToken(testSetupToken) + if err != nil { + t.Fatal(err) + } + if err := SwitchLogin("claude", tok); err != nil { + t.Fatal(err) + } + if err := ForgetLogin("claude", tok); err != nil { + t.Fatal(err) + } + if _, has := envTokenOf(t); has { + t.Fatal("a removed account's token stayed in settings.json") + } + if _, err := os.Stat(claudeTokenRecordPath()); !os.IsNotExist(err) { + t.Fatalf("the record stayed: %v", err) + } +} + +// Claude Code on a setup-token the user picked is left there by magpie's +// own switching (Switch accounts only), whose allowance it can't read: +// the spent sign-in under it is no reason to move. +func TestClaudeSetupTokenInUseNotMovedOff(t *testing.T) { + claudeThree(t) // pro@x.com signed in; team and max saved + var text atomic.Value + text.Store("Current session: 100% used") + fakeClaudeUsage(t, &text, nil) + forget := func() { + lastQuotas.Lock() + lastQuotas.m, lastQuotas.loaded = nil, false + lastQuotas.Unlock() + loginUsageCache.Lock() + loginUsageCache.m = nil + loginUsageCache.Unlock() + } + forget() + t.Cleanup(forget) + if err := SetSwitchOnly("claude", true); err != nil { + t.Fatal(err) + } + for _, l := range Logins("claude") { + if !l.Active { + if err := SetLoginOn("claude", l.User, true); err != nil { + t.Fatal(err) + } + } + } + UsageClaudeVia(func(_ context.Context, dir string) (string, error) { + if dir == "" { + return "Current session: 100% used", nil + } + return "Current session: 10% used", nil + }) + tok, err := AddClaudeSetupToken(testSetupToken) + if err != nil { + t.Fatal(err) + } + if err := SwitchLogin("claude", tok); err != nil { + t.Fatal(err) + } + forget() + if _, to, _, ok := NextLogin(context.Background(), "claude"); ok || to != "" { + t.Fatalf("NextLogin moved Claude Code off the setup-token to %q", to) + } + if v, _ := envTokenOf(t); v != testSetupToken { + t.Fatalf("settings.json's token became %q", v) + } + // back on its sign-in, magpie moves it as before + if err := SwitchLogin("claude", "pro@x.com"); err != nil { + t.Fatal(err) + } + forget() + if _, to, _, ok := NextLogin(context.Background(), "claude"); !ok || to == "" { + t.Fatalf("NextLogin no longer moves the spent sign-in: %q ok=%v", to, ok) + } +} diff --git a/internal/provider/codex_switch.go b/internal/provider/codex_switch.go index 505eeee4d..05cfb680c 100644 --- a/internal/provider/codex_switch.go +++ b/internal/provider/codex_switch.go @@ -285,6 +285,11 @@ func NextLogin(ctx context.Context, agent string) (from, to string, back, ok boo if leftAlone(agent) { return "", "", false, false // magpie has no say in its sign-in, or was told to leave it be } + if agent == "claude" && claudeTokenInUse() != "" { + // on a setup-token the user switched it to, whose allowance can't + // be read: it stays there till they switch it again + return "", "", false, false + } var spares []Login var first *Login ls := Logins(agent) diff --git a/internal/provider/logins.go b/internal/provider/logins.go index 19b883ed7..085a9d8e8 100644 --- a/internal/provider/logins.go +++ b/internal/provider/logins.go @@ -64,8 +64,13 @@ type Login struct { // spent, and signs it back in to once it has room again (#408). Returns bool `json:"returns,omitempty"` // Token is a Claude account added by a setup-token: magpie's - // requests use it, Claude Code itself can't be signed in to it. + // requests use it, and Claude Code itself only through its + // settings.json (Uses). Token bool `json:"token,omitempty"` + // Uses is the setup-token account Claude Code itself uses now, its + // token put in its settings.json by magpie (claude_token_env.go). The + // account Claude Code's stored sign-in is (Active) stays as it is. + Uses bool `json:"uses,omitempty"` // AccessOnly is a ChatGPT account kept access token only // (codex_access_only.go): magpie never renews its sign-in, nor signs // Codex in to it. @@ -1242,6 +1247,10 @@ func loginsNow(agent string) []Login { active["claude"] = u } } + tokenUser := "" + if agent == "" || agent == "claude" { + tokenUser = claudeTokenUserIn(ls, claudeTokenInUse()) + } standIn := "" if _, ok := active["claude"]; !ok { // the one the provider is listed on (claudeStandInAccount), a @@ -1283,6 +1292,7 @@ func loginsNow(agent string) []Login { if l.Agent == "claude" { lg.Lapsed = claudeSignedOut(l) lg.Token = claudeSetupToken(l.Auth) != "" + lg.Uses = lg.Token && strings.EqualFold(tokenUser, l.User) } else { // the one in use too, its sign-in revoked (#1793) lg.Lapsed = revokedLapse(l) @@ -1508,8 +1518,34 @@ func switchSavedLogin(agent, user string) (from string, _ error) { // whichever refreshed first would sign the other out return "", fmt.Errorf("%s is signed in to Codex in %s: run Codex there (CODEX_HOME=%s codex) to use it, or turn it on for magpie's requests", target.User, home, home) } - if agent == "claude" && claudeSetupToken(target.Auth) != "" { - return "", fmt.Errorf(errClaudeTokenSwitch, target.User) + // the setup-token account Claude Code itself uses now, if magpie has + // it use one (claude_token_env.go): its stored sign-in is then not + // the one it is on + tokenFrom := "" + if agent == "claude" { + tokenFrom = claudeTokenUserIn(ls, claudeTokenInUse()) + } + if tok := claudeSetupToken(target.Auth); agent == "claude" && tok != "" { + // no sign-in to put in its store: Claude Code is given the token + // in its settings.json's env, over its stored sign-in, which stays + if why := claudeSignedOut(*target); why != "" { + return "", fmt.Errorf("%s: %s", target.User, why) + } + if strings.EqualFold(tokenFrom, target.User) { + return "", nil + } + from = tokenFrom + if from == "" { + if live, ok := liveLogin(agent); ok { + from = live.User + } + } + if err := setClaudeEnvToken(tok); err != nil { + return "", err + } + loginsSeenAt.Store(0) + forgetAccountCaches() + return from, nil } if agent == "codex" && target.AccessOnly { return "", fmt.Errorf(errCodexAccessOnlySwitch, target.User) @@ -1551,7 +1587,17 @@ func switchSavedLogin(agent, user string) (from string, _ error) { } if live, ok := liveLogin(agent); ok { if strings.EqualFold(live.User, want.User) { - return "", nil + if tokenFrom == "" { + return "", nil + } + // signed in to it still: the setup-token goes, and Claude + // Code is on its sign-in again + if err := setClaudeEnvToken(""); err != nil { + return "", err + } + loginsSeenAt.Store(0) + forgetAccountCaches() + return tokenFrom, nil } from = live.User // the credentials being replaced, as fresh as the agent has them; @@ -1574,6 +1620,15 @@ func switchSavedLogin(agent, user string) (from string, _ error) { // there that couldn't be read err = saveCodexLogin(codexHome(), want.Auth) case "claude": + // magpie's setup-token out of its settings.json first, or Claude + // Code would stay on that over the sign-in; one that can't be + // taken out (settings.json unreadable) leaves it where it is + if err = setClaudeEnvToken(""); err != nil { + break + } + if tokenFrom != "" { + from = tokenFrom + } if err = putClaudeLogin(want); err == nil { // Claude Code's own now: its only holder forgetClaudeDir(want.User) @@ -1726,8 +1781,10 @@ func nextOnForget(agent, user string) string { return "" } -// switchable is an account an agent can be signed in to: not a Claude -// setup-token one (errClaudeTokenSwitch), nor a ChatGPT account Codex +// switchable is an account magpie signs an agent in to by itself: not a +// Claude setup-token one, which Claude Code is switched to by the user +// alone (claude_token_env.go: its allowance can't be read, so magpie +// can't tell when to move off or back), nor a ChatGPT account Codex // keeps in another folder (codexHeldIn). func switchable(l Login) bool { return !l.Token && !l.AccessOnly && l.home == "" } @@ -1780,9 +1837,10 @@ func forgetLogin(agent, user string) (signedOut bool, err error) { } out := ls[:0] found := false + var gone savedLogin for _, l := range ls { if l.Agent == agent && strings.EqualFold(l.User, user) { - found = true + found, gone = true, l continue } out = append(out, l) @@ -1794,6 +1852,11 @@ func forgetLogin(agent, user string) (signedOut bool, err error) { return false, fmt.Errorf("no saved %s account %q", agent, user) } if agent == "claude" { + // a setup-token Claude Code uses: taken out of its settings.json, + // and Claude Code is on its own sign-in again + if err := claudeTokenGone(gone); err != nil { + return false, fmt.Errorf("removing %s, which Claude Code uses: %w", user, err) + } forgetClaudeDir(user) } return signedOut, writeLogins(out)