diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index b4463fc1e..ab48815a3 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -51,7 +51,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`). `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). 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. `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 c2d5c2f33..af77fa3a9 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -14129,6 +14129,8 @@ function quotaFill(w) { function quotaText(w) { if (w.unlimited) return t("Unlimited"); if (w.balance != null) return t("{n} left", { n: (countFormat.format(w.balance) + " " + t(w.unit || "")).trim() }); + // a text row used 100 is Claude's overages (claudeOveragesWindow): "In use", said in the reader's language + if (w.text && w.used >= 100) return t("In use"); if (quotaNoShare(w)) return w.display || t("No allowance reported"); const used = to100(w.used); const n = quotaLeft ? 100 - used : used; diff --git a/internal/gui/tests/claude-overages.test.cjs b/internal/gui/tests/claude-overages.test.cjs new file mode 100644 index 000000000..1f8b68b30 --- /dev/null +++ b/internal/gui/tests/claude-overages.test.cjs @@ -0,0 +1,68 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A Claude account on overages (#4532) is read with its windows and an +// "Extra usage" row of text, used 100 (claudeOveragesWindow): it reads +// "In use" in the reader's language, with no meter, ring or share, and +// the windows beside it keep theirs. No backend, the API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); + +function serve(lang) { + const settings = { theme: "light", lang, tray: "panel" }; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings }); + if (url.pathname === "/api/settings") return json(settings); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const IN_USE = { en: "In use", zh: "使用中", "zh-TW": "使用中", ja: "使用中", de: "In Verwendung" }; +const EXTRA = { en: "Extra usage", zh: "额外用量", "zh-TW": "額外用量", ja: "追加使用量", de: "Zusätzliche Nutzung" }; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + test(`${engine} ${lang}: Claude's overages row reads in use`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width: 440, height: 700 } })).newPage(); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + await page.goto("http://magpie.test/"); + await page.waitForFunction(() => typeof panelQuotaCard === "function"); + const got = await page.evaluate(() => { + const extra = { name: "Extra usage", used: 100, display: "In use", text: true }; + const q = { windows: [{ name: "5 hours", used: 100 }, { name: "7 days", used: 40 }, extra], name: "Claude", user: "test" }; + const row = accountQuota({ test: q }, "test"), panel = panelQuotaCard(q), usage = quotaWindows(q); + return { + text: quotaText(extra), row: row.textContent, panel: panel.textContent, usage: usage.textContent, + tracks: usage.querySelectorAll(".quota-track").length, rings: panel.querySelectorAll(".pq-ring").length, + // a plugin's text row with its display keeps it as it came + plugin: quotaText({ name: "积分余额", used: 0, display: "1,234 积分", text: true }), + }; + }); + assert.equal(got.text, IN_USE[lang]); + assert.equal(got.plugin, "1,234 积分"); + assert.match(got.usage, new RegExp(EXTRA[lang])); + assert.match(got.usage, new RegExp(IN_USE[lang])); + if (lang !== "en") assert.doesNotMatch(got.usage, /In use/); + // the two windows keep their meters and shares; the row has none + assert.equal(got.tracks, 2, got.usage); + assert.equal((got.usage.match(/%/g) || []).length, 2, got.usage); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/provider/claude_usage_cli.go b/internal/provider/claude_usage_cli.go index 308ac72bf..a994f034b 100644 --- a/internal/provider/claude_usage_cli.go +++ b/internal/provider/claude_usage_cli.go @@ -70,7 +70,33 @@ var errClaudeCannotRun = errors.New("Claude Code can't be run from here") // An account error stays visible even when it also mentions a timeout or // rate limit. It is not a temporary failure to read the usage endpoint. -var claudeUsageDenied = regexp.MustCompile(`(?i)\b(401|403)\b|not (logged|signed) in|signed out|sign-in (has )?expired|unauthorized|forbidden|authentication (failed|required)|invalid (access )?token|(session|usage) limit|hit your limit|using your overages`) +var claudeUsageDenied = regexp.MustCompile(`(?i)\b(401|403)\b|not (logged|signed) in|signed out|sign-in (has )?expired|unauthorized|forbidden|authentication (failed|required)|invalid (access )?token|(session|usage) limit|hit your limit`) + +// claudeOverages is /usage's line for an account past its plan's limits +// and billed for what it uses ("You are currently using your overages to +// power your Claude Code usage. We will automatically switch you back to +// your subscription rate limits when they reset"), which Claude Code +// prints above the account's windows. It is no account error: read as +// one, the reading had no windows and an error, and the switch, which +// stays on an account it can't read, left Claude Code spending overages +// with other accounts that had room (StringKe, #4532). +var claudeOverages = regexp.MustCompile(`(?i)using your overages`) + +// claudeOveragesWindow is the window an account on overages is read with, +// beside ws: spent (usedPast, roomLeft), so the switch moves Claude Code +// off it as off one whose window is used up, and told as its text. It +// ends when the last of ws's used-up windows renews, as Claude Code's +// overages do; none named, at the next reading. +func claudeOveragesWindow(ws []QuotaWindow) QuotaWindow { + // the GUI says a Text row used 100 "In use" in the reader's language + w := QuotaWindow{Name: "Extra usage", Used: 100, Display: "In use", Text: true} + for _, x := range ws { + if x.Used >= 100 && x.ResetsAt != nil && (w.ResetsAt == nil || x.ResetsAt.After(*w.ResetsAt)) { + w.ResetsAt = x.ResetsAt + } + } + return w +} // parseClaudeUsage reads /usage's windows; now dates a reset that names no // year. @@ -109,6 +135,9 @@ func parseClaudeUsage(text string, now time.Time) ([]QuotaWindow, error) { } out = append(out, w) } + if slices.ContainsFunc(lines, claudeOverages.MatchString) { + out = append(out, claudeOveragesWindow(out)) + } if len(out) == 0 { if text == "" || slices.ContainsFunc(lines, func(line string) bool { return strings.TrimSuffix(strings.TrimSpace(line), ".") == "You are currently using your subscription to power your Claude Code usage" diff --git a/internal/provider/claude_usage_fallback_test.go b/internal/provider/claude_usage_fallback_test.go index d744dff90..3a4a5bf8d 100644 --- a/internal/provider/claude_usage_fallback_test.go +++ b/internal/provider/claude_usage_fallback_test.go @@ -191,7 +191,6 @@ func TestClaudeUsageFailureDoesNotHideAccountErrors(t *testing.T) { subscriptionNotice + ".\nHTTP 401 Unauthorized", "Current session: 40% used\nHTTP 401 Unauthorized", "You've hit your limit · resets 3:30am (UTC)", - "You are currently using your overages to power your Claude Code usage. We will automatically switch you back to your subscription rate limits when they reset", } { t.Run(text, func(t *testing.T) { out, card := claudeUsageCards(t, "Current session: 40% used", nil) diff --git a/internal/provider/claude_usage_overages_test.go b/internal/provider/claude_usage_overages_test.go new file mode 100644 index 000000000..644e6bcbf --- /dev/null +++ b/internal/provider/claude_usage_overages_test.go @@ -0,0 +1,119 @@ +package provider + +import ( + "context" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +// claudeOveragesText is Claude Code's /usage for an account past a limit +// and billed for what it uses: its overages line, then its windows (the +// strings as Claude Code 2.1.316 has them). +const claudeOveragesText = `You are currently using your overages to power your Claude Code usage. We will automatically switch you back to your subscription rate limits when they reset + +Current session: 100% used · resets 3pm (UTC) +Current week (all models): 40% used · resets Nov 6 at 11am (UTC) +` + +// StringKe (#4532): the overages line made the whole reading an error, +// so the card showed no windows and the switch, which stays on an account +// it can't read, left Claude Code on overages. It is read with the +// windows, and a spent "Extra usage" row that ends with the window used +// up. +func TestClaudeUsageOverages(t *testing.T) { + now := time.Date(2026, 11, 1, 13, 0, 0, 0, time.UTC) + ws, err := parseClaudeUsage(claudeOveragesText, now) + if err != nil { + t.Fatal(err) + } + if len(ws) != 3 || ws[0].Name != "5 hours" || ws[0].Used != 100 || ws[1].Name != "7 days" || ws[1].Used != 40 { + t.Fatalf("windows: %+v", ws) + } + x := ws[2] + if x.Name != "Extra usage" || !x.Text || x.Used != 100 || x.ResetsAt == nil || !x.ResetsAt.Equal(*ws[0].ResetsAt) { + t.Fatalf("overages row: %+v", x) + } + if !usedUp(SubscriptionQuota{Windows: ws}, now) { + t.Fatal("an account on overages read as having room") + } + // past the session's reset, the row is gone with it + if usedPast(SubscriptionQuota{Windows: elapsed(ws, now.Add(3*time.Hour))}, 98, now.Add(3*time.Hour)) { + t.Fatal("still spent after the used-up window renewed") + } + // on overages with every window under the line it names (a model's + // own week used up), the account is still spent, till the next reading + text := strings.Replace(claudeOveragesText, "Current session: 100%", "Current session: 10%", 1) + ws, err = parseClaudeUsage(text, now) + if err != nil || len(ws) != 3 || ws[2].ResetsAt != nil || !usedPast(SubscriptionQuota{Windows: ws}, 98, now) { + t.Fatalf("overages, windows under the line: %+v %v", ws, err) + } +} + +// The switch moves Claude Code off an account on overages to a spare +// with room, as off one whose window is used up. +func TestClaudeSwitchOffOverages(t *testing.T) { + claudeThree(t) // pro@x.com signed in; team and max saved + var text atomic.Value + text.Store("") + 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) + } + spare := "" + for _, l := range Logins("claude") { + if strings.HasPrefix(l.User, "max@x.com") { + spare = l.User + if err := SetLoginOn("claude", l.User, true); err != nil { + t.Fatal(err) + } + } + } + // windows under the line, so only the overages line says it's spent + reset := time.Now().UTC().Add(72*time.Hour).Format("Jan 2 at 3pm") + " (UTC)" + under := "Current session: 10% used · resets " + reset + "\nCurrent week (all models): 40% used · resets " + reset + "\n" + var mu sync.Mutex + active := under + UsageClaudeVia(func(_ context.Context, dir string) (string, error) { + mu.Lock() + defer mu.Unlock() + if dir == "" { + return active, nil + } + return under, nil // the spare + }) + ctx := context.Background() + if to, err := SwitchWhenSpent(ctx, "claude"); err != nil || to != "" { + t.Fatalf("with room: switched to %q: %v", to, err) + } + mu.Lock() + active = strings.SplitN(claudeOveragesText, "\n", 2)[0] + "\n\n" + under + mu.Unlock() + forget() + claudeUsage.Lock() + for k, e := range claudeUsage.m { + e.tried, e.at = e.tried.Add(-time.Hour), e.at.Add(-time.Hour) + claudeUsage.m[k] = e + } + claudeUsage.Unlock() + if to, err := SwitchWhenSpent(ctx, "claude"); err != nil || to != spare { + t.Fatalf("on overages: switched to %q: %v, want %q", to, err, spare) + } + for user, u := range LoginUsage(ctx, "claude") { + if strings.HasPrefix(user, "pro@x.com") && (u.Error != "" || len(u.Windows) != 3) { + t.Fatalf("the overages account's card: %+v", u) + } + } +} diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index 8b764f61c..5ecd3713a 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -38,7 +38,8 @@ type QuotaWindow struct { // (AutoClaw's 积分余额 and 每日签到, Cursor's on-demand spend, ZCode's // gift to claim), which plugins send set aside with used 0 and no // count. Its Used is no reading, so it is told as its text, never as - // "100% left". + // "100% left". Claude's "Extra usage" row (claudeOveragesWindow) is + // the one Text window with Used 100: the account counts as spent. Text bool `json:"text,omitempty"` // Amount of Limit is the window's own count in Unit, when the vendor // counts it so (WorkBuddy's credits): Used is Amount as a share of