diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index a982e7816..c86d81040 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -256,7 +256,6 @@ recorded as a prediction failure (`noPrediction`). - An agent's fast pick (`settings.FastPicks`, the bolt in its picker, #954) may also be in `settings.UltraPicks` (#1954), offered by the GUI only where one of Codex's accounts lists Ultrafast on the model (`provider.CanUltra`, `UltraModels`). `fastPick` marks its candidates `ultra`; a try of one goes with `service_tier: "ultrafast"` on Chat and Responses, and an agent on Messages carries it in the context (`withUltra`) to `forwardTranslated`, which sets `Request.Ultrafast` for the ChatGPT backend. Either way the same check as a client's own Ultrafast ask applies, now on Chat as well as Responses: an account whose list doesn't offer it is put after a mate that does (`tierMate`), or, with none left, sent `priority`. A Chat body's own `service_tier: "ultrafast"` is parsed as Ultrafast too (`chat.go`). `TestUltraPickSentUltrafast`. - A group's member may be Ultrafast as well as fast (`Group.Ultra`, a subset of `Fast`, `Group.SetMemberTier`; the member's button steps Standard speed, Fast, Ultrafast where `ultraOK`; `ultra=` in `magpie group`), and a model has its own speed (`settings.ModelTiers`, "/" to `priority` or `ultrafast`, `provider.SetModelTier`, Model settings and `magpie model tier`; kdajenks on X). The gateway sends it on a direct pick for an agent with no fast pick of its own (`provider.ModelTier`, the branch after `IsFastPick`), through the same `fastPick`, so an account without Ultrafast is sent `priority`. A group member goes as the group says. `TestModelTierSentToEveryAgent`, `TestGroupMemberUltrafast`, `model-speed.test.cjs`. - Codex's service tier (`settings.CodexServiceTier`, a row in Codex's settings, JackyFill on X) sets the `service_tier` of every request of Codex's, whatever Codex's own `/fast` asked: empty is as Codex asks (the default, nothing changed), `default` sends none (standard), `priority` is Codex's Fast and `ultrafast` its Ultra Fast (the request values in Codex's `ServiceTier`; Flex is not offered, since the ChatGPT backend's requests drop it in `codex_request.go`). `codexTiered` ([`codex_tier.go`](../../internal/gateway/codex_tier.go)) rewrites the body as it comes in, on both of Codex's ways in: `codexBackend` (Codex signed in, `/backend-api/codex`) and the main handler's Codex-on-Responses block, which a websocket turn reaches too. Everything after treats it as Codex's own ask: an account whose list lacks Ultrafast is put after a mate that offers it (`tierMate`) or sent `priority`, and a provider that refuses a tier drops it. A model with no provider (`gpt-…`, Codex's own sign-in, whose plan magpie doesn't know) is sent `ultrafast` only where one of magpie's Codex accounts lists it on the model (`UltraModels`), else `priority`. Another agent's request is never touched, and fast picks still apply after. `TestCodexServiceTierSet`, `codex-service-tier.test.cjs`. -- The Codex client magpie presents to the ChatGPT backend (`settings.CodexClient`, a row in Codex's settings, ouhthuo on X) is Codex CLI by default (`originator: codex_cli_rs`, `User-Agent: codex_cli_rs/ (; ) `) or `desktop`: `originator: Codex Desktop` and `Codex Desktop/ (; ) unknown (Codex Desktop; )`, as codex-rs `default_client.rs` builds it from the originator the app sets. Only these two values are accepted. `codexClientHeaders` in `internal/provider/codex_request.go` is the one place both headers are set, so a model request (`codexSign`), the account calls (`/wham`, resets, token refresh, device sign-in) and a test asked as Codex all follow it; the sign-in's authorize URL keeps `codex_cli_rs`. A real Codex client's own originator never reaches the backend on a signed-in account: `codexSign` replaces it, which this setting now chooses. - A usage record carries its prompt's cache beside `in` and `out` (#1839): `cache_read` (tokens read from the vendor's cache) and `cache_write` (cache creation, Anthropic's `cache_creation_input_tokens`; `cache_write_1h` the part written for an hour). `in` holds neither. Both are written on every record, 0 too, so a prompt that missed the cache reads as that. A record from before then has neither and reads as 0. Every route fills them: Anthropic's messages, Chat (OpenAI's `prompt_tokens_details.cached_tokens`, DeepSeek's `prompt_cache_hit_tokens`), Responses (`input_tokens_details.cached_tokens`) and Gemini (`cachedContentTokenCount`), passed through or translated, whole or streamed, a plugin's fetch, and the Claude subscription bridge. System One's decision calls report no cache. `TestUsageRecordsCacheTokensOnEveryRoute`, `TestPluginUsageRecordsCacheTokens`, `TestClaudeSubscriptionUsageKeepsCacheTokens`, `TestRecordAlwaysCarriesCacheTokens`. - What the vendor read from its cache reaches the agent in the names its SDK reads, not only the record. A relayed Chat reply whose usage tells the cache in another vendor's names (a relay's Anthropic `cache_read_input_tokens` and `cache_creation_input_tokens`, DeepSeek's `prompt_cache_hit_tokens` or Moonshot's top-level `cached_tokens` beside a 0 in `prompt_tokens_details`) is told in OpenAI's too, streamed (`chatTidy`) and whole (`chatWhole`), by `openAIUsage` in [`chattidy.go`](../../internal/gateway/chattidy.go): `prompt_tokens_details.cached_tokens` (and `cache_write_tokens`), with `prompt_tokens` and `total_tokens` made to hold the cached part where the vendor left it out. Every other field stays, and a usage already in OpenAI's names, or with no cache, goes byte for byte; one in OpenAI's names alone isn't even decoded (`mayMendUsage`). pi-ai, which DeepSeek Harness and Pi use, reads `prompt_tokens_details.cached_tokens` first, a 0 there too, and maps no Anthropic names at all, so such a relay showed DSH 缓存命中 0% while magpie had counted the hit (B3TT3R on Discord asked; DeepSeek's own API sends both names and was already read right). Relayed Responses and Messages replies, translated replies and a plugin's need nothing: their usage is written in the agent's own names. `TestAgentReadsCacheTokensOnEveryRoute`, `TestPluginAgentReadsCacheTokens`, `TestOpenAIUsageLeavesOpenAIsAlone`, `TestMayMendUsageOnlyOtherNames` in [`usage_cache_agent_test.go`](../../internal/gateway/usage_cache_agent_test.go). - A request whose key is a Claude sign-in (`claudeSignIn`: `Authorization: Bearer sk-ant-oat…`, Claude Code signed in to claude.ai with magpie as its base URL) is never told a 401, nor a 403 saying "OAuth token has been revoked". magpie never passes that sign-in on, so such an answer is a provider refusing magpie's credential, or one of magpie's own Claude accounts lapsing; told it, Claude Code renews its own sign-in before each of its retries (ten for one request) and then asks to `/login`. Any error whose message mentions x-api-key, whatever its status, Claude Code tells as "Not logged in · Please run /login" too. It is told as a 502 in magpie's words, an `api_error` saying " refused magpie's credential (HTTP 401): …" with x-api-key said as "API key", and any other error such a request is told keeps its status with x-api-key said as "API key", as does a stream's error after its 200 (`keepsSignIn`, `claude_signin.go`). Recent calls and the usage log keep the provider's status and message. Any other 403, and a request with magpie's key or an API key, is answered as before. The sign-in's beta (`oauth-…` in `anthropic-beta`) isn't passed on either (`askedBetas`), so a provider gets the request as Claude Code with magpie's key sends it; a provider's own `header.anthropic-beta` still goes. diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 01fe8f728..bbc7e7d94 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -68,7 +68,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | 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 Remote magpie's cards (`GET /v1/magpie/quotas/cards`, `writeCards`) carry the estimate too, for the owner or a key with no limits on what it sees, since the computer reading them has none of the remote's calls to reckon from (linkaww on Discord: a Docker magpie's ChatGPT Pro week showed no whole on the other computer; `TestRemoteMagpieCardsCarryTheirWholes`). A Codex card's estimate counts the calls of a ChatGPT API account (`chatgpt-api`) that is the same ChatGPT account, whose plan limits they share: the tokens of both must name the same `chatgpt_account_id` and `chatgpt_user_id`, never matched by name, so two Team seats of one email stay apart (`SamePlanAccounts` in [`chatgpt_same_plan.go`](../../internal/provider/chatgpt_same_plan.go), jctaoo on Discord, `TestWindowHoldsCountsTheSameChatGPTAccountThroughTheAPI`). A window that has just reset, with too little used to scale (`HoldsLow`, `HoldsNoneRouted`), keeps the account's last whole for that window, marked `holds.prevAt` (the time it was reckoned; the GUI's tooltip says which window it came from, as a past cycle's does) until it tells its own; the last whole per account and window is kept in `window-holds.json` (`carryHolds` in [`window_holds_carry.go`](../../internal/usage/window_holds_carry.go), every provider's, Musikrv77852 on X; `TestWholeKeptAcrossReset`, `quota-holds.test.cjs`). 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). What it has kept includes its own Remote magpies' cards as it last read them (`passedOnCards`, no remote asked), so a chain passes every card on (yuyong_id on Discord: magpie3 → magpie2 → magpie1 showed none of magpie1's Codex at magpie3), named after each magpie (`magpie2/magpie1/codex`, "Codex · magpie1 · magpie2"); the card standing for a remote and its keys' limits stay the reader's own. Each card carries `via`, the `catalog.Self` of each magpie it went through, and a reader leaves out one that loops (`catalog.Loops`, as a model's `magpie_via`). A refresh of such a card is passed to the magpie it came from (`quotaCardsRefresh` takes a card id this magpie has from a remote); a Codex reset is offered on the magpie next door only, and quota history isn't passed on. The status line's kept report (`KeptQuotaReport`) has a remote's cards the same way. A ChatGPT account's card has an *Image generation* row (`WithImageLane`, [`image_lane.go`](../../internal/provider/image_lane.go), `Lane` `images`, Text and Aside so routing, holds and history never see it; hqqqqqqqh on X, #6160): ChatGPT's images have a quota apart from the 5-hour and weekly windows, and neither `/wham/usage` (`additional_rate_limits` is null) nor the reply headers (`x-codex-primary-*`, `x-codex-secondary-*`) tell it. So the row says *Used up* with the reset time while the image model is resting on that account after a refusal (`ImageRest`, the gateway's `restingUntil`, whose time is the refusal's `resets_at`, #2244) and *Unknown* otherwise, never a share or a count (`TestWithImageLaneOnlyReadCodexCards`, `TestCodexImageRowIsTheRefusalsResetTime`, `codex-image-row.test.cjs`). Not done: the count of images made in the window. 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 beside the key's own card the remote's card says it tells this key no quotas, and that on that computer Quotas is turned on for the key and it is let use every model of a provider whose usage it is to see (`errRemoteHeld`; yi_time on Discord saw the remote's Claude vanish from every page with no word). 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 held as before when that is none (`writeCards`), so that key shows the same card. 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) | -| Two magpies each the other's remote | The list a magpie gives another magpie (`X-Magpie-Drawers`) names, as `magpie_via`, the magpies each model passes through to its vendor, itself last (`catalog.ViaHere`, `viaOf`; a routing group's are its members' together, so a group with the other magpie's own group of the model in it is left out there too). Each process has a random id (`catalog.Self`). A fetched list leaves out a model whose `magpie_via` has this magpie and another one (it went out of here and came back), or more than `MaxVia` (8), so two magpies that are each other's remote no longer list each other's models back one level deeper on every 10-minute fetch, without end, each level another member of the found `auto/` group and another trip round the two (cdredfox on Discord, 100-200% CPU). A remote that is this magpie itself (sync carries a Remote magpie provider to the computer it names, hanslin1666) has its models through this id alone, taken once; one through this id twice or more is left out. Such a remote is found by its own list: a fetch whose models' `magpie_via` ends with this magpie's own `Self` is kept, by provider id and the address it answered at, in `remote-self.json` (`noteSelf`; another lister, or a list with no via, takes it away; an empty list or a failed fetch changes nothing; this computer's own file, never in a backup or a sync). The provider is then left out (`SelfLeftOut` in `On`, `SwitchedOff`, `remoteMagpies`): its models are not listed beside this magpie's own nor in a found group, and a request naming one, an agent's pick sync brought from the other computer, is served here with the remote's id taken off the front (`ThroughSelf` in `Resolve` and `ResolveRoute`), not passed through the gateway again. The Providers row says *This magpie* (greyed while left out) and its editor says why, with **Use it anyway** (`KeepSelf`, `provider/keepself`, `SetKeepSelf`), the user's to set (hanslin1666): kept, it is served as any remote, each request twice through this magpie. `KeepSelf` is this computer's own like `KeepLogin` (`Mirror`, `Restore`, blanked in davsync's `hashes`), since the other computer's copy points at this one, which is not itself (`TestRemoteMagpieThatIsThisOneIsLeftOut`, `TestRemoteSelfRecord`, `remote-self.test.cjs`). Each request passed on to a Remote magpie says how many magpies it went through (`X-Magpie-Hops`, `passOnCaller`); one that arrives having passed `MaxVia` is answered 508 Loop Detected (`withCaller`), read only from a magpie's request and taken off every request as it arrives. A magpie older than the field sends none, and its models are taken as they were. The quota cards a Remote passes on follow the same ways (X on 0.1.3678: A → B → C → A told Kiro and Codex by `remote-B/kiro` and `remote-B/remote-C/remote-A/remote-B/remote-C/kiro`, hours apart, to a Remote enabled for one local model): a card's `via` that names any magpie twice is a loop too, so one that came round after this magpie restarted (its old `Self` is no longer this one's) is left out (`catalog.Loops`), and isn't kept in `remoteCardCache` (`keepRemoteCards`). A Remote's cards are shown, and passed on, only for the providers it is enabled for: the card's provider id must be the provider path of an exposed model there (its id less the last part, or a parent of it, whole parts only: relay/strata enabled tells relay/strata, never relay/kiro; `remoteCardWanted`, `cardWantedFor`, `TestRemoteCardWantedByWholePath`, 748975219 on X), unknown, so all shown, while its list isn't read. One subscription account's copies (same provider, same `user`) are one card, the newest complete reading, then the shorter way (`oneCardPerAccount`, in `RemoteCards` and `CachedCards`; a key's cards, whose `user` is a name two keys may share, are not merged) (`TestRemoteCardsFollowEnabledModelsAndDedupe`, `TestLoopsOnARepeatedMagpie`). | [`magpie_via.go`](../../internal/catalog/magpie_via.go), [`live.go`](../../internal/catalog/live.go), [`gateway.go`](../../internal/gateway/gateway.go), [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`remote_self.go`](../../internal/provider/remote_self.go), [`remote_quotas_scope.go`](../../internal/provider/remote_quotas_scope.go) | +| Two magpies each the other's remote | The list a magpie gives another magpie (`X-Magpie-Drawers`) names, as `magpie_via`, the magpies each model passes through to its vendor, itself last (`catalog.ViaHere`, `viaOf`; a routing group's are its members' together, so a group with the other magpie's own group of the model in it is left out there too). Each process has a random id (`catalog.Self`). A fetched list leaves out a model whose `magpie_via` has this magpie and another one (it went out of here and came back), or more than `MaxVia` (8), so two magpies that are each other's remote no longer list each other's models back one level deeper on every 10-minute fetch, without end, each level another member of the found `auto/` group and another trip round the two (cdredfox on Discord, 100-200% CPU). A remote that is this magpie itself (sync carries a Remote magpie provider to the computer it names, hanslin1666) has its models through this id alone, taken once; one through this id twice or more is left out. Such a remote is found by its own list: a fetch whose models' `magpie_via` ends with this magpie's own `Self` is kept, by provider id and the address it answered at, in `remote-self.json` (`noteSelf`; another lister, or a list with no via, takes it away; an empty list or a failed fetch changes nothing; this computer's own file, never in a backup or a sync). The provider is then left out (`SelfLeftOut` in `On`, `SwitchedOff`, `remoteMagpies`): its models are not listed beside this magpie's own nor in a found group, and a request naming one, an agent's pick sync brought from the other computer, is served here with the remote's id taken off the front (`ThroughSelf` in `Resolve` and `ResolveRoute`), not passed through the gateway again. The Providers row says *This magpie* (greyed while left out) and its editor says why, with **Use it anyway** (`KeepSelf`, `provider/keepself`, `SetKeepSelf`), the user's to set (hanslin1666): kept, it is served as any remote, each request twice through this magpie. `KeepSelf` is this computer's own like `KeepLogin` (`Mirror`, `Restore`, blanked in davsync's `hashes`), since the other computer's copy points at this one, which is not itself (`TestRemoteMagpieThatIsThisOneIsLeftOut`, `TestRemoteSelfRecord`, `remote-self.test.cjs`). Each request passed on to a Remote magpie says how many magpies it went through (`X-Magpie-Hops`, `passOnCaller`); one that arrives having passed `MaxVia` is answered 508 Loop Detected (`withCaller`), read only from a magpie's request and taken off every request as it arrives. A magpie older than the field sends none, and its models are taken as they were. The quota cards a Remote passes on follow the same ways (X on 0.1.3678: A → B → C → A told Kiro and Codex by `remote-B/kiro` and `remote-B/remote-C/remote-A/remote-B/remote-C/kiro`, hours apart, to a Remote enabled for one local model): a card's `via` that names any magpie twice is a loop too, so one that came round after this magpie restarted (its old `Self` is no longer this one's) is left out (`catalog.Loops`), and isn't kept in `remoteCardCache` (`keepRemoteCards`). A Remote's cards are shown, and passed on, only for the providers it is enabled for: the card's provider id must be the provider path of an exposed model there (its id less the last part, or a parent of it, whole parts only: relay/strata enabled tells relay/strata, never relay/kiro; `remoteCardWanted`, `cardWantedFor`, `TestRemoteCardWantedByWholePath`, 748975219 on X), unknown, so all shown, while its list isn't read, and all shown for a Remote set to Select none (it serves no model, its usage is still read; a user on X, 0.1.3929, `TestRemoteSelectNoneStillShowsItsCards`). One subscription account's copies (same provider, same `user`) are one card, the newest complete reading, then the shorter way (`oneCardPerAccount`, in `RemoteCards` and `CachedCards`; a key's cards, whose `user` is a name two keys may share, are not merged) (`TestRemoteCardsFollowEnabledModelsAndDedupe`, `TestLoopsOnARepeatedMagpie`). | [`magpie_via.go`](../../internal/catalog/magpie_via.go), [`live.go`](../../internal/catalog/live.go), [`gateway.go`](../../internal/gateway/gateway.go), [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`remote_self.go`](../../internal/provider/remote_self.go), [`remote_quotas_scope.go`](../../internal/provider/remote_quotas_scope.go) | | A remote magpie that moved | Computer A's router hands it a new address now and then (luckymanjc on Discord), and B's Remote magpie, saved at the old one, reached nothing. When B can't connect to it at all (a dial error, `unconnected`), its list fetch (`fetch` in [`models.go`](../../internal/provider/models.go)) and the gateway's request (`forward` in [`gateway.go`](../../internal/gateway/gateway.go)) call `SeekMoved` ([`remote_moved.go`](../../internal/provider/remote_moved.go)): every address of the old one's /24 and of up to four of B's own private /24s is dialled at A's port (500ms each, 128 at once, `lanNeighbours`). Whatever takes the connection there may be anyone's (a café's network, A switched off), so it is sent neither the key nor the provider's headers until it proves it holds the key (`proves`): B POSTs a nonce of its own and `RemoteKeyID` (the key's sha256, hex) to `RemoteProvePath` (`/v1/magpie/prove`) with no key and no proxy, and checks with `hmac.Equal` that the answer is `RemoteProof`: HMAC-SHA256 under the key of the nonce and the address B dialled. A answers it ([`remote_prove.go`](../../internal/gateway/remote_prove.go)) for an enabled gateway key of that id (`access.ProveSecret`: constant-time compares over every key, then `Check`) at the address the connection reached it on (`http.LocalAddrContextKey`), so a host passing B's nonce on to A elsewhere hands back a proof for A's address, not its own; 404 for a key it hasn't or has turned off. Only an address that proved is asked `/v1/models` with the key, and the first that lists 200 and whose list this magpie didn't make (`magpie_via`) is saved as the provider's address and asked again. A magpie from before the route, one behind a port forward or NAT (it is reached at another address than its own), or one behind a proxy that needs the provider's headers, is not found, and the user types the new address. A name or a public address is never looked around, an address the user changed meanwhile stands, and a provider is looked for once a minute at most, callers at once sharing the look (`TestRemoteMagpieKeyGoesToNoNeighbour`: an impostor that lists 200 for anything, one with a proof under another key, one with a garbled proof and one relaying to the real magpie are sent no key or header and not saved, and the real one is; `TestRemoteProof`, `TestRemoteMagpieFoundMoved`, `TestRemoteMagpieNotFoundStays`, `TestRemoteMagpieMovedIsFound`, `TestRemoteProveAnswersOnlyTheKeysHolder`). | | 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) | | An endpoint's catalog | A key's provider with no catalog of its own (none named, none from a preset) is priced from the models.dev catalog whose `api` is one of its endpoints (`EndpointCatalog`, `catalog.AtEndpoint`; a trailing slash and case don't count, and an Anthropic base, kept as its root, is also matched with its `/v1`). Only when exactly one catalog is at that address, and it isn't a plan's (an id with `-plan`, or a `membershipCatalogs` one): a plan lists its membership's $0, and two catalogs at one address can't be told apart. A subscription's account never gets one. A provider at AMD's own endpoint is priced from `amd`, which lists Qwen3.8-27B at $0, a price, where its maker sells no such model and it had none (#2052); a relay's endpoint matches nothing and its model stays unpriced, never priced at a reseller's guess. `magpie model price` names the catalog, and says how to give a price when none is known. | [`models.go`](../../internal/provider/models.go), [`catalog.go`](../../internal/catalog/catalog.go) | diff --git a/internal/gui/api.go b/internal/gui/api.go index bc5c24a05..123c0658d 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -2199,20 +2199,6 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { } writeJSON(rw, settingsState()) }) - // the Codex client magpie presents to the ChatGPT backend: "" (Codex - // CLI) or "desktop" (ouhthuo on X) - mux.HandleFunc("POST /api/settings/codex-client", func(rw http.ResponseWriter, r *http.Request) { - var in struct{ Client string } - if err := json.NewDecoder(r.Body).Decode(&in); err != nil { - fail(rw, err) - return - } - if err := provider.SetCodexClient(in.Client); err != nil { - fail(rw, err) - return - } - writeJSON(rw, settingsState()) - }) // what the Open button of Codex's Agents row opens: "", "app" or // "terminal" (Yink88564391 on X) mux.HandleFunc("POST /api/settings/codex-open", func(rw http.ResponseWriter, r *http.Request) { diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index b2d3cd2eb..ff33bf363 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -21186,7 +21186,7 @@ function renderAlerts(s, keep) { // AGENT_PREFS: an agent's own settings rows, by its id (openAgentPrefs) const AGENT_PREFS = { - codex: ["codexAgentsV1Row", "codexOpenRow", "codexSubagentModelRow", "codexServiceTierRow", "codexClientRow", "fullContextRow", "codexAsyncRow", "codexTitlesRow", "codexDescriptionsRow", "codexPredictionsRow", "codexAutoReviewRow", "codexMemoriesRow"], + codex: ["codexAgentsV1Row", "codexOpenRow", "codexSubagentModelRow", "codexServiceTierRow", "fullContextRow", "codexAsyncRow", "codexTitlesRow", "codexDescriptionsRow", "codexPredictionsRow", "codexAutoReviewRow", "codexMemoriesRow"], claude: ["fullContextRow"], grok: ["fullContextRow"], }; @@ -21270,7 +21270,6 @@ function renderAgentPrefs() { homeAgentPrefRows(); // what each row does, in its tooltip (#2120) for (const [row, en] of [ - ["#codexClientRow", "Which Codex requests to your ChatGPT accounts say they come from: the CLI or the desktop app"], ["#codexServiceTierRow", "Every request Codex sends goes at this tier, whatever /fast is set to in Codex; Ultrafast goes as Fast where the plan has none"], ["#codexTitlesRow", "Names each thread in a hidden request of its own; same as the session, it goes on the session’s model, as Codex sends it when that is one of Codex’s own"], ["#codexDescriptionsRow", "Writes each thread’s short description in a hidden request of its own; same as the session, it goes on the session’s model, as Codex sends it when that is one of Codex’s own"], @@ -21328,7 +21327,6 @@ function renderAgentPrefs() { if (held.length) box.append(el("div", "hint codex-async-held", codexHeld(held))); $("#codexAsyncSegs").replaceChildren(box); renderCodexServiceTier(s); - renderCodexClient(s); renderCodexOpen(s); renderCodexTitles(s); renderCodexDescriptions(s); @@ -21415,31 +21413,39 @@ const CODEX_TIERS = [ { v: "priority", name: "Fast", note: "priority" }, { v: "ultrafast", name: "Ultrafast", note: "ultrafast" }, ]; -function renderCodexServiceTier(s) { codexMenuPick(CODEX_TIERS, s.codexServiceTier, "Codex service tier", "codexServiceTier", "tier"); } - -// a Codex row's button: the choice made, and the app's menu to change it, -// posted on its own to settings/ as {: value} -function codexMenuPick(opts, v, label, key, field) { - const cur = opts.find((o) => o.v === (v || "")) || opts[0]; - const b = el("button", "rt-cond on", t(cur.name)); +function renderCodexServiceTier(s) { + const v = s.codexServiceTier || ""; + const cur = CODEX_TIERS.find((o) => o.v === v) || CODEX_TIERS[0]; + const b = el("button", "rt-cond on"); b.type = "button"; - b.setAttribute("aria-label", t(label)); + b.setAttribute("aria-label", t("Codex service tier")); b.setAttribute("aria-haspopup", "menu"); + b.append(el("span", "", t(cur.name))); b.onclick = (e) => { e.stopPropagation(); if (b.classList.contains("open")) return closeProtoMenu(); - openProtoMenu(b, opts, cur.v, (x) => x !== cur.v && prefWrite(api("settings/" + key.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase()), { [field]: x })), label, "sess-menu"); + openProtoMenu(b, CODEX_TIERS, cur.v, (tier) => { + if (tier === cur.v) return; + prefWrite(api("settings/codex-service-tier", { tier })); + }, "Codex service tier", "sess-menu"); }; - $("#" + key + "Pick").replaceChildren(b); + $("#codexServiceTierPick").replaceChildren(b); } -// the Codex magpie presents to ChatGPT (ouhthuo on X) -const CODEX_CLIENTS = [{ v: "", name: "Codex CLI" }, { v: "desktop", name: "Codex Desktop" }]; -function renderCodexClient(s) { codexMenuPick(CODEX_CLIENTS, s.codexClient, "Codex client", "codexClient", "client"); } - // what Codex's Open button opens (Yink88564391 on X) const CODEX_OPENS = [{ v: "", name: "Automatic" }, { v: "app", name: "Codex app" }, { v: "terminal", name: "Terminal" }]; -function renderCodexOpen(s) { codexMenuPick(CODEX_OPENS, s.codexOpen, "Open Codex with", "codexOpen", "open"); } +function renderCodexOpen(s) { + const cur = CODEX_OPENS.find((o) => o.v === (s.codexOpen || "")) || CODEX_OPENS[0]; + const b = el("button", "rt-cond on", t(cur.name)); + b.type = "button"; + b.setAttribute("aria-label", t("Open Codex with")); + b.onclick = (e) => { + e.stopPropagation(); + if (b.classList.contains("open")) return closeProtoMenu(); + openProtoMenu(b, CODEX_OPENS, cur.v, (open) => open !== cur.v && prefWrite(api("settings/codex-open", { open })), "Open Codex with", "sess-menu"); + }; + $("#codexOpenPick").replaceChildren(b); +} // Codex's descriptions: as sent, off, or a model function renderCodexDescriptions(s) { codexSidePick(s, "codexDescriptions", "Codex thread descriptions", "no description, nothing sent", "codex-descriptions"); } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index a7fa8a06a..f57b3b10f 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -30,10 +30,6 @@ const I18N = { "/fast in Codex": "Codex 里的 /fast", "Standard": "标准", "Every request Codex sends goes at this tier, whatever /fast is set to in Codex; Ultrafast goes as Fast where the plan has none": "Codex 发出的每个请求都走这个层级,不管 Codex 里的 /fast 怎么设;套餐没有极速时按快速发", - "Codex client": "Codex 客户端", - "Codex CLI": "Codex 命令行", - "Codex Desktop": "Codex 桌面版", - "Which Codex requests to your ChatGPT accounts say they come from: the CLI or the desktop app": "发往 ChatGPT 账号的请求自称是哪个 Codex:命令行或桌面版应用", "Check-in time": "签到时间", "From {at} each day, for every vendor's check-in": "每天 {at} 起签到,所有服务商的签到都按这个时间", "As soon as each vendor's day starts": "每个服务商的新一天一开始就签到", @@ -5177,10 +5173,6 @@ const I18N = { "/fast in Codex": "Codex 裡的 /fast", "Standard": "標準", "Every request Codex sends goes at this tier, whatever /fast is set to in Codex; Ultrafast goes as Fast where the plan has none": "Codex 送出的每個請求都走這個層級,不論 Codex 裡的 /fast 怎麼設;方案沒有極速時按快速送出", - "Codex client": "Codex 用戶端", - "Codex CLI": "Codex 命令列", - "Codex Desktop": "Codex 桌面版", - "Which Codex requests to your ChatGPT accounts say they come from: the CLI or the desktop app": "送往 ChatGPT 帳號的請求自稱是哪個 Codex:命令列或桌面版應用程式", "Check-in time": "簽到時間", "From {at} each day, for every vendor's check-in": "每天 {at} 起簽到,所有服務商的簽到都按這個時間", "As soon as each vendor's day starts": "每個服務商的新一天一開始就簽到", @@ -10309,10 +10301,6 @@ const I18N = { "/fast in Codex": "Codex の /fast", "Standard": "標準", "Every request Codex sends goes at this tier, whatever /fast is set to in Codex; Ultrafast goes as Fast where the plan has none": "Codex が送るすべてのリクエストをこのティアで送ります。Codex の /fast の設定は問いません。プランに超高速がなければ高速で送ります", - "Codex client": "Codex クライアント", - "Codex CLI": "Codex CLI", - "Codex Desktop": "Codex Desktop", - "Which Codex requests to your ChatGPT accounts say they come from: the CLI or the desktop app": "ChatGPT アカウントへのリクエストが名乗る Codex:CLI またはデスクトップアプリ", "Check-in time": "チェックインの時刻", "From {at} each day, for every vendor's check-in": "毎日 {at} からチェックイン(すべてのサービスのチェックインに共通)", "As soon as each vendor's day starts": "各サービスの日付が変わったらすぐにチェックイン", @@ -15443,10 +15431,6 @@ const I18N = { "/fast in Codex": "/fast in Codex", "Standard": "Standard", "Every request Codex sends goes at this tier, whatever /fast is set to in Codex; Ultrafast goes as Fast where the plan has none": "Jede Anfrage von Codex geht in dieser Stufe, egal wie /fast in Codex steht; Ultrafast geht als Schnell, wo der Tarif es nicht hat", - "Codex client": "Codex-Client", - "Codex CLI": "Codex CLI", - "Codex Desktop": "Codex Desktop", - "Which Codex requests to your ChatGPT accounts say they come from: the CLI or the desktop app": "Als welches Codex sich Anfragen an ChatGPT-Konten ausgeben: CLI oder Desktop-App", "Check-in time": "Check-in-Zeit", "From {at} each day, for every vendor's check-in": "Täglich ab {at}, für den Check-in jedes Anbieters", "As soon as each vendor's day starts": "Sobald der Tag des jeweiligen Anbieters beginnt", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index 5aefe4fcd..c6164ec1c 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -576,10 +576,6 @@
Codex service tier
-
-
Codex client
-
-
Codex thread titles
diff --git a/internal/gui/settings_keep_test.go b/internal/gui/settings_keep_test.go index 60a2c3346..8e2eb9438 100644 --- a/internal/gui/settings_keep_test.go +++ b/internal/gui/settings_keep_test.go @@ -176,7 +176,6 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) { CodexAutoReview: "fake/m1", CodexSubagentModel: "codex/gpt-6-astra", CodexServiceTier: "priority", - CodexClient: "desktop", CodexOpen: "terminal", DesktopSubagentModel: "fake/m2", DesktopGateway: "https://192.168.1.20:3425", diff --git a/internal/gui/tests/agent-prefs.test.cjs b/internal/gui/tests/agent-prefs.test.cjs index fa56bd834..3b667fdd3 100644 --- a/internal/gui/tests/agent-prefs.test.cjs +++ b/internal/gui/tests/agent-prefs.test.cjs @@ -20,7 +20,7 @@ const { chromium, webkit } = require("playwright"); const { watchSettingsReads, agentRow, openAgentSettings } = require("./reader.cjs"); const assets = path.resolve(__dirname, "../assets"); -const CODEX = ["codexAgentsV1Row", "codexOpenRow", "codexServiceTierRow", "codexClientRow", "fullContextRow", "codexAsyncRow", "codexTitlesRow", "codexDescriptionsRow", "codexPredictionsRow", "codexAutoReviewRow", "codexMemoriesRow"]; +const CODEX = ["codexAgentsV1Row", "codexOpenRow", "codexServiceTierRow", "fullContextRow", "codexAsyncRow", "codexTitlesRow", "codexDescriptionsRow", "codexPredictionsRow", "codexAutoReviewRow", "codexMemoriesRow"]; function settingsPayload(over) { return { diff --git a/internal/gui/tests/codex-client.test.cjs b/internal/gui/tests/codex-client.test.cjs deleted file mode 100644 index 89433befe..000000000 --- a/internal/gui/tests/codex-client.test.cjs +++ /dev/null @@ -1,128 +0,0 @@ -// Run with Node's test runner and Playwright on the module path; see README.md. -// The Codex magpie presents to ChatGPT (ouhthuo on X): a row in Codex's -// settings on the Agents page. Its button says the choice, "Codex CLI" by -// default; the app's menu (no native select) offers Codex CLI and Codex -// Desktop, and a pick posts settings/codex-client on its own: "" or -// "desktop". Every language, Chromium and WebKit, a wide and a narrow -// window; 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 { watchSettingsReads, agentRow, openAgentSettings } = require("./reader.cjs"); - -const assets = path.resolve(__dirname, "../assets"); - -function server(lang, posted) { - let cur = { theme: "light", lang, version: "0.1.400", titleModels: [], codexClient: "" }; - return async (route) => { - const req = route.request(), url = new URL(req.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 = {};" }); - // agents below Codex, so its opened row is not the list's end: a choice - // that rewraps its row at the very bottom must move the list - if (url.pathname === "/api/state") return json({ agents: [agentRow("codex", "Codex"), agentRow("claude", "Claude Code"), agentRow("pi", "Pi"), agentRow("opencode", "OpenCode"), agentRow("gemini", "Gemini CLI"), agentRow("kimi", "Kimi CLI"), agentRow("droid", "Droid"), agentRow("cline", "Cline"), agentRow("qwen", "Qwen Code"), agentRow("crush", "Crush")], profiles: [], settings: { lang, theme: "light" } }); - if (url.pathname === "/api/settings/codex-client") { - const body = req.postDataJSON(); - posted.push(["codex-client", body]); - cur = { ...cur, codexClient: body.client }; - return json(cur); - } - if (url.pathname === "/api/settings") { - if (req.method() === "POST") posted.push(["settings", req.postDataJSON()]); - return json(cur); - } - if (url.pathname === "/api/plugins") return json({ plugins: [] }); - if (url.pathname === "/api/usage/quotas") return json([]); - if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); - 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)]; - try { - await route.fulfill({ body: await fs.readFile(file), contentType }); - } catch { - await route.fulfill({ status: 404, body: "" }); - } - }; -} - -// the words as i18n.js has them -const W = { - en: { name: "Codex client", cli: "Codex CLI", desktop: "Codex Desktop" }, - zh: { name: "Codex 客户端", cli: "Codex 命令行", desktop: "Codex 桌面版" }, - "zh-TW": { name: "Codex 用戶端", cli: "Codex 命令列", desktop: "Codex 桌面版" }, - ja: { name: "Codex クライアント", cli: "Codex CLI", desktop: "Codex Desktop" }, - de: { name: "Codex-Client", cli: "Codex CLI", desktop: "Codex Desktop" }, -}; -const engines = process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"]; -const langs = process.env.LANGS ? process.env.LANGS.split(",") : Object.keys(W); - -for (const engine of engines) { - for (const lang of langs) { - for (const width of [900, 400]) { - test(`${engine} ${lang} ${width}px: the Codex client is picked from the app menu in its settings`, async (t) => { - const w = W[lang]; - const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); - const page = await (await browser.newContext({ viewport: { width, height: 720 }, reducedMotion: "reduce" })).newPage(); - page.setDefaultTimeout(5000); - page.setDefaultNavigationTimeout(60000); - const errors = [], posted = []; - page.on("pageerror", (e) => errors.push(e.message)); - await page.route("**/*", server(lang, posted)); - t.after(async () => { - if (process.env.ARTIFACT_DIR) { - await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); - await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-codex-client.png`) }); - } - await browser.close(); - }); - await watchSettingsReads(page); - await page.goto("http://magpie.test/?view=agents"); - await openAgentSettings(page); - const row = page.locator('.row.agent[data-id="codex"] #codexClientRow'); - const pick = page.locator("#codexClientPick button"); - await pick.waitFor(); - assert.equal((await row.locator(".name").textContent()).trim(), w.name); - assert.equal((await pick.textContent()).trim(), w.cli, "Codex CLI by default"); - assert.equal(await page.locator("select").count(), 0, "a native select"); - // only Codex's settings have it - await page.locator('.row.agent[data-id="claude"] .ag-link').click(); - await page.locator('.row.agent[data-id="claude"] .ag-prefs').waitFor(); - assert.equal(await page.locator('.row.agent[data-id="claude"] #codexClientRow').count(), 0, "the row in Claude Code's settings"); - await openAgentSettings(page); - await pick.waitFor(); - await pick.scrollIntoViewIfNeeded(); - const box = await pick.boundingBox(); - assert(box && box.x >= 0 && box.x + box.width <= width, `the button runs off the window: ${JSON.stringify(box)}`); - assert(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), "the page scrolls sideways"); - - // where the button sits on screen: a pick that moved the page would - // move it. At a narrow width the row rewraps as the choice's words - // change (the button under the name or beside it), which moves the - // button with no scroll at all, so it is held to its place only - // while the row keeps its height. - const top = () => pick.evaluate((b) => Math.round(b.getBoundingClientRect().top)); - const tall = () => row.evaluate((r) => Math.round(r.getBoundingClientRect().height)); - for (const [label, client] of [[w.desktop, "desktop"], [w.cli, ""]]) { - const y = await top(), h = await tall(); - await pick.click(); - const menu = page.locator(".proto-menu"); - await menu.waitFor(); - const items = (await menu.locator(".pm-item .pm-name").allTextContents()).map((s) => s.trim()); - assert.deepEqual(items, [w.cli, w.desktop]); - const mb = await menu.boundingBox(); - assert(mb.x >= 0 && mb.x + mb.width <= width, `the menu runs off the window: ${JSON.stringify(mb)}`); - await menu.locator(".pm-item").filter({ has: page.locator(".pm-name", { hasText: new RegExp("^" + label + "$") }) }).click(); - await page.locator("#codexClientPick button", { hasText: new RegExp("^\\s*" + label + "\\s*$") }).waitFor(); - assert.deepEqual(posted.at(-1), ["codex-client", { client }]); - await page.waitForTimeout(200); - if (await tall() === h) assert(Math.abs((await top()) - y) <= 1, `picking ${label} moved the button from ${y} to ${await top()}`); - } - assert.equal(posted.length, 2, JSON.stringify(posted)); - assert.deepEqual(errors, []); - }); - } - } -} diff --git a/internal/gui/traytip_words_test.go b/internal/gui/traytip_words_test.go index fc1ff3016..c6a92f0bd 100644 --- a/internal/gui/traytip_words_test.go +++ b/internal/gui/traytip_words_test.go @@ -65,7 +65,7 @@ func TestPluginWindowWordsSaidInEveryLanguage(t *testing.T) { } for _, lang := range []string{"zh", "zh-TW", "ja", "de"} { for _, w := range words { - if _, ok := pageWords(lang)[w]; !ok { + if _, ok := pageWords()[lang][w]; !ok { t.Errorf("i18n.js's %s doesn't say %q", lang, w) } } @@ -84,16 +84,3 @@ func TestParsePageWords(t *testing.T) { t.Errorf("parsed a comment or past the table: %v", got) } } - -// parsePageWordsIn reads only the language asked for: the tray holds one -// language's words, not the page's four. -func TestParsePageWordsInOneLanguage(t *testing.T) { - src := "const I18N = {\n zh: {\n \"Credits\": \"积分\",\n },\n \"zh-TW\": {\n \"Credits\": \"積分\",\n },\n};\n" - got := parsePageWordsIn(src, "zh-TW") - if len(got) != 1 || got["zh-TW"]["Credits"] != "積分" { - t.Errorf("parsed %v", got) - } - if pageWords("ja")["Credits"] == "" || pageWords("zh")["Credits"] == pageWords("ja")["Credits"] { - t.Errorf("ja then zh: %q %q", pageWords("ja")["Credits"], pageWords("zh")["Credits"]) - } -} diff --git a/internal/gui/traywords.go b/internal/gui/traywords.go index 3adf4e948..6084e1c6c 100644 --- a/internal/gui/traywords.go +++ b/internal/gui/traywords.go @@ -8,37 +8,20 @@ import ( "github.com/yetone/magpie/internal/lazyre" ) -// pageWords are the page's own translations (assets/i18n.js's I18N) in -// one language, read when first asked for it: the words a usage card's -// window is named and counted in ("Credits", "credits", "5 hours") come -// from the vendor or a plugin in English, and the Usage page says them -// with t(). The tray's tooltip says them with the same table (pageWord), -// so a window reads in the tray as on its card, in every language the -// page has (yi_time on Discord: "Credits 0 / 500 credits · 已用 0%"). -// Only the language last asked for is kept: all four blocks held ~4.5 MB -// of an idle tray magpie's heap, for the few words one language needs. -func pageWords(lang string) map[string]string { - pageWordsMu.Lock() - defer pageWordsMu.Unlock() - if pageWordsLang == lang && pageWordsHeld != nil { - return pageWordsHeld - } +// pageWords are the page's own translations (assets/i18n.js's I18N), by +// language, read once: the words a usage card's window is named and +// counted in ("Credits", "credits", "5 hours") come from the vendor or a +// plugin in English, and the Usage page says them with t(). The tray's +// tooltip says them with the same table (pageWord), so a window reads in +// the tray as on its card, in every language the page has (yi_time on +// Discord: "Credits 0 / 500 credits · 已用 0%"). +var pageWords = sync.OnceValue(func() map[string]map[string]string { b, err := assets.ReadFile("assets/i18n.js") if err != nil { return nil } - pageWordsLang, pageWordsHeld = lang, parsePageWordsIn(string(b), lang)[lang] - if pageWordsHeld == nil { - pageWordsHeld = map[string]string{} - } - return pageWordsHeld -} - -var ( - pageWordsMu sync.Mutex - pageWordsLang string - pageWordsHeld map[string]string -) + return parsePageWords(string(b)) +}) var ( pageLangHead = lazyre.New(`^ "?([\w-]+)"?: \{`) @@ -51,12 +34,6 @@ var ( // JSON can't read (a JS-only escape) is left out: that word reads in // English, as the page's own fallback does. func parsePageWords(src string) map[string]map[string]string { - return parsePageWordsIn(src, "") -} - -// parsePageWordsIn is parsePageWords with only lang's block read ("" for -// every block). -func parsePageWordsIn(src, lang string) map[string]map[string]string { if i := strings.Index(src, "\n};"); i >= 0 { src = src[:i] } @@ -64,11 +41,8 @@ func parsePageWordsIn(src, lang string) map[string]map[string]string { var cur map[string]string for _, line := range strings.Split(src, "\n") { if m := pageLangHead.FindStringSubmatch(line); m != nil { - cur = nil - if lang == "" || m[1] == lang { - cur = map[string]string{} - out[m[1]] = cur - } + cur = map[string]string{} + out[m[1]] = cur continue } if cur == nil || !strings.HasPrefix(line, " \"") { @@ -88,7 +62,7 @@ func parsePageWordsIn(src, lang string) map[string]map[string]string { // pageWord is s as the page says it in lang (its t()): s itself in // English, or where the page has no word for it. func pageWord(lang, s string) string { - if v, ok := pageWords(lang)[s]; ok && v != "" { + if v, ok := pageWords()[lang][s]; ok && v != "" { return v } return s diff --git a/internal/provider/codex_autoreset.go b/internal/provider/codex_autoreset.go index 1b8b9ea3f..f59154bec 100644 --- a/internal/provider/codex_autoreset.go +++ b/internal/provider/codex_autoreset.go @@ -23,6 +23,7 @@ import ( "time" "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/steady" ) // The two times an account the user lets spend its resets by itself @@ -341,7 +342,7 @@ func (a *autoResets) save() { } b, _ := json.MarshalIndent(a.spent, "", " ") _ = os.MkdirAll(settings.Dir(), 0o755) - if err := writeChanged(a.path, append(b, '\n'), 0o644); err != nil { + if err := steady.WriteFile(a.path, append(b, '\n'), 0o644); err != nil { log.Printf("writing what a week's auto-use spent to %s: %v", a.path, err) } } diff --git a/internal/provider/codex_request.go b/internal/provider/codex_request.go index 41a291c44..567e5d8b2 100644 --- a/internal/provider/codex_request.go +++ b/internal/provider/codex_request.go @@ -60,43 +60,11 @@ func codexSign(token func(context.Context) (tok, accountID string, err error)) f // sent with). The ChatGPT account's own calls that aren't a model's // (/wham/usage, the reset credits, the token refresh) went with Go's // User-Agent and no originator, unlike any request Codex makes. -// -// Which Codex that is is settings.CodexClient's: Codex CLI by default, the -// Codex app when the user chose it (ouhthuo on X: the backend routes some -// models by the client's originator). func codexClientHeaders(h http.Header, ver string) { - if CodexClient() == "desktop" { - h.Set("originator", codexDesktopOriginator) - h.Set("User-Agent", codexDesktopUserAgent(ver)) - return - } h.Set("originator", "codex_cli_rs") h.Set("User-Agent", codexUserAgent(ver)) } -// codexDesktopOriginator is the originator the Codex app gives -// (set_default_originator, which codex-rs login/src/auth/default_client.rs -// turns into the first word of the User-Agent as well); its threads record -// the same name. -const codexDesktopOriginator = "Codex Desktop" - -// codexDesktopBuild is the app's own version, the last part of the -// User-Agent it sends, from the app's logs (26.1026.10807 is the newest -// build seen); its codex-rs version is ver. -const codexDesktopBuild = "26.1026.10807" - -// codexDesktopUserAgent is the User-Agent the Codex app of codex-rs version -// v sends: "Codex Desktop/0.166.0 (Mac OS 26.6.0; arm64) unknown (Codex -// Desktop; 26.1026.10807)". The terminal is "unknown" on every system, -// since the app has none. -func codexDesktopUserAgent(v string) string { - ua := codexUserAgent(v) - if i := strings.Index(ua, ") "); i >= 0 { - ua = ua[:i+2] - } - return codexDesktopOriginator + strings.TrimPrefix(ua, "codex_cli_rs") + "unknown (" + codexDesktopOriginator + "; " + codexDesktopBuild + ")" -} - // codexAccountHeaders are the headers of a call Codex makes about the // ChatGPT account (its /wham reads): the account it is about and // codexClientHeaders. Codex sends no version header with them. diff --git a/internal/provider/codex_request_test.go b/internal/provider/codex_request_test.go index fd9fdc4ac..0e758f3a5 100644 --- a/internal/provider/codex_request_test.go +++ b/internal/provider/codex_request_test.go @@ -6,7 +6,6 @@ import ( "net/http" "os" "path/filepath" - "regexp" "strings" "testing" @@ -409,57 +408,3 @@ func TestCodexInputDropsStatusWithID(t *testing.T) { } } } - -// The Codex client magpie presents is the user's choice (ouhthuo on X): Codex -// CLI unless "desktop" is set, and then the Codex app's originator and -// User-Agent on a model request and on the account calls alike (/wham, the -// token refresh), and as a test is asked as Codex asks. Anything else is -// refused, and read as Codex CLI from a file edited by hand. -func TestCodexClientSetting(t *testing.T) { - signIn(t) - p, _ := find(All(), "codex") - sign := func() http.Header { - t.Helper() - req, _ := http.NewRequest("POST", p.Responses+"/responses", nil) - if err := p.Sign(context.Background(), req, Responses, []byte(`{"prompt_cache_key":"thread-1"}`)); err != nil { - t.Fatal(err) - } - return req.Header - } - cli := func(h http.Header) bool { - return h.Get("originator") == "codex_cli_rs" && strings.HasPrefix(h.Get("User-Agent"), "codex_cli_rs/0.") - } - if h := sign(); !cli(h) { - t.Fatalf("by default: %v", h) - } - for _, bad := range []string{"Codex Desktop", "codex_cli_rs", "evil", "desktop2"} { - if err := SetCodexClient(bad); err == nil { - t.Errorf("%q was accepted", bad) - } - } - if err := SetCodexClient("desktop"); err != nil { - t.Fatal(err) - } - h := sign() - if h.Get("originator") != "Codex Desktop" || !regexp.MustCompile(`^Codex Desktop/0\.\d+[^ ]* \([^;]+; [^)]+\) unknown \(Codex Desktop; \d+\.\d+\.\d+\)$`).MatchString(h.Get("User-Agent")) { - t.Fatalf("as the Codex app: %v", h) - } - if h.Get("version") == "" || h.Get("session-id") != "thread-1" || h.Get("chatgpt-account-id") != "acct-1" { - t.Fatalf("the rest of the headers: %v", h) - } - acct := codexAccountHeaders("acct-1") - if acct["Originator"] != "Codex Desktop" || !strings.HasPrefix(acct["User-Agent"], "Codex Desktop/") { - t.Fatalf("an account call: %v", acct) - } - asked := http.Header{} - clientHeaders(ClientCodex, asked) - if asked.Get("originator") != "Codex Desktop" || !strings.HasPrefix(asked.Get("User-Agent"), "Codex Desktop/") { - t.Fatalf("a test asked as Codex: %v", asked) - } - if err := SetCodexClient(""); err != nil { - t.Fatal(err) - } - if h := sign(); !cli(h) { - t.Fatalf("back to the default: %v", h) - } -} diff --git a/internal/provider/codex_resets_used.go b/internal/provider/codex_resets_used.go index e81a0bdd9..a41e78691 100644 --- a/internal/provider/codex_resets_used.go +++ b/internal/provider/codex_resets_used.go @@ -22,6 +22,7 @@ import ( "github.com/yetone/magpie/internal/filelock" "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/steady" ) // Why a reset was used: by itself as the account's week was used up and no @@ -104,7 +105,7 @@ func noteResetUsed(user, why string, out ResetOutcome) error { if err := os.MkdirAll(settings.Dir(), 0o755); err != nil { return fmt.Errorf("keeping that a reset was used to %s: %w", resetsUsedPath(), err) } - if err := writeChanged(resetsUsedPath(), append(b, '\n'), 0o600); err != nil { + if err := steady.WriteFile(resetsUsedPath(), append(b, '\n'), 0o600); err != nil { return fmt.Errorf("keeping that a reset was used to %s: %w", resetsUsedPath(), err) } return nil diff --git a/internal/provider/codex_tier.go b/internal/provider/codex_tier.go index 8024adcfd..0b3b47610 100644 --- a/internal/provider/codex_tier.go +++ b/internal/provider/codex_tier.go @@ -48,29 +48,3 @@ func SetCodexOpen(v string) error { s.CodexOpen = v return settings.Save(s) } - -// CodexClient is the Codex client magpie presents to the ChatGPT backend -// (settings.CodexClient): "" for Codex CLI, "desktop" for the Codex app. A -// value this magpie doesn't know (a newer one's, a file edited by hand) is -// read as "" and changes nothing. -func CodexClient() string { - v := strings.TrimSpace(heldSettings().CodexClient) - if !slices.Contains(settings.CodexClients, v) { - return "" - } - return v -} - -// SetCodexClient sets settings.CodexClient. -func SetCodexClient(v string) error { - v = strings.TrimSpace(v) - if !slices.Contains(settings.CodexClients, v) { - return fmt.Errorf("the Codex client must be one of %q, not %q", settings.CodexClients[1:], v) - } - s := settings.Load() - if s.CodexClient == v { - return nil - } - s.CodexClient = v - return settings.Save(s) -} diff --git a/internal/provider/kiro.go b/internal/provider/kiro.go index 5823ac87b..38b53424a 100644 --- a/internal/provider/kiro.go +++ b/internal/provider/kiro.go @@ -42,6 +42,7 @@ import ( "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/proc" "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/steady" ) // KiroExecutable finds kiro-cli, which refreshes its own sign-in; a var so @@ -465,7 +466,7 @@ func writeFileAtomic(path string, b []byte) error { if err != nil { return err } - return writeChanged(path, b, 0o600) // on the disk before it is renamed in (#1505) + return steady.WriteFile(path, b, 0o600) // on the disk before it is renamed in (#1505) } // kiroPost posts to a sign-in endpoint. diff --git a/internal/provider/logins.go b/internal/provider/logins.go index 1fd95d1e0..ae6e891e0 100644 --- a/internal/provider/logins.go +++ b/internal/provider/logins.go @@ -19,7 +19,6 @@ import ( "log" "os" "path/filepath" - "runtime" "slices" "sort" "strings" @@ -320,15 +319,6 @@ func writeLoginsTold(ls []savedLogin, tell bool) error { defer Changed() // an account added, switched or gone: All builds anew } beforeLoginsWrite() - b = append(b, '\n') - if fileHolds(loginsPath(), b, 0o600) { - // the bytes are on the disk already (#6289): no new generation, no - // new mtime, and what filememo parsed stays - lastLoginsMu.Lock() - lastLogins, loginsKnown = slices.Clone(ls), true - lastLoginsMu.Unlock() - return nil - } // the file there now is kept first: as its last good generation, or // copied aside when it doesn't read, never written over unkept if err := lastgood.Keep(loginsPath(), validLogins, 0o600); err != nil { @@ -338,7 +328,7 @@ func writeLoginsTold(ls []savedLogin, tell bool) error { if !tell { write = writePrivateQuiet } - if err := write(loginsPath(), b); err != nil { + if err := write(loginsPath(), append(b, '\n')); err != nil { return err } lastLoginsMu.Lock() @@ -375,9 +365,6 @@ func sortLogins(ls []savedLogin) { // an agent reading it at that moment sees either version, never half; the // new one is on the disk before it is renamed over the old (#1505). func writePrivate(path string, b []byte) error { - if fileHolds(path, b, 0o600) { // the file has these bytes (#6289): nothing moves - return nil - } defer filememo.Forget() // read again, where a request holds it return writePrivateQuiet(path, b) } @@ -385,9 +372,6 @@ func writePrivate(path string, b []byte) error { // writePrivateQuiet is writePrivate with nothing read forgotten: a // request holding the file reads the old bytes for up to a second. func writePrivateQuiet(path string, b []byte) error { - if fileHolds(path, b, 0o600) { - return nil - } path, err := edit.Target(path) // a symlink stays, its target written if err != nil { return err @@ -398,33 +382,6 @@ func writePrivateQuiet(path string, b []byte) error { return steady.WriteFile(path, b, 0o600) } -// fileHolds reports whether path is a file of exactly b, with the mode -// the write would give it. A read that fails is "no": it is written. -// writeChanged is steady.WriteFile for a file that is left alone, mtime -// and all, when it already holds b (#6289). -func writeChanged(path string, b []byte, perm os.FileMode) error { - if fileHolds(path, b, perm) { - return nil - } - return steady.WriteFile(path, b, perm) -} - -func fileHolds(path string, b []byte, perm os.FileMode) bool { - path, err := edit.Target(path) - if err != nil { - return false - } - fi, err := os.Stat(path) - if err != nil || !fi.Mode().IsRegular() || fi.Size() != int64(len(b)) { - return false - } - if runtime.GOOS != "windows" && fi.Mode().Perm() != perm { - return false - } - old, err := os.ReadFile(path) - return err == nil && bytes.Equal(old, b) -} - func upsertLogin(ls []savedLogin, l savedLogin) []savedLogin { l.User = codexName(ls, l) if claudeSignInOfAnother(ls, l) { diff --git a/internal/provider/logins_unchanged_test.go b/internal/provider/logins_unchanged_test.go deleted file mode 100644 index d4746bed7..000000000 --- a/internal/provider/logins_unchanged_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package provider - -import ( - "os" - "testing" - "time" - - "github.com/yetone/magpie/internal/filememo" -) - -// An unchanged save leaves logins.json alone (#6289): its mtime stays and -// what filememo parsed of it is not parsed again. -func TestUnchangedLoginsSaveKeepsFileAndParse(t *testing.T) { - signIn(t) - if err := writeLogins([]savedLogin{{Agent: "codex", User: "me@example.com", Plan: "pro"}}); err != nil { - t.Fatal(err) - } - old := time.Now().Add(-time.Hour).Truncate(time.Second) - if err := os.Chtimes(loginsPath(), old, old); err != nil { - t.Fatal(err) - } - if _, err := filememo.ReadNow("logins", loginsPath(), parseLogins); err != nil { - t.Fatal(err) - } - if err := writeLogins(readLogins()); err != nil { - t.Fatal(err) - } - fi, err := os.Stat(loginsPath()) - if err != nil { - t.Fatal(err) - } - if !fi.ModTime().Equal(old) { - t.Fatalf("an unchanged save moved logins.json's time to %v", fi.ModTime()) - } - parses := 0 - if _, err := filememo.ReadNow("logins", loginsPath(), func(b []byte) ([]savedLogin, error) { - parses++ - return parseLogins(b) - }); err != nil { - t.Fatal(err) - } - if parses != 0 { - t.Fatalf("an unchanged save made logins.json parse again: %d parses", parses) - } - // a real change is still written - ls := readLogins() - ls[0].Order = 7 - if err := writeLogins(ls); err != nil { - t.Fatal(err) - } - if fi, _ := os.Stat(loginsPath()); fi.ModTime().Equal(old) { - t.Fatal("a changed account was not written") - } -} - -// The siblings written through writePrivate hold still too. -func TestWritePrivateSameBytesLeavesFile(t *testing.T) { - p := t.TempDir() + "/x.json" - if err := writePrivate(p, []byte("{}\n")); err != nil { - t.Fatal(err) - } - old := time.Now().Add(-time.Hour).Truncate(time.Second) - os.Chtimes(p, old, old) - if err := writePrivate(p, []byte("{}\n")); err != nil { - t.Fatal(err) - } - if fi, _ := os.Stat(p); !fi.ModTime().Equal(old) { - t.Fatal("the same bytes moved the file's time") - } - if err := writePrivate(p, []byte("{\"a\":1}\n")); err != nil { - t.Fatal(err) - } - if b, _ := os.ReadFile(p); string(b) != "{\"a\":1}\n" { - t.Fatalf("changed bytes not written: %q", b) - } -} diff --git a/internal/provider/remote_quotas_scope.go b/internal/provider/remote_quotas_scope.go index 7976edda0..2a896e2b2 100644 --- a/internal/provider/remote_quotas_scope.go +++ b/internal/provider/remote_quotas_scope.go @@ -27,10 +27,14 @@ import ( // remoteCardWanted says whether a card of provider id (as the remote p // tells it: "kiro", "remote-C/kiro") is of a provider p is enabled for. // It is unknown, and so wanted, while p's list isn't read, or a model of -// it is listed with no provider before its name. +// it is listed with no provider before its name; and all are wanted when p +// is set to serve no model (Select none), which still reads usage. func remoteCardWanted(p Provider) func(id string) bool { + // Select none serves no model, "while its balance and usage are still + // read and shown" (Provider.NoModels): a Remote kept for its quotas + // alone tells every card it has (a user on X, 0.1.3929) if p.ServesNone() { - return func(string) bool { return false } + return func(string) bool { return true } } ms := p.Exposed() if len(ms) == 0 { diff --git a/internal/provider/remote_quotas_test.go b/internal/provider/remote_quotas_test.go index 617b2c3e9..1a09ad9a2 100644 --- a/internal/provider/remote_quotas_test.go +++ b/internal/provider/remote_quotas_test.go @@ -703,3 +703,33 @@ func TestRemoteCardWantedByWholePath(t *testing.T) { } } } + +// A user on X (0.1.3929): a Remote magpie added for the Usage page's +// quotas, with Select none (no model of it served), showed the remote's +// cards before cfd49e36a and none after, as no card was wanted of a +// provider with no enabled model. Select none still reads and shows usage. +func TestRemoteSelectNoneStillShowsItsCards(t *testing.T) { + peer := &fakePeer{cards: []SubscriptionQuota{ + {Provider: "kiro", Name: "Kiro", Kind: "subscription", User: "k@x.com", Windows: []QuotaWindow{{Name: "credits", Used: 10}}}, + {Provider: "codex", Name: "Codex", Kind: "subscription", User: "a@x.com", Windows: []QuotaWindow{{Name: "5h", Used: 40}}}, + }} + remoteQuotaHome(t, peer) + p, err := Find("office") + if err != nil { + t.Fatal(err) + } + p.NoModels, p.Models = true, nil + if err := Save(*p); err != nil { + t.Fatal(err) + } + ForgetRemoteCardsForTest() + got := map[string]bool{} + for _, q := range RemoteCards(context.Background()) { + if q.Kind == "subscription" && q.Error == "" { + got[q.Provider] = true + } + } + if !got["office/kiro"] || !got["office/codex"] { + t.Fatalf("a Remote set to serve no model still tells its cards: %v", got) + } +} diff --git a/internal/provider/test_as.go b/internal/provider/test_as.go index bfa3cff30..2a17d253e 100644 --- a/internal/provider/test_as.go +++ b/internal/provider/test_as.go @@ -210,8 +210,7 @@ func clientHeaders(client string, h http.Header) { shape := clientShape(client) if shape == nil && client == ClientCodex { v := codexVersion() - shape = http.Header{"Version": {v}} - codexClientHeaders(shape, v) + shape = http.Header{"User-Agent": {codexUserAgent(v)}, "Originator": {"codex_cli_rs"}, "Version": {v}} } for k, vs := range shape { h[k] = vs diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 9abf1624a..114c3123b 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -53,10 +53,6 @@ const CodexTierStandard = "default" // CodexOpens are the values CodexOpen may take, "" for the default. var CodexOpens = []string{"", "app", "terminal"} -// CodexClients are the values CodexClient may take, "" for Codex CLI, the -// default. Each is a client OpenAI makes, and only those. -var CodexClients = []string{"", "desktop"} - // CodexServiceTiers are the values CodexServiceTier may take, "" (as // Codex asks) first. var CodexServiceTiers = []string{"", CodexTierStandard, "priority", "ultrafast"} @@ -853,11 +849,6 @@ type Settings struct { // Ultra Fast). Codex's words, as codex-rs ServiceTier::request_value // sends them; its Flex is not offered, the ChatGPT backend takes none. CodexServiceTier string `json:"codexServiceTier,omitempty"` - // CodexClient is the Codex client magpie presents to the ChatGPT - // backend on a signed-in account's requests (ouhthuo on X): "" is Codex - // CLI (originator codex_cli_rs), "desktop" the Codex app (originator - // "Codex Desktop"), each with the User-Agent that client sends. - CodexClient string `json:"codexClient,omitempty"` // CodexOpen is what the Open button of Codex's Agents row opens // (Yink88564391 on X): "app" the Codex desktop app, "terminal" the CLI // in a terminal. "" is the app where one is installed, else the @@ -2588,10 +2579,6 @@ func saveOwn(s Settings, recording, reads bool) error { if !slices.Contains(CodexServiceTiers, s.CodexServiceTier) { return fmt.Errorf("Codex's service tier must be one of %q, not %q", CodexServiceTiers[1:], s.CodexServiceTier) } - s.CodexClient = strings.TrimSpace(s.CodexClient) - if !slices.Contains(CodexClients, s.CodexClient) { - return fmt.Errorf("the Codex client must be one of %q, not %q", CodexClients[1:], s.CodexClient) - } s.CodexOpen = strings.TrimSpace(s.CodexOpen) if !slices.Contains(CodexOpens, s.CodexOpen) { return fmt.Errorf("Codex's Open button must open one of %q, not %q", CodexOpens[1:], s.CodexOpen) diff --git a/internal/settingsapi/settingsapi.go b/internal/settingsapi/settingsapi.go index 34166ca70..c64eb0889 100644 --- a/internal/settingsapi/settingsapi.go +++ b/internal/settingsapi/settingsapi.go @@ -377,7 +377,6 @@ func Merge(body []byte, cur settings.Settings, web bool) (settings.Settings, err in.DesktopSubagentModel = cur.DesktopSubagentModel in.DesktopGateway = cur.DesktopGateway // Desktop's address, set in its row in.CodexServiceTier = cur.CodexServiceTier // codex-service-tier - in.CodexClient = cur.CodexClient // codex-client // and the model DeepSeek Harness compacts on, set in its row in.DshCompactModel = cur.DshCompactModel // and the model Codex compacts on, set in its row