From 0a6cccc3ffd974e7bf421d3ac4fbd7e1cb9e0512 Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 4 Nov 2026 23:27:53 +0800 Subject: [PATCH] groups: a found group the user changed takes in a new provider with its model MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Kxsg79bEYFP4 on X: magpie found auto/deepseek-v4.1-flash over two providers, the user changed the group, then added a third provider (a plugin's) with the model, and it never joined. Cause: SaveGroup stores a changed found group under its auto-… id with the members it had then, and buildGroupsIn skips the found group of that id ("the user changed it: theirs now"). Nothing recorded which of the found models the user had taken out, so a stored group could only stay frozen. Plugin providers, id spelling and a one-time creation were ruled out: a plugin's models are in providerEntries like any provider's, and the found group itself has all three. Fix: SaveGroup stores Group.Seen for an auto-… id: the models magpie found in it by that save plus those the user names. Reading a changed found group (joined) appends the found members it neither names nor has seen, after the user's own. A model the user took out was seen and stays out (magpie's default never overrides the user's value); a provider kept out of found groups (AutoGroupSkip) doesn't join; with found groups off nothing joins. Seen follows a provider's rename/SetModelID (mapModelRefs) and a fold, and ShareGroup leaves it behind. A group changed before this (no Seen) takes in nothing, since nothing says what the user took out; its next save sees what is found then, and providers added after that join. docs/subsystems/providers-accounts.md says so. Tests: TestChangedFoundGroupTakesInANewProvider (join, order, routed by FindGroup, the user's name/routing kept, taken out stays out before and after joining, rename, skip, share), TestChangedFoundGroupFromBefore- KeepsItsMembers (old stored group), TestChangedFoundGroupTakesInA- PluginProvider (the reporter's surface: the fake plugin under real Bun). Run on mote at base f280b12e5 plus this change: - gofmt -l: clean - GOOS=windows go vet ./...: ok; GOOS=linux go vet -tags nogui ./...: ok - go test -tags nogui -count=1 -timeout 45m ./internal/provider/ ./internal/cli/ ./internal/gui/ ./internal/tui/ ./internal/agent/ ./internal/gateway/: all ok (provider 214s, cli 86s, gui 127s, tui 23s, agent 372s, gateway 876s) Broken by hand (each red, then restored): - joined returning g unchanged (the old behaviour): all three new tests red - dropping the Seen check and the legacy no-Seen guard: c came back at once, and the pre-Seen group took c in - not mapping Seen in mapModelRefs: c came back as cee/… after Rename - not clearing Seen in ShareGroup: the shared text carried it Not tried: a real magpie with the reporter's providers; the GUI suite (app.js is unchanged, /api/groups only gains a "seen" field); an editor opened before a provider was added and saved after it treats that provider as taken out. --- docs/subsystems/providers-accounts.md | 2 +- internal/provider/fold.go | 1 + internal/provider/group.go | 90 +++++++++++- internal/provider/group_follow_test.go | 186 +++++++++++++++++++++++++ internal/provider/group_share.go | 1 + internal/provider/rename.go | 5 +- 6 files changed, 280 insertions(+), 5 deletions(-) create mode 100644 internal/provider/group_follow_test.go diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 0a8f683eb..09c72a810 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -56,7 +56,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Used-up switch | When the account Codex or Claude Code is signed in to has used its allowance, the agent is signed in to the next account that is on and has room (#208). Codex's sign-in goes back to the account it moved off once that has room again, as the gateway's Smart and In order give it requests again; routed Until used up it doesn't, as the gateway keeps the requests on the next (`routes.Drain`), so it stays with them till that one is used up too, as Claude Code's and a switch-only Codex's do unless routed In order (`returnsToFirst`; WalterAIBuilder on X: Codex signed back in to the first showed that one in use while the second's week was spent, `TestCodexDrainSignInStaysOnTheNext`). When every one is past its line too, it goes to the one with the most room left (`roomLeft`: the fullest stopping window's distance below the switch share, or the account's own cap when lower), when that has more than the account it is on by `roomMargin` (1 point), so two all but even accounts don't trade it each look; else it stays (StringKe in #4532, after cswap's `best`; `TestNextLoginTakesTheMostRoomWhenAllArePast`). A Claude account on overages (/usage's "You are currently using your overages…" line) is read with its windows and a spent *Extra usage* row of text (`claudeOveragesWindow`: Used 100, ending when the last used-up window renews, else at the next reading), so it is moved off as a used-up one; before, the line made the reading an error, and the switch, which stays on an account it can't read, left Claude Code billing overages (StringKe, #4532; `TestClaudeSwitchOffOverages`). The GUI says the row *In use* in the reader's language. Routing (`Allowances`) skips Text rows, so the gateway's own choice of account doesn't count it. A model's own week (`Current week (Sonnet only)`, `(Fable)`) counts for that model in routing, not for the switch, which moves the sign-in only on windows that count every model (`usedPast`); "Sonnet only" is read as the Sonnet week, `7 days · Sonnet` counting `sonnet`, the window the `seven_day_sonnet` header keeps (#4532, `TestClaudeUsageSonnetOnly`). `magpie accounts switch next` (`NextInOrder`) takes the other accounts the agent can be signed in to (`switchable`, not lapsed), on or off in magpie as the accounts list's *Use* does, so one the agent signed itself in to, which starts off, is in the rotation (StringKe, #4532; `TestNextTakesAccountsThatAreOff`), from the one after the account the agent is on, wrapping round: the first with room, else the one with the most room left, said to be past its line; with no reading of any, it refuses rather than guess (`TestNextInOrder`). For Codex, *Only switch Codex's sign-in* (`SwitchOnly`, `SetSwitchOnly`) keeps magpie's `openai_base_url` failover out of Codex's config, so the switch is all magpie does (#1907); an unreadable providers.json reads as switch-only, so the failover is not written on a guess. For Claude, the same setting keeps the accounts to Claude Code (`Provider.KeptToAgent`): `On()` is false, so the gateway, catalog and groups serve nothing on them, while switching and usage, gated by `leftAlone` on the raw `Off`, go on. No request of a saved Claude account passes magpie then, so one Claude Code wasn't signed in to since has no reading: once the account Claude Code is on is spent, `NextLogin` reads such a spare (`readSpare`, `spareRead` in `claudeWindows`) by Claude Code's own `/usage` in the account's directory, in order and only till one has room; a spare read once is not read again, and one whose read failed waits `claudeUsageWait` (cn_Vincentzyx on X, `TestClaudeSwitchOnlyReadsUnreadSpares`). Codex's spares are read through their saved tokens and had no such gap. Claude Code on its own login is out long before a five-minute look notices (#4443: 4% left to refused in two minutes): while Claude has an account to move to, `KeepOnAnAccountWithRoom` looks at its sign-in every `claudeLookEvery` (a minute) between its full looks when `claudeLookDue`, that is when the account Claude Code is on is near out (`claudeNearOut`, `codexNearShare`; its `/usage` is then due after `claudeNearOutWait` rather than `claudeUsageWait`), or when Claude Code wrote a `rate_limit` refusal ("You've hit your … limit") into one of its sessions since that account's last `/usage` (`scanClaudeLimits`, which reads only what was appended to each `projects/*/*.jsonl` since the last scan). The refusal names no account, so it only makes the `/usage` read due (and the reading stale, `StaleAllowance`); the read decides (`TestClaudeNearOutIsReadEveryMinute`, `TestClaudeRefusalInSessionReadsAtOnce`, `TestKeepOnAnAccountWithRoomLooksAtClaudeNearOut`). | [`codex_switch.go`](../../internal/provider/codex_switch.go) | | Removing the signed-in account | `ForgetLogin` signs Codex or Claude Code in to another of its accounts first (`nextOnForget`: the first other that is on, else one whose sign-in holds, else any, never a setup-token account or one Codex keeps in another folder: `switchable`), then forgets this one; a switch that fails removes nothing (StringKe, #4532: Claude's was refused while Codex's switched). Codex's only account is signed out as `codex logout` does. Claude Code is never signed out: its last account it can be signed in to is refused with `SignedInError{Only}` (GUI code `signed_in_only`, and that account has no *Remove*). Claude Code's own credential is never deleted; the forgotten account's folder (`forgetClaudeDir`) is its own. `TestForgetLiveClaudeSwitchesFirst`, `TestForgetOnlyClaudeIsKept`, `codex-signout.test.cjs`. | | Claude Code's proxy | Claude Code on its own subscription asks Anthropic itself, through the proxy its env names. While any Claude account has a proxy of its own (`AccountProxies`), the `env` of Claude Code's `settings.json` names the proxy of the account it is signed in to (#1807): `HTTPS_PROXY` and `HTTP_PROXY` set to that account's own, else the subscription's `Proxy` (`ProxyOfLogin`), and `NO_PROXY` to loopback; none for `direct` or a SOCKS proxy, which Claude Code can't use. It is written on every switch (`switchLogin`, the user's or `SwitchWhenSpent`), when the Claude subscription is saved, and at the gateway's look every `loginSwitchEvery` (a sign-in made in Claude Code itself). Claude Code reads its env at start, so only sessions started after the switch take it. A proxy key the user set (in either case) is theirs: magpie then writes none and takes out none of theirs. What magpie wrote is kept in `claude-proxy-env.json`, and a key is magpie's only while it holds that value. A `settings.json` that doesn't parse is left as it is. Its log lines name the proxy through `netproxy.Redact`, without its user and password (#1886); the env gets it whole. | [`claude_proxy_env.go`](../../internal/provider/claude_proxy_env.go) | -| Routing groups | User-made groups from the Routing view, and auto-found groups of the same model across providers (derived, never stored). The same model is the same id as vendors agree on it (`sameModel`): lowercase, without a vendor's prefix, a version's dot as `-`, a run of spaces, `_` and `-` as one `-` (a relay listing its display name as the id, `GPT-6 Sol`, joins `gpt-6-sol`, Chill on Discord: `TestSameModelDisplayNameAsID`), and without a YYYYMMDD or Ark YYMMDD snapshot date. Every word still counts (`gpt-6`, `gpt-6-mini` and `gpt-6-sol` stay apart), as do a `:variant`, a four-digit release and OpenAI's dashed date (`gpt-4o-2024-08-06`, a pinned snapshot whose group id agents may already name). A provider kept "Only through routing groups" joins them the same way. Members are `provider/model[:effort]`. A group can nest another (`group/`); `SaveGroup` refuses loops. A group given another id (`agent.RenameGroup`: the Routing page, `magpie groups rename`, the TUI) moves every agent field on `group/` to `group/`, spelled as the agent spells it, through the same `renameRefs` a provider's rename uses, then `SyncCatalog`; before, the agents stayed on a group magpie no longer had (lucis0116 on X, `TestRenameGroupMovesTheAgentsOnIt`). A provider's or group's display name needs no move: `store` and `SaveGroup` drop the catalog, and `SyncCatalog` writes the new labels into every agent's list. `Match` takes a glob or `re:` pattern (#766), both matched in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter). What a pattern matches follows the members named, in the catalog's order, until the user drags it elsewhere (usrname1833 on Discord): `Placed` keeps the whole order, named and matched alike, and the group is read and routed in it (`placedIn`); a model matched since goes last, one no longer matched drops out, a save that sends the named members only leaves the matched where they were (`placedOver`), and a provider's or group's rename carries it (`TestGroupPatternMembersKeepTheirPlace`, `group-member-drag.test.cjs`). A found group follows the providers magpie has: one removed leaves it, while one switched off stays in it (`foundGroups`, `heldOffEntries`; one without a key, such as a plugin not signed in, finds no group), skipped by `membersIn`, left off a found group's card, logos and TUI line with a count of those switched off (XYenon on Discord: `routing-provider-off.test.cjs`, `TestFoundGroupLineLeavesASwitchedOffProviderOut`) and said as switched off in its editor and the TUI's group page, so switching one of two providers off for a while doesn't take the group away from the agents, rules and groups set to it; it is back in its place once on again (#2671: `TestFoundGroupStaysWithAProviderOff`, `TestFoundGroupWithAProviderOff`, `TestReseatKeepsAFoundGroupWithAProviderOff`, `TestFoundGroupMemberOfASwitchedOffProvider`). A found group the user changed (an `auto-…` id stored) is read without the members of providers magpie no longer has (`withoutRemoved`, not written back, so a provider back under its id is back in it), except a manual group's pick, a rule's model, or all of them when none would be left. A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing page says them as switched off (`memberJSON.providerOff`). The user's own groups keep their members. Three templates make a group in one click from the models the user has (`provider.Templates`, `AddTemplate`; the Routing page's cards before a first group and its Templates menu after, `magpie group template [kind] [name]`): `smart` sends a hard turn to the strongest model and an easy one or a compaction to a cheap one, asked by a classifier (the decision API when there is one, else the cheapest priced model that doesn't reason); `thrifty` starts on two cheap models of different providers and sends high reasoning to the strongest; `steady` fails over between the strongest model of up to three providers. A model is weighed by its maker's list price when known, else what its provider charges, else by its id's size words (`sizeOf`); one over `tooDear` (USD 100 a million output tokens) is never picked. A template that can't be made says what is missing (`Need`). It is saved under a name and id no group has (`freeGroupName`, shared with `CopyGroup`), never over one. A group is shared as text (`ShareGroup`, a group row's Copy to share): JSON marked `"magpie": "routing-group"` with a format `version` (`ShareVersion`), holding the group's members as it names them, patterns, routing, rules, classifier and settings. A group holds only `provider/model` ids, never a key, account or address, and the derived matches, found/hidden/off flags and the rules that hold by a folder (a path on the sharer's machine, `Rule.Folders`) stay behind; a pasted one is left out too. `ImportGroup` (the Routing page's Import, `POST /api/groups/import`) reads it with words or a code fence around it, refuses another text, a newer format or none (`ShareError`, said in the reader's language). A member whose provider the importer has is kept; else the same model (`AutoGroupOf`) under the first provider of theirs that serves it (`Instead`); else it is left out and named (`Missing`), with the rules that send to it, its place among the off and fast members, and a classifier gone takes the intent rules and auto effort with it. Nothing is added when no member is left; what is added gets a free name, never replacing a group. A group of patterns only that match nothing now (a plugin's models not listed) has no members: `/api/groups` says them, and an unmakeable template's, as `[]`, never `null`; the Routing page reads the response through `groupsFrom` and draws a group it still can't draw as one row saying so, so one bad group never hides the rest (#1585). | [`group.go`](../../internal/provider/group.go), [`grouptemplate.go`](../../internal/provider/grouptemplate.go), [`group_share.go`](../../internal/provider/group_share.go) | +| 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. It keeps following its model as a found group does (Kxsg79bEYFP4 on X: a third provider with the model, a plugin's, had stayed out of a group the user had changed): `SaveGroup` stores, for an `auto-…` id, what it had seen (`Group.Seen`: the models magpie found in it by that save, and those the user named, as `provider/model`), and a provider that serves the model since joins it as it is read, after the user's own members (`joined`, not written back), unless kept out of found groups. A model seen and not a member is one the user took out, and stays out; a provider's rename or a fold carries `Seen` (`mapModelRefs`), and a shared group leaves it behind. A found group changed before `Seen` was kept takes in nothing, as nothing says which of its models the user took out; its next save sees what is found then (`TestChangedFoundGroupTakesInANewProvider`, `TestChangedFoundGroupFromBeforeKeepsItsMembers`, `TestChangedFoundGroupTakesInAPluginProvider`). 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'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) | diff --git a/internal/provider/fold.go b/internal/provider/fold.go index e7b1d9067..71fb91d7f 100644 --- a/internal/provider/fold.go +++ b/internal/provider/fold.go @@ -343,6 +343,7 @@ func foldWhere(candidates func([]Provider) [][]int) (int, error) { } g.Fast = compact(mapEach(g.Fast, ref)) g.Placed = compact(mapEach(g.Placed, ref)) + g.Seen = compact(mapEach(g.Seen, ref)) g.Off = compact(mapEach(g.Off, ref)) g.Weights = renamedWeights(g.Weights, ref) g.Classifier = ref(g.Classifier) diff --git a/internal/provider/group.go b/internal/provider/group.go index 0b51c361e..adcb33bf6 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -279,6 +279,14 @@ type Group struct { Spelled string `json:"-"` // Hidden is stored for a found group the user removed. Hidden bool `json:"hidden,omitempty"` + // Seen is stored for a found group the user changed (an auto-… id): + // the models, as "provider/model", magpie had found in it by the + // user's last save, and those the user named. A provider that serves + // the model since joins the group as it is read (joined), as it joins + // one magpie finds; one seen and not a member is one the user took + // out, and stays out. Empty, the group was changed before magpie + // kept this, and gets no member it doesn't name (Kxsg79bEYFP4 on X). + Seen []string `json:"seen,omitempty"` // Disabled is a group of the user's switched off (PAMI on Discord): // kept on the Routing page as it is, but not offered to agents, a // request to it turned away with a word of why, and skipped where @@ -425,7 +433,7 @@ func cloneGroups(gs []Group) []Group { for i, g := range gs { g.Members, g.Match, g.Matched, g.Placed = slices.Clone(g.Members), slices.Clone(g.Match), slices.Clone(g.Matched), slices.Clone(g.Placed) g.Off, g.Levels, g.Fast = slices.Clone(g.Off), slices.Clone(g.Levels), slices.Clone(g.Fast) - g.Accounts = slices.Clone(g.Accounts) + g.Accounts, g.Seen = slices.Clone(g.Accounts), slices.Clone(g.Seen) g.Weights = maps.Clone(g.Weights) if g.Rules != nil { rs := make([]Rule, len(g.Rules)) @@ -455,6 +463,10 @@ func buildGroupsIn(entries []Entry) []Group { var out []Group hidden := map[string]bool{} var have map[string]bool // the providers magpie has, switched off or not + var found []Group // the groups magpie finds, for a changed one to follow + if !f.NoAutoGroups { + found = foundGroups(entries) + } for _, g := range f.Groups { if g.Hidden { hidden[g.ID] = true @@ -467,7 +479,7 @@ func buildGroupsIn(entries []Entry) []Group { have[p.ID] = true } } - g = withoutRemoved(g, have) + g = joined(withoutRemoved(g, have), found, entries) } out = append(out, withMatches(entries, g.own())) } @@ -475,7 +487,7 @@ func buildGroupsIn(entries []Entry) []Group { out = slices.DeleteFunc(out, func(g Group) bool { return !g.Auto }) } if !f.NoAutoGroups { - for _, g := range foundGroups(entries) { + for _, g := range found { if slices.ContainsFunc(out, func(o Group) bool { return o.ID == g.ID }) { continue // the user changed it: theirs now } @@ -530,6 +542,66 @@ func withoutRemoved(g Group, have map[string]bool) Group { return g } +// joined is a found group the user changed (an "auto-…" id kept in +// providers.json) with the providers that serve its model since the +// user's last save: found's members it neither names nor has seen +// (Group.Seen), after its own. A third provider with the model, a +// plugin's among them, joins it as it joins one magpie finds +// (Kxsg79bEYFP4 on X: changed, the group had stayed at the two it was +// found with). One the user took out was seen, and stays out; so does +// every provider of a group changed before Seen was kept, as nothing +// says which of its models the user took out. It is how the group is +// read, not stored: a save names the joined, and sees them. +func joined(g Group, found []Group, entries []Entry) Group { + if len(g.Seen) == 0 { + return g + } + i := slices.IndexFunc(found, func(o Group) bool { return o.ID == g.ID }) + if i < 0 { + return g + } + names := make(map[string]bool, len(g.Members)) + for _, m := range g.Members { + base, _ := memberEffortIn(entries, m) + names[base] = true + } + var add []string + for _, m := range found[i].Members { + if !names[m] && !slices.Contains(g.Seen, m) { + add = append(add, m) + } + } + if len(add) == 0 { + return g + } + g.Members = slices.Concat(g.Members, add) + return g +} + +// seenIn is the Seen a found group the user changed is saved with: what +// it had seen (was), the models magpie finds in it now, and those the +// user names (own), each "provider/model" once. +func seenIn(id string, was, own []string, entries []Entry) []string { + seen := slices.Clone(was) + see := func(m string) { + if m != "" && !strings.HasPrefix(m, GroupPrefix) && !IsPattern(m) && !slices.Contains(seen, m) { + seen = append(seen, m) + } + } + for _, g := range foundGroups(entries) { + if g.ID == id { + for _, m := range g.Members { + see(m) + } + } + } + for _, m := range own { + base, _ := memberEffortIn(entries, m) + see(base) + } + return seen +} + // own is the group with lists of its own. f.Groups is the providers.json // every look-up shares while a request holds the catalog (heldOf), so a // caller changing its group in place — the TUI deleting a rule, SaveGroup @@ -544,6 +616,7 @@ func (g Group) own() Group { g.Levels = slices.Clone(g.Levels) g.Fast = slices.Clone(g.Fast) g.Accounts = slices.Clone(g.Accounts) + g.Seen = slices.Clone(g.Seen) g.Weights = maps.Clone(g.Weights) g.Rules = slices.Clone(g.Rules) for i, r := range g.Rules { @@ -1547,6 +1620,17 @@ func SaveGroup(g Group) error { } g.Auto, g.Hidden = false, false g.Members = own // what the patterns match is found again as it is read + // a found group changed keeps following its model: what magpie had + // found in it is seen, so a model taken out stays out and one a new + // provider serves joins it (joined) + g.Seen = nil + if strings.HasPrefix(g.ID, "auto-") { + var was []string + if i := slices.IndexFunc(f.Groups, func(x Group) bool { return x.ID == g.ID }); i >= 0 { + was = f.Groups[i].Seen + } + g.Seen = seenIn(g.ID, was, own, entries) + } g.Disabled = false for i := range f.Groups { if f.Groups[i].ID == g.ID { diff --git a/internal/provider/group_follow_test.go b/internal/provider/group_follow_test.go new file mode 100644 index 000000000..a20491f6d --- /dev/null +++ b/internal/provider/group_follow_test.go @@ -0,0 +1,186 @@ +package provider + +import ( + "context" + "encoding/json" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/testenv" +) + +// groupMembers are the members of the group id as Groups reads it, nil +// when there is none (or it is hidden). +func groupMembers(t *testing.T, id string) []string { + t.Helper() + for _, g := range Groups() { + if g.ID == id && !g.Hidden { + return g.Members + } + } + return nil +} + +func saveKeyProvider(t *testing.T, id string, models ...string) { + t.Helper() + if err := Save(Provider{ID: id, Name: id, Key: "k", Chat: "http://127.0.0.1:1/v1", Models: models}); err != nil { + t.Fatal(err) + } +} + +// A found group the user changed follows its model as one magpie finds +// does (Kxsg79bEYFP4 on X: auto/deepseek-v4.1-flash, changed, stayed at +// the two providers it was found with when a third with the model was +// added): a provider that serves the model since joins it, after the +// members the user named. A model the user took out stays out, the one +// taken out before the new provider came and the new one taken out +// after it joined alike; a provider kept out of found groups doesn't +// join; and a provider's rename carries what was seen, so the renamed +// provider's model the user took out doesn't come back by its new id. +func TestChangedFoundGroupTakesInANewProvider(t *testing.T) { + claudeHome(t) + saveKeyProvider(t, "a", "deepseek-v4.1-flash") + saveKeyProvider(t, "b", "deepseek-v4-1-flash") + saveKeyProvider(t, "c", "deepseek-v4.1-flash") + if got := groupMembers(t, "auto-deepseek-v4-1-flash"); !slices.Equal(got, []string{"a/deepseek-v4.1-flash", "b/deepseek-v4-1-flash", "c/deepseek-v4.1-flash"}) { + t.Fatalf("found: %v", got) + } + // the user changes it: routing by turns, without c + if err := SaveGroup(Group{ID: "auto-deepseek-v4-1-flash", Name: "DS Flash", Members: []string{"b/deepseek-v4-1-flash", "a/deepseek-v4.1-flash:high"}, Routing: Rotate}); err != nil { + t.Fatal(err) + } + want := []string{"b/deepseek-v4-1-flash", "a/deepseek-v4.1-flash:high"} + if got := groupMembers(t, "auto-deepseek-v4-1-flash"); !slices.Equal(got, want) { + t.Fatalf("changed: %v", got) + } + // a fourth provider with the model joins it, last; c stays out + saveKeyProvider(t, "d", "DeepSeek-V4.1-Flash") + want = append(want, "d/DeepSeek-V4.1-Flash") + if got := groupMembers(t, "auto-deepseek-v4-1-flash"); !slices.Equal(got, want) { + t.Fatalf("d added: %v, want %v", got, want) + } + // the group the gateway routes has it too + if _, ms, ok := FindGroup("group/auto-deepseek-v4-1-flash"); !ok || !slices.ContainsFunc(ms, func(m Member) bool { return m.Provider.ID == "d" }) { + t.Fatalf("routed without d: %v %v", ms, ok) + } + // saved as read, it is named; the user's name and routing stay + gs := Groups() + g := gs[slices.IndexFunc(gs, func(g Group) bool { return g.ID == "auto-deepseek-v4-1-flash" })] + if g.Name != "DS Flash" || g.Routing != Rotate { + t.Fatalf("the user's settings: %q %q", g.Name, g.Routing) + } + // the user takes d out: it stays out, as c does + g.Members = slices.DeleteFunc(slices.Clone(g.Members), func(m string) bool { return strings.HasPrefix(m, "d/") }) + if err := SaveGroup(g); err != nil { + t.Fatal(err) + } + want = []string{"b/deepseek-v4-1-flash", "a/deepseek-v4.1-flash:high"} + if got := groupMembers(t, "auto-deepseek-v4-1-flash"); !slices.Equal(got, want) { + t.Fatalf("d taken out: %v", got) + } + // renamed, c is still one the user took out + if err := Rename("c", "cee"); err != nil { + t.Fatal(err) + } + if got := groupMembers(t, "auto-deepseek-v4-1-flash"); !slices.Equal(got, want) { + t.Fatalf("c renamed came back: %v", got) + } + // one kept out of found groups doesn't join; let back in, it does + saveKeyProvider(t, "e", "deepseek-v4.1-flash") + if err := SetAutoGroupSkip([]string{"e"}); err != nil { + t.Fatal(err) + } + if got := groupMembers(t, "auto-deepseek-v4-1-flash"); !slices.Equal(got, want) { + t.Fatalf("e kept out joined: %v", got) + } + if err := SetAutoGroupSkip(nil); err != nil { + t.Fatal(err) + } + if got := groupMembers(t, "auto-deepseek-v4-1-flash"); !slices.Equal(got, append(slices.Clone(want), "e/deepseek-v4.1-flash")) { + t.Fatalf("e let back in: %v", got) + } + // what this magpie saw is its own: a shared group doesn't carry it + text, err := ShareGroup("auto-deepseek-v4-1-flash") + if err != nil { + t.Fatal(err) + } + var shared SharedGroup + if err := json.Unmarshal([]byte(text), &shared); err != nil || len(shared.Group.Seen) != 0 { + t.Fatalf("shared with what was seen: %v %v", shared.Group.Seen, err) + } +} + +// A found group changed before magpie kept what it had seen has no +// record of which of its models the user took out: none joins it, as +// before, so one taken out by hand never comes back. Its next save +// sees what is found then, and from that on a new provider joins. +func TestChangedFoundGroupFromBeforeKeepsItsMembers(t *testing.T) { + claudeHome(t) + saveKeyProvider(t, "a", "glm-5.3") + saveKeyProvider(t, "b", "glm-5.3") + saveKeyProvider(t, "c", "glm-5.3") + f, err := read() + if err != nil { + t.Fatal(err) + } + // as an older magpie stored it: c taken out, nothing seen + f.Groups = append(f.Groups, Group{ID: "auto-glm-5-3", Name: "GLM", Members: []string{"a/glm-5.3", "b/glm-5.3"}, Routing: Ordered}) + if err := store(f); err != nil { + t.Fatal(err) + } + want := []string{"a/glm-5.3", "b/glm-5.3"} + if got := groupMembers(t, "auto-glm-5-3"); !slices.Equal(got, want) { + t.Fatalf("an older change: %v", got) + } + saveKeyProvider(t, "d", "glm-5.3") + if got := groupMembers(t, "auto-glm-5-3"); !slices.Equal(got, want) { + t.Fatalf("an older change took a model in: %v", got) + } + gs := Groups() + if err := SaveGroup(gs[slices.IndexFunc(gs, func(g Group) bool { return g.ID == "auto-glm-5-3" })]); err != nil { + t.Fatal(err) + } + if got := groupMembers(t, "auto-glm-5-3"); !slices.Equal(got, want) { + t.Fatalf("saved again: %v", got) + } + saveKeyProvider(t, "e", "glm-5.3") + if got := groupMembers(t, "auto-glm-5-3"); !slices.Equal(got, append(want, "e/glm-5.3")) { + t.Fatalf("a provider after the save: %v", got) + } +} + +// The reporter's case on its own surface: a provider a plugin serves, +// added after the user changed a found group of two key providers, +// joins it. +func TestChangedFoundGroupTakesInAPluginProvider(t *testing.T) { + bun := testenv.Bun(t) + claudeHome(t) + t.Setenv("MAGPIE_BUN", bun) + t.Setenv("FAKE_DEEPSEEK", "1") + t.Cleanup(plugin.Settle) + saveKeyProvider(t, "a", "deepseek-v4-pro") + saveKeyProvider(t, "b", "deepseek-v4-pro") + if err := SaveGroup(Group{ID: "auto-deepseek-v4-pro", Name: "DS Pro", Members: []string{"b/deepseek-v4-pro", "a/deepseek-v4-pro"}, Routing: Ordered}); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + abs, _ := filepath.Abs("../plugin/testdata/fake/index.js") + if _, err := plugin.Add(ctx, abs); err != nil { + t.Fatal(err) + } + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + if _, err := plugin.APIKey(ctx, "fakeco", 0, nil, "k1", plugin.NewAccount); err != nil { + t.Fatal(err) + } + got := groupMembers(t, "auto-deepseek-v4-pro") + if len(got) != 3 || !slices.Equal(got[:2], []string{"b/deepseek-v4-pro", "a/deepseek-v4-pro"}) || !strings.HasSuffix(got[2], "/deepseek-v4-pro") || strings.HasPrefix(got[2], "a/") || strings.HasPrefix(got[2], "b/") { + t.Fatalf("the plugin's provider didn't join: %v", got) + } +} diff --git a/internal/provider/group_share.go b/internal/provider/group_share.go index fc4a1edd8..91c942a30 100644 --- a/internal/provider/group_share.go +++ b/internal/provider/group_share.go @@ -53,6 +53,7 @@ func ShareGroup(id string) (string, error) { g.Matched = nil g.Auto, g.Hidden, g.Disabled = false, false, false g.Accounts = nil // this magpie's accounts: another has its own + g.Seen = nil // what this magpie found: another finds its own g.Rules = slices.DeleteFunc(g.Rules, Rule.ByFolder) out, err := json.Marshal(SharedGroup{Magpie: ShareMark, Version: ShareVersion, Group: g}) return string(out), err diff --git a/internal/provider/rename.go b/internal/provider/rename.go index fa2f99358..0f63fcd81 100644 --- a/internal/provider/rename.go +++ b/internal/provider/rename.go @@ -119,7 +119,7 @@ func Rename(from, to string) error { } // mapModelRefs gives every model ref the file keeps for routing — the -// providers' fallbacks, and the routing groups' members, rules, fast and +// providers' fallbacks, and the routing groups' members, rules, fast, seen and // placed members, those turned off, weights, classifiers and picks — as // to has it: what a provider's rename (Rename) and a model given another // id at its provider (SetModelID) both rewrite. @@ -143,6 +143,9 @@ func mapModelRefs(f *file, to func(string) string) { for k, m := range g.Placed { g.Placed[k] = to(m) } + for k, m := range g.Seen { + g.Seen[k] = to(m) + } for k, m := range g.Off { g.Off[k] = to(m) }