provider: a provider switched off for a while stays in the groups magpie found, so agents on auto-<model> aren't rewritten to the one left (#2671)

timonwong (#2671, with the branch this is): a found group, auto-<model>,
was built from the providers that are on only, so switching off one of
its two providers took the group away. Every agent on group/auto-<model>
was reseated to the other provider's model (agent.Reseat → sameModel),
rules and groups naming it went 404, and switching the provider back on
brought the group back but not the agents' settings.

timonwong's change, ported as is (05927b833, 063fe15a2):
- models.go: entriesOf(of, off), and heldOffEntries(), the models of the
  providers that are Ready and Off (a keyless one, a plugin not signed in,
  finds no group), held per request like the other entries.
- group.go: foundGroups/foundFrom merge those back in the Providers order
  before autoGroups, in groupsIn, DeleteGroup and RenameGroup. membersIn
  already skips a switched-off member, and the Routing page already says
  it as switched off (memberJSON.providerOff).
- A removed provider still leaves the group; NoAutoGroups and
  ModelSameAs are honoured; a hidden found group stays hidden.
  Side effect: a found group whose only usable member is left shows while
  a provider is off, which is the point.
Reviewed line by line; nothing writes a user-set value, and Reseat now
has nothing to move for these agents, so there is nothing to restore when
the provider is on again.

Added here: TestReseatKeepsAFoundGroupWithAProviderOff (internal/agent:
Claude Code and Hermes on group/auto-gpt-5 are not moved when cop is
switched off, a model only cop served still is, the group resolves, and
switching cop on moves nobody) and TestFoundGroupMemberOfASwitchedOffProvider
(internal/gui: auto-x is on the Routing page with b/x said as switched
off). The docs row names the tests.

Red on bf931f82c's provider code (models.go and group.go from main): both
new tests, timonwong's TestFoundGroupWithAProviderOff (404 as in the
issue) and the updated TestProviderOff. Broken by hand (heldOffEntries
returning nil): the agent and gui tests and TestFoundGroupStaysWithAProviderOff
and TestFoundGroupRemovedWithAProviderOff go red.

