diff --git a/docs/reference.md b/docs/reference.md index 4bef0ab59..b1ce89584 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -552,7 +552,12 @@ vendors, and it answers from what it has kept (`GET /v1/magpie/quotas/cards`). A card's refresh here has it read that card once more (`POST /v1/magpie/quotas/refresh`, at most once in 30 seconds a card); until it has read anything, the remote's one card says so. Their history is shown with -its own. A Codex reset or a check-in is pressed on that computer, not here. +its own. A check-in is pressed on that computer, not here. A Codex card's +reset can be used from here (#3850): **Use one…** asks first, as for this +computer's accounts, and that magpie spends it on its account +(`POST /v1/magpie/quotas/codex-reset`, below). It takes the provider's key +with full access there; a read-only or held key is told so. A GLM team's +resets are still used on bigmodel.cn. Codex's native image tool first asks the provider that served its conversation turn for the requested image model. If that provider does not list the model, @@ -2385,6 +2390,23 @@ told none of the cards is answered `/v1/magpie/quotas/cards` 403 that nothing was read. `/v1/magpie/concurrency` and `/v1/magpie/usage` still refuse it. +A Codex account's rate-limit reset can be used through the gateway as +the Usage page's **Use a reset** does (#3850, the same code): +`POST /v1/magpie/quotas/codex-reset?user=` spends one of that +account's resets (`&credit=` one of its `resets.each`, else the one +that runs out first) and answers `{"code": "reset", "windows": 2}`, or +`no_credit` or `nothing_to_reset` with nothing spent. It can't be +undone, so it takes an enabled gateway key with full access, from this +computer too: a request without a key is refused 401 even on loopback, a +browser page or app the gateway otherwise lets in there (Origin `null`, an +app's scheme, a `*.localhost` page) included; a read-only key 403 +`gateway_key_read_only`; a key held to a budget, models or accounts 403 +`gateway_key_held`, whether or not it is told quotas. The account is +always named (400 without `user`). A second ask for the same account +while one is out is answered 409. Another magpie's Codex card uses this, +and so can an app reading `/v1/magpie/quotas/cards`, such as a DSH +provider plugin, with a key of full access. + An app of your own can read the Usage page's numbers too. `GET /v1/magpie/usage?period=` is the page's summary, the same JSON as the window's `/api/usage` (`path` is left out for another diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index eea1ed48c..a375aa962 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -535,7 +535,7 @@ page and its data, the concurrency, and the route events' snapshot and stream) and refuses every other with 403 `gateway_key_read_only`: every model route, `count_tokens`, the Responses WebSocket's upgrade, every MCP server, Codex's and Gemini's backends, the catch-all and every write -(`POST /v1/magpie/usage/requests`, the quotas' refresh). A route added later +(`POST /v1/magpie/usage/requests`, the quotas' refresh, a Codex reset). A route added later is refused it until it is put in that list. A read-only key is held to nothing else, so `heldKey` leaves it alone and it reads the usage summary and every account's quotas as a key held to nothing does; none of those @@ -547,6 +547,25 @@ route the router has is in neither `readOnlyRoutes` nor its refused list, and sends each refused pattern, by each method it takes, from loopback and from the network. +`POST /v1/magpie/quotas/codex-reset` (`Server.codexReset` in +[`gateway.go`](../../internal/gateway/gateway.go), #3850) spends one of a +Codex account's resets, which can't be undone, so its admission is +stricter than the quotas': a key is required from loopback too. Every +origin exemption `corsGuard` makes without a key (app schemes, `null`, +loopback page names, a request with no Origin) reaches the handler with +an empty `access.Caller(ctx).KeyID`, and is refused 401 there. A +read-only key is refused by `readOnlyGuard` (and again in the handler), +and a held key (`heldKey`) 403 `gateway_key_held` even when it is told +quotas. The account is named in `?user=`, and `codexResetsAsked` lets one +ask per account run at a time (409). It calls `provider.SpendCodexReset`, +the Usage page's own code, then `RefreshUsage` of that card. +`TestCodexResetNeedsAFullKey` in +[`codex_reset_api_test.go`](../../internal/gateway/codex_reset_api_test.go) +sends it without a key from loopback, `Origin: null`, an app scheme, a +`*.localhost` page, a rebound Host and a foreign page, then with a wrong, +read-only and held key, and expects nothing spent until the full key +asks. + A remote provider serves the conversation, token-counting, System One, embeddings, rerank, speech-to-text, image generation/edit and video creation/status/content APIs. Gemini clients enter through the local Gemini adapter and follow the diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 0004d9d67..dc62458da 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -57,7 +57,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | 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) | -| Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it, each window with its whole-window estimate (`Holds`/`HoldsWhy`, `usage.WithWindowHolds`, which `quotaReport` reaches through the `ReckonHolds` hook since package provider can't import usage, #2333). A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). Each key of a remote-magpie provider also gets a card of its own, under `/~keys`, one section per key (#1547, `remoteKeyCards` in `remote_key_limits.go`): the gateway key's limit as that magpie holds it, read from `GET /v1/magpie/limit` asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus `GatewayKey` (what is left, calls, a cycle of days, used up); a key held to no limit shows `Unlimited`. It is kept for `remoteCardsFor` like the remote's cards and read again by the card's refresh (`?provider=/~keys&user=`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). A remote that holds the key to a budget, models or accounts answers its cards 403 `gateway_key_held` (#1981, `errKeyHeld`): the cards kept from before are dropped and only the key's own card shows. Its owner can let the key be told the cards of what it may use (#2216, `magpie gateway-key quotas on`); the remote then answers those, and 403 as before when that is none. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, `quotasOpened`, #1588) or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. A plugin's window may carry a prepaid wallet's `balance` in its `unit` and no share (`QuotaWindow.Balance`, #3950): the card and `magpie quota` show the figure (`BalanceText`), and routing reads it through `Allowance.Left`. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`quota_asked.go`](../../internal/provider/quota_asked.go) | +| Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it, each window with its whole-window estimate (`Holds`/`HoldsWhy`, `usage.WithWindowHolds`, which `quotaReport` reaches through the `ReckonHolds` hook since package provider can't import usage, #2333). A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). Each key of a remote-magpie provider also gets a card of its own, under `/~keys`, one section per key (#1547, `remoteKeyCards` in `remote_key_limits.go`): the gateway key's limit as that magpie holds it, read from `GET /v1/magpie/limit` asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus `GatewayKey` (what is left, calls, a cycle of days, used up); a key held to no limit shows `Unlimited`. It is kept for `remoteCardsFor` like the remote's cards and read again by the card's refresh (`?provider=/~keys&user=`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). A remote's Codex card keeps its `Resets` (not a GLM team's, `ByWindow`), and its check-ins are dropped: **Use one…** there goes through `/api/usage/codex-reset` with the card's `provider`, and `UseRemoteCodexReset` asks the remote's `POST /v1/magpie/quotas/codex-reset?user=` with the provider's key (#3850). The remote spends it with `SpendCodexReset`, the same function as the Usage page (`UseCodexResetCard`, then `AwaitAllowance`). The account is always named. A 403 `gateway_key_read_only` is told as a read-only key there, and a 404 as a remote too old. No answer within `RemoteResetWait` says the reset may have been used, and it is never asked again by itself. A remote that holds the key to a budget, models or accounts answers its cards 403 `gateway_key_held` (#1981, `errKeyHeld`): the cards kept from before are dropped and only the key's own card shows. Its owner can let the key be told the cards of what it may use (#2216, `magpie gateway-key quotas on`); the remote then answers those, and 403 as before when that is none. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, `quotasOpened`, #1588) or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. A plugin's window may carry a prepaid wallet's `balance` in its `unit` and no share (`QuotaWindow.Balance`, #3950): the card and `magpie quota` show the figure (`BalanceText`), and routing reads it through `Allowance.Left`. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`quota_asked.go`](../../internal/provider/quota_asked.go) | | A remote magpie's prices | A local magpie asks a remote magpie's `/v1/models` with `X-Magpie-Prices` (`PricesHeader`, sent by `listHeaders`). The remote answers each model's `magpie_price`: what its own Usage page counts the model at (`EntryPriceIn`: the price its user set, else its provider's list price at its price rate; a routing group only when every member costs the same). It tells it only to a request from its own computer or one let in with a gateway key (`local` or `sharedWith`); a list that didn't ask gets no `magpie_price` (a remote request without a valid key never reaches the list: `lanGuard` refuses it); every list told to those callers also carries the same price as OpenRouter's `pricing`, for agents ([gateway routing](gateway-routing.md)). The local keeps the price with the fetched list (`catalog.Model.Price`; a value that isn't a price, or has a negative part, is dropped, the model kept) and uses it as that provider's list price (`ListPrice` → `remotePrice`). A price the local user set (`provider/model`, `provider/*`, `*/model`) still comes first, and the local provider's own price rate still applies on top. A remote from before this sends no field and the models stay priced as before; an older local sends no header and is sent nothing new. The model editor says the greyed price is the other magpie's (`remoteList`). | [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`models.go`](../../internal/provider/models.go), [`gateway.go`](../../internal/gateway/gateway.go) (`models`), [`live.go`](../../internal/catalog/live.go) | | A remote magpie's service tiers | A remote magpie's `/v1/models` gives each model the `service_tiers` its own Codex is offered on it (`codexTiers` → `codexcat.ServiceTiers`, from the same `CodexCatalog` and `codexcat.Entries` as its `/v1/codex/models`: Fast on a ChatGPT account's GPT model, the tiers of Codex's own entry on a relay's, none on a model it offers none). The local keeps the ids (`catalog.Model.Tiers` → `Entry.Tiers`), `codexListed` hands them on for the remote's models, and `codexcat.Entries` offers them to the local Codex with Codex's own names (`namedTiers`). The gateway sends the tier Codex asks for to a remote magpie as it was asked (`Request.OwnTier`, as for a provider added by its address; dropped and not sent again if refused), and the remote serves it as its own Codex's turn (#1234). An agent's picker offers the bolt on a remote's model whose tiers hold `priority` (`provider.CanFast` reads them with `RemoteTiers`; Ultrafast too where they hold `ultrafast`, `UltraOn`), and a fast pick of one goes on with `service_tier` `priority` on the remote's Chat or Responses: an agent on Messages, whose fast is Claude's `speed`, has it turned into the tier the remote offers (`forwardTranslated`), so Claude Code's pick reaches the remote's vendor too (littlekk88 on Discord; `TestRemoteMagpieFastPick`, red without either half). A remote from before this sends no tiers, and its models are offered none, as before. The list gives every client the tiers, not only a magpie asking with `X-Magpie-Drawers`: Cindy shows its Fast switch on a model whose `service_tiers` hold `priority` (#1914, `TestModelsListTiersForEveryClient`). | [`codexcat.go`](../../internal/codexcat/codexcat.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`gateway.go`](../../internal/gateway/gateway.go), [`live.go`](../../internal/catalog/live.go) | | A relay's Codex entries | A provider the user added by its address with a Responses URL may list its models in Codex's own shape (`slug`, `supported_reasoning_levels`, `shell_type`, `base_instructions`: `catalog.CodexEntry`), plainly or when asked with Codex's `client_version`, as sub2api does (ctopsc on Discord: GPT-6.1 Terra was handed models.dev's 922000 window where the relay said 272000). `fetchOne` keeps such a row whole (`catalog.Model.Codex`, with its window, max window and inputs read off it), and when the plain list has none it asks the same URL once more with `client_version` (`codexEntries`): only where the list is fetched (add, key change, Refresh), never per Codex poll. The answer only adds entries to models the plain list has; one that fails or can't be read keeps the last list's entries (failed read = unknown), one that answers plainly says there are none. `codexcat.listedEntry` hands Codex the relay's entry as given, `base_instructions` included, with magpie's slug, name, priority and " via magpie" description; the user's window, compaction, levels and image setting still win (levels keep the relay's descriptions). A saved list from before is enriched at its next Refresh. `TestCodexListedEntry`, `TestCodexListedEntryInPlainList`. | [`codex_entries.go`](../../internal/provider/codex_entries.go), [`live.go`](../../internal/catalog/live.go), [`codexcat.go`](../../internal/codexcat/codexcat.go) | diff --git a/internal/gateway/codex_reset_api_test.go b/internal/gateway/codex_reset_api_test.go new file mode 100644 index 000000000..369b81e8f --- /dev/null +++ b/internal/gateway/codex_reset_api_test.go @@ -0,0 +1,173 @@ +package gateway + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/provider" +) + +// #3850 (prgrmrwy): magpie runs on a home server, and the office's remote +// magpie card (or DSH's, reading the cards) said "1 reset" with no way to +// use it but walking to the server. POST /v1/magpie/quotas/codex-reset +// spends it there, through the Usage page's own code. A reset can't be +// undone, so only a gateway key with full access spends one: never a +// request with no key, from this computer or a page or app the gateway +// lets in on loopback without one, nor a read-only key or a held one. +func TestCodexResetNeedsAFullKey(t *testing.T) { + codexSignedIn(t) + t.Setenv("MAGPIE_ADDR", "") + b := newResetBackend(t, "acct-1") + keys, secrets := newCaller(t, "Full", "Read only", "Held") + if _, err := access.Update("access-key", access.Change{Key: keys[1].ID, ReadOnly: true}); err != nil { + t.Fatal(err) + } + if _, err := access.Update("limit-key", access.Change{Key: keys[2].ID, Limit: &access.Limit{Period: "day", Tokens: 1_000_000}}); err != nil { + t.Fatal(err) + } + h := lanGuard(New().Handler()) + path := provider.RemoteCodexResetPath + "?user=" + url.QueryEscape("me@example.com") + do := func(path, from, host, origin, secret string) (int, string) { + t.Helper() + r := httptest.NewRequest("POST", path, nil) + r.RemoteAddr = from + r.Host = host + if origin != "" { + r.Header.Set("Origin", origin) + r.Header.Set("Sec-Fetch-Site", "cross-site") + r.Header.Set("Sec-Fetch-Mode", "cors") + r.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.2 Safari/605.1.15") + } + if secret != "" { + r.Header.Set("Authorization", "Bearer "+secret) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w.Code, w.Body.String() + } + const loop, lan, gw = "127.0.0.1:50123", "192.168.1.9:5000", "127.0.0.1:3425" + refused := []struct { + why string + from, host, origin, secret string + }{ + {"this computer, no key", loop, gw, "", ""}, + {"a sandboxed frame (Origin null), no key", loop, gw, "null", ""}, + {"an app's scheme, no key", loop, gw, "tauri://localhost", ""}, + {"a *.localhost page, no key", loop, gw, "http://evil.localhost:8080", ""}, + {"a rebound page (its own Host), no key", loop, "evil.example:3425", "", ""}, + {"a foreign page, no key", loop, gw, "https://evil.example", ""}, + {"a foreign page with the full key", loop, gw, "https://evil.example", secrets[0]}, + {"another machine, no key", lan, gw, "", ""}, + {"another machine, a wrong key", lan, gw, "", "sk-magpie-wrong"}, + {"a read-only key", lan, gw, "", secrets[1]}, + {"a read-only key, this computer", loop, gw, "", secrets[1]}, + {"a held key", lan, gw, "", secrets[2]}, + } + for _, c := range refused { + if code, body := do(path, c.from, c.host, c.origin, c.secret); code < 400 || code == http.StatusNotFound || strings.Contains(body, `"code":"reset"`) { + t.Errorf("%s: %d %s", c.why, code, body) + } + if _, spent := b.seen(); spent != "" { + t.Fatalf("%s spent a reset of %s", c.why, spent) + } + } + if code, body := do(provider.RemoteCodexResetPath, lan, gw, "", secrets[0]); code != http.StatusBadRequest || !strings.Contains(body, "name the Codex account") { + t.Fatalf("no account named: %d %s", code, body) + } + if code, body := do(path, lan, gw, "", secrets[1]); code != http.StatusForbidden || !strings.Contains(body, ReadOnlyCode) { + t.Fatalf("read-only key: %d %s", code, body) + } + if code, body := do(path, lan, gw, "", secrets[2]); code != http.StatusForbidden || !strings.Contains(body, provider.KeyHeldCode) { + t.Fatalf("held key: %d %s", code, body) + } + if _, spent := b.seen(); spent != "" { + t.Fatalf("spent before the full key asked: %s", spent) + } + // the full key, from another machine: one reset, of the account named + code, body := do(path, lan, gw, "", secrets[0]) + var out provider.ResetOutcome + if code != 200 || json.Unmarshal([]byte(body), &out) != nil || out.Code != "reset" || out.Windows != 2 { + t.Fatalf("full key: %d %s", code, body) + } + if _, spent := b.seen(); spent != "acct-1" { + t.Fatalf("spent %q, want acct-1 once", spent) + } + // none left: said so, nothing more spent + code, body = do(path, loop, gw, "", secrets[0]) + if code != 200 || json.Unmarshal([]byte(body), &out) != nil || out.Code != "no_credit" { + t.Fatalf("none left: %d %s", code, body) + } + if _, spent := b.seen(); spent != "acct-1" { + t.Fatalf("spent %q after none was left", spent) + } +} + +// The office's magpie spends the home server's reset through its remote +// magpie provider (#3850): the card here keeps the remote's resets, and +// using one asks the remote with the provider's key. A read-only key there +// says so in words the card can show. +func TestRemoteCodexResetThroughTheGateway(t *testing.T) { + codexSignedIn(t) + t.Setenv("MAGPIE_ADDR", "") + provider.ForgetRemoteCardsForTest() + t.Cleanup(provider.ForgetRemoteCardsForTest) + b := newResetBackend(t, "acct-1") + keys, secrets := newCaller(t, "Office", "Viewer") + if _, err := access.Update("access-key", access.Change{Key: keys[1].ID, ReadOnly: true}); err != nil { + t.Fatal(err) + } + srv := httptest.NewServer(lanGuard(New().Handler())) + defer srv.Close() + ctx := context.Background() + save := func(secret string) { + t.Helper() + if err := provider.Save(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Key: secret, Chat: srv.URL}); err != nil { + t.Fatal(err) + } + provider.ForgetRemoteCardsForTest() + } + save(secrets[1]) + if _, err := provider.UseRemoteCodexReset(ctx, "office/codex", "me@example.com", ""); err == nil || !strings.Contains(err.Error(), "read-only") { + t.Fatalf("read-only key: %v", err) + } + if _, err := provider.UseRemoteCodexReset(ctx, "office/codex", "", ""); err == nil { + t.Fatal("no account named was asked") + } + if _, err := provider.UseRemoteCodexReset(ctx, "office/bal", "me@example.com", ""); err == nil { + t.Fatal("a card not Codex's was asked") + } + if _, spent := b.seen(); spent != "" { + t.Fatalf("spent %q before a full key asked", spent) + } + save(secrets[0]) + // the remote's card, read there, carries its reset here + provider.RefreshUsage(ctx, "office", "") + var card *provider.SubscriptionQuota + for _, q := range provider.RemoteCards(ctx) { + if q.Provider == "office/codex" { + card = &q + } + } + if card == nil || card.Resets == nil || card.Resets.Count != 1 || card.User != "me@example.com" || card.Checkins { + t.Fatalf("office/codex: %+v", card) + } + out, err := provider.UseRemoteCodexReset(ctx, "office/codex", card.User, "") + if err != nil || out.Code != "reset" { + t.Fatalf("full key: %+v %v", out, err) + } + if _, spent := b.seen(); spent != "acct-1" { + t.Fatalf("spent %q, want acct-1 once", spent) + } + // read again after: the card shows none left + for _, q := range provider.RemoteCards(ctx) { + if q.Provider == "office/codex" && q.Resets != nil && q.Resets.Count != 0 { + t.Fatalf("after the reset: %+v", q.Resets) + } + } +} diff --git a/internal/gateway/cors_test.go b/internal/gateway/cors_test.go index a91c0b148..e5bcb8d23 100644 --- a/internal/gateway/cors_test.go +++ b/internal/gateway/cors_test.go @@ -246,6 +246,7 @@ func TestForeignPagesRefused(t *testing.T) { {"POST", "/mcp/notes", `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`}, {"POST", "/_magpie/claude-mcp/tok", `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`}, {"POST", provider.RemoteRefreshPath, ""}, + {"POST", provider.RemoteCodexResetPath + "?user=me@example.com", ""}, {"GET", "/v1/magpie/quotas", ""}, {"GET", "/v1/models", ""}, {"OPTIONS", "/v1/chat/completions", ""}, diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index cd7f265c7..2682ebef9 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -935,6 +935,7 @@ func (s *Server) routes() *routeMux { mux.HandleFunc("GET /v1/magpie/quotas/history", s.quotasHistory) mux.HandleFunc("GET "+provider.RemoteCardsPath, s.quotaCards) mux.HandleFunc("POST "+provider.RemoteRefreshPath, s.quotaCardsRefresh) + mux.HandleFunc("POST "+provider.RemoteCodexResetPath, s.codexReset) mux.HandleFunc("GET /v1/magpie/route", s.sessionRoute) mux.HandleFunc("GET /v1/magpie/trace", s.gatewayTrace) mux.HandleFunc("GET "+routeSnapshotPath, s.routeSnapshot) @@ -1178,6 +1179,79 @@ func (s *Server) quotaCardsRefresh(w http.ResponseWriter, r *http.Request) { writeCards(w, r, scope) } +// codexResetsAsked are the Codex accounts a reset is being spent on now +// (codexReset): a second ask while the first is out is refused, not +// spent as well. +var codexResetsAsked = struct { + sync.Mutex + m map[string]bool +}{m: map[string]bool{}} + +// codexReset spends one of a Codex account's rate-limit resets, as the +// Usage page's "Use a reset" does (provider.SpendCodexReset, the same +// code), asked by another magpie's card or an app holding a gateway key +// (#3850, prgrmrwy). A reset can't be undone, so beyond what +// quotaCardsRefresh asks it takes a gateway key, from this computer too, +// never one that is read-only (readOnlyGuard refuses that before here) +// nor one held to a budget, models or accounts: a browser page or an app the gateway lets in on loopback +// without a key (Origin null, an app's scheme, a *.localhost page) is +// refused, as is a request with no key at all. The account is named +// (?user=), never "whichever is signed in", which a caller elsewhere +// can't see; ?credit= picks one of its resets.each. +func (s *Server) codexReset(w http.ResponseWriter, r *http.Request) { + if !local(r) && !sharedWith(r) { + writeError(w, provider.Chat, http.StatusForbidden, "magpie's quotas are told to another machine only when magpie is shared on the local network (Settings → Network and sharing → Share on local network) and the request carries its API key (Authorization: Bearer or x-api-key: )") + return + } + who := access.Caller(r.Context()) + if who.KeyID == "" || who.ReadOnly { + writeError(w, provider.Chat, http.StatusUnauthorized, "using a Codex reset can't be undone, so it takes an enabled magpie gateway key with full access (Gateway → Gateway keys), sent as Authorization: Bearer or x-api-key, from this computer too; or use it on this computer's Usage page") + return + } + // a key held to a budget, models or accounts is someone else's to + // use: told some cards (#2216) or none, it spends no reset of the + // owner's + if refuseHeld(w, r, "this gateway key is held to a budget, models or accounts, so it uses none of this magpie's Codex resets: use a key with full access") { + return + } + q := r.URL.Query() + user, credit := strings.TrimSpace(q.Get("user")), q.Get("credit") + if user == "" { + writeError(w, provider.Chat, http.StatusBadRequest, "name the Codex account whose reset is used: ?user=") + return + } + key := strings.ToLower(user) + codexResetsAsked.Lock() + busy := codexResetsAsked.m[key] + codexResetsAsked.m[key] = true + codexResetsAsked.Unlock() + if busy { + writeError(w, provider.Chat, http.StatusConflict, "a reset of "+user+" is being used already; read its card to see what it did") + return + } + defer func() { + codexResetsAsked.Lock() + delete(codexResetsAsked.m, key) + codexResetsAsked.Unlock() + }() + log.Printf("Codex reset of %s asked by gateway key %q", user, who.KeyName) + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) + out, err := provider.SpendCodexReset(ctx, user, credit) + cancel() + if err != nil { + writeError(w, provider.Chat, http.StatusBadGateway, err.Error()) + return + } + // the card read again, so the cards answered next show its windows + // started again and a reset fewer + if out.Code == "reset" { + read, done := context.WithTimeout(context.WithoutCancel(r.Context()), 15*time.Second) + provider.RefreshUsage(read, "codex", user) + done() + } + writeJSON(w, 200, out) +} + func modelObject(e provider.Entry) map[string]any { type reasoningLevel struct { Effort string `json:"effort"` diff --git a/internal/gateway/lan_test.go b/internal/gateway/lan_test.go index 19823e421..bacc654da 100644 --- a/internal/gateway/lan_test.go +++ b/internal/gateway/lan_test.go @@ -335,6 +335,7 @@ func TestNetworkGatewayGuardsEveryRoute(t *testing.T) { {"GET", "/api/version"}, {"GET", "/api/tags"}, {"POST", "/api/show"}, {"GET", "/v1/magpie/quotas"}, {"GET", "/v1/magpie/quotas/history"}, {"GET", provider.RemoteCardsPath}, {"POST", provider.RemoteRefreshPath}, + {"POST", provider.RemoteCodexResetPath + "?user=me@example.com"}, {"GET", "/v1/magpie/route?session=s"}, {"GET", "/v1/magpie/concurrency"}, {"GET", "/v1/magpie/limit"}, {"POST", "/v1/chat/completions"}, {"POST", "/chat/completions"}, {"POST", "/v1/responses"}, {"POST", "/responses"}, {"GET", "/v1/responses"}, {"GET", "/responses"}, diff --git a/internal/gateway/readonly.go b/internal/gateway/readonly.go index aaa0ee324..c72e8a35c 100644 --- a/internal/gateway/readonly.go +++ b/internal/gateway/readonly.go @@ -44,7 +44,7 @@ var readOnlyRoutes = map[string]bool{ } // ReadOnlyCode is the error code a read-only key is refused a route with. -const ReadOnlyCode = "gateway_key_read_only" +const ReadOnlyCode = provider.KeyReadOnlyCode // routeMux is a ServeMux that keeps the patterns it was given. type routeMux struct { diff --git a/internal/gateway/readonly_test.go b/internal/gateway/readonly_test.go index 590dd8839..6d8e5adc0 100644 --- a/internal/gateway/readonly_test.go +++ b/internal/gateway/readonly_test.go @@ -25,6 +25,8 @@ var readOnlyRefused = []string{ "POST /api/show", "POST /api/chat", "POST /api/generate", // writes, another key's routes, the whole trace, debugging "POST /v1/magpie/usage/requests", "POST " + provider.RemoteRefreshPath, + // a Codex reset, which can't be undone (#3850) + "POST " + provider.RemoteCodexResetPath, "GET /v1/magpie/route", "GET /v1/magpie/trace", "GET " + ClaudeRunsPath, "GET " + HeapPath, "GET " + CPUPath, "GET " + GoroutinesPath, "POST " + RestartPath, diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index a2d045bad..bbf13b3d9 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -15876,7 +15876,7 @@ function renderQuotas(lazy) { r.append(resetsWords(sub.resets, sub)); // only Codex's are spent from here: a GLM team's are spent on // bigmodel.cn, a plugin's wherever its vendor spends them - if (!sub.resets.byWindow && sub.provider === "codex") { + if (codexResetCard(sub)) { const use = el("button", "text", t("Use a reset")); use.title = resetUseTitle(sub); use.onclick = () => askReset(sub); @@ -17535,7 +17535,7 @@ function panelQuotaCard(q) { if (q.resets?.count) { const r = el("div", "pq-resets"); r.append(resetsWords(q.resets, q)); - if (!q.resets.byWindow && q.provider === "codex") { // as on the Usage page + if (codexResetCard(q)) { // as on the Usage page const use = el("button", "pq-use", t("Use one…")); use.title = resetUseTitle(q); use.onclick = () => askReset(q); @@ -17635,6 +17635,12 @@ function resetsEach(r) { }).join("\n"); } +// codexResetCard: this computer's Codex card, or a remote magpie's (#3850) +function codexResetCard(q) { + if (!q.resets || q.resets.byWindow) return false; + return q.provider === "codex" || !!(q.from && q.user && /^[^/]+\/codex$/.test(q.provider || "")); +} + // resetUseTitle: a use spends the one that runs out first function resetUseTitle(q) { const r = q.resets; @@ -18097,21 +18103,6 @@ document.addEventListener("keydown", (e) => { // an open menu in it (the reset to use) closes first, on its own if (!confirmationPending && confirmAsk && !protoMenu && e.key === "Escape") { e.preventDefault(); e.stopImmediatePropagation(); closeConfirmAsk(); } }, true); -function resetOutcome(out) { - switch (out.code) { - case "reset": return t(out.windows === 1 ? "1 window started again" : "{n} windows started again", { n: out.windows }); - case "nothing_to_reset": return t("nothing to start again — no window has been used, and the reset is kept"); - case "no_credit": return t("no reset left on the account"); - case "already_redeemed": - case "already_used": return t("that reset was already used"); - // Anthropic's - case "not_limited": return t("nothing to reset — no window is used up yet, and the reset is kept"); - case "cooldown": return t("a reset was used a short while ago — try again later"); - case "ineligible": return t("the account can't use a reset"); - case "unavailable": return t("resets can't be used right now — try again later"); - } - return out.code; -} // panelAge: on the Usage tab, the footer says how old what it shows is. function panelAge() { diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 6225e2778..b9561bd59 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3262,6 +3262,11 @@ const I18N = { "That computer's magpie isn't shared — turn on Settings → Network and sharing → Share on local network there": "那台电脑的 magpie 没有共享 — 请在那台电脑上打开 设置 → 网络与共享 → 局域网共享", "That computer's magpie didn't take this key — use one of its gateway keys in this provider": "那台电脑的 magpie 不认这个密钥 — 请在这个服务商里填它的一个网关密钥", "Couldn't reach that computer's magpie — check that it is running and its address": "连不上那台电脑的 magpie — 请确认它在运行、地址正确", + "The magpie on {computer}, where this account is signed in, uses it.": "由 {computer} 上的 magpie 使用,这个账号登录在那里。", + "This key is read-only on that computer's magpie — give this provider a key with full access to use a reset from here": "这个密钥在那台电脑的 magpie 上是只读的 — 想在这里使用重置,请给这个服务商填一个完全权限的密钥", + "That computer didn't say in time whether the reset was used — it may have been. Refresh the card before asking again": "那台电脑没有及时回复重置是否已使用 — 可能已经用掉了。再次尝试前请先刷新这张卡片", + "That computer's magpie can't use a reset from here yet — update magpie there": "那台电脑的 magpie 还不能从这里使用重置 — 请在那台电脑上更新 magpie", + "That computer's magpie holds this key to a budget, models or accounts, so it uses none of its resets — give this provider a key with full access": "那台电脑的 magpie 给这个密钥设了预算、模型或账号限制,所以不会用它的重置 — 请给这个服务商填一个完全权限的密钥", "That computer's magpie is too old to tell this key's limit — update magpie there": "那台电脑的 magpie 版本太旧,无法告知这个密钥的限额 — 请在那边更新 magpie", "That computer answered this key's limit in a form magpie doesn't read — hover for more": "那台电脑返回的密钥限额格式 magpie 读不懂 — 悬停查看详情", "Gateway keys · {name}": "网关密钥 · {name}", @@ -7776,6 +7781,11 @@ const I18N = { "That computer's magpie isn't shared — turn on Settings → Network and sharing → Share on local network there": "那臺電腦的 magpie 沒有共享 — 請在那臺電腦上開啟 設定 → 網路與共享 → 區域網共享", "That computer's magpie didn't take this key — use one of its gateway keys in this provider": "那臺電腦的 magpie 不認這個金鑰 — 請在這個服務商裡填它的一個閘道金鑰", "Couldn't reach that computer's magpie — check that it is running and its address": "連不上那臺電腦的 magpie — 請確認它在執行、位址正確", + "The magpie on {computer}, where this account is signed in, uses it.": "由 {computer} 上的 magpie 使用,這個帳號登入在那裡。", + "This key is read-only on that computer's magpie — give this provider a key with full access to use a reset from here": "這個密鑰在那臺電腦的 magpie 上是唯讀的 — 想在這裡使用重置,請給這個供應商填一個完整權限的密鑰", + "That computer didn't say in time whether the reset was used — it may have been. Refresh the card before asking again": "那臺電腦沒有及時回覆重置是否已使用 — 可能已經用掉了。再次嘗試前請先重新整理這張卡片", + "That computer's magpie can't use a reset from here yet — update magpie there": "那臺電腦的 magpie 還不能從這裡使用重置 — 請在那臺電腦上更新 magpie", + "That computer's magpie holds this key to a budget, models or accounts, so it uses none of its resets — give this provider a key with full access": "那臺電腦的 magpie 給這個密鑰設了預算、模型或帳號限制,所以不會用它的重置 — 請給這個供應商填一個完整權限的密鑰", "That computer's magpie is too old to tell this key's limit — update magpie there": "那臺電腦的 magpie 版本太舊,無法告知這個金鑰的限額 — 請在那邊更新 magpie", "That computer answered this key's limit in a form magpie doesn't read — hover for more": "那臺電腦回傳的金鑰限額格式 magpie 讀不懂 — 懸停查看詳情", "Gateway keys · {name}": "閘道金鑰 · {name}", @@ -12294,6 +12304,11 @@ const I18N = { "That computer's magpie isn't shared — turn on Settings → Network and sharing → Share on local network there": "そのコンピューターの magpie は共有されていません — そちらで 設定 → ネットワークと共有 → ローカルネットワークで共有 をオンにしてください", "That computer's magpie didn't take this key — use one of its gateway keys in this provider": "そのコンピューターの magpie はこのキーを受け付けませんでした — このプロバイダーにそちらのゲートウェイキーを入れてください", "Couldn't reach that computer's magpie — check that it is running and its address": "そのコンピューターの magpie に接続できません — 起動しているか、アドレスが正しいか確認してください", + "The magpie on {computer}, where this account is signed in, uses it.": "このアカウントがサインインしている {computer} の magpie が使います。", + "This key is read-only on that computer's magpie — give this provider a key with full access to use a reset from here": "このキーはそのコンピューターの magpie では読み取り専用です — ここからリセットを使うには、このプロバイダーにフルアクセスのキーを設定してください", + "That computer didn't say in time whether the reset was used — it may have been. Refresh the card before asking again": "そのコンピューターからリセットが使われたかどうかの返事が時間内にありませんでした — 使われた可能性があります。もう一度試す前にカードを更新してください", + "That computer's magpie can't use a reset from here yet — update magpie there": "そのコンピューターの magpie はまだここからリセットを使えません — そちらで magpie を更新してください", + "That computer's magpie holds this key to a budget, models or accounts, so it uses none of its resets — give this provider a key with full access": "そのコンピューターの magpie はこのキーを予算・モデル・アカウントで制限しているため、リセットを使いません — このプロバイダーにフルアクセスのキーを設定してください", "That computer's magpie is too old to tell this key's limit — update magpie there": "そのコンピューターの magpie は古く、このキーの上限を伝えられません — そちらで magpie を更新してください", "That computer answered this key's limit in a form magpie doesn't read — hover for more": "そのコンピューターが返したキーの上限は magpie が読めない形式です — ホバーで詳細", "Gateway keys · {name}": "ゲートウェイキー · {name}", @@ -16823,6 +16838,11 @@ const I18N = { "That computer's magpie isn't shared — turn on Settings → Network and sharing → Share on local network there": "Das magpie dieses Computers ist nicht freigegeben — schalte dort Einstellungen → Netzwerk und Freigabe → Im lokalen Netzwerk freigeben ein", "That computer's magpie didn't take this key — use one of its gateway keys in this provider": "Das magpie dieses Computers hat diesen Schlüssel nicht angenommen — trage bei diesem Anbieter einen seiner Zugangsschlüssel ein", "Couldn't reach that computer's magpie — check that it is running and its address": "Das magpie dieses Computers ist nicht erreichbar — prüfe, ob es läuft und die Adresse stimmt", + "The magpie on {computer}, where this account is signed in, uses it.": "Das magpie auf {computer}, wo dieses Konto angemeldet ist, verwendet ihn.", + "This key is read-only on that computer's magpie — give this provider a key with full access to use a reset from here": "Dieser Schlüssel ist im magpie dieses Computers schreibgeschützt — gib diesem Anbieter einen Schlüssel mit vollem Zugriff, um von hier einen Reset zu verwenden", + "That computer didn't say in time whether the reset was used — it may have been. Refresh the card before asking again": "Dieser Computer hat nicht rechtzeitig gesagt, ob der Reset verwendet wurde — vielleicht wurde er es. Aktualisiere die Karte, bevor du es erneut versuchst", + "That computer's magpie can't use a reset from here yet — update magpie there": "Das magpie dieses Computers kann noch keinen Reset von hier verwenden — aktualisiere magpie dort", + "That computer's magpie holds this key to a budget, models or accounts, so it uses none of its resets — give this provider a key with full access": "Das magpie dieses Computers begrenzt diesen Schlüssel auf ein Budget, Modelle oder Konten und verwendet daher keinen seiner Resets — gib diesem Anbieter einen Schlüssel mit vollem Zugriff", "That computer's magpie is too old to tell this key's limit — update magpie there": "Das magpie auf diesem Computer ist zu alt, um das Limit dieses Schlüssels zu nennen — aktualisiere magpie dort", "That computer answered this key's limit in a form magpie doesn't read — hover for more": "Dieser Computer hat das Limit des Schlüssels in einer Form gesendet, die magpie nicht liest — für mehr darüberfahren", "Gateway keys · {name}": "Zugangsschlüssel · {name}", diff --git a/internal/gui/assets/resetask.js b/internal/gui/assets/resetask.js index b4a1cdf3a..75dd001b4 100644 --- a/internal/gui/assets/resetask.js +++ b/internal/gui/assets/resetask.js @@ -12,6 +12,10 @@ window.askResetSheet = function (q) { ed.append(el("p", "lib-confirm", t(q.resets.count === 1 ? "{who} has 1 reset. Using it starts its windows again at once, as if none of them had been used. It can't be undone." : "{who} has {n} resets. Using one starts its windows again at once, as if none of them had been used. It can't be undone.", { who, n: q.resets.count }))); + // a remote magpie's card (office/codex, #3850): that magpie spends it, + // on the account signed in there + const remote = q.provider !== "codex" && q.from; + if (remote) ed.append(el("p", "lib-confirm reset-remote", t("The magpie on {computer}, where this account is signed in, uses it.", { computer: q.from }))); // which of them is used: the one that runs out first unless the user // picks another of those listed one by one (01huadalang on Discord), // and the dialog names the one it spends @@ -72,7 +76,10 @@ window.askResetSheet = function (q) { go.disabled = true; go.classList.add("busy"); try { - const out = await api("usage/codex-reset", chosen ? { user: q.user || "", credit: cards[chosen].id } : { user: q.user || "" }); + const ask = { user: q.user || "" }; + if (remote) ask.provider = q.provider; + if (chosen) ask.credit = cards[chosen].id; + const out = await api("usage/codex-reset", ask); // the providers' editor and Settings read the account's windows // and resets on their own, kept a minute: read again, as Usage is // (#1491); asked from the editor, closing goes back to it @@ -85,7 +92,7 @@ window.askResetSheet = function (q) { } catch (err) { go.disabled = false; go.classList.remove("busy"); - statusErr(err); + status(remote ? remoteResetError(err.message) : err.message, "err"); } }; const cancel = el("button", "text", t("Cancel")); @@ -99,3 +106,32 @@ window.askResetSheet = function (q) { $("#modal").classList.add("lib"); go.focus(); }; + +// remoteResetError says why a remote magpie used no reset (remote_quotas.go) +function remoteResetError(err) { + if (/^this key is read-only on the remote magpie/.test(err)) return t("This key is read-only on that computer's magpie — give this provider a key with full access to use a reset from here"); + if (/didn't say in time whether the reset was used/.test(err)) return t("That computer didn't say in time whether the reset was used — it may have been. Refresh the card before asking again"); + if (/^remote magpie doesn't share its quotas/.test(err)) return t("That computer's magpie can't use a reset from here yet — update magpie there"); + if (/^remote magpie holds this key/.test(err)) return t("That computer's magpie holds this key to a budget, models or accounts, so it uses none of its resets — give this provider a key with full access"); + if (/^remote magpie isn't shared/.test(err)) return t("That computer's magpie isn't shared — turn on Settings → Network and sharing → Share on local network there"); + if (/^remote magpie didn't take this key/.test(err)) return t("That computer's magpie didn't take this key — use one of its gateway keys in this provider"); + if (/^couldn't reach the remote magpie/.test(err)) return t("Couldn't reach that computer's magpie — check that it is running and its address"); + return err; +} + +// what a reset came to, in words (moved here from app.js; only this sheet says it) +function resetOutcome(out) { + switch (out.code) { + case "reset": return t(out.windows === 1 ? "1 window started again" : "{n} windows started again", { n: out.windows }); + case "nothing_to_reset": return t("nothing to start again — no window has been used, and the reset is kept"); + case "no_credit": return t("no reset left on the account"); + case "already_redeemed": + case "already_used": return t("that reset was already used"); + // Anthropic's + case "not_limited": return t("nothing to reset — no window is used up yet, and the reset is kept"); + case "cooldown": return t("a reset was used a short while ago — try again later"); + case "ineligible": return t("the account can't use a reset"); + case "unavailable": return t("resets can't be used right now — try again later"); + } + return out.code; +} diff --git a/internal/gui/tests/remote-codex-reset.test.cjs b/internal/gui/tests/remote-codex-reset.test.cjs new file mode 100644 index 000000000..51d25eea3 --- /dev/null +++ b/internal/gui/tests/remote-codex-reset.test.cjs @@ -0,0 +1,132 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// #3850 (prgrmrwy): magpie on a home server, and the office's remote magpie +// card said "1 reset" with no way to use it there. A remote magpie's Codex +// card now offers the reset as this computer's does: the same in-app +// confirmation (no confirm()), which says the magpie on that computer uses +// it, and nothing is spent before the user says so. The use names the +// card's remote provider and the account. A GLM team's resets (byWindow), +// spent on the vendor's page, and a remote's other cards offer none. What +// the remote answered goes in the user's words (a read-only key, no answer +// in time). The Usage page at 900px and 390px and the menu bar panel at +// 440px; English, Chinese (both), Japanese and German; Chromium and WebKit. +// No backend, the API is faked. +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(process.env.ASSET_DIR || path.resolve(__dirname, "../assets")); +const day = 864e5, base = Date.now(); +const soon = new Date(base + 2 * day).toISOString(); +const windows = [{ name: "5 hours", used: 100, resetsAt: new Date(base + 3600e3).toISOString() }, { name: "7 days", used: 60, resetsAt: new Date(base + 3 * day).toISOString() }]; +const quotas = [ + { provider: "office/codex", name: "Codex · Office", icon: "codex-color", from: "Office", user: "me@example.com", plan: "Plus", kind: "subscription", windows, + resets: { count: 1, until: soon } }, + // a GLM team's, read on the remote: spent on bigmodel.cn, not from here + { provider: "office/zhipu-team", name: "GLM Team · Office", icon: "zhipu", from: "Office", user: "team@example.com", kind: "subscription", windows, + resets: { count: 2, byWindow: true } }, +]; + +const READ_ONLY = "this key is read-only on the remote magpie; give the provider a key with full access to use a reset from here"; +const LATE = "Office didn't say in time whether the reset was used; it may have been. Refresh the card to see before asking again"; + +function serve(lang, posted, answer) { + const settings = { theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd", trayUsages: ["office/codex", "office/zhipu-team"], trayUsageEvery: 3 }; + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data, status = 200) => route.fulfill({ status, 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/usage/quotas") return json(quotas); + if (url.pathname === "/api/usage/codex-reset") { + posted.push(JSON.parse(req.postData() || "{}")); + return answer.error ? json({ error: answer.error }, 400) : json({ code: "reset", windows: 2 }); + } + 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).catch(() => ""), contentType }); + }; +} + +const KEYS = ["The magpie on {computer}, where this account is signed in, uses it.", + "This key is read-only on that computer's magpie — give this provider a key with full access to use a reset from here", + "That computer didn't say in time whether the reset was used — it may have been. Refresh the card before asking again", + "That computer's magpie can't use a reset from here yet — update magpie there", + "That computer's magpie holds this key to a budget, models or accounts, so it uses none of its resets — give this provider a key with full access"]; + +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}: a remote magpie's Codex reset is used from here, asked first`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const errors = []; + const say = (page, key, vars) => page.evaluate(([lang, key, vars]) => { + if (lang !== "en" && !I18N[lang]?.[key]) return "untranslated: " + key; + return t(key, vars); + }, [lang, key, vars]); + + const run = async (url, viewport, useSel, cardSel) => { + const posted = [], answer = {}; + const page = await (await browser.newContext({ viewport, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + page.on("dialog", (d) => { errors.push("a browser dialog: " + d.message()); d.dismiss(); }); + await page.route("**/*", serve(lang, posted, answer)); + await page.goto(url); + if (url.includes("panel")) await page.locator('#ptabs [data-ptab="usage"]').click(); + for (const k of KEYS) assert.notEqual(await say(page, k, { computer: "x" }), "untranslated: " + k); + + // the remote's Codex card offers its reset; the GLM team's doesn't + await page.locator(cardSel).first().waitFor(); + assert.equal(await page.locator(useSel).count(), 1, "one Use, on the remote Codex card"); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "nothing wider than the page"); + const ask = page.locator(".reset-ask"); + await page.locator(useSel).click(); + await ask.waitFor(); + assert.equal((await ask.locator(".reset-remote").textContent()).trim(), await say(page, "The magpie on {computer}, where this account is signed in, uses it.", { computer: "Office" })); + assert.equal(await page.evaluate(() => { const e = document.querySelector(".reset-ask").getBoundingClientRect(); return e.right <= innerWidth && e.left >= 0; }), true, "the confirmation fits"); + // Cancel spends nothing + await page.keyboard.press("Escape"); + await ask.waitFor({ state: "detached" }); + assert.equal(posted.length, 0, "nothing spent before the user says so"); + + // a read-only key there: said in the user's words, the sheet stays + answer.error = READ_ONLY; + await page.locator(useSel).click(); + await ask.locator("button.primary").click(); + await page.locator("#status.err").waitFor(); + assert.equal((await page.locator("#status").textContent()).trim(), await say(page, KEYS[1])); + assert.equal(await ask.isVisible(), true, "the confirmation stays to try again"); + // no answer in time: it may have been used + answer.error = LATE; + await ask.locator("button.primary").click(); + await page.waitForFunction((want) => document.querySelector("#status")?.textContent.trim() === want, await say(page, KEYS[2])); + await page.keyboard.press("Escape"); + await ask.waitFor({ state: "detached" }); + + // used: the remote card's provider and account are named + delete answer.error; + await page.locator(useSel).click(); + await ask.locator("button.primary").click(); + await ask.waitFor({ state: "detached" }); + assert.deepEqual(posted, [ + { user: "me@example.com", provider: "office/codex" }, + { user: "me@example.com", provider: "office/codex" }, + { user: "me@example.com", provider: "office/codex" }, + ]); + await page.context().close(); + }; + + for (const width of [900, 390]) await run("http://magpie.test/?view=usage", { width, height: 800 }, ".quota-resets button", ".quota-resets"); + await run("http://magpie.test/?mode=panel", { width: 440, height: 700 }, ".pq-use", ".pq-use"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/gui/usage.go b/internal/gui/usage.go index 2c9378033..b8f9748c0 100644 --- a/internal/gui/usage.go +++ b/internal/gui/usage.go @@ -399,32 +399,32 @@ func usageRoutes(mux *http.ServeMux, w Windows) { // spends one of a Codex account's rate-limit resets, which the page // has asked the user about first: the one they chose (Credit, an id // of its resets.each), else the one that runs out first; what it did - // comes back + // comes back. A card from a remote magpie (Provider "office/codex") + // has that magpie spend it, on its account (#3850) mux.HandleFunc("POST /api/usage/codex-reset", func(rw http.ResponseWriter, r *http.Request) { - var in struct{ User, Credit string } + var in struct{ Provider, User, Credit string } if err := json.NewDecoder(r.Body).Decode(&in); err != nil { fail(rw, err) return } + if in.Provider != "" && in.Provider != "codex" { + ctx, cancel := context.WithTimeout(r.Context(), provider.RemoteResetWait+10*time.Second) + defer cancel() + out, err := provider.UseRemoteCodexReset(ctx, in.Provider, in.User, in.Credit) + if err != nil { + fail(rw, err) + return + } + writeJSON(rw, out) + return + } ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) defer cancel() - out, err := provider.UseCodexResetCard(ctx, in.User, in.Credit) + out, err := provider.SpendCodexReset(ctx, in.User, in.Credit) if err != nil { fail(rw, err) return } - if out.Code == "reset" { - // routing and the Providers page know the windows started - // again by the time the page hears so, not at a later - // request's reading (#1491) - who := in.User - if who == "" { - who, _ = provider.CodexSignedIn() - } - wait, done := context.WithTimeout(ctx, 10*time.Second) - provider.AwaitAllowance(wait, "codex", who) - done() - } writeJSON(rw, out) }) } diff --git a/internal/provider/codex_resets.go b/internal/provider/codex_resets.go index 106998376..ce1ce2e83 100644 --- a/internal/provider/codex_resets.go +++ b/internal/provider/codex_resets.go @@ -249,6 +249,26 @@ func UseCodexResetCard(ctx context.Context, user, credit string) (ResetOutcome, return spendCodexReset(ctx, user, credit, ResetUsedByHand) } +// SpendCodexReset is a reset used by hand wherever it is asked: the Usage +// page's "Use a reset" and the gateway's RemoteCodexResetPath, for another +// magpie's card or an app holding a gateway key (#3850, prgrmrwy). It is +// UseCodexResetCard, then, when the windows started again, a wait of up +// to 10s for routing and the Providers page to know so (#1491). +func SpendCodexReset(ctx context.Context, user, credit string) (ResetOutcome, error) { + out, err := UseCodexResetCard(ctx, user, credit) + if err != nil || out.Code != "reset" { + return out, err + } + who := user + if who == "" { + who, _ = CodexSignedIn() + } + wait, done := context.WithTimeout(ctx, 10*time.Second) + AwaitAllowance(wait, "codex", who) + done() + return out, nil +} + // useCodexReset is UseCodexReset, the use kept as made for why. func useCodexReset(ctx context.Context, user, why string) (ResetOutcome, error) { return spendCodexReset(ctx, user, "", why) diff --git a/internal/provider/remote_quotas.go b/internal/provider/remote_quotas.go index 37de272f5..58804d700 100644 --- a/internal/provider/remote_quotas.go +++ b/internal/provider/remote_quotas.go @@ -37,6 +37,19 @@ const RemoteCardsPath = "/v1/magpie/quotas/cards" // RemoteCardsPath. const RemoteRefreshPath = "/v1/magpie/quotas/refresh" +// RemoteCodexResetPath has the gateway spend one of its Codex account's +// rate-limit resets (?user=, the account always named; &credit=, one of +// its resets.each, else the one that runs out first), as its Usage page's +// "Use a reset" does (#3850, prgrmrwy): a reset shown on another magpie's +// card, or in an app reading the cards, can be used from there too. It +// can't be undone, so the gateway takes it only with a gateway key of full +// access, never from a page or app it lets in without one. +const RemoteCodexResetPath = "/v1/magpie/quotas/codex-reset" + +// RemoteResetWait is how long a remote magpie is waited for to spend a +// reset: its use (20s at most) and its wait for routing to know (10s). +const RemoteResetWait = 35 * time.Second + // remoteCardsFor is how long another magpie's cards are kept here before // they are asked for again: reading its cache costs it nothing from the // vendors, but the menu bar and alerts ask often. @@ -59,6 +72,14 @@ const errRemoteNotShared = "remote magpie isn't shared; turn on Share on local n // errRemoteKey is a remote magpie that didn't take this provider's key (401). const errRemoteKey = "remote magpie didn't take this key; use one of its enabled gateway keys" +// KeyReadOnlyCode is the error code a gateway answers a read-only key +// with on a route that uses or changes anything. +const KeyReadOnlyCode = "gateway_key_read_only" + +// errRemoteReadOnly is a remote magpie whose key here is read-only: it +// shows the cards, and spends nothing. +const errRemoteReadOnly = "this key is read-only on the remote magpie; give the provider a key with full access to use a reset from here" + // KeyHeldCode is the error code a gateway answers a key held to a budget, // models or accounts with, where its own accounts would be told (#1981): // the key is someone else's to use, and is told its own limit alone. @@ -238,8 +259,13 @@ func remoteCards(ctx context.Context, p Provider, fresh bool) []SubscriptionQuot q.Name += " · " + name q.From = name // what is pressed on a card acts on this computer's accounts: - // a Codex reset or a check-in is the other magpie's to do - q.Resets, q.Checkins, q.CheckinBy, q.Checkin, q.CheckinOff = nil, false, "", nil, false + // a check-in is the other magpie's to do. A Codex reset is + // spent there when pressed here (UseRemoteCodexReset, #3850); + // a GLM team's (byWindow) is spent on the vendor's page + if q.Provider != p.ID+"/codex" || q.Resets != nil && q.Resets.ByWindow { + q.Resets = nil + } + q.Checkins, q.CheckinBy, q.Checkin, q.CheckinOff = false, "", nil, false if q.Windows == nil { q.Windows = []QuotaWindow{} } @@ -393,46 +419,10 @@ func remoteKey(h http.Header, key string) { // remoteJSON asks p's gateway, with its key, for a {"data": …} list. func remoteJSON(ctx context.Context, p Provider, method, path string, dst any) error { - ctx, cancel := context.WithTimeout(ctx, 8*time.Second) - defer cancel() - req, err := http.NewRequestWithContext(ctx, method, p.Anthropic+path, nil) + b, err := remoteBody(ctx, p, method, path, 8*time.Second) if err != nil { return err } - req.Header.Set("Accept", "application/json") - p.signRemote(req, p.Key) - res, err := p.Do(http.DefaultClient, req) - if err != nil { - return fmt.Errorf("%s %s: %w", errRemoteUnreachable, remoteName(p), err) - } - defer res.Body.Close() - b, _ := io.ReadAll(io.LimitReader(res.Body, 8<<20)) - switch { - case res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusMethodNotAllowed: - return fmt.Errorf("%s", errRemoteNoShare) - case res.StatusCode == http.StatusForbidden: - var e struct { - Error struct { - Code string `json:"code"` - } `json:"error"` - } - if json.Unmarshal(b, &e) == nil && e.Error.Code == KeyHeldCode { - return errKeyHeld - } - return fmt.Errorf("%s", errRemoteNotShared) - case res.StatusCode == http.StatusUnauthorized: - return fmt.Errorf("%s", errRemoteKey) - case res.StatusCode < 200 || res.StatusCode >= 300: - var e struct { - Error struct { - Message string `json:"message"` - } `json:"error"` - } - if json.Unmarshal(b, &e) == nil && e.Error.Message != "" { - return fmt.Errorf("%s: %s", remoteName(p), e.Error.Message) - } - return fmt.Errorf("%s answered %s", remoteName(p), res.Status) - } var list struct { Data json.RawMessage `json:"data"` } @@ -444,3 +434,97 @@ func remoteJSON(ctx context.Context, p Provider, method, path string, dst any) e } return json.Unmarshal(list.Data, dst) } + +// remoteBody asks p's gateway, with its key, waiting wait at most, and +// gives back the body of a 2xx answer; any other is an error that says +// what to do about it. +func remoteBody(ctx context.Context, p Provider, method, path string, wait time.Duration) ([]byte, error) { + ctx, cancel := context.WithTimeout(ctx, wait) + defer cancel() + req, err := http.NewRequestWithContext(ctx, method, p.Anthropic+path, nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/json") + p.signRemote(req, p.Key) + res, err := p.Do(http.DefaultClient, req) + if err != nil { + return nil, fmt.Errorf("%s %s: %w", errRemoteUnreachable, remoteName(p), err) + } + defer res.Body.Close() + b, err := io.ReadAll(io.LimitReader(res.Body, 8<<20)) + if err != nil && ctx.Err() != nil { + return nil, fmt.Errorf("%s %s: %w", errRemoteUnreachable, remoteName(p), ctx.Err()) + } + var e struct { + Error struct { + Code string `json:"code"` + Message string `json:"message"` + } `json:"error"` + } + switch { + case res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusMethodNotAllowed: + return nil, fmt.Errorf("%s", errRemoteNoShare) + case res.StatusCode == http.StatusForbidden: + json.Unmarshal(b, &e) + switch e.Error.Code { + case KeyHeldCode: + return nil, errKeyHeld + case KeyReadOnlyCode: + return nil, fmt.Errorf("%s", errRemoteReadOnly) + } + return nil, fmt.Errorf("%s", errRemoteNotShared) + case res.StatusCode == http.StatusUnauthorized: + return nil, fmt.Errorf("%s", errRemoteKey) + case res.StatusCode < 200 || res.StatusCode >= 300: + if json.Unmarshal(b, &e) == nil && e.Error.Message != "" { + return nil, fmt.Errorf("%s: %s", remoteName(p), e.Error.Message) + } + return nil, fmt.Errorf("%s answered %s", remoteName(p), res.Status) + } + return b, nil +} + +// errRemoteResetUnknown is a reset asked of a remote magpie that didn't +// answer in time: it may have been spent there, so it isn't asked again. +const errRemoteResetUnknown = "%s didn't say in time whether the reset was used; it may have been. Refresh the card to see before asking again" + +// UseRemoteCodexReset has the remote magpie whose card id is (its Codex +// card, "office/codex") spend one of user's resets there, as its own +// Usage page would (#3850, prgrmrwy: the card here said "1 reset", and +// using it took a walk to the other computer). credit is one of the +// card's resets.each, "" for the one that runs out first. The account is +// always named: which one the remote is signed in to isn't known here, +// and a reset can't be undone. The remote's cards are read afresh after, +// so the card shows its windows started again. +func UseRemoteCodexReset(ctx context.Context, id, user, credit string) (ResetOutcome, error) { + p, card, ok := remoteOf(id) + if !ok || card != "codex" { + return ResetOutcome{}, fmt.Errorf("%s is no remote magpie's Codex card", id) + } + if user == "" { + return ResetOutcome{}, errors.New("name the Codex account whose reset is used") + } + q := url.Values{"user": {user}} + if credit != "" { + q.Set("credit", credit) + } + b, err := remoteBody(ctx, p, http.MethodPost, RemoteCodexResetPath+"?"+q.Encode(), RemoteResetWait) + if err != nil { + // no answer: the remote may have spent it all the same + if errors.Is(err, context.DeadlineExceeded) { + return ResetOutcome{}, fmt.Errorf(errRemoteResetUnknown, remoteName(p)) + } + return ResetOutcome{}, err + } + var out ResetOutcome + if err := json.Unmarshal(b, &out); err != nil || out.Code == "" { + return ResetOutcome{}, fmt.Errorf(errRemoteResetUnknown, remoteName(p)) + } + // the remote read the card again after the reset; what it has now + read, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second) + remoteCards(read, p, true) + cancel() + toldUsage() + return out, nil +} diff --git a/internal/provider/remote_quotas_test.go b/internal/provider/remote_quotas_test.go index 239f4112e..3d8afa0a7 100644 --- a/internal/provider/remote_quotas_test.go +++ b/internal/provider/remote_quotas_test.go @@ -7,6 +7,7 @@ import ( "net/http/httptest" "strings" "sync" + "sync/atomic" "testing" "time" ) @@ -106,7 +107,8 @@ func TestRemoteMagpieCards(t *testing.T) { peer := &fakePeer{cards: []SubscriptionQuota{ {Provider: "codex", Name: "Codex", Icon: "codex", User: "a@x.com", Kind: "subscription", Windows: []QuotaWindow{{Name: "5h", Used: 40}}, Resets: &ResetCredits{Count: 1}, Checkins: true}, - {Provider: "zhipu", Name: "GLM Coding", Kind: "plan", Windows: []QuotaWindow{{Name: "5h", Used: 10}}}, + {Provider: "zhipu", Name: "GLM Coding", Kind: "plan", Windows: []QuotaWindow{{Name: "5h", Used: 10}}, + Resets: &ResetCredits{Count: 2, ByWindow: true}}, {Provider: "deepseek", Name: "DeepSeek", Kind: "balance", Balance: "¥12.00"}, {Provider: "home/codex", Name: "Codex · Home", Kind: "subscription", From: "Home"}, }} @@ -125,10 +127,12 @@ func TestRemoteMagpieCards(t *testing.T) { if c == nil || c.Name != "Codex · Office" || c.From != "Office" || c.User != "a@x.com" || c.Icon != "codex" || len(c.Windows) != 1 || c.Windows[0].Used != 40 { t.Fatalf("subscription card: %+v", c) } - if c.Resets != nil || c.Checkins { - t.Errorf("a remote card's buttons are kept: %+v", c) + // a Codex reset is used there when pressed here (#3850); a check-in + // isn't asked of another computer + if c.Checkins || c.Resets == nil || c.Resets.Count != 1 { + t.Errorf("a remote Codex card's buttons: %+v", c) } - if p := find(plans, "office/zhipu"); p == nil || p.Name != "GLM Coding · Office" { + if p := find(plans, "office/zhipu"); p == nil || p.Name != "GLM Coding · Office" || p.Resets != nil { t.Errorf("plan: %+v", plans) } if b := find(balances, "office/deepseek"); b == nil || b.Balance != "¥12.00" { @@ -474,3 +478,71 @@ func TestRemoteMagpieCardsKeptByKey(t *testing.T) { } } } + +// #3850: a reset asked of a remote magpie that is too old to spend one, +// or that doesn't answer in time, says what it means for the card: update +// magpie there, or the reset may have been used there, so read the card +// before asking again (never asked again by itself). +func TestRemoteCodexResetAnswers(t *testing.T) { + var asks atomic.Int32 + stall := make(chan struct{}) + t.Cleanup(func() { close(stall) }) + var mode atomic.Value + mode.Store("old") + remoteQuotaHome(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != RemoteCodexResetPath { + w.Write([]byte(`{"data":[]}`)) + return + } + asks.Add(1) + if r.Method != http.MethodPost || r.URL.Query().Get("user") != "a@x.com" || r.URL.Query().Get("credit") != "c-2" || r.Header.Get("Authorization") != "Bearer sk-magpie-office" { + w.WriteHeader(http.StatusBadRequest) + return + } + switch mode.Load() { + case "old": + w.WriteHeader(http.StatusNotFound) + case "stall": + select { + case <-stall: + case <-r.Context().Done(): + } + case "readonly": + w.WriteHeader(http.StatusForbidden) + w.Write([]byte(`{"error":{"message":"read-only","code":"` + KeyReadOnlyCode + `"}}`)) + case "ok": + w.Write([]byte(`{"code":"reset","windows":2}`)) + } + })) + ctx := context.Background() + if _, err := UseRemoteCodexReset(ctx, "office/codex", "a@x.com", "c-2"); err == nil || !strings.HasPrefix(err.Error(), "remote magpie doesn't share its quotas") { + t.Fatalf("an old remote: %v", err) + } + mode.Store("readonly") + if _, err := UseRemoteCodexReset(ctx, "office/codex", "a@x.com", "c-2"); err == nil || !strings.HasPrefix(err.Error(), "this key is read-only on the remote magpie") { + t.Fatalf("a read-only key: %v", err) + } + mode.Store("stall") + short, cancel := context.WithTimeout(ctx, 300*time.Millisecond) + _, err := UseRemoteCodexReset(short, "office/codex", "a@x.com", "c-2") + cancel() + if err == nil || !strings.Contains(err.Error(), "may have been") { + t.Fatalf("no answer in time: %v", err) + } + mode.Store("ok") + out, err := UseRemoteCodexReset(ctx, "office/codex", "a@x.com", "c-2") + if err != nil || out.Code != "reset" || out.Windows != 2 { + t.Fatalf("spent: %+v %v", out, err) + } + if n := asks.Load(); n != 4 { + t.Fatalf("asked %d times, want once each", n) + } + for _, id := range []string{"office/zhipu", "office", "codex", "nowhere/codex"} { + if _, err := UseRemoteCodexReset(ctx, id, "a@x.com", ""); err == nil { + t.Errorf("%s was asked", id) + } + } + if n := asks.Load(); n != 4 { + t.Fatalf("a card not a remote's Codex card asked the remote (%d)", n) + } +}