From 59bdd4dbc302ebc522a1e997cdaffac3eef0c379 Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 31 Oct 2026 01:02:29 +0800 Subject: [PATCH] routing: a group's pattern members can be put in order by hand (usrname1833) In a routing group, members a pattern added followed the catalog's order. The editor gave them no grip or Up/Down, and the gateway tried them in that order. Now every row gets the same grip, Alt+arrow and Up/Down that named members have. Matched rows still have no Remove, since the pattern decides those. The order is stored as Group.Placed, keyed by provider/model as Members spells them. It is nil while the order equals the default (named, then matched in catalog order), so existing groups.json files don't change. Read (withMatches -> placedIn): members follow Placed. A model matched since goes after them, and one no longer matched drops out. The gateway tries members in the order the group is read, so it follows the editor. Saved (SaveGroup -> placedOver): Members orders the named members, and Placed (sent, or the stored one when a save doesn't send it) places the matched ones. A save that doesn't know Placed (card routing, the CLI's models+=, TUI, import) keeps the matched where they were, and a model it names newly goes after the last named one. A provider rename, fold, group rename and RenameMember carry Placed along. Run: - go test -timeout 45m -count=1 ./... on mote: 80 packages ok. internal/gui fails 10 AppKit window tests at 30s (TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt, TestMainWindowCorners, ...). On a fresh origin/main cf9ea977c the five I reran fail the same way. That is mote's #4125 (open). - TestGroupPatternMembersKeepTheirPlace is red on the old code (read [zen/y or/a:free or/c:free]). - Broken by hand, each red at its own step: no stored-Placed fallback ("after a named-only save"), a newly named model put last instead of after the last named one ("after an add"). On the earlier draft, no rename mapping ("after a rename"). - GUI: group-member-drag and group-patterns in chromium and webkit on Linux (wsl-run), 8/8 at this head. group-member-drag was red on the old client.js. The whole GUI suite ran at the draft before the save payload's `placed` field. It was still running when this was pushed, and its reds will be filed once it ends. - gofmt -l clean; GOOS=linux and GOOS=windows go vet of provider and gateway on mote. Not tried: a real account or the real app's window; WebKit on macOS (mote's browser launches hang, #4125), so WebKit only on Linux. The TUI has no way to reorder matched members; it keeps the stored order. --- docs/subsystems/providers-accounts.md | 2 +- internal/gui/assets/plugins/routing/client.js | 34 ++++---- internal/gui/tests/group-member-drag.test.cjs | 38 ++++---- internal/gui/tests/group-patterns.test.cjs | 5 +- internal/provider/fold.go | 1 + internal/provider/group.go | 35 +++++++- internal/provider/groupfast.go | 5 ++ internal/provider/groupmatch.go | 85 +++++++++++++++++- internal/provider/groupmatch_test.go | 87 +++++++++++++++++++ internal/provider/rename.go | 3 + 10 files changed, 255 insertions(+), 40 deletions(-) diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 97e822cff..030bd9e67 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -52,7 +52,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Switch accounts only | magpie as a Claude Code (or Codex) account switcher alone, with nothing connected (the owner on X; growaiskills, Rennix7t). In the window, the Agents row of a Claude Code or Codex not connected says the account it is signed in to (`switchEntry` in app.js, from the providers list `prefetchProviders` reads at start, so `/api/state` reads no keychain for it), also when magpie has no models to connect (`switchable`, before the `empty` line). Its menu, headed *Switch accounts only*, lists the agent's saved accounts: a pick goes through `POST /api/login/switch` (`SwitchLogin`), or `provider/keeplogin` with `keepLoginAs` when the agent is kept signed in to an account of the user's choosing, as the account rows do; the button says *Switched* for five seconds and the status line says new sessions use the account, one already open keeps its own until started again. *Only switch {agent}'s sign-in* (`SwitchOnly` above, `provider/switchonly`) is a ticked item there (Codex: with more than one usable account, as under Providers), and the row then says *Not connected · switching accounts only*. *Manage accounts…*, and a pick whose sign-in lapsed, open Providers › the agent. A Codex failing over (#1385) has it in place of the old *ChatGPT accounts* button. In the tray panel (whose Quick panel shortcut opens it from any app, shuizhuyu on X) it is the *account* line of the agent's opened row (`.ag-who`), drawn from the list kept from the last read (`panelAccounts`, `GET /api/providers?last=1`, no keychain read; a fresh read only when none is kept), so opening the panel reads no sign-in. The menu waits for one fresh `/api/providers` read and opens on what it says; *Manage accounts…* and a lapsed pick open the window's Providers (`window/main?view=providers`). The provider and login actions keep their answer as the last list (`keepProviders`), so a switch made anywhere is in the panel's next line at once (`TestKeptProvidersFollowActions`, `panel-switch-accounts.test.cjs`). Not on a WSL twin's row, not on a connected agent's. | [`app.js`](../../internal/gui/assets/app.js), [`logins.go`](../../internal/provider/logins.go) | | Used-up switch | When the account Codex or Claude Code is signed in to has used its allowance, the agent is signed in to the next account that is on and has room (#208). 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) | | 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). 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. A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing page says them as switched off (`memberJSON.providerOff`). The user's own groups keep their members. Three templates make a group in one click from the models the user has (`provider.Templates`, `AddTemplate`; the Routing page's cards before a first group and its Templates menu after, `magpie group template [kind] [name]`): `smart` sends a hard turn to the strongest model and an easy one or a compaction to a cheap one, asked by a classifier (the decision API when there is one, else the cheapest priced model that doesn't reason); `thrifty` starts on two cheap models of different providers and sends high reasoning to the strongest; `steady` fails over between the strongest model of up to three providers. A model is weighed by its maker's list price when known, else what its provider charges, else by its id's size words (`sizeOf`); one over `tooDear` (USD 100 a million output tokens) is never picked. A template that can't be made says what is missing (`Need`). It is saved under a name and id no group has (`freeGroupName`, shared with `CopyGroup`), never over one. A group is shared as text (`ShareGroup`, a group row's Copy to share): JSON marked `"magpie": "routing-group"` with a format `version` (`ShareVersion`), holding the group's members as it names them, patterns, routing, rules, classifier and settings. A group holds only `provider/model` ids, never a key, account or address, and the derived matches, found/hidden/off flags and the rules that hold by a folder (a path on the sharer's machine, `Rule.Folders`) stay behind; a pasted one is left out too. `ImportGroup` (the Routing page's Import, `POST /api/groups/import`) reads it with words or a code fence around it, refuses another text, a newer format or none (`ShareError`, said in the reader's language). A member whose provider the importer has is kept; else the same model (`AutoGroupOf`) under the first provider of theirs that serves it (`Instead`); else it is left out and named (`Missing`), with the rules that send to it, its place among the off and fast members, and a classifier gone takes the intent rules and auto effort with it. Nothing is added when no member is left; what is added gets a free name, never replacing a group. A group of patterns only that match nothing now (a plugin's models not listed) has no members: `/api/groups` says them, and an unmakeable template's, as `[]`, never `null`; the Routing page reads the response through `groupsFrom` and draws a group it still can't draw as one row saying so, so one bad group never hides the rest (#1585). | [`group.go`](../../internal/provider/group.go), [`grouptemplate.go`](../../internal/provider/grouptemplate.go), [`group_share.go`](../../internal/provider/group_share.go) | | Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it, each window with its whole-window estimate (`Holds`/`HoldsWhy`, `usage.WithWindowHolds`, which `quotaReport` reaches through the `ReckonHolds` hook since package provider can't import usage, #2333). A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). Each key of a remote-magpie provider also gets a card of its own, under `/~keys`, one section per key (#1547, `remoteKeyCards` in `remote_key_limits.go`): the gateway key's limit as that magpie holds it, read from `GET /v1/magpie/limit` asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus `GatewayKey` (what is left, calls, a cycle of days, used up); a key held to no limit shows `Unlimited`. It is kept for `remoteCardsFor` like the remote's cards and read again by the card's refresh (`?provider=/~keys&user=`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). A remote that holds the key to a budget, models or accounts answers its cards 403 `gateway_key_held` (#1981, `errKeyHeld`): the cards kept from before are dropped and only the key's own card shows. Its owner can let the key be told the cards of what it may use (#2216, `magpie gateway-key quotas on`); the remote then answers those, and 403 as before when that is none. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, `quotasOpened`, #1588) or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. A plugin's window may carry a prepaid wallet's `balance` in its `unit` and no share (`QuotaWindow.Balance`, #3950): the card and `magpie quota` show the figure (`BalanceText`), and routing reads it through `Allowance.Left`. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`quota_asked.go`](../../internal/provider/quota_asked.go) | | 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/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index a3211c804..019eb127b 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -5951,19 +5951,18 @@ function routingPage(part) { const sortBtn = el("button", "text rt-wsort", t("Sort by weight")); sortBtn.type = "button"; sortBtn.title = t("Heaviest first. When a model fails, the next one in this order takes over"); - const byWeight = () => d.members.slice(0, named()).map((id, i) => [id, i]).sort(([a, i], [b, j]) => Math.max(d.weights[b] || 0, 1) - Math.max(d.weights[a] || 0, 1) || i - j).map(([id]) => id); - sortBtn.onclick = () => { d.members.splice(0, named(), ...byWeight()); draw(); }; - // moveMember puts the member at `from` at `to` among those named — a - // pattern's follow them, in the catalog's order — and keeps the - // keyboard on its handle when it was there - const named = () => d.members.filter((x) => !d.matched.includes(x)).length; + const byWeight = () => d.members.map((id, i) => [id, i]).sort(([a, i], [b, j]) => Math.max(d.weights[b] || 0, 1) - Math.max(d.weights[a] || 0, 1) || i - j).map(([id]) => id); + sortBtn.onclick = () => { d.members = byWeight(); draw(); }; + // moveMember puts the member at `from` at `to`, a pattern's as well as + // one named (usrname1833 on Discord: provider.Group.Placed), and keeps + // the keyboard on its handle when it was there const moveMember = (from, to, keep) => { - if (to < 0 || to >= named() || to === from) return; + if (to < 0 || to >= d.members.length || to === from) return; d.members.splice(to, 0, d.members.splice(from, 1)[0]); draw(); if (keep) list.querySelector(`.rt-mhandle[data-at="${to}"]`)?.focus({ preventScroll: true }); }; - // memberHandle is a named member's place in the order, which is also + // memberHandle is a member's place in the order, which is also // its handle (PAMI on Discord: only Up, one step a click): drag it to // move the model, or Alt+↑/↓ from the keyboard; Up and Down stay // beside it. The grip that says so shows only on hover, as on the @@ -6053,7 +6052,7 @@ function routingPage(part) { sw.append(el("i")); sw.onclick = () => { d.off = off ? d.off.filter((x) => x !== id) : [...d.off, id]; draw(); }; if (off) row.classList.add("muted"); - row.append(sw, matched ? el("span", "i", String(i + 1)) : memberHandle(id, i, row), memberIcon(id), n, el("span", "grow")); + row.append(sw, memberHandle(id, i, row), memberIcon(id), n, el("span", "grow")); // what the model is, in the same chips the Gateway page's list says it // in (modelInfo): its reasoning levels, whether it sees images and the // window it holds. A group mixing members that see images with ones @@ -6150,6 +6149,8 @@ function routingPage(part) { if (d.routing === "weight") row.append(memberWeight(id, off)); if (s) row.title = s.members.map((x) => memberLabel(s, x)).join(s.routing === "order" ? " → " : " · "); if (!m && !s) { row.classList.add("off"); row.title = info?.providerOff ? offWords(info) : t("No provider serves {id} now; it is skipped", { id }); } + if (i) { const up = el("button", "text", t("Up")); up.onclick = () => moveMember(i, i - 1); row.append(up); } + if (i < d.members.length - 1) { const down = el("button", "text", t("Down")); down.onclick = () => moveMember(i, i + 1); row.append(down); } if (matched) { // a pattern's: it follows the catalog, so it is switched off // rather than taken out — the pattern would find it again @@ -6157,8 +6158,6 @@ function routingPage(part) { list.append(row); return; } - if (i) { const up = el("button", "text", t("Up")); up.onclick = () => moveMember(i, i - 1); row.append(up); } - if (i < named() - 1) { const down = el("button", "text", t("Down")); down.onclick = () => moveMember(i, i + 1); row.append(down); } const rm = el("button", "text", t("Remove")); rm.onclick = () => { d.members.splice(i, 1); rematch(); draw(); drawRules(); }; row.append(rm); @@ -6194,7 +6193,7 @@ function routingPage(part) { openPicker({ id: "", name: "", fields: [] }, { key: "member", label: "model", value: "", options, multi: true, picked: (id) => !!holding(id), onPick: (id) => { if (!id) return; const m = holding(id); - if (!m) d.members.splice(named(), 0, id); // after those named, before a pattern's + if (!m) d.members.splice(d.members.findLastIndex((x) => !d.matched.includes(x)) + 1, 0, id); // after the last named else if (d.matched.includes(m)) return status(t("In the group by a pattern: switch it off to send it nothing"), "warn"); else { d.members.splice(d.members.indexOf(m), 1); rematch(); } draw(); drawRules(); @@ -6209,11 +6208,14 @@ function routingPage(part) { ed.append(el("label", "", t("Models")), mw); // patterns: models found by their ids, now and as providers list new - // ones (#766); what they match follows the models named above + // ones (#766): after the models named, in the catalog's order, until + // the user puts them in another; then each keeps its place, one gone + // drops out and one new goes last function rematch() { - const named = d.members.filter((x) => !d.matched.includes(x)); + const named = d.members.filter((x) => !d.matched.includes(x)), was = [...named, ...d.matched]; + const placed = d.members.some((x, i) => x !== was[i]); d.matched = matchedBy(d.match, named); - d.members = [...named, ...d.matched]; + d.members = placed ? [...d.members.filter((x) => named.includes(x) || d.matched.includes(x)), ...d.matched.filter((x) => !d.members.includes(x))] : [...named, ...d.matched]; // a rule keeps the models still here; it goes with its last d.rules = d.rules.filter((r) => { setUses(r, rUses(r).filter((x) => d.members.includes(x))); return !!r.use; }); d.fast = d.fast.filter((x) => d.members.includes(x)); @@ -7075,7 +7077,7 @@ function routingPage(part) { if (own && !d.levels.length) return status(t("Pick a level to offer, or leave them to its models"), "warn"); saveBtn.classList.add("busy"); // refused, Add can be pressed again (busy, it takes no clicks) - groupAction("save", { id: idOf(), from: g?.id, name: d.name.trim() || idOf(), members: namedOf(d), match: d.match, routing: d.routing, pick: d.pick || "", affinity: d.affinity, sink: !!d.sink && sinkable(d.routing), firstToken: d.firstToken || 0, patience: d.patience || 0, rules: d.rules, effort: d.effort, classifier: d.rules.some((r) => r.intent) || d.effort === "auto" ? d.classifier : "", context: d.context || 0, levels: own ? d.levels : [], family: g?.family || "", fast: d.fast.filter((x) => d.members.includes(x)), off: d.off.filter((x) => d.members.includes(x)), weights: Object.fromEntries(Object.entries(d.weights).filter(([x, n]) => d.members.includes(x) && n > 1)), unlists: !!d.unlists }, t(g ? "{name} saved" : "{name} added", { name: d.name.trim() || idOf() })) + groupAction("save", { id: idOf(), from: g?.id, name: d.name.trim() || idOf(), members: namedOf(d), placed: d.members, match: d.match, routing: d.routing, pick: d.pick || "", affinity: d.affinity, sink: !!d.sink && sinkable(d.routing), firstToken: d.firstToken || 0, patience: d.patience || 0, rules: d.rules, effort: d.effort, classifier: d.rules.some((r) => r.intent) || d.effort === "auto" ? d.classifier : "", context: d.context || 0, levels: own ? d.levels : [], family: g?.family || "", fast: d.fast.filter((x) => d.members.includes(x)), off: d.off.filter((x) => d.members.includes(x)), weights: Object.fromEntries(Object.entries(d.weights).filter(([x, n]) => d.members.includes(x) && n > 1)), unlists: !!d.unlists }, t(g ? "{name} saved" : "{name} added", { name: d.name.trim() || idOf() })) .then(() => saveBtn.classList.remove("busy")); }; // what goes wrong is said where it is seen, never a click that does nothing diff --git a/internal/gui/tests/group-member-drag.test.cjs b/internal/gui/tests/group-member-drag.test.cjs index 14dcd3838..12d12df78 100644 --- a/internal/gui/tests/group-member-drag.test.cjs +++ b/internal/gui/tests/group-member-drag.test.cjs @@ -3,10 +3,10 @@ // one step a click). In the editor a named member's number is its handle, // with a grip beside it drawn only while the row is under the pointer; // dragging it moves the model, Alt+↑/↓ moves it from the keyboard, which -// stays on it, and Up and Down stay beside it. A pattern's members follow -// the named ones and have no handle. Saved, the members go in the new -// order. No click or drag moves the page. In English and Chinese, Chromium -// and WebKit. +// stays on it, and Up and Down stay beside it. A pattern's members are +// moved the same way (usrname1833 on Discord), among the named ones too. +// Saved, the order of them all goes as placed. No click +// or drag moves the page. In English and Chinese, Chromium and WebKit. const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); const path = require("node:path"); @@ -80,21 +80,21 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const row = (name) => ed.locator(".fbrow", { has: page.locator(".n > span:first-child", { hasText: new RegExp(`^${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`) }) }); const handle = (name) => row(name).locator(".rt-mhandle"); - // every named member has a handle with its number; the pattern's none - assert.deepEqual(await ed.locator(".fbrow .rt-mhandle").allTextContents(), ["1", "2", "3"]); - assert.equal(await handle("free:free").count(), 0, "a pattern's member has a handle"); + // every member has a handle with its number, a pattern's too + assert.deepEqual(await ed.locator(".fbrow .rt-mhandle").allTextContents(), ["1", "2", "3", "4"]); assert.equal(await handle("two").getAttribute("aria-label"), w.move); - // Up on all but the first named, Down on all but the last named + // Up on all but the first, Down on all but the last const btns = async (name) => row(name).locator("button.text").allTextContents(); assert(!(await btns("one")).includes(w.up) && (await btns("one")).includes(w.down)); - assert((await btns("three")).includes(w.up) && !(await btns("three")).includes(w.down)); + assert((await btns("three")).includes(w.up) && (await btns("three")).includes(w.down)); + assert((await btns("free:free")).includes(w.up) && !(await btns("free:free")).includes(w.down)); // the grip shows on the row under the pointer only await page.mouse.move(1, 1); const grip = (name) => handle(name).evaluate((h) => getComputedStyle(h, "::before").opacity); assert.equal(await grip("two"), "0"); await row("two").locator(".n").hover(); - await page.waitForFunction(() => [...document.querySelectorAll(".rt-mhandle")].map((h) => getComputedStyle(h, "::before").opacity).join() === "0,1,0"); + await page.waitForFunction(() => [...document.querySelectorAll(".rt-mhandle")].map((h) => getComputedStyle(h, "::before").opacity).join() === "0,1,0,0"); await ed.evaluate((x) => x.scrollIntoView({ block: "center" })); // by the test, as the reader would await page.waitForTimeout(200); @@ -115,14 +115,21 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.keyboard.press("Alt+ArrowDown"); assert.deepEqual(await order(), ["three", "two", "one", "free:free"]); assert.equal(await page.evaluate(() => document.activeElement?.closest(".fbrow")?.querySelector(".n > span")?.textContent), "one", "the keyboard left the moved model"); - // it never goes past the pattern's + // past a pattern's too await page.keyboard.press("Alt+ArrowDown"); - assert.deepEqual(await order(), ["three", "two", "one", "free:free"]); + assert.deepEqual(await order(), ["three", "two", "free:free", "one"]); // Down and Up still move it a step await row("three").locator("button.text", { hasText: w.down }).click(); - assert.deepEqual(await order(), ["two", "three", "one", "free:free"]); + assert.deepEqual(await order(), ["two", "three", "free:free", "one"]); await row("one").locator("button.text", { hasText: w.up }).click(); - assert.deepEqual(await order(), ["two", "one", "three", "free:free"]); + assert.deepEqual(await order(), ["two", "three", "one", "free:free"]); + // a pattern's dragged to the top + const hf = await handle("free:free").boundingBox(), first = await row("two").boundingBox(); + await page.mouse.move(hf.x + hf.width / 2, hf.y + hf.height / 2); + await page.mouse.down(); + for (let i = 1; i <= 8; i++) await page.mouse.move(hf.x + hf.width / 2, hf.y + hf.height / 2 - ((hf.y - first.y + 6) * i) / 8); + await page.mouse.up(); + assert.deepEqual(await order(), ["free:free", "two", "three", "one"], "a pattern's was dragged"); assert.equal(await at(), before, "a click or drag moved the page"); const b = ed.locator("button.primary", { hasText: w.save }); @@ -135,7 +142,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.mouse.click(bb.x + bb.width / 2, bb.y + bb.height / 2); await page.waitForFunction(() => !document.querySelector(".rt-gedit")); const sent = posts.find((p) => p.path === "/api/groups/save"); - assert.deepEqual(sent.body.members.slice(0, 3), ["a/two", "a/one", "b/three"]); + assert.deepEqual(sent.body.members, ["a/two", "b/three", "a/one"]); + assert.deepEqual(sent.body.placed, ["c/free:free", "a/two", "b/three", "a/one"], "the order, a pattern's among them"); const missing = await page.evaluate(() => ["Down", "Move {name}", "Drag to reorder · Alt+↑/↓ to move"].filter((k) => !I18N.zh[k] || !I18N.ja[k] || !I18N.de[k])); assert.deepEqual(missing, [], "every string has its Chinese, Japanese and German"); diff --git a/internal/gui/tests/group-patterns.test.cjs b/internal/gui/tests/group-patterns.test.cjs index 6583cd756..9919091b5 100644 --- a/internal/gui/tests/group-patterns.test.cjs +++ b/internal/gui/tests/group-patterns.test.cjs @@ -4,8 +4,8 @@ // In the editor the matched models follow those named, marked "by pattern", // with an off switch and no Remove; a pattern is added and removed in its // own box, its models coming and going with it. Saved, the group sends the -// models it names and its patterns, never what they matched. In English and -// Chinese. +// models it names and its patterns, never what they matched, and the +// order of them all (placed). In English and Chinese. const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); const path = require("node:path"); @@ -125,6 +125,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.waitForFunction(() => !document.querySelector(".rt-gedit")); const sent = posts.find((p) => p.path === "/api/groups/save"); assert.deepEqual(sent.body.members, ["an/claude-opus-5-5"], "only the models named are sent"); + assert.deepEqual(sent.body.placed, ["an/claude-opus-5-5", "zen/d-free"], "and the order of them all"); assert.deepEqual(sent.body.match, ["nope/*", "*-free"]); assert.deepEqual(sent.body.off, ["zen/d-free"], "a matched model may be off"); diff --git a/internal/provider/fold.go b/internal/provider/fold.go index 1b5347684..d21a5b68f 100644 --- a/internal/provider/fold.go +++ b/internal/provider/fold.go @@ -342,6 +342,7 @@ func foldWhere(candidates func([]Provider) [][]int) (int, error) { g.Rules[k].MapUses(ref) } g.Fast = compact(mapEach(g.Fast, ref)) + g.Placed = compact(mapEach(g.Placed, 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 8245ebe90..a51df6131 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -177,7 +177,15 @@ type Group struct { Match []string `json:"match,omitempty"` // Matched are the members the patterns match now, as Members has them // after its own. Derived each time the group is read, never stored. - Matched []string `json:"matched,omitempty"` + Matched []string `json:"matched,omitempty"` + // Placed is the order the user put the members in, those the + // patterns match among those it names (usrname1833 on Discord), as + // Members spells them. Read, the members follow it: a model matched + // since comes after them in the catalog's order, and one no longer + // matched drops out (placedIn). Empty when it is the order the group + // has unasked, its own members first, then the matched. Saved, it + // places the matched; the named go in Members' order (placedOver). + Placed []string `json:"placed,omitempty"` Routing string `json:"routing,omitempty"` // as Provider.Routing, over all the members' keys and accounts; or Manual Affinity string `json:"affinity,omitempty"` // as Provider.Affinity // Sink is Provider.Sink over the group's members' accounts and keys @@ -399,7 +407,7 @@ func cloneGroups(gs []Group) []Group { } out := make([]Group, len(gs)) for i, g := range gs { - g.Members, g.Match, g.Matched = slices.Clone(g.Members), slices.Clone(g.Match), slices.Clone(g.Matched) + 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.Weights = maps.Clone(g.Weights) if g.Rules != nil { @@ -514,6 +522,7 @@ func (g Group) own() Group { g.Members = slices.Clone(g.Members) g.Match = slices.Clone(g.Match) g.Matched = slices.Clone(g.Matched) + g.Placed = slices.Clone(g.Placed) g.Off = slices.Clone(g.Off) g.Levels = slices.Clone(g.Levels) g.Fast = slices.Clone(g.Fast) @@ -1366,6 +1375,23 @@ func SaveGroup(g Group) error { } own := cleanList(g.Members[:named]) g.Members = append(slices.Clone(own), slices.DeleteFunc(cleanList(g.Members[named:]), func(m string) bool { return slices.Contains(own, m) })...) + // the order the user put them in, a pattern's members among them: as + // the caller sends it (the Routing page's editor), or as it was. The + // models named go in the order the caller names them, so one added + // to a group as read (models+=, the TUI) goes after those named + before := g.Placed + if len(before) == 0 { + if i := slices.IndexFunc(f.Groups, func(x Group) bool { return x.ID == g.ID }); i >= 0 { + before = f.Groups[i].Placed + } + } + key := func(m string) string { + id, _ := memberFastIn(entries, strings.TrimSpace(m)) + return cleanMember(entries, id) + } + if g.Placed = placedOver(g.Members, mapEach(before, key), mapEach(members, key)); g.Placed != nil { + own = slices.DeleteFunc(slices.Clone(g.Placed), func(m string) bool { return !slices.Contains(own, m) }) + } var off []string for _, m := range cleanList(g.Off) { if m = cleanMember(entries, m); slices.Contains(g.Members, m) && !slices.Contains(off, m) { @@ -1780,6 +1806,11 @@ func RenameGroup(from, to string) error { f.Groups[i].Members[j] = now } } + for j, m := range f.Groups[i].Placed { + if m == old { + f.Groups[i].Placed[j] = now + } + } for j := range f.Groups[i].Rules { f.Groups[i].Rules[j].MapUses(func(u string) string { if u == old { diff --git a/internal/provider/groupfast.go b/internal/provider/groupfast.go index d50542137..fb0ab67fc 100644 --- a/internal/provider/groupfast.go +++ b/internal/provider/groupfast.go @@ -250,6 +250,11 @@ func (g *Group) RenameMember(from, to string) { g.Fast[i] = to } } + for i, p := range g.Placed { + if p == from { + g.Placed[i] = to + } + } for i, o := range g.Off { if o == from { g.Off[i] = to diff --git a/internal/provider/groupmatch.go b/internal/provider/groupmatch.go index dfe00dc29..8a1234c21 100644 --- a/internal/provider/groupmatch.go +++ b/internal/provider/groupmatch.go @@ -12,8 +12,9 @@ package provider // again. Every reader — the gateway's routing, /v1/models, rules, the // Routing view, the TUI and the CLI — gets the group from there, so all of // them see the same members: those the user named, in their order, then -// those the patterns match, in the catalog's order. A model named and -// matched both keeps the place it was named at. +// those the patterns match, in the catalog's order, or in the order the +// user put them in (Group.Placed). A model named and matched both keeps +// the place it was named at. import ( "fmt" @@ -115,16 +116,92 @@ func matchesIn(entries []Entry, g Group) []string { } // withMatches is a stored group as it is read: the members its patterns -// match now after those it names (Matched says which they are). +// match now after those it names (Matched says which they are), or in +// the order the user put them in (Placed). func withMatches(entries []Entry, g Group) Group { if len(g.Match) == 0 { return g } g.Matched = matchesIn(entries, g) - g.Members = append(slices.Clone(g.Members), g.Matched...) + g.Members = placedIn(append(slices.Clone(g.Members), g.Matched...), g.Placed) return g } +// placedIn are members in the order placed has them: those it names +// first, as it has them, then the rest in their own order — a model a +// pattern matches since it was placed, at the end. One placed that isn't +// a member now is left out. +func placedIn(members, placed []string) []string { + if len(placed) == 0 { + return members + } + in := make(map[string]bool, len(members)) + for _, m := range members { + in[m] = true + } + out := make([]string, 0, len(members)) + for _, p := range placed { + if in[p] { + out = append(out, p) + delete(in, p) + } + } + for _, m := range members { + if in[m] { + out = append(out, m) + delete(in, m) + } + } + return out +} + +// placedOver is the Placed a group is saved with: its members (named +// first, then the matched) in the order placed before (the caller's, or +// the one stored), with those the caller names (given) put in the places +// those have, in the caller's order. So the named are reordered as the +// caller says and the pattern's stay where they were placed; a model +// named since goes after the last one named, one matched since last. +// nil when that is the members' own order. +func placedOver(members, before, given []string) []string { + if len(before) == 0 { + return nil + } + sent := map[string]bool{} + var order []string + for _, m := range given { + if !sent[m] && slices.Contains(members, m) { + sent[m] = true + order = append(order, m) + } + } + var seq []string + for _, m := range before { + if slices.Contains(members, m) && !slices.Contains(seq, m) { + seq = append(seq, m) + } + } + for _, m := range order { + if !slices.Contains(seq, m) { + at := len(seq) + for at > 0 && !sent[seq[at-1]] { + at-- + } + seq = slices.Insert(seq, at, m) + } + } + seq = placedIn(members, seq) + for i, j := 0, 0; i < len(seq); i++ { + if sent[seq[i]] { + seq[i] = order[j] + j++ + } + } + if slices.Equal(seq, members) { + return nil + } + return seq +} + // ownMembers are the members a group names itself and its patterns, from a // group as it was read: the members its patterns matched (Matched) are // left out, so that saving a group never writes today's matches into it, diff --git a/internal/provider/groupmatch_test.go b/internal/provider/groupmatch_test.go index 9a8d3ee60..665150b88 100644 --- a/internal/provider/groupmatch_test.go +++ b/internal/provider/groupmatch_test.go @@ -93,6 +93,93 @@ func TestGroupPatterns(t *testing.T) { } } +// The members a pattern matches are put in order by hand as a named one +// is (usrname1833 on Discord): the group is read, and routed, in the order +// the user put them in, a model matched since joins at the end in the +// catalog's order, one no longer matched drops out, and the order is kept +// through a save that sends the named members only, and a provider's +// rename. +func TestGroupPatternMembersKeepTheirPlace(t *testing.T) { + patternHome(t) + or := func(models ...string) { + t.Helper() + if err := Save(Provider{ID: "or", Name: "OR", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: models}); err != nil { + t.Fatal(err) + } + } + or("a:free", "b", "c:free") + if err := Save(Provider{ID: "zen", Name: "Zen", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"y"}}); err != nil { + t.Fatal(err) + } + if err := SaveGroup(Group{Name: "Free", Members: []string{"zen/y", "or/*:free"}}); err != nil { + t.Fatal(err) + } + if got := routedIDs(t, "group/free"); !slices.Equal(got, []string{"zen/y", "or/a:free", "or/c:free"}) { + t.Fatalf("unplaced: %v", got) + } + // dragged in the Routing page's editor, which sends the order: + // a matched one first, the named one between + g, _, _ := FindGroup("group/free") + g.Placed = []string{"or/c:free", "zen/y", "or/a:free"} + if err := SaveGroup(g); err != nil { + t.Fatal(err) + } + want := []string{"or/c:free", "zen/y", "or/a:free"} + if g, _, _ := FindGroup("group/free"); !slices.Equal(g.Members, want) || !slices.Equal(g.Matched, []string{"or/a:free", "or/c:free"}) { + t.Fatalf("read: %v matched %v", g.Members, g.Matched) + } + if got := routedIDs(t, "group/free"); !slices.Equal(got, want) { + t.Fatalf("routed: %v", got) + } + if s, _ := StoredGroups(); !slices.Equal(s[0].Members, []string{"zen/y"}) { + t.Fatalf("stored members: %v", s[0].Members) + } + // a save of the named ones only (the card's routing menu) keeps it + if err := SaveGroup(Group{ID: "free", Name: "Free", Members: []string{"zen/y"}, Match: []string{"or/*:free"}, Routing: Ordered}); err != nil { + t.Fatal(err) + } + if got := routedIDs(t, "group/free"); !slices.Equal(got, want) { + t.Fatalf("after a named-only save: %v", got) + } + // the vendor drops one and adds another: gone, and joined at the end + or("b", "c:free", "d:free") + if got := routedIDs(t, "group/free"); !slices.Equal(got, []string{"or/c:free", "zen/y", "or/d:free"}) { + t.Fatalf("after the catalog changed: %v", got) + } + // the provider renamed: its models keep their places + if err := Rename("or", "op"); err != nil { + t.Fatal(err) + } + if err := SaveGroup(Group{ID: "free", Name: "Free", Members: []string{"zen/y"}, Match: []string{"op/*:free"}}); err != nil { + t.Fatal(err) + } + if got := routedIDs(t, "group/free"); !slices.Equal(got, []string{"op/c:free", "zen/y", "op/d:free"}) { + t.Fatalf("after a rename: %v", got) + } + // a model added to the group as read (models+=, the TUI) goes after + // those named, the pattern's staying where they were + if err := Save(Provider{ID: "zen", Name: "Zen", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"y", "z"}}); err != nil { + t.Fatal(err) + } + g, _, _ = FindGroup("group/free") + g.Members = append(g.Members, "zen/z") + if err := SaveGroup(g); err != nil { + t.Fatal(err) + } + if got := routedIDs(t, "group/free"); !slices.Equal(got, []string{"op/c:free", "zen/y", "zen/z", "op/d:free"}) { + t.Fatalf("after an add: %v", got) + } + // put back in the order it has unasked, nothing is kept + g, _, _ = FindGroup("group/free") + g.Placed = []string{"zen/y", "zen/z", "op/c:free", "op/d:free"} + if err := SaveGroup(g); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(Path()); strings.Contains(string(b), `"placed"`) { + t.Fatalf("placed kept: %s", b) + } +} + // A matched member may be switched off, picked, or ruled, like a named one; // and named at an effort of its own it is not matched again. func TestGroupPatternMembersOffAndRules(t *testing.T) { diff --git a/internal/provider/rename.go b/internal/provider/rename.go index f1a27c465..79d5fbe62 100644 --- a/internal/provider/rename.go +++ b/internal/provider/rename.go @@ -108,6 +108,9 @@ func Rename(from, to string) error { for k, m := range g.Fast { g.Fast[k] = renamedRef(m, from, to) } + for k, m := range g.Placed { + g.Placed[k] = renamedRef(m, from, to) + } for k, m := range g.Off { g.Off[k] = renamedRef(m, from, to) }