Run at this change on bf931f82c: gofmt -l clean; go vet ./... (darwin),
GOOS=linux and GOOS=windows go vet -tags nogui ./... ok; full go test
-tags nogui -count=1 -timeout 45m ./... (load average ~140): every package
ok, internal/gateway and internal/provider included, except
internal/agent, which ran past 45m (#2544), and internal/middleware's
TestDocsExample, a strategy's wall-clock budget under load that passes
alone (filed as #2728). internal/agent then alone, -timeout 100m: ok in
2971s.
No GUI asset changed (the gui test is a Go test of groupsState), so the
Playwright suite was not run.

Co-authored-by: timonwong <timon86.wang@gmail.com>
This commit is contained in:
yetone
2026-10-17 20:38:06 +08:00
co-authored by timonwong
parent 992f288e20
commit 2042123f43
9 changed files with 320 additions and 11 deletions
+1 -1
View File
@@ -40,7 +40,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| Import from files | `ImportLogins` (ChatGPT, Claude), `ImportGoogleAccounts` (Antigravity) and `ImportFactoryKeys` take other tools' files, from the window (`signin/import`) or `magpie accounts import` (#1453). ChatGPT reads Codex's `auth.json`, CLIProxyAPI's and Cockpit Tools' files, Sub2API's export (`sub2apiEntry`) and codexbar's `~/.codexbar/config.json` (`codexbarEntries`: the `openai_oauth` provider's accounts and `openAI.remoteConnectionAccounts`, the workspace from `openAIAccountId`). Each ChatGPT and Google sign-in is refreshed before it is added, so the tool the file came from is signed out of it; both surfaces say so first, and the command imports nothing without `--yes` or a yes. Claude reads CLIProxyAPI's files and Sub2API's export, whose Claude account says its email as Anthropic does, `email_address`, in `credentials` or `extra`, and keeps its `scope`, `account_uuid` and `org_uuid` as Claude Code's scopes, `accountUuid` and `organizationUuid` (#1975); a file with no email is refused, as Claude Code's own `.credentials.json` is. Claude's are kept as the file has them. A refresh token magpie holds already is `exists`, never refreshed; accounts are matched by email and workspace, or for Claude organization (`sameLogin`). An entry with an access token and no refresh token is refused (`accessOnly`). One file of several that holds no account is a failed row with its place (`ImportedAccount.File`), never skipped. The files are only read. | [`login_import.go`](../../internal/provider/login_import.go), [`google_import.go`](../../internal/provider/google_import.go), [`factory_key.go`](../../internal/provider/factory_key.go), [`accounts_cli.go`](../../internal/cli/accounts_cli.go) |
| 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). 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. | [`codex_switch.go`](../../internal/provider/codex_switch.go) |
| 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). Members are `provider/model[:effort]`. A group can nest another (`group/<id>`); `SaveGroup` refuses loops. `Match` takes a glob or `re:` pattern (#766). A found group follows its providers: one switched off or removed leaves it, and one on again is back. 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). Members are `provider/model[:effort]`. A group can nest another (`group/<id>`); `SaveGroup` refuses loops. `Match` takes a glob or `re:` pattern (#766). 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` and said as switched off on the Routing page, so switching one of two providers off for a while doesn't take the group away from the agents, rules and groups set to it; it is back in its place once on again (#2671: `TestFoundGroupStaysWithAProviderOff`, `TestFoundGroupWithAProviderOff`, `TestReseatKeepsAFoundGroupWithAProviderOff`, `TestFoundGroupMemberOfASwitchedOffProvider`). A found group the user changed (an `auto-…` id stored) is read without the members of providers magpie no longer has (`withoutRemoved`, not written back, so a provider back under its id is back in it), except a manual group's pick, a rule's model, or all of them when none would be left. A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing page says them as switched off (`memberJSON.providerOff`). The user's own groups keep their members. Three templates make a group in one click from the models the user has (`provider.Templates`, `AddTemplate`; the Routing page's cards before a first group and its Templates menu after, `magpie group template [kind] [name]`): `smart` sends a hard turn to the strongest model and an easy one or a compaction to a cheap one, asked by a classifier (the decision API when there is one, else the cheapest priced model that doesn't reason); `thrifty` starts on two cheap models of different providers and sends high reasoning to the strongest; `steady` fails over between the strongest model of up to three providers. A model is weighed by its maker's list price when known, else what its provider charges, else by its id's size words (`sizeOf`); one over `tooDear` (USD 100 a million output tokens) is never picked. A template that can't be made says what is missing (`Need`). It is saved under a name and id no group has (`freeGroupName`, shared with `CopyGroup`), never over one. A group is shared as text (`ShareGroup`, a group row's Copy to share): JSON marked `"magpie": "routing-group"` with a format `version` (`ShareVersion`), holding the group's members as it names them, patterns, routing, rules, classifier and settings. A group holds only `provider/model` ids, never a key, account or address, and the derived matches, found/hidden/off flags and the rules that hold by a folder (a path on the sharer's machine, `Rule.Folders`) stay behind; a pasted one is left out too. `ImportGroup` (the Routing page's Import, `POST /api/groups/import`) reads it with words or a code fence around it, refuses another text, a newer format or none (`ShareError`, said in the reader's language). A member whose provider the importer has is kept; else the same model (`AutoGroupOf`) under the first provider of theirs that serves it (`Instead`); else it is left out and named (`Missing`), with the rules that send to it, its place among the off and fast members, and a classifier gone takes the intent rules and auto effort with it. Nothing is added when no member is left; what is added gets a free name, never replacing a group. A group of patterns only that match nothing now (a plugin's models not listed) has no members: `/api/groups` says them, and an unmakeable template's, as `[]`, never `null`; the Routing page reads the response through `groupsFrom` and draws a group it still can't draw as one row saying so, so one bad group never hides the rest (#1585). | [`group.go`](../../internal/provider/group.go), [`grouptemplate.go`](../../internal/provider/grouptemplate.go), [`group_share.go`](../../internal/provider/group_share.go) |
| Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it, each window with its whole-window estimate (`Holds`/`HoldsWhy`, `usage.WithWindowHolds`, which `quotaReport` reaches through the `ReckonHolds` hook since package provider can't import usage, #2333). A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). Each key of a remote-magpie provider also gets a card of its own, under `<remote>/~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=<remote>/~keys&user=<key name>`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). A remote that holds the key to a budget, models or accounts answers its cards 403 `gateway_key_held` (#1981, `errKeyHeld`): the cards kept from before are dropped and only the key's own card shows. Its owner can let the key be told the cards of what it may use (#2216, `magpie gateway-key quotas <id> on`); the remote then answers those, and 403 as before when that is none. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, `quotasOpened`, #1588) or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. | [`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 prices (a remote request without a valid key never reaches the list: `lanGuard` refuses it). 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). 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) |
+4 -3
View File
@@ -130,9 +130,10 @@ func served(ref string) bool {
// sameModel is the option for ref's model from another provider still
// serving it: the same id, else one that differs only in how it is spelt
// (claude-sonnet-4.5 and claude-sonnet-4-5-20250929). For a group magpie
// found (group/auto-…), gone as found groups are turned off or its model is
// down to one provider, it is that model from the first provider still
// serving it; none for any other routing group, which is nobody else's.
// found (group/auto-…), gone as found groups are turned off or its model
// is down to one provider magpie has, it is that model from the first
// provider still serving it; none for any other routing group, which is
// nobody else's.
func sameModel(opts []Option, ref string) Option {
// a group's id carries Claude Code's [1m] mark as a model's does, and
// this ref comes from the agent's own settings
+36
View File
@@ -237,3 +237,39 @@ func TestReseatFoundGroupsOff(t *testing.T) {
t.Fatalf("on again: %+v %v", moves, err)
}
}
// #2671 (timonwong): a provider switched off for a while leaves the found
// group of a model another provider still serves, so an agent on that
// group stays on it, rather than being rewritten to the one provider left
// and not put back when the provider is on again. A model only the
// switched-off provider served still moves.
func TestReseatKeepsAFoundGroupWithAProviderOff(t *testing.T) {
reseatHome(t)
c, h := mustFind(t, "claude"), mustFind(t, "hermes")
mustApply(t, c, "model", "group/auto-gpt-5")
mustApply(t, c, "haiku", "cop/only-here")
mustApply(t, h, "model", "magpie/group/auto-gpt-5")
moves, err := Reseat(func() error { return provider.SetOff("cop", true) })
if err != nil {
t.Fatal(err)
}
if got := c.Field("model").Get(); got != "group/auto-gpt-5" {
t.Errorf("claude model with cop off: %q", got)
}
if got := h.Field("model").Get(); got != "magpie/group/auto-gpt-5" {
t.Errorf("hermes with cop off: %q", got)
}
if len(moves) != 1 || moves[0].Field != "haiku" || moves[0].From != "cop/only-here" {
t.Errorf("moves with cop off: %+v", moves)
}
if _, _, ok := provider.Resolve("group/auto-gpt-5"); !ok {
t.Error("group/auto-gpt-5 gone with cop off")
}
// on again, nobody is moved, and the group has cop in it again
if moves, err = Reseat(func() error { return provider.SetOff("cop", false) }); err != nil || len(moves) != 0 {
t.Fatalf("on again: %+v %v", moves, err)
}
if got := c.Field("model").Get(); got != "group/auto-gpt-5" {
t.Errorf("claude model on again: %q", got)
}
}
+32
View File
@@ -42,3 +42,35 @@ func TestFoundGroupOff(t *testing.T) {
t.Fatalf("bare m: %d %s", code, body)
}
}
// An agent set to a group magpie found keeps it while the user switches
// one of its two providers off for a while: the request is the group's,
// answered by the provider still on, not refused as a model magpie
// doesn't know, and the other is asked again once it is back on.
func TestFoundGroupWithAProviderOff(t *testing.T) {
fresh(t)
a, b := &keyed{}, &keyed{}
serveOn(t, "a", "ka", []string{"m"}, a)
serveOn(t, "b", "kb", []string{"m"}, b)
s := New()
if err := provider.SetOff("a", true); err != nil {
t.Fatal(err)
}
for _, model := range []string{"group/auto-m", "m"} {
a.tried, b.tried = nil, nil
code, body := postAs(t, s, "", `{"model":"`+model+`","messages":[{"role":"user","content":"hi"}]}`)
if code != 200 || !strings.Contains(body, "from kb") || len(a.tried) != 0 {
t.Fatalf("%s with a off: %d %s, a tried %v", model, code, body, a.tried)
}
if r := s.trace.routes[len(s.trace.routes)-1]; r.Group == nil {
t.Fatalf("%s with a off, not routed as the group: %+v", model, r)
}
}
if err := provider.SetOff("a", false); err != nil {
t.Fatal(err)
}
// another conversation, so b's answer to the one above doesn't hold it
if code, body := postAs(t, s, "", `{"model":"group/auto-m","messages":[{"role":"user","content":"a new one"}]}`); code != 200 || !strings.Contains(body, "from ka") {
t.Fatalf("a on again: %d %s", code, body)
}
}
+7 -2
View File
@@ -10,7 +10,8 @@ import (
// A provider switched off (#163) is kept, but agents are given none of its
// models, no request, group or fallback goes to it, and one naming it is
// told it is switched off; switched on, all of it comes back.
// told it is switched off; switched on, all of it comes back. A group
// magpie found with it stays, served by the providers still on.
func TestProviderOff(t *testing.T) {
fresh(t)
a, b := &keyed{}, &keyed{}
@@ -45,7 +46,7 @@ func TestProviderOff(t *testing.T) {
if err != nil || !pb.Off || pb.Key != "kb" {
t.Fatalf("switched off, b is kept with its key: %+v %v", pb, err)
}
if got := catalog(); got != "group/mine a/m a/only-a" {
if got := catalog(); got != "group/mine group/auto-m a/m a/only-a" {
t.Fatalf("catalog with b off: %s", got)
}
if _, _, ok := provider.Resolve("b/vendor/m"); ok {
@@ -74,6 +75,10 @@ func TestProviderOff(t *testing.T) {
if code != 200 || !strings.Contains(body, "from ka") || len(b.tried) != 0 {
t.Fatalf("group/mine with b off: %d %s, b tried %v", code, body, b.tried)
}
code, body = postAs(t, s, "", `{"model":"group/auto-m","messages":[{"role":"user","content":"found"}]}`)
if code != 200 || !strings.Contains(body, "from ka") || len(b.tried) != 0 {
t.Fatalf("group/auto-m with b off: %d %s, b tried %v", code, body, b.tried)
}
// a's fallback is b's: with b off there is none to go to
a.fail = map[string]int{"ka": 429}
code, _ = postAs(t, s, "", `{"model":"a/m","messages":[{"role":"user","content":"hi"}]}`)
@@ -0,0 +1,47 @@
package gui
import (
"os"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// #2671 (timonwong): a provider switched off for a while leaves the found
// group of a model another provider serves on the Routing page, with its
// member said as its provider being off, rather than the group vanishing.
func TestFoundGroupMemberOfASwitchedOffProvider(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("USERPROFILE", os.Getenv("HOME"))
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
for _, id := range []string{"a", "b"} {
if err := provider.Save(provider.Provider{ID: id, Name: strings.ToUpper(id) + " Cloud", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"x"}}); err != nil {
t.Fatal(err)
}
}
if err := provider.SetOff("b", true); err != nil {
t.Fatal(err)
}
var found *groupJSON
st := groupsState()
for i := range st.Groups {
if st.Groups[i].ID == "auto-x" {
found = &st.Groups[i]
}
}
if found == nil {
t.Fatalf("no group auto-x with b off: %+v", st.Groups)
}
info := map[string]memberJSON{}
for _, m := range found.Info {
info[m.ID] = m
}
if m := info["a/x"]; !m.Ready || m.ProviderOff {
t.Fatalf("a/x: %+v", m)
}
if m := info["b/x"]; m.Ready || !m.ProviderOff || m.Name != "B Cloud" {
t.Fatalf("b/x, its provider off: %+v", m)
}
}
+39 -4
View File
@@ -21,6 +21,7 @@ package provider
// into providers.json by hand is cut where it closes.
import (
"cmp"
"errors"
"fmt"
"maps"
@@ -377,7 +378,7 @@ func groupsIn(entries []Entry) []Group {
if f.NoAutoGroups {
return orderedGroups(out, f.GroupOrder)
}
for _, g := range autoGroups(entries, heldSettings().ModelSameAs) {
for _, g := range foundGroups(entries) {
if slices.ContainsFunc(out, func(o Group) bool { return o.ID == g.ID }) {
continue // the user changed it: theirs now
}
@@ -564,7 +565,41 @@ func AutoStandIn(id string) (string, bool) {
return "", false
}
// autoGroups are the models more than one ready provider serves under the
// foundGroups are the groups magpie finds (autoGroups) among entries and
// the models of the providers switched off: one switched off for a while
// stays in the group, a member the gateway skips (membersIn), rather than
// taking a group of two away with every agent, rule and group set to it.
func foundGroups(entries []Entry) []Group {
return autoGroups(foundFrom(entries, heldOffEntries()), heldSettings().ModelSameAs)
}
// foundFrom is entries with idle's models it lacks, each provider's in
// the Providers order, so a provider on again is back in its place.
func foundFrom(entries, idle []Entry) []Entry {
have := make(map[string]bool, len(entries))
for _, e := range entries {
have[e.ID] = true
}
idle = slices.DeleteFunc(slices.Clone(idle), func(e Entry) bool { return have[e.ID] })
if len(idle) == 0 {
return entries
}
at := map[string]int{}
for i, p := range All() {
at[p.ID] = i
}
pos := func(e Entry) int {
if i, ok := at[e.Provider.ID]; ok {
return i
}
return len(at)
}
out := append(slices.Clone(entries), idle...)
slices.SortStableFunc(out, func(a, b Entry) int { return cmp.Compare(pos(a), pos(b)) })
return out
}
// autoGroups are the models more than one provider serves under the
// same name — however each vendor spells it (see sameModel), or as the
// user said one is the same as another (same: settings' ModelSameAs) — in
// the order the providers were added.
@@ -1301,7 +1336,7 @@ func DeleteGroup(id string) error {
}
return false
})
if slices.ContainsFunc(autoGroups(providerEntries(), settings.Load().ModelSameAs), func(g Group) bool { return g.ID == id }) {
if slices.ContainsFunc(foundGroups(providerEntries()), func(g Group) bool { return g.ID == id }) {
f.Groups = append(f.Groups, Group{ID: id, Hidden: true})
found = true
}
@@ -1482,7 +1517,7 @@ func RenameGroup(from, to string) error {
slices.ContainsFunc(f.Groups, func(o Group) bool { return o.ID == to }) {
return fmt.Errorf("there is a group %q already", to)
}
found := slices.ContainsFunc(autoGroups(providerEntries(), settings.Load().ModelSameAs), func(o Group) bool { return o.ID == from })
found := slices.ContainsFunc(foundGroups(providerEntries()), func(o Group) bool { return o.ID == from })
g.ID, g.Auto, g.Hidden = to, false, false
f.Groups = slices.DeleteFunc(f.Groups, func(o Group) bool { return o.ID == from })
if found {
+139
View File
@@ -0,0 +1,139 @@
package provider
import (
"slices"
"testing"
)
// A group magpie found stays while a provider of it is switched off for a
// while: agents set to it, rules and groups naming it keep working on the
// providers still on, and the one switched off is back in its place once
// it is on again. Only removing a provider takes it out for good.
func TestFoundGroupStaysWithAProviderOff(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("USERPROFILE", t.TempDir())
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
// c serves y alone, so no group is found for it
for _, id := range []string{"a", "b", "c"} {
models := []string{"x"}
if id == "c" {
models = append(models, "y")
}
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)
}
}
members := func() []string {
t.Helper()
g, ok := groupOf(Groups(), "auto-x")
if !ok {
t.Fatal("no group auto-x")
}
if !g.Auto {
t.Fatalf("auto-x is no longer a found group: %+v", g)
}
return g.Members
}
routed := func() (out []string) {
_, ms, _ := FindGroup(GroupPrefix + "auto-x")
for _, m := range ms {
out = append(out, m.Provider.ID+"/"+m.Model)
}
return out
}
listed := func() bool {
return slices.ContainsFunc(Served(), func(e Entry) bool { return e.ID == GroupPrefix+"auto-x" })
}
all := []string{"a/x", "b/x", "c/x"}
if got := members(); !slices.Equal(got, all) {
t.Fatalf("found: %v", got)
}
// two of three off: one member left, the group stays, in its order
for _, id := range []string{"a", "b"} {
if err := SetOff(id, true); err != nil {
t.Fatal(err)
}
}
if got := members(); !slices.Equal(got, all) {
t.Fatalf("a and b off, members: %v", got)
}
if got := routed(); !slices.Equal(got, []string{"c/x"}) {
t.Fatalf("a and b off, routes to %v", got)
}
if !listed() {
t.Fatal("a and b off, the group is gone from the models agents are offered")
}
if gid, ok := GroupFor("x"); !ok || gid != GroupPrefix+"auto-x" {
t.Fatalf("a and b off, x names %q %v", gid, ok)
}
// a model only one provider has, switched off or not, is no group
if _, ok := groupOf(Groups(), "auto-y"); ok {
t.Fatal("y, which only c serves, is a group")
}
// every one off: still the group, with nothing to route to
if err := SetOff("c", true); err != nil {
t.Fatal(err)
}
if got := members(); !slices.Equal(got, all) {
t.Fatalf("all off, members: %v", got)
}
if got := routed(); len(got) != 0 {
t.Fatalf("all off, routes to %v", got)
}
// on again, each is back in its place
for _, id := range []string{"a", "b", "c"} {
if err := SetOff(id, false); err != nil {
t.Fatal(err)
}
}
if got := routed(); !slices.Equal(got, all) {
t.Fatalf("on again, routes to %v", got)
}
// removed, a provider leaves it; with one left there is no group
for _, id := range []string{"a", "b"} {
if err := Delete(id); err != nil {
t.Fatal(err)
}
}
if _, ok := groupOf(Groups(), "auto-x"); ok {
t.Fatal("a and b removed, auto-x is still found")
}
}
// A found group the user removed stays removed while a provider of it is
// switched off, and removing it then hides it rather than failing.
func TestFoundGroupRemovedWithAProviderOff(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("USERPROFILE", t.TempDir())
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
for _, id := range []string{"a", "b"} {
if err := Save(Provider{ID: id, Name: id, Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"x"}}); err != nil {
t.Fatal(err)
}
}
if err := SetOff("b", true); err != nil {
t.Fatal(err)
}
if err := DeleteGroup("auto-x"); err != nil {
t.Fatal(err)
}
hidden := func() bool {
i := slices.IndexFunc(Groups(), func(g Group) bool { return g.ID == "auto-x" })
return i >= 0 && Groups()[i].Hidden
}
if !hidden() {
t.Fatal("removed with b off, auto-x isn't marked removed")
}
if err := SetOff("b", false); err != nil {
t.Fatal(err)
}
if !hidden() {
t.Fatal("b on again, the removed group is back")
}
}
+15 -1
View File
@@ -2378,11 +2378,25 @@ func buildEntries() []Entry { return entriesOff(disabledNow()) }
// entriesOff is the providers' catalog less the models off reports.
func entriesOff(off func(pid, model string) bool) []Entry {
return entriesOf(Provider.On, off)
}
// heldOffEntries are the models of the providers the user switched off,
// which the groups magpie finds keep (foundFrom). One without a key, a
// plugin not signed in, finds no group.
func heldOffEntries() []Entry {
return heldOf("off entries", func() []Entry {
return slices.Clip(entriesOf(func(p Provider) bool { return p.Ready() && p.Off }, disabledNow()))
})
}
// entriesOf is the catalog of the providers of, less the models off reports.
func entriesOf(of func(Provider) bool, off func(pid, model string) bool) []Entry {
var out []Entry
s := settings.Load()
gone := retiredNow() // its vendor said it is retired (retired.go)
for _, p := range All() {
if !p.On() || p.DecideOnly() { // a dedicated decision API only routes
if !of(p) || p.DecideOnly() { // a dedicated decision API only routes
continue
}
for _, m := range p.Exposed() {