diff --git a/docs/reference.md b/docs/reference.md index 96240647c..e04a3f3c0 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -2049,7 +2049,7 @@ provider or group still set to one of them is tried in its listed order. Your own routing groups are the built-in plugin `groups` (Routing groups in Plugins › Built-in), which stays on while you have one. The groups magpie finds for a model two providers serve don't need it. Turned off, the gateway -doesn't list or serve a group of your own, and the Routing page has no New +doesn't list or serve a group of your own, and the Routing groups page has no New group button; `magpie groups` still lists them. **Make first** sets the accounts' order. How much that order counts diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 20c874278..f6aa58d4a 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -34,7 +34,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | A found group's two ids | A group magpie found is listed (`/v1/models`, the catalog, the lists written into agents, the pickers, the CLI and TUI) as `auto/`: the model's id as a vendor spells it, dots kept and with no vendor prefix (`auto/claude-opus-5.5`; `provider.Group.Ref`, `spelledIn`), so a client that looks the part after the slash up on models.dev finds it (ZeroClover on X). The spelling is the one models.dev gives the model most (`catalog.Spelling`, its `normal` index: `glm-5.3-flash` whether the members serve `glm-5-3-flash`, Ark's dated id or `glm-5.3-flash`), so it no longer follows the order the providers were added in; for a model models.dev doesn't know, the first member's spelling it lists, else the first member's. The group's name comes from the same choice (`autoGroups`): the name models.dev gives that spelling (`catalog.NameOf`), else a vendor's own name for it, else the spelling itself; they were picked apart, a name of `glm-5-3-flash` beside `auto/glm-5.3-flash` (XYenon on Discord, `TestFoundGroupIDAndNameAreOneSpelling`). A found group the user changed keeps the name they saved. Every spelling it was listed by before is still the group (`CanonicalRef`), and `PublicRef` takes one to the spelling now. Its old id `group/auto-` is served forever. Inside magpie the group keeps that one id: `validateModel` takes `auto/` (with `:level` or `[1m]`) back to it with `provider.CanonicalRef` before key limits, routing, affinity and the usage log see the request, and the request body is rewritten to it, so both ids count as one group. A gateway key naming either id, `group/*` or `auto/*` passes for both (`allows` in `key_models.go`). `SaveGroup` stores a member, rule or classifier picked as `auto/` by the old id. An agent field magpie set to `group/auto-`, or to an `auto/` spelt otherwise than the group is listed now, moves to `auto/` on the next `SyncCatalog` (`agent.renameFoundGroups`, `TestFoundGroupMovedOffAnOldSpelling`), but only while its value is still what applied.json says magpie wrote; a value the user set or changed stays, and is still served. A pick of the group by its old id written now (`Agent.Apply`) is written as `auto/`. An agent's hidden, picked and ordered models saved by the old id hold for the new one (`PublicRef` in `visible.go`), and a bare model id still reaches its found group (`bareTarget`). Claude Code is given a dotted Claude version dashed, so it may send `auto/claude-sonnet-4-5`: that is the same group, and `Reseat` still moves an agent off it once the group is gone (`samePick`). `auto` is no provider id: `Save` and `Rename` refuse it for a new provider, and a plugin's `auto` is `auto-plugin` (`PluginID`). A provider of the user's saved as `auto` before keeps its models: while it exists, `auto/` is its model and found groups list as `group/auto-` (`autoRefsOn`). Hand-made groups stay `group/`. | [`internal/provider/autoref.go`](../../internal/provider/autoref.go), [`key_models.go`](../../internal/gateway/key_models.go), [`internal/agent/autoref.go`](../../internal/agent/autoref.go) | | A model's own id at a provider | A model the user lists by an id of theirs at a provider (a signed-in account's and a plugin's too; settings' `ModelIDs`, `magpie model id `, the editor's "Listed as"; [Providers and accounts](providers-accounts.md#runtime-path)) is that id everywhere the gateway names it: `/v1/models` and the lists written into agents (`Available`), `Resolve`, the routing groups and the group magpie finds for it (`auto/`, with every other provider serving that id), a gateway key's models, `X-Magpie-Model` and the usage log's `model`. Only the upstream request differs: every place that sends a wire name reads `settings.Wires()`, which is `ModelWires` with each `ModelIDs` entry turned round (`"/"` → the vendor's own id, wrapped by a `/*` wire), so the body, a Vertex path and the usage log's endpoint carry the vendor's id; an explicit `ModelWires` entry for that id wins. The vendor's reply names its own id, which the usage log, recent calls and the Routing page keep as `served`; the agent gets the id it asked for back in the reply, in every protocol, streamed or whole (`memberWriter` in [`member.go`](../../internal/gateway/member.go), `replyNamingOf`: the reply's `model`, Responses' `response.model`, Anthropic's `message.model`, Gemini's `modelVersion`; issennknight on Discord, whose agent warned that `deepseek-v4.1-flash` came back as `deepseek-v4.1-flash-1017`). The same holds for a group or a `provider/model` id the vendor knows by another name. A reply whose vendor sent the wire name as asked keeps the vendor's name (a dated `-20261017` included). Settings' `replyModel` (Settings › Models › Replies › Model name in replies) picks for every request: `""` the model asked for, `member` the group's member, `vendor` the vendor's own name, as before the asked-for name, each for every agent, Claude Code, Claude Desktop and Codex included (ZoeCats on Discord: in v0.1.2760 `member` still gave those three the model asked for; `TestPluginReplyNamesMember` holds it on a plugin too). A file from before it with `memberModel` on reads as `member`, and `memberModel` is written beside `replyModel` for an older magpie (`normal` in settings.go; `Merge` in settingsapi takes an older page's `memberModel` only when its switch moved). A request's `X-Magpie-Response-Model` (`asked`, `member` or `vendor`) overrides the setting for that request, for every agent (`TestReplyNamesAskedModel`, `TestGeminiReplyNamesAskedModel`, `TestReplyNamesMember`, `TestReplyModelFoldsMemberModel`, `TestReplyModelSaves`). A request still naming `provider/` (an agent's file magpie didn't rewrite) resolves and goes out as it is. A key held to either id passes for both (`modelAllowed` checks the ref, then `OwnModelID`, then `ListedModelID`); a group member passes the same way. An id is given to a model of the provider's chat list or its picks; the image, video and embeddings routes send no wire name, so they are not served under one (`TestLocalModelIDOnEveryRoute`). At an account or a plugin the account's own say of the model is read by the vendor's id: a plugin's API and fetch, Claude Code's `--model`, Antigravity's variant, and which accounts list it and at what levels (`TestLocalModelIDAtAPlugin`, `TestLocalModelIDAtAClaudeAccount`, `TestLocalModelIDAtAnAntigravityAccount`). | [`internal/provider/localid.go`](../../internal/provider/localid.go), [`internal/settings/settings.go`](../../internal/settings/settings.go), [`key_models.go`](../../internal/gateway/key_models.go) | | Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). A fallback the user unchecked in its own provider's model list is skipped, as a group's member is (`provider.ResolveRoute`, #3911; `fallback_unpicked_test.go`), and so is it where fallbacks are read for careful accounts, native compaction, redaction and Codex's own turns. A fallback can be a routing group (`group/`, 01huadalang on Discord): `planPaused` hands its members to `planLevel` as a request to the group would (`planFallbackGroup`), in the group's own routing and sink, its pause rules applied in `serve`, and its trace rows marked `Fallback` with the group in `Via`. Its turn rules (`ruleFor`, which may ask a classifier) are not applied: the plan is made before the primary is tried, and a classifier call on every request the primary answers costs too much. Each provider/model is tried once a round: a member that is the primary, an earlier fallback or another fallback group's is left out where it came second, so a group holding this provider is no loop (groups have no fallbacks of their own, and a member's are not followed). A group that is gone is passed over. Every place that reads fallbacks (careful accounts, native compaction, redaction, Codex's own turns, Claude's review) reads a group's members through `provider.FallbackModels`. `fallback_group_test.go`. `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576); one left on the default (Smart) in a group that pools (Smart, In turn, Least used, Use before expiry, Free first, Speed first, a plugin's) takes the outer group's, as a provider left on the default does (`provider.Group.Within`, set on `Member.Via`, so the trace's `Subs` and the Routing page read the routing that applies, #3847). In a group In order, By weight or Manual it stays Smart. `TestFreeFirstReachesAGroupInItLeftOnTheDefault`. So does a member whose provider routes other than Smart (`ownRouting`): weighed as one by its first not resting (`firstAwake`), tried whole in its own order; `leastHeld` leaves such a group's order alone too. A provider on Smart, or routed as the group is, is pooled with the group's other keys and accounts. `group_own_routing_test.go`. A member's own fallbacks are not the group's. | [`fallback.go`](../../internal/gateway/fallback.go) | -| Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace`, `weight`, `free` (free first), `fast` (speed first), `drain` (until used up) or, a group's only, `cheap` (cheapest first) or `expiring` (free quota by expiry). `weighRouted` reads each candidate into a `routes.Seat` and asks the strategy serving its routing (`routes.Find`, the router strategy point of [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)) for the order: Smart is `routes.Smart`, the core's; the others are `routes.Builtin`, registered by the built-in plugin `rotation`. With it off a routing no strategy serves is tried in its listed order, and `routingOf` treats it as `order` wherever the core asks about a routing (a turn's mark, `goesRound`, `sinks`, a rotate group's sessions, a group's heads). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. Among accounts a plugin reads as prepaid wallets (a window's `balance`, #3950), Smart, `usage` and `pace` put the one with more left first where they would otherwise tie, only within one provider and unit (`routes.Seat.Left`/`LeftIn`, see [provider plugins](provider-plugins.md#a-wallets-balance)): each kind is ordered in the places its own seats take, so a group weighing several providers' accounts as one pool orders each provider's wallets too (#4095, `TestGroupWalletsGoByWhatTheyHaveLeft`). `free` weighs by what a model costs there and nothing else: only a strategy with `routes.Strategy.ByFree` set (`routes.FreeFirst` is the one) has `weighRouted` fill `routes.Seat.Free`, from `provider.FreeModel` — the user's word that the whole provider costs them nothing (`Provider.CountFree`: the editor's Free for me, `magpie provider set free=yes`; jiabubu on Discord, ModelScope's free daily quota), else the vendor's own `catalog.Model.Free` word, else a list price of $0 on every count — so a pool routed any other way never reads a model list for it, and one routed `free` spends the members whose model costs nothing before those that spend the allowance or credits, each tier in its listed order (nothing free is left behind a paid one, and a pool with no free model behaves as `order`). A group routed `free` weighs its members whole, each over its own accounts or keys as its provider routes them. Whatever a group's routing, the Routing page tags a member `provider.FreeModel` counts free "free", on the group's card and beside its provider in the editor (`groupsState`'s `memberInfo[].free`, jiabubu on Discord, `TestGroupMemberSaysFree`, `group-member-free.test.cjs`). `fast` weighs by speed lately and nothing else: only a strategy with `routes.Strategy.BySpeed` set (`routes.Fastest`) has `weighRouted` fill `routes.Seat.TTFT` and `TPS`, from `speedOf` ([`speed.go`](../../internal/gateway/speed.go)): per `restID` (account or key, and model), a decayed average (half-life 20m) of a streamed answer's ms to its first content and of its output tokens a second as `usage.DecodeOf` counts them, written once as an answer ends (`noteTrySpeed`, beside `servedCandidate`) and read with one map lookup per candidate, never from the usage history; past an hour since its last answer a seat counts as not measured, the records are capped at 4096, and a restart forgets them. `routes.Fastest` ranks the awake by their first token plus 200 tokens at their pace (a seat with no pace at the measured seats' middle pace), keeps seats within a tenth of their band's fastest in listed order, and of a pool's requests with seats both measured and not, gives every fifth to one not measured (round the unmeasured, `probes`, so one is never starved); resting seats go after the awake, used-up ones (`UsedShare`) after those, and rests and failover are as for any routing. The trace's rows carry `lateTtft`/`lateTps` for the Routing page's story ("answered fastest lately — first token in 0.8s"). A non-streamed reply tells nothing (no first token), so a pool that never streams stays in listed order bar the probes. `cheap` (a group's only: `provider.normalize` drops it from a provider, whose keys and accounts all bill one price, and the CLI refuses it there) weighs by price now and nothing else: only a strategy with `routes.Strategy.ByPrice` set (`routes.Cheapest`) has `weighRouted` fill `routes.Seat.Priced`, `Cost` and `CacheCost`, from `provider.Provider.PriceAt` at `priceClock()` — the price Usage would count a call made then (the user's `ModelPrices`, else list or maker price, at the price rate and `RateAt`'s window, a `FreeModel` at 0), doubled in its vendor's peak hours by `catalog.Price.In` (`PeakOf`: DeepSeek's API, Command Code's and OpenCode Go's DeepSeek models, each at DeepSeek's hours; Ollama Cloud's deepseek-v4.1-flash and deepseek-v4-pro, dated tags too, at its own 12:00–18:00 UTC weekdays, `catalog.PeakOllama`). `routes.Cheapest` sorts stably by a million in plus a million out, a tie (within a millionth) by cache read, and unpriced seats after every priced one in listed order; rests and failover are as for any routing. The trace's rows carry `price` (`input`, `output`, `cacheRead`, `peak`) for the Routing page's story ("costs least on Ollama now — $0.150 in, $0.600 out a million tokens"). `TestCheapestFirstGroupFollowsPeakHours` holds the clock at a peak and an off-peak hour, and `TestCheapestFirstGroupFollowsOllamaOffPeak` at each edge of Ollama Cloud's hours, a Saturday, and in far zones. A group routed `expiring` (`provider.FreeExpiring`, `routes.FreeExpiring`; wowbbs on Discord, five check-in accounts of WorkBuddy, MiniMax, Trae and Qoder in one group) spends free quota before paid, the soonest lost first. Its strategy sets `ByFree` and `ByPlan`, so `weighRouted` fills `Seat.Free` (the model is free there, as for `free`) and `Seat.FreePlan` (`provider.FreePlan` of the account's `Plan`: free, trial, 免费, 试用, 体验, 體驗). It orders three tiers: the free ones with quota left, by `routes.Expires` (the earliest of a window's renewal and a credit's `RunsOut`, `Lapse` included) truncated to the hour, a stable tie in listed order and an unknown expiry after every known one; then the paid ones as `Smart` orders them among themselves; then the used up and resting, by when they come back. A paid account takes a request only when no free one has quota left, and failover walks the same tiers. The trace's rows carry `free` and `expires` for the Routing page's story ("its free quota is lost soonest, in 1d 2h"). It is a group's only: `provider.normalize` keeps it off a provider, and `magpie provider set … routing=expiring` is refused like `cheap`. Nothing changes for a group not routed `expiring`. `TestGroupSpendsFreeQuotaSoonestToExpireFirst` (gateway), `TestFreeExpiringSpendsSoonestFreeFirst` (routes) and routing-free-expiring.test.cjs hold it. A plugin whose usage doesn't say when free credits lapse (Trae, Qoder's add-on pools) is ordered after the ones that do. A group routed `weight` (#1910) takes its members, not their keys, by smooth weighted round robin: `planLevel` makes each model member (its keys ordered by its own provider's routing) and each nested group one unit, and `weightedUnits` puts the round's pick (`routes.Round` over `group/`, keyed by the member's spelling, `Group.Weights`, 1 if unset) first and the rest in member order for failover; a unit whose head rests leaves the round, while one whose accounts are only near their limit (Smart's 90% band, not resting) keeps its share, the band ordering only its own accounts (`TestWeightedGroupGivesALowGroupItsShare`; Creat.wu on Discord read the Routing page's "kept for when the others can't" as the member passed over, so the page now tells a member behind another by a group's weights or order as such, `memberSplit` in the routing plugin's `client.js`), and a kept conversation moves the round's charge to the member that kept it (`wrrSeat`, `routes.MoveRound`). `weight` on a provider spreads its keys by each key's `Weight` and a subscription's accounts by each account's (`AccountWeights`, rubbzha on X): `keyWeight` gives a seat its `Weight`, 1 when none is set, and `routes.Weighted` takes them by smooth weighted round robin, a resting one leaving the round and a kept conversation staying as Stays says (`TestWeightedKeys`, `TestAccountWeightSharesRequests`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). `drain` (dzxx0496 on Discord: free accounts one after another, the first not taking the requests back once it renews) stays on one seat per pool (`routes.Drain`, which remembers the seat's `Key` per pool) until it is used up — a known window at 100% (`provider.SpentShareOf`, as In order) or resting out of quota or credit (`routes.Seat.Spent`, filled by `spentRest` from `restingOf`'s `failQuota`/`failCredit`) — then goes on to the next not used up in listed order and stays there, wrapping round; the others follow it in listed order for failover. A rate limit or a failure only rests the seat, tried last meanwhile, and the pool comes back to it; with every seat used up it stays put, and a seat that leaves the pool leaves it on the first not used up. A group routed `drain` pools its members' accounts and keys under `group/`, as Smart does. A restart forgets where each pool was, and it starts again at the first not used up (`TestDrainKeepsTheOneThatTookOver`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/routes/`](../../internal/routes), [`internal/provider/routing.go`](../../internal/provider/routing.go) | +| Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace`, `weight`, `free` (free first), `fast` (speed first), `drain` (until used up) or, a group's only, `cheap` (cheapest first) or `expiring` (free quota by expiry). `weighRouted` reads each candidate into a `routes.Seat` and asks the strategy serving its routing (`routes.Find`, the router strategy point of [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)) for the order: Smart is `routes.Smart`, the core's; the others are `routes.Builtin`, registered by the built-in plugin `rotation`. With it off a routing no strategy serves is tried in its listed order, and `routingOf` treats it as `order` wherever the core asks about a routing (a turn's mark, `goesRound`, `sinks`, a rotate group's sessions, a group's heads). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. Among accounts a plugin reads as prepaid wallets (a window's `balance`, #3950), Smart, `usage` and `pace` put the one with more left first where they would otherwise tie, only within one provider and unit (`routes.Seat.Left`/`LeftIn`, see [provider plugins](provider-plugins.md#a-wallets-balance)): each kind is ordered in the places its own seats take, so a group weighing several providers' accounts as one pool orders each provider's wallets too (#4095, `TestGroupWalletsGoByWhatTheyHaveLeft`). `free` weighs by what a model costs there and nothing else: only a strategy with `routes.Strategy.ByFree` set (`routes.FreeFirst` is the one) has `weighRouted` fill `routes.Seat.Free`, from `provider.FreeModel` — the user's word that the whole provider costs them nothing (`Provider.CountFree`: the editor's Free for me, `magpie provider set free=yes`; jiabubu on Discord, ModelScope's free daily quota), else the vendor's own `catalog.Model.Free` word, else a list price of $0 on every count — so a pool routed any other way never reads a model list for it, and one routed `free` spends the members whose model costs nothing before those that spend the allowance or credits, each tier in its listed order (nothing free is left behind a paid one, and a pool with no free model behaves as `order`). A group routed `free` weighs its members whole, each over its own accounts or keys as its provider routes them. Whatever a group's routing, the Routing groups page tags a member `provider.FreeModel` counts free "free", on the group's card and beside its provider in the editor (`groupsState`'s `memberInfo[].free`, jiabubu on Discord, `TestGroupMemberSaysFree`, `group-member-free.test.cjs`). `fast` weighs by speed lately and nothing else: only a strategy with `routes.Strategy.BySpeed` set (`routes.Fastest`) has `weighRouted` fill `routes.Seat.TTFT` and `TPS`, from `speedOf` ([`speed.go`](../../internal/gateway/speed.go)): per `restID` (account or key, and model), a decayed average (half-life 20m) of a streamed answer's ms to its first content and of its output tokens a second as `usage.DecodeOf` counts them, written once as an answer ends (`noteTrySpeed`, beside `servedCandidate`) and read with one map lookup per candidate, never from the usage history; past an hour since its last answer a seat counts as not measured, the records are capped at 4096, and a restart forgets them. `routes.Fastest` ranks the awake by their first token plus 200 tokens at their pace (a seat with no pace at the measured seats' middle pace), keeps seats within a tenth of their band's fastest in listed order, and of a pool's requests with seats both measured and not, gives every fifth to one not measured (round the unmeasured, `probes`, so one is never starved); resting seats go after the awake, used-up ones (`UsedShare`) after those, and rests and failover are as for any routing. The trace's rows carry `lateTtft`/`lateTps` for the Routing page's story ("answered fastest lately — first token in 0.8s"). A non-streamed reply tells nothing (no first token), so a pool that never streams stays in listed order bar the probes. `cheap` (a group's only: `provider.normalize` drops it from a provider, whose keys and accounts all bill one price, and the CLI refuses it there) weighs by price now and nothing else: only a strategy with `routes.Strategy.ByPrice` set (`routes.Cheapest`) has `weighRouted` fill `routes.Seat.Priced`, `Cost` and `CacheCost`, from `provider.Provider.PriceAt` at `priceClock()` — the price Usage would count a call made then (the user's `ModelPrices`, else list or maker price, at the price rate and `RateAt`'s window, a `FreeModel` at 0), doubled in its vendor's peak hours by `catalog.Price.In` (`PeakOf`: DeepSeek's API, Command Code's and OpenCode Go's DeepSeek models, each at DeepSeek's hours; Ollama Cloud's deepseek-v4.1-flash and deepseek-v4-pro, dated tags too, at its own 12:00–18:00 UTC weekdays, `catalog.PeakOllama`). `routes.Cheapest` sorts stably by a million in plus a million out, a tie (within a millionth) by cache read, and unpriced seats after every priced one in listed order; rests and failover are as for any routing. The trace's rows carry `price` (`input`, `output`, `cacheRead`, `peak`) for the Routing page's story ("costs least on Ollama now — $0.150 in, $0.600 out a million tokens"). `TestCheapestFirstGroupFollowsPeakHours` holds the clock at a peak and an off-peak hour, and `TestCheapestFirstGroupFollowsOllamaOffPeak` at each edge of Ollama Cloud's hours, a Saturday, and in far zones. A group routed `expiring` (`provider.FreeExpiring`, `routes.FreeExpiring`; wowbbs on Discord, five check-in accounts of WorkBuddy, MiniMax, Trae and Qoder in one group) spends free quota before paid, the soonest lost first. Its strategy sets `ByFree` and `ByPlan`, so `weighRouted` fills `Seat.Free` (the model is free there, as for `free`) and `Seat.FreePlan` (`provider.FreePlan` of the account's `Plan`: free, trial, 免费, 试用, 体验, 體驗). It orders three tiers: the free ones with quota left, by `routes.Expires` (the earliest of a window's renewal and a credit's `RunsOut`, `Lapse` included) truncated to the hour, a stable tie in listed order and an unknown expiry after every known one; then the paid ones as `Smart` orders them among themselves; then the used up and resting, by when they come back. A paid account takes a request only when no free one has quota left, and failover walks the same tiers. The trace's rows carry `free` and `expires` for the Routing page's story ("its free quota is lost soonest, in 1d 2h"). It is a group's only: `provider.normalize` keeps it off a provider, and `magpie provider set … routing=expiring` is refused like `cheap`. Nothing changes for a group not routed `expiring`. `TestGroupSpendsFreeQuotaSoonestToExpireFirst` (gateway), `TestFreeExpiringSpendsSoonestFreeFirst` (routes) and routing-free-expiring.test.cjs hold it. A plugin whose usage doesn't say when free credits lapse (Trae, Qoder's add-on pools) is ordered after the ones that do. A group routed `weight` (#1910) takes its members, not their keys, by smooth weighted round robin: `planLevel` makes each model member (its keys ordered by its own provider's routing) and each nested group one unit, and `weightedUnits` puts the round's pick (`routes.Round` over `group/`, keyed by the member's spelling, `Group.Weights`, 1 if unset) first and the rest in member order for failover; a unit whose head rests leaves the round, while one whose accounts are only near their limit (Smart's 90% band, not resting) keeps its share, the band ordering only its own accounts (`TestWeightedGroupGivesALowGroupItsShare`; Creat.wu on Discord read the Routing page's "kept for when the others can't" as the member passed over, so the page now tells a member behind another by a group's weights or order as such, `memberSplit` in the routing plugin's `client.js`), and a kept conversation moves the round's charge to the member that kept it (`wrrSeat`, `routes.MoveRound`). `weight` on a provider spreads its keys by each key's `Weight` and a subscription's accounts by each account's (`AccountWeights`, rubbzha on X): `keyWeight` gives a seat its `Weight`, 1 when none is set, and `routes.Weighted` takes them by smooth weighted round robin, a resting one leaving the round and a kept conversation staying as Stays says (`TestWeightedKeys`, `TestAccountWeightSharesRequests`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). `drain` (dzxx0496 on Discord: free accounts one after another, the first not taking the requests back once it renews) stays on one seat per pool (`routes.Drain`, which remembers the seat's `Key` per pool) until it is used up — a known window at 100% (`provider.SpentShareOf`, as In order) or resting out of quota or credit (`routes.Seat.Spent`, filled by `spentRest` from `restingOf`'s `failQuota`/`failCredit`) — then goes on to the next not used up in listed order and stays there, wrapping round; the others follow it in listed order for failover. A rate limit or a failure only rests the seat, tried last meanwhile, and the pool comes back to it; with every seat used up it stays put, and a seat that leaves the pool leaves it on the first not used up. A group routed `drain` pools its members' accounts and keys under `group/`, as Smart does. A restart forgets where each pool was, and it starts again at the first not used up (`TestDrainKeepsTheOneThatTookOver`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/routes/`](../../internal/routes), [`internal/provider/routing.go`](../../internal/provider/routing.go) | | Limits | Each key or account (a candidate's `who()`) has at most `MaxConcurrency` requests out at once (its own `AccountConcurrency` over it); one more waits in its lane's queue, bounded by `QueueLimit` and `QueueWait` and turned away with a 429 past either (`lanes.take`). One with no limit still counts its requests out in a lane of `Limit` 0, which never waits, so `Lanes` (`/v1/magpie/concurrency`, the GUI's `/api/lanes`) says how many run there too and the Providers page's pill shows it (chentuoyan on Discord, `TestLanesCountWithNoLimit`); a limit set while they are out counts them. `MaxRPM` (coeo91 on Discord: OpenRouter's free models take 20 a minute) bounds how many requests it sends the vendor in any rolling 60 seconds (`rpms`), counting each for a second more (`rpmSlack`), since the vendor counts a request when it arrives and the first on a new connection arrives later by its dial: one more waits for room in the minute, in the order they came, after it has its slot and right before it is sent. A wait that would be longer than 2 minutes (or the provider's `QueueWait`, when shorter: `rpmWait`) is turned away at once with a 429 whose `Retry-After` is when the minute has room; nothing rests for it. An agent gone while it waits gives its place back. Every request that reaches the vendor counts: each try of the candidate loop (a retry, the next key, a fallback) waits in `serve`, and the requests a try makes on the way and the gateway's own asks (count_tokens, System One's decisions, embeddings, drawing, Kimi's search) are counted by `rpmTransport` on `s.client` (`metered`, `paidFor`). count_tokens never waits: a candidate with no room is skipped, and the local estimate answers. A full lane or a minute with no room gives way to a ready key or account of the provider or the group (`laneMate`, `ready`) that isn't resting: its lane is free only because nothing is sent there. A request already waiting in a lane doesn't stay bound to it: whenever a slot is given back in any lane or a rest is lifted (`lanes.freed`, signalled by the releaser, `Unrest` and `UnrestAll`), and when the soonest rest among the others runs out (at most every `laneRecheck`), it goes to the first key or account after it in the planned order that has a free slot with no queue, minute room, isn't resting and isn't a reserve now (`waitMate`, `keepAtOnce` re-derived over the provider's candidates, `errMoved`). So one that took a seat while those before it rested, then became a reserve once they were back, doesn't keep requests waiting behind its own long turns (01huadalang on Discord: three ZCode accounts at three at once, the first two back from a 405 while the waiting ones stayed on the third until its requests were cut by hand; `TestWaitingRequestGoesToAccountBackFromRest` under Smart and In turn, with Stays on and off, `TestWaitingRequestTakesSlotGivenBackElsewhere` under every routing). Strict stays leaves no other candidate, so the request waits for its own. A fallback is never asked for want of a slot or a minute (`TestFullMemberGivesWay`). A plugin's account sends through its own transport, so only its tries are counted, not a plugin's own extra requests. Set in the provider editor (Concurrency, Requests per minute, Queue size, Queue wait) or with `magpie provider account-concurrency`, `queue` and `rpm`; a subscription's are kept with its picks, and every account of it keeps them, those on beside the first as well (`withPicks`, called by `All` and `AlsoOn`; #1899: a second WorkBuddy AI account had none, and queued 62s with the wait set to 1s). | [`concurrency.go`](../../internal/gateway/concurrency.go), [`rpm.go`](../../internal/gateway/rpm.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | | Accounts at once | A provider's `MaxAccounts` (01huadalang on Discord: three ZCode accounts used at once got the exit address refused with a 405, two didn't) is how many of its keys or accounts take requests at the same time: `provider.AtOnce()` is the user's own value, else what its plugin declares (`maxAccounts` on the auth hook or in package.json's `magpie`, read by host.js `atOnceOf`; zcode says 2), else no limit; the user's 0 is no limit over the plugin's. `perKeyBarred` keeps the first N in the user's own order (`rank`, so a dragged list counts), preferring ones not resting, and hands the rest to `keepAtOnce`'s reserves: they go after everything else as asides with `candidate.reserve` set (`Weighed.Reserve`), so whatever the routing mode, a reserve is asked only once the kept ones failed or rest, and a kept one that rests gives its seat to the first reserve on the next request. Three guards keep a reserve from being reached for anything else: `laneMate` never spills a full lane onto one, a full queue (`laneErr`) drops the provider's reserves before passing on (`dropReserves`), so the request is turned away with the 429 instead, and session affinity keeps no conversation on a reserve once the kept ones can take it (`affine`'s "reserve"; Strict still holds). Leak known: a failure that rests nobody (a 5xx on one try) still passes that one request to the reserve, as it does to any next candidate. Set in the provider editor's Advanced (Accounts at once, beside Concurrency) or with `magpie provider at-once`; Routing's row says "in reserve · {n} at once" (`TestAtOnceKeepsFirstInUserOrder`, `TestAtOnceFullLaneWaitsForTheKept`, `TestAtOnceReserveTakesOverAndGivesBack`, `provider-at-once.test.cjs`). | [`fallback.go`](../../internal/gateway/fallback.go), [`concurrency.go`](../../internal/gateway/concurrency.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | | Sink | With `Sink` on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart, or until its rest is lifted by hand (Try now, `Unrest` calls `unsink`, `UnrestAll` `unsinkAll` for the key and each of its models), which puts it back in its place (`TestTryNowPutsASunkAccountBack`, `TestUnrestAllUnsinksTheModels`). Another magpie's model rate limited there, whose rest is the model's alone (`remoteModelRest`), sinks alone too (`restID`), and `sunkAt` reads a candidate's model before its key, so the remote's other models keep their place (#2167, ggbdpq; `TestRemoteMagpieRateLimitSinksTheModel`, `TestMagpieAddedByHandRateLimitSinksTheModel`). A group in a group sinks by its own Sink, within its own order (`sinkOwn`, #2255), and the group asked for then sinks the whole by its own; `TestNestedGroupSinksItsOwnOrder`. | [`sink.go`](../../internal/gateway/sink.go) | @@ -165,10 +165,10 @@ recorded as a prediction failure (`noPrediction`). - Rules and image inputs are handled here too. - A rule is decided as a user's turn begins and held for the rest of it (`ruleFor`, [`rules.go`](../../internal/gateway/rules.go)). What counts as the user's own words is one helper, `userWords`/`userSaid` in [`prompt.go`](../../internal/gateway/prompt.go), which the turn count (`turnIn`), the classifier's question (`userText`), the conversation's key (`firstWords`, in `ruleKey` and the affinity scope), the conversation's id where no session header names it (`userOpens`, in `conversationID`), Copilot's Auto (`lastUserText`) and the prompt breakdown's turns (`userSays`) all go by. It drops `` blocks (a `source=` attribute too) and any text that begins as an agent writes for the model alone: Codex's ``, ``, ``, ``, `` and `# AGENTS.md instructions for …`; Claude Code's and ZCode's ``, ``, agent lists ("Available agent types …", "New agent types are now available …"), TodoWrite and task-tool nudges and rewind notices; ZCode's ``; the Codex app's ``; Reasonix's ``, its snapshot of the workspace (keeyangyy, #3938). The Codex app's context before `## My request (for Codex):` is dropped and what follows it kept (the `injected` list beside `agentsFor`). A user message with nothing of the user's in it (and no image or file) begins no turn: after an answer or a tool round it carries the turn on (`within`), so the turn's rule and stick hold and the classifier isn't asked; right after the user's words it leaves their turn as it began. The classifier is asked about the last user message that has words of the user's, only those words (`userText`: past 4000 runes, its first 3000 and last 1000). It is told what came before it too (`turnBefore`, @HirotaNagai on X: a short follow-up said alone, 继续 or fix that, came out the hardest kind): the user's message before it, the same way and cut to 1000 runes (`priorCap`: the first 750 and the last 250), and the assistant's last reply between the two, its text parts alone and their last 1000 runes. A tool call's arguments, a tool's result, thinking, a search's hits and the system prompt are never in either, and a reply of only tool calls is none. Jev gets them in its `state` as `previous_user_message` and `previous_assistant_reply` beside `message`, `previous_message_kind` and `previous_message_reasoning`, each only when there is one, and its intent, level and effort instructions name the ones there are (`jevState`, `priorAsk` in [`decide.go`](../../internal/gateway/decide.go)); a classifier asked in words gets them in `` and `` before `` (`writePrior`). Both come from the request the rules parsed, so Privacy masks them as it masks the message, and the answer kept for a message is kept for it with what came before (`classify`'s key). `TestTurnBeforeEachProtocol`, `TestTurnBeforeCuts`, `TestJevIsToldWhatCameBefore`, `TestChatClassifierIsToldWhatCameBefore`, `TestClassifyKeepsAnAnswerPerTurnBefore`, `TestJevSeesTheTurnBefore`. `firstWords` hashes the words of the first user message that has any, so an instruction file or notice the agent changes beside them doesn't move the conversation to a new key and lose its stick mid-turn (#1826: ZCode's TodoWrite nudge classified as a new, harder turn, and three keys for one ZCode session). `TestTurnInSkipsWhatTheAgentPutIn`, `TestUserTextSkipsWhatTheAgentPutIn`, `TestFirstWordsAreWhatTheUserSaid`, `TestIntentHoldsPastWhatTheAgentPutIn`. - A rule's members go first (`ruleOver`, `applyRule`): the members it names, in order, then those the matching rules after it name (`ruleOrder`), each not resting, then the group's others to fail over to. A member that is a group in the group is one member here: its models keep the order the group's own routing planned them, where ranking each by the group's listed order pinned a rotate group's first member on every request the rule put it first (#2407, `TestRuleNamingARotateGroupKeepsItsTurns`). That holds within the turn too, at the group's rule and at each nested group's (`nestedRules`): the one the turn stays on (affinity) stays first while it is of the rule's member that goes first, and the member's others follow it ahead of the group's others, so a failure fails over within the member the rule chose before going outside it. One the turn was kept on outside that member, which took over when the member failed, isn't held there: once one of the member is out of its rest, the turn's next request goes back to it (`Affinity.Why` `rule`). Before #1946 (XcodeFish) a held rule's order wasn't applied to a kept turn at all: a coding-quality member failing mid-turn failed over to coding-fast, the parent's first, and the turn stayed there. `TestHeldRuleFailsOverWithinItsMember`. Two groups in the group may share a model (the same provider, model and effort): it is asked once a request, where the walk met it first, and `provider.Member.Also` keeps its later places, each with its own path, `At` (its place in the walk) and Fast. A rule naming the later group has the model as that group does (`Member.In`, `membersNamed`), in that group's own order, and the nested rules below it, Fast and the first token's wait go by that group's way down (`homed`, `homeCands`). Before #2361 (davisjiahao) such a rule found none of the shared models, read unready, and the group ahead of it answered. A pause rule naming the later group still leaves a shared model to the group ahead of it. `rule_shared_test.go`. - - How sure a decision model (Jev) must be of an intent for it to count is the group's own (`provider.Group.IntentSure`, JSON `intentSure`, 0 to 1; missing keeps `jevSure`, 0.4; `magpie group set intent-sure=0.25`, empty to unset; SaveGroup and the CLI refuse a value outside 0 to 1, NaN too; `cloneGroups` copies it). `readJev` keeps Jev's likeliest intent with its sure and marks a topic answer (`verdict.Topic`); `ruleFor` applies the group's sure (`intentOf`), so two groups sharing one classifier and its cached answer each judge it at their own. "none of these" is never an intent, at 0 too, and levels keep the turn before's level when torn, as before. A chat model asked in words answers with no sure and is taken as it answers. The Routing page carries the value through every save of a group but has no field for it yet (#5101). `TestGroupIntentSure*`. + - How sure a decision model (Jev) must be of an intent for it to count is the group's own (`provider.Group.IntentSure`, JSON `intentSure`, 0 to 1; missing keeps `jevSure`, 0.4; `magpie group set intent-sure=0.25`, empty to unset; SaveGroup and the CLI refuse a value outside 0 to 1, NaN too; `cloneGroups` copies it). `readJev` keeps Jev's likeliest intent with its sure and marks a topic answer (`verdict.Topic`); `ruleFor` applies the group's sure (`intentOf`), so two groups sharing one classifier and its cached answer each judge it at their own. "none of these" is never an intent, at 0 too, and levels keep the turn before's level when torn, as before. A chat model asked in words answers with no sure and is taken as it answers. The Routing groups page carries the value through every save of a group but has no field for it yet (#5101). `TestGroupIntentSure*`. - A classifier's timeout is global (`Settings.ClassifyTimeout`, JSON `classifyTimeout`, seconds, in [`settings.go`](../../internal/settings/settings.go)). Missing or 0 keeps the 8-second default; saving accepts 1–60 seconds or 0 and rejects negative values or values above 60. `Settings.ClassifyWait` bounds a hand-edited value above 60 to 60 seconds and uses the default for a value below 1. `classifyTimeout()` reads it for each call: both `askChat` in [`classify.go`](../../internal/gateway/classify.go) and `askJev` in [`decide.go`](../../internal/gateway/decide.go) give the classifier that time, including its provider's failover. A request shares one such wait across every routing group it goes through (`Server.askWaited`, from the first classifier asked): a nested ruled group asked with less left gets only that, one asked once it is spent goes by its order at once (`waitSpent`, "spent by the routing group above"), and a classifier or decision key cut short that way is not rested (`cutShort`). Each nested level had a whole wait of its own before, so three ruled levels whose classifiers didn't answer held a request past the unrouted watch's 2 minutes, a 504 (heatonz on Discord, v0.1.2215; `TestNestedGroupsShareTheClassifierWait`, `TestDecisionKeyCutShortIsNotRested`). Settings → Models → Replies → *Intent classifier timeout* (`renderReplies` in [`app.js`](../../internal/gui/assets/app.js)) offers 8, 15, 30 and 60 seconds and shows a custom valid value as its own choice. A change applies to the next classifier call, with no restart; the existing fallback, 30-second cooldown (`classifyRest`) and 10-minute answer cache (`classifyKeep`) still apply. - A classifier that can't say which kind a turn is (an error, no answer within `classifyTimeout()`, an answer that isn't a number, or resting `classifyRest` after a failure) leaves a turn whose conversation had an intent, still one of this turn's, with that intent (`Classified.Fallback` is `previous`, its `Error` kept), so the turn goes where the turn before went rather than to the group's first member; with no intent before, no rule with an intent matches, as before. The Routing page says the turn kept it (`classWhy`). The turn's decision itself (`turnRules`) is kept in memory only: after a restart a turn under way waits for the next one and the stick holds it meanwhile. `TestIntentClassifierFailsKeepsThePreviousIntent`, `routing-intent-fallback.test.cjs`. - - A group's classifier is asked only for that group's own turns: a request whose model is the group (`group/`, its bare name, or a stand-in an agent's config names it by: Claude Code's tiers, Codex's bare name), or a group in it that its rules or order put first (`nestedRules`). A request for another model or group asks it nothing. The Routing page's card says why the classifier couldn't say the last time *that group* asked it (`GroupClassifierFailure`, kept by `classifiedFor` in `ruleFor`): the classifier's own words and time, resting or not, until it answers that group, and nothing once the group's classifier changed. Keyed by the classifier model alone, a group nothing reached showed another group's failure on a classifier they share (jjt on Discord). A classifier on a subscription out of its quota is not asked of the vendor again until the reset: out of quota, its account rests until the quota comes back (`restAfter`: the time the refusal names, else when the account's window renews), and the classifier's call meanwhile gets that refusal back from magpie, at most once each `classifyRest`. `TestClassifierFailureIsTheGroupsOwn`. + - A group's classifier is asked only for that group's own turns: a request whose model is the group (`group/`, its bare name, or a stand-in an agent's config names it by: Claude Code's tiers, Codex's bare name), or a group in it that its rules or order put first (`nestedRules`). A request for another model or group asks it nothing. The Routing groups page's card says why the classifier couldn't say the last time *that group* asked it (`GroupClassifierFailure`, kept by `classifiedFor` in `ruleFor`): the classifier's own words and time, resting or not, until it answers that group, and nothing once the group's classifier changed. Keyed by the classifier model alone, a group nothing reached showed another group's failure on a classifier they share (jjt on Discord). A classifier on a subscription out of its quota is not asked of the vendor again until the reset: out of quota, its account rests until the quota comes back (`restAfter`: the time the refusal names, else when the account's window renews), and the classifier's call meanwhile gets that refusal back from magpie, at most once each `classifyRest`. `TestClassifierFailureIsTheGroupsOwn`. - The classifier's requests are magpie's own (#1839). Asked in words, they go out with `RouterAgent`'s User-Agent (`magpie-router/1`), so their records' agent is magpie and `callKind` marks them `routing`; a decision model's (Jev, System One) record is written with `Kind: "routing"` too. They go to the same key or account as any other request and count in its totals, while `usage.Group.Own` (`Record.ByMagpie`: agent `magpie` or one of its `magpie-` User-Agents, with search's and image description's) says how many of an account's, key's or model's calls, tokens and cost were magpie's own. A classifier set to a subscription's model (`modelRef.Sub`, or a group whose first member is one) asks that subscription as every turn begins, twice when it picks both intent and effort in words; the Routing page says so beside it (`classifierSub` in `plugins/routing/client.js`). `TestIntentRoutesATurn`, `TestJevPicksTheIntent`, `TestSummaryCountsMagpiesOwnCallsApart`, `TestByMagpie`, `TestServedRefSaysASubscription`, `own-requests.test.cjs`. - A rule may name several members (`Rule.More` after `Rule.Use`, `more` in the group's JSON, `use=a,b` typed; monkeyin_92 on X: one rule, several models, not a rule each). They go first in that order, ahead of the later matching rules' members (`ThenUses` leaves out every one the rule names) and the group's others: when the first fails or rests the rule's next takes the request, and the hit says so (`RuleHit.More`; `Instead` is that next one with `Unready` false, where an `Instead` from a later rule comes with `Unready` true). `Uses`, `SetUses`, `MapUses`, `Without` and `Names` in [`grouprule.go`](../../internal/provider/grouprule.go) are how every reader goes through them: `cleanRules` (each must be the group's, each named once, a pause names one), the turn's hold, the tool rounds and compaction (`ruleFor`, the rule's first that takes the summary), `nestedRules` and `ruleLed` (the one of them a nested group's turn stays on), `ruleEffort` (the rule's `useEffort` asked of each), `ruledEntry` (what a group takes is what every one of them takes), a model's rename and removal (a rule goes with its last), `ShareGroup` and its import (one this magpie hasn't is left out of the rule), the CLI's `groups rules` and the TUI. The editor draws a chip per member with a + for the next and an × on each while there is more than one (`rUses`/`setUses` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js)). A rule of one member writes no `more`, so a group saved before it reads and saves as it was. A magpie from before it reads `use` alone: its requests go to the first, and the others are plain members in the group's order; if it saves the group, `more` is dropped. `TestRuleSeveralModelsInOrder`, `TestCleanRulesSeveralModels`, `routing-rule-models.test.cjs`. - The editor's rules are checked top first, so their order is theirs to set: a rule's number is its handle (`ruleHandle`, `.rt-rhandle`), dragged (`dragRows`, as the members are) or moved a place with Alt+↑/↓, the rules renumbered at once; the grip beside it shows on hover only, and Move up and down stay under its ⋯ (`moveRule`). Saved as the group's `rules` in their new order. `routing-rule-drag.test.cjs`. @@ -176,7 +176,7 @@ recorded as a prediction failure (`noPrediction`). - A rule by folder (`Rule.Folders`, `folders=~/work/acme,~/oss`; Cario0x on X: routing by the project being worked on) matches when the folder the agent works in is one of them or inside one (`provider.FolderUnder`, [`rulefolder.go`](../../internal/provider/rulefolder.go)): at a path's boundary, so `/a/b` is not under `/a/bc`; `~` is the home folder; a Windows drive is one with its WSL mount (`C:\work` is `/mnt/c/work`) and a `\\wsl$\` or `\\wsl.localhost\` share is the distro's own path; case doesn't count on macOS and Windows, nor ever for a drive. A rule outside folders (`Rule.ExceptFolders`, `except-folders=~/big-task`; #1606, Ti800) matches when the folder is in none of them, and an agent that says none isn't known to be in one, so it matches; a rule may have both (`Rule.ByFolder`, `inFolders`). The folder is read from the request only when a rule of the group has folders or except-folders (`workDir` in [`workdir.go`](../../internal/gateway/workdir.go)), in each agent's own words, taken from captured requests: Claude Code's ` - Primary working directory: ` (its `<`/`>` as entities; ` (was )` after a change dropped), Codex's `` ``, Pi's `` or `Current working directory:` in the system prompt, and OpenCode's `Working directory:` inside its `` block. The caller's own layer — the system prompt and its `{role: "system"}` messages — is read whole, a `claude --bare` run's `CWD: ` among the forms; a user turn counts only for the forms a caller states in one (``, OpenCode's ``, Claude Code's ``, which says a folder it moved to): a working-directory line a user message quotes is no caller's word (#4940). Never the model's words or a tool's result, and the last said wins. An agent that says none has no folder, and no `folders=` rule matches it (unknown, never empty). The same reading tells a plugin's fetch where its agent works ([provider-plugins](provider-plugins.md#where-the-agent-works-for-a-plugins-fetch)). A pause rule may hold by folder too (below). The trace's `RuleHit.Folder` is the folder read, and the Routing page tells it beside the rule's `folder …` condition. `TestFolderUnder`, `TestRuleMatchesByFolder`, `TestParseRuleFolders`, `TestWorkDirOfEachAgent`, `TestRuleByFolder`, `TestRuleMatchesExceptFolders`, `routing-folder.test.cjs`. Rules by folder are never in a shared group (`ShareGroup` drops every `ByFolder` rule). - A rule by agent (`Rule.Agents`, `agents=codex,sillytavern`) matches the agent the gateway names the request's (`agentOf` in [`gateway.go`](../../internal/gateway/gateway.go): its `magpie-` key, else its User-Agent), in lower case (`cleanRules`, `MatchesBesidesIntent`, `Pauses`). A client magpie doesn't know is named by its User-Agent's product name, before the first `/` or space (`usage.AgentOf`), so a rule can hold SillyTavern or one's own app (raikyou on Discord). The editor's agent picker lists the agents magpie knows, then those `/api/usage?period=30d` heard from that it doesn't (not `other`, nor `magpie`), and takes a name typed in its filter as the gateway reads a User-Agent (`uaName` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js), through the picker's `field.typed`): "MyApp/2.0 (Linux)" is `myapp`. `routing-rule-agent-typed.test.cjs`. - A pause rule (`Rule.Pause`, `pause=`; John on Discord: a model of the group paused in its vendor's peak hours) leaves the model it names out of the group while it holds (`provider.PausedOut`, on `ruleClock`): the group's own rules and each nested group's on the way down to a member, a group named taking all its models, and a model named taking it wherever a group in the group has it (#625). It runs before planning, on every request rather than once a turn, so the model is not first, not a failover, and not kept by affinity, and comes back as soon as the hours end. It holds by hours, days, agents and folders only (`cleanRules` refuses another condition), and is not a send-to rule: `Matches`, `MatchRule`, `ThenUses`, `Ruled` and the compaction rules leave it out. A send-to rule naming a paused model finds it unready and the group routes as without it. The trace keeps what was paused (`GroupRef.Paused`), and the Routing page says so. Every model paused answers 503 (`pausedError`) naming each rule. Embeddings go by the same pauses; manual groups have no rules (`Live`), so none pause there. A pause by folder (#1606, Ti800: a subscription's quota kept for the long task in one folder, `pause= except-folders=~/big-task`) reads the folder only when such a pause is on the way (`provider.PausesByFolder`, then `workDir`): outside its except-folders, which includes a request that says no folder (a subagent's or a small model's that doesn't), the model is left out; with `folders=`, only requests known to be in them. Embeddings and System One's decision calls have no folder. `Paused.Folder`/`ByFolder` carry what was read, and the Routing page says the folder or that none was said. `rules_pause_test.go`, `TestPauseByFolder`, `TestPauseByFolderRule`, `TestParsePauseByFolder`, `routing-pause-folder.test.cjs`. - - A rule's hours and days (`Rule.Time`, `provider.TimeWindow`) are read on `ruleClock` in the zone they were set in (`TimeWindow.Zone`, an IANA name; gaubeebangeel on X: magpie on a cloud server in UTC, its user in Beijing, the hours 8 off). The GUI saves the browser's zone when the hours or days are changed in the editor and leaves a rule's zone alone otherwise; the CLI (`magpie group rule add … time=09:00-18:00@Asia/Shanghai` or `tz=`) and the TUI save the one typed, or this computer's (`provider.LocalZone`: `$TZ`, `time.Local`, the `/etc/localtime` link) when it has an IANA name. A window with no zone, every one saved before zones were kept, stays on magpie's own clock. A zone magpie doesn't know is refused on save (`TimeWindow.clean`), and one in a file edited by hand makes the window never hold (`zoneOf`): the rule is as if absent, never always on and never hours off. Zones come from Go's embedded tzdata, so Windows knows them too. `/api/groups` gives magpie's clock (`clock`: its zone and offset in seconds), and when it differs from the hours' zone the Routing page tells the zone beside them, on the group's rules and in the editor (`zoneNote` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js)): the zone's name, or the server's offset for hours with none. `TestRuleTimeWindowInItsZone`, `TestRuleTimeWindowInItsZoneAtTurnStart`, `TestRuleTimeWindowUnknownZone`, `TestParseRuleTimeZone`, `TestGroupRuleTimeZoneCmd`, `routing-time-zone.test.cjs`. + - A rule's hours and days (`Rule.Time`, `provider.TimeWindow`) are read on `ruleClock` in the zone they were set in (`TimeWindow.Zone`, an IANA name; gaubeebangeel on X: magpie on a cloud server in UTC, its user in Beijing, the hours 8 off). The GUI saves the browser's zone when the hours or days are changed in the editor and leaves a rule's zone alone otherwise; the CLI (`magpie group rule add … time=09:00-18:00@Asia/Shanghai` or `tz=`) and the TUI save the one typed, or this computer's (`provider.LocalZone`: `$TZ`, `time.Local`, the `/etc/localtime` link) when it has an IANA name. A window with no zone, every one saved before zones were kept, stays on magpie's own clock. A zone magpie doesn't know is refused on save (`TimeWindow.clean`), and one in a file edited by hand makes the window never hold (`zoneOf`): the rule is as if absent, never always on and never hours off. Zones come from Go's embedded tzdata, so Windows knows them too. `/api/groups` gives magpie's clock (`clock`: its zone and offset in seconds), and when it differs from the hours' zone the Routing groups page tells the zone beside them, on the group's rules and in the editor (`zoneNote` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js)): the zone's name, or the server's offset for hours with none. `TestRuleTimeWindowInItsZone`, `TestRuleTimeWindowInItsZoneAtTurnStart`, `TestRuleTimeWindowUnknownZone`, `TestParseRuleTimeZone`, `TestGroupRuleTimeZoneCmd`, `routing-time-zone.test.cjs`. 3. Candidates come from `planGroup` for a group or `plan` for a provider. They are filtered by `sealedReaders` and `allowedCandidates`. An account past its share is held out of the candidates (`capHeld`): a usage cap's share, each window at its own where the account gives it one (`AccountWindowCaps`, willz on Discord: 50% of the five hours, 40% of the week) and at the account's cap otherwise, or 100% of a window for a Codex account set not to spend its credits (`provider.HoldCaps`, `WindowCaps.Of`, `CodexNoCredits`). A ChatGPT account's call on `codex-auto-review`, which OpenAI counts in no window, is held by no usage cap, only by credits it may not spend (`freeOnChatGPT`, #1593, `TestAccountCapLetsAutoReviewThrough`); a Free plan's call is capped as any other (`TestAccountCapHoldsAutoReviewOnAFreePlan`). The account is held while any window is past its own share, and `cappedError` and the trace name the fullest such window's share and cap. When every candidate is held and one held for its credits spends its resets by itself, `autoReset` spends a reset on it and it is tried (`planned.held`). A Codex account let spend its credits is never held or refused for its week, so before a try goes to one whose week its last reading says is used up and that spends a reset when its week runs out, `resetBeforeCredits` spends one first, one a week at most, in routing and in the relay (`resetBeforeCreditsOn`); a reset is free and credits cost money (tongzhenbao on X, `TestCodexResetBeforeCredits`). Otherwise a capped or barred set returns `cappedError` or `barredError`. A provider with Stop at the caps on (`CapStop`, plugins#349) answers that 429 instead of going on to its fallbacks when every primary account is held (`plan`, `TestCapStopSkipsTheFallbacks`); off, the default, the fallbacks take it as before. A careful provider (`CapCareful`, plugins#349, off by default, `cap_careful.go`) has `readCareful` read a capped account's usage again before planning when its reading is over 15s old within 5 points of a cap, or over 5m old at all, waiting at most 10s and asking a failed account again at most every 15s; `capHold` then holds an account whose usage was never read, whose last read failed or whose reading is still that old (`carefulDoubt`, `Weighed.Unread` in the trace), as one at its cap is: unknown is not spent (`TestCarefulHoldsWhatItCantTell`, `TestCarefulReadsAgainNearTheCap`, `TestCarefulEveryAccountUnread`, `TestCarefulOffByDefault`). Planning goes by the last reading, so turns sent together were each planned on the same one: an account a point under its cap took all of them and went past it by what they used between them (dyzdyz010 on Discord: capped at 90%, used to 100%). In serve's walk an account within 5 points of a usage cap (`nearCapOf`, `nearCapPoints`, `cap_near.go`) takes one turn at a time (`Server.nearCap`, its turn held until the try ends): a turn that finds it busy goes to the next candidate first, the account moved behind them once (`nearBehind`); the last candidate waits. Once its turn comes `capHeld` judges it again, by what the reply before it left (Codex's `codex.rate_limits`, Claude's `rate_limit_event`), or, when that reply said nothing of the account's usage, by a reading taken again then (`nearCapAgain`, at most `carefulWait`); held, it is passed over, and when it was the last the agent gets `cappedError`'s 429. The cap is passed by one turn at most, as a gateway key's limit is, Claude Code accounts as Codex's (`TestNearCapTakesOneTurnAtATime`, `TestNearCapWaitsThenHolds`, `TestNearCapReadsAgainAfterASilentReply`, `TestFarFromCapTurnsGoTogether`, `TestNearCapClaudeAccountsTakeOneTurnEach`). A conversation kept on its account by Stays: Strict goes on past the cap as `strictKeep` keeps it, and takes no turn there (`TestStrictAffinityGoesPastTheCap`). Then `affine` moves the conversation's last answerer first, unless it is resting or nearly used up. An `X-Magpie-Account` header (`AccountHeader`) pins the request to one account: only that account is tried, and when it can't answer the caller is told why. A header value is ASCII on the wire and fetch refuses one that isn't, so an account whose user isn't ASCII (北冥, plugins#615) is named percent-encoded; `pinnedName` decodes it, the value as written matches too, and the trace and the call's record name it decoded (`TestAccountPinnedPercentEncoded`). 4. The candidate loop calls `attempt` on each candidate in turn, through a `holdWriter`. The writer holds the reply until it is clearly passing. A candidate that fails before anything is sent rests (`failure`): out of credit for 30 minutes (a key longer each time it is refused so again once its rest has ended: 30 minutes, 2 hours, 8 hours, a day, 3 days, then a week (`creditLadder`, `creditBackoff`), the same rung while a rest still runs, a new run after "Try now" (`Unrest`) or an answer; each such rest, its rung and when it ends, is kept in `rests.json` beside `providers.json` (written through a renamed temp file whenever one is set or dropped, `saveRests`) and read once as the gateway starts to listen (`loadRests`), so a restart rests out what is left and climbs on from the rung: an ended rest keeps its rung there as in memory, unless it ended over `restsKeep` (35 days) ago, a key no longer in `providers.json` is let go, and a file or `providers.json` that can't be read or parsed adds no rest (PaulT on Discord, `TestKeyCreditRestOutlivesRestart`, `TestKeyCreditRestFileCorrupt`); a refusal that names its reset rests till then, and one that says it can pass soon (a `Retry-After`, OpenRouter's in-flight budget or "can only afford", a "try again in 30 seconds", `creditSoon`) rests 30 minutes or less and doesn't climb; a remote magpie's model rests 30 minutes as before: PaulT on Discord, `TestKeyOutOfCreditRestsLongerEachTime`; a ChatGPT account until the reset its refusal names, else until its full window renews, else 5 hours, `chatgptCreditRest`, and a reading finding its window renewed has it back: PaulT on Discord, `TestChatGPTOutOfCreditsRestsLong`), out of quota until reset, rate limited until retry-after, otherwise a minute and longer on repeats: doubled each time, up to `longestRetry` (10 minutes) for a failure and `longestRateRest` (30 minutes) for a rate limit back as soon as its rest is over, or up to the provider's own `restCap` in minutes (`Provider.RestCapOr`, at most `MaxQuotaRest`; `magpie provider rest-cap 4h`, #2008: a free key down for hours was asked every 10 minutes). A time the vendor names stands over it as before (`TestOwnRestCap`). An error `failure` reads as out of credit is `retryable` at any 4xx, so the next account or member is asked and this one rests as credit; before, a 400 or 422 counted only by `quotaWords`, and SuperMagic's 400 「您的可用积分已不足…通过「充值」通道补充积分」 went to the agent with another account of 6,467 points unasked, the empty one never rested (#4095, mycf_711; `TestCredit400MovesToTheNextAccount`). A shape refusal that also says so (`creditWords` in `shapeRefused`) is the credit it says. The failure count is kept per key or account (`restKey`), and any of its models' answers clears it (`served`). Each model's own count (`restID`) is kept beside it and cleared only by that model's answer (`servedCandidate`): once it is past the account's, a sibling model answered since it last did, so the failure is the model's and it climbs its own ladder and rests alone, its siblings still served (#2241, weizsw: an Antigravity seat's gemini-3.5-flash-lite rested a minute 41 times of 43 while gemini-3.8-flash kept answering; `TestModelLadderClimbsPastSiblingAnswers`). Every model failing with no answer between still climbs the account's ladder and rests the account, and a candidate naming no model has the account's count alone. `rest-cap off` (`provider.RestCapOff`, `restCap: -1`) is for a relay or account pool whose unknown errors come now and then and pass by the next request (Kismet Alan on Discord): a failure that says nothing of why (`failOther`: a 5xx, a dropped connection) then rests nobody and isn't counted, its trace rest `by: "off"` with no time left. A 401 or 403, a model not served, an account's window full, a rate limit (magpie's own 30-minute cap), quota, credit and a restriction still rest it as before (`TestRestCapOff`). A provider the user added can be set never to rest for a limit instead (`provider.LimitRestOff`, `limitRestOff` in providers.json; the editor's Advanced fold, "Set it aside when out of quota or rate limited", ticked by default): a refusal `restAfterMarked` reads as out of quota, out of credit or rate limited, and any 429, then rests nothing, isn't counted or sunk, and is `by: "off"`; `restDrawer` rests no image model of it. The next request is sent to it as usual. It is for a relay whose limits pass in a moment (zoecats on Discord: a local aggregator said "quota exhausted" while it switched upstreams, and magpie answered itself for 30 minutes; `TestLimitRestOffKeepsAsking`, `TestLimitRestOffRestsNothingForALimit`). A 401, a model not served and a plain failure still rest it. The shortest cap otherwise is a minute, the first rest; `rest-cap 30s` is turned away and names `off`. A 400, 403, 404 or 422 that says the model isn't served (`unservedWords`) and says nothing of quota, credit or a rate limit rests only that key's or account's model (`modelRefused`, keyed by `restID`, its backoff counted apart): its other models are still served first in order (#1235, SenseNova's 403 "model is not available in the current token plan"). A Google account's Code Assist (the Antigravity and Gemini CLI built-ins) answering 404 `NOT_FOUND` ("Requested entity was not found.") rests its model the same way, as its endpoint is the same for every model (`codeAssistModelMissing`; Packing1 on Discord: Argon, listed for a Google AI Pro account, answered 404 and rested the whole account; `TestCodeAssistMissingModelRestsTheModel`). A refusal for want of quota, credit or rate, for an account its vendor restricted, or for a verify it asks of its account there, from another computer's magpie (a Remote magpie provider, LAN share) rests only the model it was about (`remoteModelRest`, keyed by `restID`, in `restAfterMarked` and `rateRest`): that magpie serves each of its models from its own providers and rests them itself, so one out of quota there says nothing of the others (bigsteven on Discord: a 429 for one model rested every model on the remote for the 3 hours it named, so a group never moved on to the remote's other models; `TestRemoteMagpieQuotaRestsTheModel`, `TestRemoteMagpieRestrictedRestsTheModel`). Such a rest out of quota or credit (`Rest.there`) still puts the model behind the others, but is never given again without asking (`quotaHeld` passes it by): that magpie holds its own rests and answers from them at once, and what it serves under a name may have changed there since (zaidu259434 on X: a routing group there moved off a spent Open Design, and this magpie gave Open Design's 402 again until the time it named, never asking; `TestRemoteMagpieQuotaIsAskedNotReplayed`, `TestHandAddedMagpieQuotaIsAskedNotReplayed`). Another magpie added by hand, as an OpenAI-compatible provider of the user's own name rather than the preset, is read as one by its reply: a magpie names the provider that answered or held it (`X-Magpie-Provider`, `providerHeader`; `noteMember`, also on a `quotaHeld` or `verifyHeld` answer), as no vendor does, and `keepRetry` notes it as `answeredThereHeader`, since this magpie writes its own provider into the same header of its reply and the note is kept from the client (lagrangepoint1813 on Discord: "Remote Magpie: Claude Code: You've hit your session limit" answered every model of it, from `quotaHeld`, for the five hours it named; `TestAnotherMagpieAddedByHandRestsTheModel`, asked there and held there). Its key refused, the computer unreachable, or the key's own limit there (`keyLimited`'s 429, which carries `X-Magpie-Limit-Reset`, `remoteKeyLimitHeader`), still rests it whole: #2077's reporter had a Claude Code session limit on the other magpie refuse its Qoder models here (`TestRemoteMagpieRestsTheModel`, two gateways over HTTP; `TestRemoteMagpieKeyLimitRestsTheKey`). The held try keeps that marker only as a note of magpie's own (`keepRetry` sets `keyLimitThereHeader`, which `holdWriter` never passes on), so the rest is whole however the 429 came, and the marker never reaches the agent or a magpie this one answers, which would read it as this magpie's own key limit (#2791, ggbdpq; `TestRemoteMagpieKeyLimitRestsTheRemote`, `TestRemoteMagpieKeyLimitMarkerStaysHere`). A 400, 404, 410 or 422 that says the model is retired (`retiredWords`: OpenCode Zen's 410 `ModelDeprecated` "Model exo-free has been deprecated.", whose own model list still names it; MOMO on Discord) rests only that model the same way, is retryable so a group's next member or another provider of it is asked, and is remembered (`provider.Retire`, `retired.json` beside `providers.json`): the model leaves that provider's entries in the catalog (`buildEntries`), so /v1/models, every agent's model list and the found groups go without it, until a request on it is answered again (`Unretire` in `servedCandidate`) or a week has passed. A refresh of the vendor's list doesn't bring it back early, since that list is where it still is. A `provider/model` request for it is still sent. A 400 or 422 that says this upstream's API can't take the request's shape (`shapeWords`: xAI's 422 "unknown item type" (#350), OpenAI's "Unknown parameter", and a limit of a model's own on tool schemas, OpenCode Go's 400 "JSON schema exceeds the maximum nesting depth of 10 levels" on muse-spark-1.3-contributor, #1870), or that it is served on another API than the one asked (`wrongEndpoint`, once the member has tried every API it has a URL for: #2670, a relay with a Chat URL alone refusing tools with reasoning and `none` too), rests nobody: the next candidate is asked once (`shapeRefused`, `failShape`), and the last one's error reaches the agent. A request missing what every API requires ("field required") isn't one, nor is a 200 that mentions it. A model asking for an earlier reply's reasoning the history doesn't have (`reasoningBackRefused` in `thinking_back.go`: Command Code's Beam answering "Missing required parameter: 'messages[1].reasoning_content'" to a second turn, DeepSeek's and Kimi's words for their tool turns) is one too, after any refill `refuseThinkingBack` makes: the request is whole, and another member's model may not ask for it (EDwinpzy on Discord, `TestGroupFailsOverAMissingReasoning`); a missing `messages` or `model` still stops (`TestMissingReasoningIsNotABadRequest`). Command Code's Provider API turning a request away with nothing but a trace id (`unsaidWords`: `{"message":"invalid request error trace_id: ","type":"invalid_request_error"}`, a 400, or a 422 before) is handled the same way: it turns away a request whose history and asked-for output together are over a limit below the model's listed context (the reporter's A/B: one ~748K-token agent conversation answered 200 with `max_completion_tokens` 64000 and this 400 with 384000, the model's listed max output), which another member's model may take, and the key is fine (#2313, `TestGroupFailsOverCommandCodesBare400`). Its overflow, which names the model's context length before the trace id, and an error that names a `param`, aren't one. A relay's own cap on one request's input that says so (`tooLongRe`: B.ai's 400 "Input token exceed the limit", on a 380K request under the model's 1M window; #2445, worksyang) is taken as an overflow (`overflowed`), which no word list of `retryable` matched: a group's next member that may hold the request is asked (`withRoom`, `failOverflow`), nobody rests, another account of the same model isn't asked, and with no member left the agent is told the conversation is too long, so it compacts. The conversation remembers the refusal (`noteOverflow` in [`affinity.go`](../../internal/gateway/affinity.go), by its stick key and the member's provider and model, with the request's size): its next request at least as large asks that member after the others (`behindOverflow`, after `roomy`, so after a rule that named it), behind and not out, until the member answers one (`forgetOverflow`) or the conversation shrinks below the refused size. Another conversation, and a 413 byte cap, are not affected (#3453, `TestOverflowRefusedOnceIsAskedLast`). A rate limit worded with input tokens (`paceWords`) isn't one, and a plain bad request is still asked of nobody else (`TestRelayInputCapGoesToTheNextMember`). Chinese that names the input rather than the context is one too (`tooLongRe`'s third line: a group member's 400 「内容太长了,请精简输入或开启新对话」, z.ai's 「Prompt 超长」, iFlytek Spark's 「…字数太多,需要精简输入」, 「输入长度超过限制」); before, it was a plain failure that rested the member and asked no other (#4420, MYCF711; `TestChineseInputTooLongGoesToTheNextMember`). Each names what was sent beside its length, so a field's or the reply's length isn't one, and Chinese pace words (速率, 频繁, 并发, 每分钟…, in `paceWords`) beside them make it a rate limit, not a size (`TestChineseNotTooLong`). A 400 or 422 whose message speaks only of length, without naming what is long (`lengthWords` in `fallback.go`: 太长, 过长, 精简, 开启新对话, "too long", "too large", "shorten"), with no pace word and no part of the request named (`partWords`: a picture, a file, the reply, a field), is the request too long for that member once the request is past half its window (`saysLength`, `lengthMargin` 0.5 in `tooLongUnsaid`), not the 1.2 margin a refusal that says nothing needs: a vendor whose own ceiling is under the window it declares answered 「内容太长了…」 at ~730K of a declared 1M (#4420, MYCF711). It then goes as an unsaid overflow goes: to a member with room, nobody resting, else to the agent as "prompt is too long" (`TestLengthWordsPastHalfTheWindowGoToTheNextMember`). A refusal that says nothing of length is read as an overflow only from the vendors seen to answer one so, by the plugin that serves them (`unsaidStatus` in `fallback.go`: Devin's 5xx, Qoder's, Qoder CN's, WorkBuddy's and WorkBuddy AI's 400/413/422, Factory's 413), once the request is 1.2 times past the window (`unsaidMargin`), the window no less than the most the model has answered here or its list's `max_context_window`; any other provider's failure, a custom relay's, OpenAI's or Anthropic's, reaches the agent with its own status and words, as does a transport failure from any vendor (#5486, NEKO-CwC; `TestRelayFailureKeepsItsOwnWords`, `TestUnsaidVendorsStillOverflow`, `TestTransportFailureIsNotTooLong`). Under half the window the same words are left as the vendor's error. A subscription account that fails any other way with a window full, by magpie's latest reading of its windows, rests until that window renews. A 401 or 403 is the exception: one that names a quota is out of quota already (`usedUpWords`), and one that doesn't is about the key or the request, so it rests on the backoff ladder whatever the reading says (plugins#243, zygs1083-dotcom: a Factory account read at 98% sat out its week over one plain 403; `TestPlain403DoesNotRestUntilTheWindow`). A plain 403 (`plainForbidden`: no quota, credit, rate, verification, restriction or model not served) from a second key or account of the same provider, model and reasoning in one request is the request refused, not each account: neither rests, the first one's rest and counted failure are taken back (`forbiddenAlike`, `unforbid`), and the provider's other mates are asked last (`matesLast`). Before, that one request walked every account of the provider into backoff (`TestPlain403OnTwoMatesRestsNeither`). One account's plain 403 alone still rests it. A 500, 502 or 503 that says nothing of why (`plainUnavailable`: no quota, credit, rate, overload, proxy down, ChatGPT reset or protection refusal, and some words) is read the same way when a second account of the same provider, model and reasoning gives it in the same words and status, ids left out (`refusalWords`), and the provider answered another request within `answeringLately` (5 minutes, `answeredLately`, noted in `servedCandidate`): neither rests, and the last one left isn't asked again after a moment (`sameRefusal`). Before, one agent's request an upstream always refused (mycf_711 on Discord: 127 of a provider's 128 503s were "AIError AI服务异常", for an empty tool schema) walked every account into backoff and the other agents found them all resting. One account's 503 alone, 503s in other words, and alike 503s from a provider that answered nothing lately (an outage) still rest as before, so an outage is backed off once 5 minutes have passed since its last answer (`TestPlain5xxOnTwoMatesRestsNeither`). Both quota rests and window rests are held to `longestQuota` (8 days), so a reset time read wrong (a year off) doesn't bench the account for that long. The next candidate is then tried. A failed provider waits `fallbackCooldown` (1 minute) at the back. An overload is no failure of the account's (`vendorOverloaded`: a 529, the ChatGPT backend's `server_is_overloaded` and Anthropic's `overloaded_error` among them, or a 5xx whose words say overloaded, as Gemini's 503 does): its model rests on that account `overloadRest` (30 seconds), or as long as a Retry-After asks up to `overloadRestMost` (a minute), every time alike, and no failure is counted on the backoff ladder (celestial_eagle_99230 on Discord: eight Codex accounts each rested up to the 10-minute cap for ChatGPT's overload, "failed 5 times in a row", leaving nothing to answer). A WorkBuddy account the vendor restricted (#1849: 403 `{"code":11140,"msg":"request illegal","displayMsg":{"en":"Your account has been restricted due to unusual activity",…}}`) rests `restrictedRest` (2 hours) as `restricted` (`failRestricted`), not the minutes of an unknown failure: only WorkBuddy lifting the restriction, after the user's appeal, brings it back. Both shapes are known: the built-in's `wbExplain` and the plugin's `explained()` (0.1.17, the mover's `min`) end the error with `provider.WBRestrictedHint` (`restrictedSaid`), and the vendor's own body, its code 11140 or its words (`provider.WBRestricted`), counts only from a WorkBuddy candidate (`restrictedRefused`, `isWorkBuddy`), as another vendor's 11140 is its own. Bare "request illegal" isn't matched. A vendor's risk control reads the request as well as the account, so a restricted account (`failRestricted`, ZCode's 3012 too) walls its provider off for the rest of the request (`riskRefused`, `elsewhere`; `busyNow` and `roomy`'s left-out list too): none of the provider's other accounts is sent it, a group's other provider is asked, and with none left the agent is told and the account rests, the last one left too. Before, one request was sent on from account to account and each was restricted in turn (_teamtaylor_ on Discord; `TestRiskRefusalNotSentToTheProvidersOtherAccounts`, `TestRiskRefusalAloneIsToldAndRests`). The next request still goes to the provider's next account. A remote magpie's restriction walls off nothing (`remoteModelRest`). WorkBuddy's 11128 channel refusal stays `promptRefused` and rests nobody. The Routing page names it "account restricted by the vendor", says the appeal is the way back, and gives the account's row a button that lifts the rest (`/api/gateway/unrest`) once the vendor has. Every other rest a key or account takes (quota, rate limit, retry-after, a failure's backoff) can be lifted by hand the same way (#1869): "Try now" on its row on the Routing page and beside its rest note in the provider's key list. It ends the rest, and with Sink on puts the key back from the back of the order; the backoff count stays, and a refusal after it rests the key again the usual way. Every lift before its time (Try now, `UnrestAll` for a replaced key, `renewed` for windows that renewed) is noted by its rest key (`restingUntil.lifted`) and handed to the Routing page in the trace (`TraceState.Lifted`, `lifted` in `/api/gateway/trace`), and a lift wakes a page waiting on the trace though no route changed (`trace.lifted`). The page stops showing a rest or a sink found before its lift, wherever the lift was asked for (zoecats on Discord: Try now in the provider's editor left Routing at 429 until a restart; `TestTryNowToldToTheRoutingPage`, `routing-lifted-elsewhere.test.cjs`). With another magpie serving the gateway, Try now lifts nothing (#3555). The vendor's safety filter refusing a reply rests nobody, whether it refuses the turn before any of the reply is said or once some of it has been said (`refused`, `refusedAfter`). So does one said in a stream a client is answered whole from (a Codex account is streamed upstream for a `stream:false` Responses, Chat or Messages request): each decoder gives the refusal's error event status 400 and its code (`filterRefused`), a whole reply it cut is answered the refusal rather than its words so far, and Anthropic's error shape, which has no code, carries it in `refusedHeader`; before, it was answered 502 `api_error`, asked again, and each account rested (#3274). `restAfterMarked` itself rests nobody, and counts no failure, for a 400 whose error object `policyRefusal` reads as a refusal, by its code, never by words a body may echo of the request. A refusal after the reasoning went through as it came (a vendor whose reasoning is never held, a trusted DeepSeek member, a hold that timed out) but before a word of the answer or a call is handed over (`refusalHandover`, `refusal_handover.go`): when the agent streams Anthropic Messages, Chat Completions or Responses, another candidate is left and `refusalAsksAgain` allows one more (`handsOver`), what passes is read event by event (`passOver`); the refusal's event and everything after it are not sent, an Anthropic block still open gets its `content_block_stop`, the try fails as a refusal with nothing said (`failRefused`, nobody rests, `matesFirst`), and the next try writes through `spliceAfter`, so its stream is the same reply: Anthropic's `message_start` is dropped and its block indexes go after those sent; Responses' `response.created`/`in_progress`/`queued` are dropped, `output_index` goes after the items sent and `sequence_number` goes on from the last one sent; Chat chunks go as they come. Once text or a call has gone, a refusal is the agent's as before (`refusalAfter`). Without another candidate nothing changes. A Gemini stream is not handed over, the reasoning item of a Responses stream handed over gets no `output_item.done`, and the next reply's `response.completed` lists only its own output (#4604). Zhipu's `finish_reason` `"sensitive"` and error 1301 (敏感), DashScope's `data_inspection_failed` and Volcengine Ark's `*SensitiveContentDetected` are refusals (`filterReasons`, `sensitiveCode`). Its note on the try (and in the error the agent gets when nobody is left) is the vendor's reason, with Anthropic's `stop_details` category and explanation when it gave them (`refusedDetail`, #1768: "safety filter: refusal (category cyber)"); none is made up when it gave none. `stop_details` is carried through the IR (`Event.StopDetails`), so a Claude subscription run through the claude CLI and a translated Anthropic route keep it for an Anthropic client too. How many more candidates a refusal before any of the reply is asked of is Settings' `RefusalRetries` (`refusalAsksAgain`, counted per request in the candidate loop; a group's other members count too): unset, every one left (#248); 0, none (#1925, DD on Discord). A Claude subscription account's refusal of a conversation of `retellMost` (100K) tokens or more leaves the subscription's other accounts out (`tooBigToRetell`, `otherThanClaudeAccounts`): each would be a new Claude Code told the whole conversation, all of it written to that account's cache again, for a refusal about the content it most likely gives too (Aisiverto on X: a 900K conversation refused and told again cost a Pro account most of its 5 hours). The size is the larger of what the account counted and `estimate`; other members are still asked, and a smaller conversation still goes to the next account (`TestClaudeSubscriptionBigRefusalNotToldAgain`, `TestClaudeSubscriptionRefusalMovesToNextAccount`). When nobody is left, an agent on Anthropic's Messages API gets the held refusal itself, the vendor's 200 with `stop_reason` `refusal` and its `stop_details`, streamed or whole (`holdWriter.handBack`), since that is what Claude Code switches to its fallback model on; a 400 is only an API error to it. Codex and Chat clients still get `failTo`'s 400 (`refusedStatus`), which they don't ask again for. `TestRefusalRetries*` in [`refusal_retries_test.go`](../../internal/gateway/refusal_retries_test.go) cover keys, a group and the Claude subscription. The ChatGPT backend's 502 "response protection is unavailable" is about the request's content, not the account: the same history fails the same on each of its accounts and models. It rests nobody, isn't tried again after a moment, and isn't asked of the provider's other accounts or models; another provider left in a group is asked once (`protectionRefused`, `elsewhere`). One cause is known (#1270): a history that replays the backend's own `web_search_call` in a request that doesn't declare the `web_search` tool is refused so, whatever the account, model or turn (a plain turn, a thread's description, a compaction, Codex's own text compaction for a custom provider with `tools: []`). Every request to the ChatGPT backend with such a history therefore declares cached-only search (`{"type":"web_search","external_web_access":false}`, `provider.DeclareSearch`): an account's in `codexBody`, Codex's own sign-in relayed in `codexUpstreamOn`. It goes in the tools, or for Responses Lite (its header, `reasoning.context` `all_turns`, or an `additional_tools` item already there), which refuses a top-level `web_search`, in the `additional_tools` item. A request that offered no tools gets `tool_choice` `none` so the model can't search; one with a forced choice keeps it. A history without a search, or a request that declares search already, is relayed unchanged; Codex's own `web.run` (a function in the `web` namespace, which Codex offers in place of the hosted tool on a Responses Lite model or with its standalone web search on, and runs through `/alpha/search`) counts as declaring it, since the backend refuses a request carrying both `web.run` and the hosted `web_search` (Savin on Discord, Codex 0.163.0-alpha; `TestSearchedConversationUnderWebRun`). siwc, API-key requests to openai.com and the legacy `/responses/compact` are left as they were. The ChatGPT backend also turns a whole request away when one tool name in it, a call's in the input or a tool's in `tools`, is outside `^[a-zA-Z0-9_.-]+\z` (400 "Invalid 'input[83].name': string does not match pattern"; wing3556 on Discord, on a compaction): a call another provider's model wrote with a space, a colon or non-ASCII in its name, kept in the history beside its "no such tool", failed every later turn on Codex. Every request to it sends each such name as `provider.CodexToolName` makes it (each refused byte `_`, cut to 55, `_` and 8 hex of its sha256, the same on every request), a valid one unchanged and a body with none byte for byte (`CodexToolNames`): an account's in `codexBody`, Codex's own sign-in's in `codexUpstreamOn` (`/responses/compact` too). A tool the agent declared under such a name is called back by its own: a translated reply through `decoderFor` (`codexNamesBack`), a relayed Responses reply through `nsTidy.back` (`codexRenamedIn`; `TestCodexToolNamesTheBackendTakes`). Namespaces, the OpenAI API, Azure and Copilot are not covered (#4875). Command Code turning a model away for its Zero Data Retention setting (its plugin's switch, 0.1.14, which sends `x-cmd-zdr: 1`; magpie-community/plugins#246) is a refusal of that request's setting, not of the model or the account: the Provider API's 422 with `"code":"cmd_zdr_no_providers"` and the 400 the plugin makes of Go's error line with `"type":"cmd_zdr_no_providers"` (`zdrCoded`, matched as the error's code or type, never by its words, whose "…a different model.","type":"invalid_request_error" read as a model unserved and rested the model on the account). `keepRetry` notes it beside the error (`zdrHeader`), since the error the agent gets may keep no code (Anthropic's shape, or the 400's numeric code). It rests nobody, anywhere (`restAfterMarked` returns `by: "off"`), so the model answers as soon as the switch is off; it isn't asked of the provider's other accounts at that model, which carry the same header (`notMates`), nor again after a moment; another member, the provider's other models among them, is asked once, and with none left the agent gets Command Code's words (`TestCommandCodeZDRRefusalRestsNothing`, `TestZDRRefusalNeverRests`). Another vendor's refusal in the same words, without the code, still rests the model (`TestZDRRefusalIsCommandCodesCodeOnly`). 5. The last candidate's error reaches the agent, with one exception for a group (#1418, `patience.go`), which a plain provider shares once its same-one retries are spent (below). When every member has failed in a way that passes (`busy`, its statuses `busyStatus`: 408, 500, 502, 503, 504, 529, or Cloudflare's 520 to 524, which a relay behind it answers with now and then (`TestCloudflareErrorIsTriedAgain`; the same-one retries of `passing` read the same list), that isn't a proxy, a quota, response protection, or an upstream that answered a stream request with a whole reply, which fails the same however often it is asked (`didNotStream`; the same-one retries of `passing` leave it alone too, `TestStreamlessMemberIsAskedOnce`), or a 429 that is a short rate limit, not a plan or credit, nor an account's token wall: a vendor code in `wallCodes`, Raccoon's `user_model_rate_limited`, which rests as a rate limit but is asked again neither here nor by the same-one retries, as each ask draws on the bucket it waits for; plugins#512, `TestTokenWallFailsFast`), and nothing of the reply has been sent, the members that failed so are asked again in turn after a pause (`replan`). The pause is `retryPause` doubled each round up to `replanLongest()` (30 times `retryPause`, 30s), and never shorter than the soonest Retry-After; a member whose Retry-After ends past the pause is asked after the others. This goes on while the group's `Patience` lasts. A member of a group in the group uses the innermost that sets `Patience` (`innerPatience`, #2410), as FirstToken (#2246) and Sink (#2255) do; unset falls back to the group asked for, and an inner `PatienceOff` skips replan for that member (`TestNestedGroupPatienceThroughOuter`, `TestNestedGroupPatienceInnerOff`, `TestNestedGroupPatienceFallsBackToOuter`). `replanRounds` (12) is only a backstop that never comes first: the pauses alone add up to `PatienceLongest` in 11 rounds (with 6, a group set to 240s gave up after 90s of pauses, real-jacket on #1418; `TestPatienceIsUsedUp`). The budget is the group's `Patience`, counted from the first time every member had failed, when the agent would have had the error (`waitFrom`; `Group.Waits`: 0 is `PatienceDefault`, 60s; -1, `PatienceOff`, turns it off; at most `PatienceLongest`, 240s). A pause that would end past the budget isn't taken, and the agent gets the error; a member the vendor said is back within a second past its budget (read in whole seconds) is asked as the budget ends (`TestReporterResetFitsTheDefaultPatience`). The last member out of its quota or credit (not `busy`), after an earlier member failed in a way that passes, has those earlier ones asked again the same way, and rests as they did (`lastSpent`): before, the agent had the relay's moment of 503 while the relay would answer a moment on (`TestGroupRelayBlipDoesNotEndOnSpentLast`). While another member is busy too, the last one isn't first tried again alone (`passing`): the members take turns, and once the budget has begun, the same-one retries aren't taken either. While the budget lasts, the last candidate's failure is held (`newHoldWriter`), and a streaming agent is kept alive through the pause with SSE comments (`pauseAlive`). The try is traced with `Again` (the pause), `Replan` (how many are asked again) and `Patience` (the budget in seconds). The group editor's "Every member busy" row sets it. A plain provider (a `provider/model` request, its accounts and fallbacks the candidates) first takes the same-one retries `passing` gives the last one left: `lastRetries` for a busy vendor, `rateRetries` for a rate limit, each pause `retryPause< patience=2m|off|default`; the provider editor shows no row for it and its save keeps it, `TestProviderSaveKeepsPatience`), unset `singlePatience` (`PatienceDefault`, 60s), counted from when the agent would have had the error, so it works with no setting and the user's value wins either way (`TestSingleProviderOwnPatienceWins`; ChatGPT's reset of a large request, `codexReset`, is left out: Codex is told it at its 503 with what may help, as `codexBusy` leaves it). A provider's own Patience is for a request to it alone: a group it is in, set or unset, keeps the group's (zoecats on Discord: a local relay's short 429 went straight to Claude Code once the few retries were spent). So a 429 whose Retry-After is 20s is waited out, the stream kept alive past `keepHeldAfter`; one of an hour, a quota, credit or plan limit, a 401 or 403, a refusal, response protection's 502 and `didNotStream` are not `busy` or don't fit the budget, and reach the agent at once as the vendor said them. Its tries are traced with `Again` alone, no `Replan` or `Patience`, so the Routing page tells it as the last one left asked again rather than as a group's members (`TestSingleProviderWaitsOutAShortRateLimit`, `TestSingleProviderPassesALongLimitThrough`, `TestSingleProviderAgentGoneInTheWait` in [`single_busy_test.go`](../../internal/gateway/single_busy_test.go)). Codex's own one-account relay (`codexUpstreamOn`, below) doesn't join it: its request is relayed unchanged outside the candidate loop, and the backend's 429 is always the plan's usage limit (`codexBusy` never retries one), so the short rate limit this waits out doesn't arise there; its overloads keep their `lastRetries` and then the subscription's fallbacks. An agent that goes away in either pause (the same-one retry's or a group's replan) ends the request there with 499: nobody is asked again, and the try whose pause it was is marked `Gone` (#1894, heng91: a relay down while its proxy was off, the agent's window closed). The Routing page says the agent canceled the request before the retry and lists it as canceled, rather than ending its story on "tried again in 2s", a retry that never came (`TestAgentGoneInTheRetryPause`, `routing-agent-gone.test.cjs`). A try that answered is recorded (`served`, `answered`) for routing, affinity and usage. A try is added to the route's `Tries` only as it is asked, so a later try is the record that the gateway went on from this one, and the Routing page tells what came of a try from that, never from where it stood in the order (#2281, xishuchkui-code: an Antigravity 502 empty reply that went on to the next account was told as "an error another account wouldn't fix, so Claude Code gets it"). The one case the record can't show is the last try left out of its allowance after an earlier failure that wasn't one, where the agent is told the earlier error: that try is marked `Earlier` (`routing-went-on.test.cjs`). diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index ace43aa71..06a112cec 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -648,16 +648,28 @@ confirmations and menus interactive through redraws. `closeModal` releases that background as soon as the close animation starts, so clicks reach the page while the editor fades away. Opening an editor during that animation protects the background again. `ux-safety.test.cjs` checks these transitions. -Routing's New group buttons share `newGroup`, which asks before replacing a +Routing groups have a page of their own, `#view-groups`, beside Routing +under Models (11-06; below every request on the Routing page they were a +long scroll down). The routing plugin adds both pages, and `routingPage` +draws the groups' section (`.rt-gsec`) into the second one's `#rtGroups` +(`window.routingGroupsHome`, again after its Try again), so one draft and +one `dirty` hook (`magpie.call("routing", "dirty")`) serve both; `rtView` +in app.js asks it on leaving either. Its toolbar is the filter, how many +groups there are and how many are on, then Templates, Import, Select and +New group (`text primary`); the list follows, then Settings (found groups, +the names agents' lists show), then the providers routing over several +keys. A request's group or pool link (`goRouting`) opens the page first, +then brings the row into sight when the reader's click asked for it. +The window opened with `view=groups&newgroup=` (`mainView` keeps +`view=routing&newgroup=` too) opens a new group of that model +(`routing-groups-page.test.cjs`). Its tab sits in the sidebar only: the +header's row has no room for it (at 860px it pushed the logo out, +`brand.test.cjs`), so there app.css hides it, `markNav` lights Routing's +tab for both pages, and Routing's head shows `#rtToGroups` instead. +The page's New group goes through `newGroup`, which asks before replacing a dirty group draft; Cancel retains the draft and Discard opens the new editor. `newGroupWith` applies the same guard when creating a group from a model and -waits for `show` to accept navigation before creating its draft. -The Routing page's head also has Routing groups (`#rtGoGroups`), since the -groups sit below every request. Its click goes through `scrollOnPurpose`, -brings `.rt-gsec` to the top of the view and focuses it; the page's layout is -unchanged. `fitGo` gives it only the head's spare room: named, its arrow -alone, or left out, so nothing else in the head moves or wraps for it -(`routing-groups-jump.test.cjs`). +waits for `show("groups")` to accept navigation before creating its draft. Live, the Routing page's card (its head, story and context window) tells of one request, `cur`, chosen by `told()` in `plugins/routing/client.js`: it stays on the request it tells of until that one is done, then goes to the diff --git a/docs/subsystems/plugin-runtime.md b/docs/subsystems/plugin-runtime.md index eb7a85f78..08fd09ff5 100644 --- a/docs/subsystems/plugin-runtime.md +++ b/docs/subsystems/plugin-runtime.md @@ -28,7 +28,7 @@ the plugin host) are a different thing; see | Ctx | What `Apply` gets: `OnDispose(f)`, `Contribute(slot, key)`, `Provide(name, v)` (withdrawn when it goes), `Service(name)`, and its composed `Config`. Disposers run in reverse, each one's panic logged and the rest still run. | [`pluginrt.go`](../../internal/pluginrt/pluginrt.go) | | plugins.yml | `appdir.Config()/plugins.yml`: `preset` (`essentials` or `all`; `all` unless the user picks Essentials), `settled` (the defaults the file was last brought up to) and `plugins`, rows of `{id, enabled, config}` holding only what the user set. | [`config.go`](../../internal/pluginrt/config.go) | | Settings schema | `SchemaOf(Settings)` makes a JSON Schema object of the struct, in its fields' order (`x-order`): each exported field with a json name is a setting, of `bool`, an int, `float64` or `string`, with tags `title` (English; the window translates it), `description`, `enum` (comma separated) and `min`/`max`. Its values are the defaults. A field a form can't draw, or a tag that doesn't parse, panics at `Register`. `Schema.Validate` takes a value only as the schema allows it (a JSON float64 or a YAML int for an integer); `SetConfig(id, config)` writes the user's row through it, and `Compose` leaves out a value edited into plugins.yml by hand that it doesn't allow, so the default stands. | [`schema.go`](../../internal/pluginrt/schema.go), [`config.go`](../../internal/pluginrt/config.go) | -| Built-in plugins | `groups`, `library`, `otel`, `sessions`, `warmups` (P0), `gateway` (P1), the Gateway page, which is Essential and in use while a gateway key is there (`access.List`), and `routing` (P2), the Routing page, Essential and in use while the user has a routing group, since the page is where groups are made and changed. `rotation` (P3), the routings besides Smart, is Essential and in use while a provider or group is routed by one of them. `middleware` (P3), the JS gateway middleware, is Essential and in use while plugins.json has a middleware on (`middleware.On`). `redact` (P3), privacy masking, is Essential and in use while Settings → Privacy asks for any masking (`masking.Wanted`). `search` (P3), magpie's web search, is Essential and in use while a search API is set up or a searcher is picked. `budget` (P3), key limits, is Essential and in use while a gateway key has a limit. `usage` (P2), the Usage page, is Essential too, with no `InUse`: what it shows the gateway counts anyway, and the tray panel's Usage tab still shows the allowances with it off. The Gateway page's one setting, `callsPage` (10, 20, 50 or 100; 20), is how many recent calls the page shows at a time. The other five aren't Essential. Each one's `InUse` counts what the user made with it: routing groups not Auto and not hidden, library items given to agents, a collector sent to, gateway conversations recorded, warm-ups and check-ins on. | [`plugins/`](../../plugins) | +| Built-in plugins | `groups`, `library`, `otel`, `sessions`, `warmups` (P0), `gateway` (P1), the Gateway page, which is Essential and in use while a gateway key is there (`access.List`), and `routing` (P2), the Routing and Routing groups pages, Essential and in use while the user has a routing group, since the second page is where groups are made and changed. `rotation` (P3), the routings besides Smart, is Essential and in use while a provider or group is routed by one of them. `middleware` (P3), the JS gateway middleware, is Essential and in use while plugins.json has a middleware on (`middleware.On`). `redact` (P3), privacy masking, is Essential and in use while Settings → Privacy asks for any masking (`masking.Wanted`). `search` (P3), magpie's web search, is Essential and in use while a search API is set up or a searcher is picked. `budget` (P3), key limits, is Essential and in use while a gateway key has a limit. `usage` (P2), the Usage page, is Essential too, with no `InUse`: what it shows the gateway counts anyway, and the tray panel's Usage tab still shows the allowances with it off. The Gateway page's one setting, `callsPage` (10, 20, 50 or 100; 20), is how many recent calls the page shows at a time. The other five aren't Essential. Each one's `InUse` counts what the user made with it: routing groups not Auto and not hidden, library items given to agents, a collector sent to, gateway conversations recorded, warm-ups and check-ins on. | [`plugins/`](../../plugins) | The boundary is checked by `TestPluginsImportOnlyCore`: no package outside `plugins/` imports one (but `main.go`, through `plugins/all`), a plugin never @@ -201,7 +201,7 @@ the core. The seven other routings are the built-in plugin `rotation`'s. | `Register`, `Find`, `Apply` | `Register(routing, s)` serves a routing until its remove; registering again stacks, and the last one serves. `Find("")` is `Smart` always. `Apply` fails open: a strategy that panics, or answers what isn't a permutation, leaves the pool in its listed order, logged. Every route is still tried. | [`routes.go`](../../internal/routes/routes.go) | | Strategies | `Smart` (core), and `Ordered`, `Rotate`, `LeastUsed`, `Pace`, `Weighted`, `FreeFirst`, `Fastest`, `Cheapest` (a group's only: `provider.normalize` drops `cheap` from a provider), `Drain` and `FreeExpiring` (a group's only too: free quota first, the soonest lost first, then the paid as `Smart` orders them) in `routes.Builtin`. `Drain` remembers the seat each pool is on (`drains`). `Rotate` keeps a turn per pool and `Weighted` a smooth weighted round (`Round`, `MoveRound`), both moved out of the gateway, and `Fastest` a probe count per pool, so a seat not measured lately gets one request in `ProbeEvery`; `Forget` clears them, `Drain`'s too. | [`strategies.go`](../../internal/routes/strategies.go), [`round.go`](../../internal/routes/round.go) | | Off | A routing no strategy serves is its listed order. `routingOf` in the gateway reads it as `order` wherever the core asks about a routing (a turn's mark, `sinks`, a rotate group's sessions, a group's heads), so nothing of the routing is left half on. | [`routing.go`](../../internal/gateway/routing.go) | -| `plugins/rotation` | Requires `providers` and `gateway`, `Essential`. Apply registers every `routes.Builtin` and removes them when turned off. `InUse` counts the providers and groups providers.json routes by one of them (`provider.Routings`, the file alone, not the catalog); an unreadable providers.json is an error, so it stays on. The gateway's `KeepFresh` watches providers.json too, so a routing set from the CLI or the TUI turns it on within 2s. Off, the window's routing pickers (the provider editor, the Routing page's pools and groups) offer Smart alone: their options are marked `data-feature="rotation"` (`routingSegs`). | [`rotation.go`](../../plugins/rotation/rotation.go), [`provider.go`](../../internal/provider/provider.go), [`app.js`](../../internal/gui/assets/app.js) | +| `plugins/rotation` | Requires `providers` and `gateway`, `Essential`. Apply registers every `routes.Builtin` and removes them when turned off. `InUse` counts the providers and groups providers.json routes by one of them (`provider.Routings`, the file alone, not the catalog); an unreadable providers.json is an error, so it stays on. The gateway's `KeepFresh` watches providers.json too, so a routing set from the CLI or the TUI turns it on within 2s. Off, the window's routing pickers (the provider editor, the Routing groups page's pools and groups) offer Smart alone: their options are marked `data-feature="rotation"` (`routingSegs`). | [`rotation.go`](../../plugins/rotation/rotation.go), [`provider.go`](../../internal/provider/provider.go), [`app.js`](../../internal/gui/assets/app.js) | The user's own routing groups are the `groups` plugin's on this point. The groups magpie finds (a model two providers serve, `auto/`) stay the diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 276197a1a..2b39ac4a7 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -56,7 +56,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Used-up switch | When the account Codex or Claude Code is signed in to has used its allowance, the agent is signed in to the next account that is on and has room (#208). Claude Code whose requests go to magpie's gateway (`ClaudeThroughMagpie`: its settings' `ANTHROPIC_BASE_URL` is the gateway, either sign-in) is not moved: the gateway already sends its requests to an account with room, and moving the sign-in only took away what the user signed it in for, such as claude.ai connectors (oreoft on Discord set it back more than ten times; `TestClaudeRoutedThroughMagpieKeepsItsSignIn`). Not routed, or with *Only switch Claude Code's sign-in*, it still moves. Codex's sign-in goes back to the account it moved off once that has room again, as the gateway's Smart and In order give it requests again; routed Until used up it doesn't, as the gateway keeps the requests on the next (`routes.Drain`), so it stays with them till that one is used up too, as Claude Code's and a switch-only Codex's do unless routed In order (`returnsToFirst`; WalterAIBuilder on X: Codex signed back in to the first showed that one in use while the second's week was spent, `TestCodexDrainSignInStaysOnTheNext`). When every one is past its line too, it goes to the one with the most room left (`roomLeft`: the fullest stopping window's distance below the switch share, or the account's own cap when lower), when that has more than the account it is on by `roomMargin` (1 point), so two all but even accounts don't trade it each look; else it stays (StringKe in #4532, after cswap's `best`; `TestNextLoginTakesTheMostRoomWhenAllArePast`). A Claude account on overages (/usage's "You are currently using your overages…" line) is read with its windows and a spent *Extra usage* row of text (`claudeOveragesWindow`: Used 100, ending when the last used-up window renews, else at the next reading), so it is moved off as a used-up one; before, the line made the reading an error, and the switch, which stays on an account it can't read, left Claude Code billing overages (StringKe, #4532; `TestClaudeSwitchOffOverages`). The GUI says the row *In use* in the reader's language. Routing (`Allowances`) skips Text rows, so the gateway's own choice of account doesn't count it. A model's own week (`Current week (Sonnet only)`, `(Fable)`) counts for that model in routing, not for the switch, which moves the sign-in only on windows that count every model (`usedPast`); "Sonnet only" is read as the Sonnet week, `7 days · Sonnet` counting `sonnet`, the window the `seven_day_sonnet` header keeps (#4532, `TestClaudeUsageSonnetOnly`). `magpie accounts switch next` (`NextInOrder`) takes the other accounts the agent can be signed in to (`switchable`, not lapsed), on or off in magpie as the accounts list's *Use* does, so one the agent signed itself in to, which starts off, is in the rotation (StringKe, #4532; `TestNextTakesAccountsThatAreOff`), from the one after the account the agent is on, wrapping round: the first with room, else the one with the most room left, said to be past its line; with no reading of any, it refuses rather than guess (`TestNextInOrder`). For Codex, *Only switch Codex's sign-in* (`SwitchOnly`, `SetSwitchOnly`) keeps magpie's `openai_base_url` failover out of Codex's config, so the switch is all magpie does (#1907); an unreadable providers.json reads as switch-only, so the failover is not written on a guess. For Claude, the same setting keeps the accounts to Claude Code (`Provider.KeptToAgent`): `On()` is false, so the gateway, catalog and groups serve nothing on them, while switching and usage, gated by `leftAlone` on the raw `Off`, go on. No request of a saved Claude account passes magpie then, so one Claude Code wasn't signed in to since has no reading: once the account Claude Code is on is spent, `NextLogin` reads such a spare (`readSpare`, `spareRead` in `claudeWindows`) by Claude Code's own `/usage` in the account's directory, in order and only till one has room; a spare read once is not read again, and one whose read failed waits `claudeUsageWait` (cn_Vincentzyx on X, `TestClaudeSwitchOnlyReadsUnreadSpares`). Codex's spares are read through their saved tokens and had no such gap. Claude Code on its own login is out long before a five-minute look notices (#4443: 4% left to refused in two minutes): while Claude has an account to move to, `KeepOnAnAccountWithRoom` looks at its sign-in every `claudeLookEvery` (a minute) between its full looks when `claudeLookDue`, that is when the account Claude Code is on is near out (`claudeNearOut`, `codexNearShare`; its `/usage` is then due after `claudeNearOutWait` rather than `claudeUsageWait`), or when Claude Code wrote a `rate_limit` refusal ("You've hit your … limit") into one of its sessions since that account's last `/usage` (`scanClaudeLimits`, which reads only what was appended to each `projects/*/*.jsonl` since the last scan). The refusal names no account, so it only makes the `/usage` read due (and the reading stale, `StaleAllowance`); the read decides (`TestClaudeNearOutIsReadEveryMinute`, `TestClaudeRefusalInSessionReadsAtOnce`, `TestKeepOnAnAccountWithRoomLooksAtClaudeNearOut`). | [`codex_switch.go`](../../internal/provider/codex_switch.go) | | Removing the signed-in account | `ForgetLogin` signs Codex or Claude Code in to another of its accounts first (`nextOnForget`: the first other that is on, else one whose sign-in holds, else any, never a setup-token account or one Codex keeps in another folder: `switchable`), then forgets this one; a switch that fails removes nothing (StringKe, #4532: Claude's was refused while Codex's switched). Codex's only account is signed out as `codex logout` does. Claude Code is never signed out: its last account it can be signed in to is refused with `SignedInError{Only}` (GUI code `signed_in_only`, and that account has no *Remove*). Claude Code's own credential is never deleted; the forgotten account's folder (`forgetClaudeDir`) is its own. `TestForgetLiveClaudeSwitchesFirst`, `TestForgetOnlyClaudeIsKept`, `codex-signout.test.cjs`. | | Claude Code's proxy | Claude Code on its own subscription asks Anthropic itself, through the proxy its env names. While any Claude account has a proxy of its own (`AccountProxies`), the `env` of Claude Code's `settings.json` names the proxy of the account it is signed in to (#1807): `HTTPS_PROXY` and `HTTP_PROXY` set to that account's own, else the subscription's `Proxy` (`ProxyOfLogin`), and `NO_PROXY` to loopback; none for `direct` or a SOCKS proxy, which Claude Code can't use. It is written on every switch (`switchLogin`, the user's or `SwitchWhenSpent`), when the Claude subscription is saved, and at the gateway's look every `loginSwitchEvery` (a sign-in made in Claude Code itself). Claude Code reads its env at start, so only sessions started after the switch take it. A proxy key the user set (in either case) is theirs: magpie then writes none and takes out none of theirs. What magpie wrote is kept in `claude-proxy-env.json`, and a key is magpie's only while it holds that value. A `settings.json` that doesn't parse is left as it is. Its log lines name the proxy through `netproxy.Redact`, without its user and password (#1886); the env gets it whole. | [`claude_proxy_env.go`](../../internal/provider/claude_proxy_env.go) | -| Routing groups | User-made groups from the Routing view, and auto-found groups of the same model across providers (derived, never stored). The same model is the same id as vendors agree on it (`sameModel`): lowercase, without a vendor's prefix, a version's dot as `-`, a run of spaces, `_` and `-` as one `-` (a relay listing its display name as the id, `GPT-6 Sol`, joins `gpt-6-sol`, Chill on Discord: `TestSameModelDisplayNameAsID`), and without a YYYYMMDD or Ark YYMMDD snapshot date. Every word still counts (`gpt-6`, `gpt-6-mini` and `gpt-6-sol` stay apart), as do a `:variant`, a four-digit release and OpenAI's dashed date (`gpt-4o-2024-08-06`, a pinned snapshot whose group id agents may already name). A provider kept "Only through routing groups" joins them the same way. Members are `provider/model[:effort]`. A group can nest another (`group/`); `SaveGroup` refuses loops. A group given another id (`agent.RenameGroup`: the Routing page, `magpie groups rename`, the TUI) moves every agent field on `group/` to `group/`, spelled as the agent spells it, through the same `renameRefs` a provider's rename uses, then `SyncCatalog`; before, the agents stayed on a group magpie no longer had (lucis0116 on X, `TestRenameGroupMovesTheAgentsOnIt`). A provider's or group's display name needs no move: `store` and `SaveGroup` drop the catalog, and `SyncCatalog` writes the new labels into every agent's list. `Match` takes a glob or `re:` pattern (#766), both matched in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter). What a pattern matches follows the members named, in the catalog's order, until the user drags it elsewhere (usrname1833 on Discord): `Placed` keeps the whole order, named and matched alike, and the group is read and routed in it (`placedIn`); a model matched since goes last, one no longer matched drops out, a save that sends the named members only leaves the matched where they were (`placedOver`), and a provider's or group's rename carries it (`TestGroupPatternMembersKeepTheirPlace`, `group-member-drag.test.cjs`). A found group follows the providers magpie has: one removed leaves it, while one switched off stays in it (`foundGroups`, `heldOffEntries`; one without a key, such as a plugin not signed in, finds no group), skipped by `membersIn`, left off a found group's card, logos and TUI line with a count of those switched off (XYenon on Discord: `routing-provider-off.test.cjs`, `TestFoundGroupLineLeavesASwitchedOffProviderOut`) and said as switched off in its editor and the TUI's group page, so switching one of two providers off for a while doesn't take the group away from the agents, rules and groups set to it; it is back in its place once on again (#2671: `TestFoundGroupStaysWithAProviderOff`, `TestFoundGroupWithAProviderOff`, `TestReseatKeepsAFoundGroupWithAProviderOff`, `TestFoundGroupMemberOfASwitchedOffProvider`). A found group the user changed (an `auto-…` id stored) is read without the members of providers magpie no longer has (`withoutRemoved`, not written back, so a provider back under its id is back in it), except a manual group's pick, a rule's model, or all of them when none would be left. It keeps following its model as a found group does (Kxsg79bEYFP4 on X: a third provider with the model, a plugin's, had stayed out of a group the user had changed): `SaveGroup` stores, for an `auto-…` id, what it had seen (`Group.Seen`: the models magpie found in it by that save, and those the user named, as `provider/model`), and a provider that serves the model since joins it as it is read, after the user's own members (`joined`, not written back), unless kept out of found groups. A model seen and not a member is one the user took out, and stays out; a provider's rename or a fold carries `Seen` (`mapModelRefs`), and a shared group leaves it behind. A found group changed before `Seen` was kept takes in nothing, as nothing says which of its models the user took out; its next save sees what is found then (`TestChangedFoundGroupTakesInANewProvider`, `TestChangedFoundGroupFromBeforeKeepsItsMembers`, `TestChangedFoundGroupTakesInAPluginProvider`). A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing page says them as switched off (`memberJSON.providerOff`). The user's own groups keep their members. Three templates make a group in one click from the models the user has (`provider.Templates`, `AddTemplate`; the Routing page's cards before a first group and its Templates menu after, `magpie group template [kind] [name]`): `smart` sends a hard turn to the strongest model and an easy one or a compaction to a cheap one, asked by a classifier (the decision API when there is one, else the cheapest priced model that doesn't reason); `thrifty` starts on two cheap models of different providers and sends high reasoning to the strongest; `steady` fails over between the strongest model of up to three providers. A model is weighed by its maker's list price when known, else what its provider charges, else by its id's size words (`sizeOf`); one over `tooDear` (USD 100 a million output tokens) is never picked. A template that can't be made says what is missing (`Need`). It is saved under a name and id no group has (`freeGroupName`, shared with `CopyGroup`), never over one. A group is shared as text (`ShareGroup`, a group row's Copy to share): JSON marked `"magpie": "routing-group"` with a format `version` (`ShareVersion`), holding the group's members as it names them, patterns, routing, rules, classifier and settings. A group holds only `provider/model` ids, never a key, account or address, and the derived matches, found/hidden/off flags and the rules that hold by a folder (a path on the sharer's machine, `Rule.Folders`) stay behind; a pasted one is left out too. `ImportGroup` (the Routing page's Import, `POST /api/groups/import`) reads it with words or a code fence around it, refuses another text, a newer format or none (`ShareError`, said in the reader's language). A member whose provider the importer has is kept; else the same model (`AutoGroupOf`) under the first provider of theirs that serves it (`Instead`); else it is left out and named (`Missing`), with the rules that send to it, its place among the off and fast members, and a classifier gone takes the intent rules and auto effort with it. Nothing is added when no member is left; what is added gets a free name, never replacing a group. A group of patterns only that match nothing now (a plugin's models not listed) has no members: `/api/groups` says them, and an unmakeable template's, as `[]`, never `null`; the Routing page reads the response through `groupsFrom` and draws a group it still can't draw as one row saying so, so one bad group never hides the rest (#1585). | [`group.go`](../../internal/provider/group.go), [`grouptemplate.go`](../../internal/provider/grouptemplate.go), [`group_share.go`](../../internal/provider/group_share.go) | +| 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 groups page, `magpie groups rename`, the TUI) moves every agent field on `group/` to `group/`, spelled as the agent spells it, through the same `renameRefs` a provider's rename uses, then `SyncCatalog`; before, the agents stayed on a group magpie no longer had (lucis0116 on X, `TestRenameGroupMovesTheAgentsOnIt`). A provider's or group's display name needs no move: `store` and `SaveGroup` drop the catalog, and `SyncCatalog` writes the new labels into every agent's list. `Match` takes a glob or `re:` pattern (#766), both matched in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter). What a pattern matches follows the members named, in the catalog's order, until the user drags it elsewhere (usrname1833 on Discord): `Placed` keeps the whole order, named and matched alike, and the group is read and routed in it (`placedIn`); a model matched since goes last, one no longer matched drops out, a save that sends the named members only leaves the matched where they were (`placedOver`), and a provider's or group's rename carries it (`TestGroupPatternMembersKeepTheirPlace`, `group-member-drag.test.cjs`). A found group follows the providers magpie has: one removed leaves it, while one switched off stays in it (`foundGroups`, `heldOffEntries`; one without a key, such as a plugin not signed in, finds no group), skipped by `membersIn`, left off a found group's card, logos and TUI line with a count of those switched off (XYenon on Discord: `routing-provider-off.test.cjs`, `TestFoundGroupLineLeavesASwitchedOffProviderOut`) and said as switched off in its editor and the TUI's group page, so switching one of two providers off for a while doesn't take the group away from the agents, rules and groups set to it; it is back in its place once on again (#2671: `TestFoundGroupStaysWithAProviderOff`, `TestFoundGroupWithAProviderOff`, `TestReseatKeepsAFoundGroupWithAProviderOff`, `TestFoundGroupMemberOfASwitchedOffProvider`). A found group the user changed (an `auto-…` id stored) is read without the members of providers magpie no longer has (`withoutRemoved`, not written back, so a provider back under its id is back in it), except a manual group's pick, a rule's model, or all of them when none would be left. It keeps following its model as a found group does (Kxsg79bEYFP4 on X: a third provider with the model, a plugin's, had stayed out of a group the user had changed): `SaveGroup` stores, for an `auto-…` id, what it had seen (`Group.Seen`: the models magpie found in it by that save, and those the user named, as `provider/model`), and a provider that serves the model since joins it as it is read, after the user's own members (`joined`, not written back), unless kept out of found groups. A model seen and not a member is one the user took out, and stays out; a provider's rename or a fold carries `Seen` (`mapModelRefs`), and a shared group leaves it behind. A found group changed before `Seen` was kept takes in nothing, as nothing says which of its models the user took out; its next save sees what is found then (`TestChangedFoundGroupTakesInANewProvider`, `TestChangedFoundGroupFromBeforeKeepsItsMembers`, `TestChangedFoundGroupTakesInAPluginProvider`). A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing groups 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 groups 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 groups 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 groups 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 Codex card's estimate counts the calls of a ChatGPT API account (`chatgpt-api`) that is the same ChatGPT account, whose plan limits they share: the tokens of both must name the same `chatgpt_account_id` and `chatgpt_user_id`, never matched by name, so two Team seats of one email stay apart (`SamePlanAccounts` in [`chatgpt_same_plan.go`](../../internal/provider/chatgpt_same_plan.go), jctaoo on Discord, `TestWindowHoldsCountsTheSameChatGPTAccountThroughTheAPI`). A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). Each key of a remote-magpie provider also gets a card of its own, under `/~keys`, one section per key (#1547, `remoteKeyCards` in `remote_key_limits.go`): the gateway key's limit as that magpie holds it, read from `GET /v1/magpie/limit` asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus `GatewayKey` (what is left, calls, a cycle of days, used up); a key held to no limit shows `Unlimited`. It is kept for `remoteCardsFor` like the remote's cards and read again by the card's refresh (`?provider=/~keys&user=`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). A remote's Codex card keeps its `Resets` (not a GLM team's, `ByWindow`), and its check-ins are dropped: **Use one…** there goes through `/api/usage/codex-reset` with the card's `provider`, and `UseRemoteCodexReset` asks the remote's `POST /v1/magpie/quotas/codex-reset?user=` with the provider's key (#3850). The remote spends it with `SpendCodexReset`, the same function as the Usage page (`UseCodexResetCard`, then `AwaitAllowance`). The account is always named. A 403 `gateway_key_read_only` is told as a read-only key there, and a 404 as a remote too old. No answer within `RemoteResetWait` says the reset may have been used, and it is never asked again by itself. A remote that holds the key to a budget, models or accounts answers its cards 403 `gateway_key_held` (#1981, `errKeyHeld`): the cards kept from before are dropped, and beside the key's own card the remote's card says it tells this key no quotas, and that on that computer Quotas is turned on for the key and it is let use every model of a provider whose usage it is to see (`errRemoteHeld`; yi_time on Discord saw the remote's Claude vanish from every page with no word). Its owner can let the key be told the cards of what it may use (#2216, `magpie gateway-key quotas on`); the remote then answers those, and 403 held as before when that is none (`writeCards`), so that key shows the same card. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, `quotasOpened`, #1588) or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. A plugin's window may carry a prepaid wallet's `balance` in its `unit` and no share (`QuotaWindow.Balance`, #3950): the card and `magpie quota` show the figure (`BalanceText`), and routing reads it through `Allowance.Left`. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`quota_asked.go`](../../internal/provider/quota_asked.go) | | A remote magpie's prices | A local magpie asks a remote magpie's `/v1/models` with `X-Magpie-Prices` (`PricesHeader`, sent by `listHeaders`). The remote answers each model's `magpie_price`: what its own Usage page counts the model at (`EntryPriceIn`: the price its user set, else its provider's list price at its price rate; a routing group only when every member costs the same). It tells it only to a request from its own computer or one let in with a gateway key (`local` or `sharedWith`); a list that didn't ask gets no `magpie_price` (a remote request without a valid key never reaches the list: `lanGuard` refuses it); every list told to those callers also carries the same price as OpenRouter's `pricing`, for agents ([gateway routing](gateway-routing.md)). The local keeps the price with the fetched list (`catalog.Model.Price`; a value that isn't a price, or has a negative part, is dropped, the model kept) and uses it as that provider's list price (`ListPrice` → `remotePrice`). A price the local user set (`provider/model`, `provider/*`, `*/model`) still comes first, and the local provider's own price rate still applies on top. A remote from before this sends no field and the models stay priced as before; an older local sends no header and is sent nothing new. The model editor says the greyed price is the other magpie's (`remoteList`). | [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`models.go`](../../internal/provider/models.go), [`gateway.go`](../../internal/gateway/gateway.go) (`models`), [`live.go`](../../internal/catalog/live.go) | | A remote magpie's service tiers | A remote magpie's `/v1/models` gives each model the `service_tiers` its own Codex is offered on it (`codexTiers` → `codexcat.ServiceTiers`, from the same `CodexCatalog` and `codexcat.Entries` as its `/v1/codex/models`: Fast on a ChatGPT account's GPT model, the tiers of Codex's own entry on a relay's, none on a model it offers none). The local keeps the ids (`catalog.Model.Tiers` → `Entry.Tiers`), `codexListed` hands them on for the remote's models, and `codexcat.Entries` offers them to the local Codex with Codex's own names (`namedTiers`). The gateway sends the tier Codex asks for to a remote magpie as it was asked (`Request.OwnTier`, as for a provider added by its address; dropped and not sent again if refused), and the remote serves it as its own Codex's turn (#1234). An agent's picker offers the bolt on a remote's model whose tiers hold `priority` (`provider.CanFast` reads them with `RemoteTiers`; Ultrafast too where they hold `ultrafast`, `UltraOn`), and a fast pick of one goes on with `service_tier` `priority` on the remote's Chat or Responses: an agent on Messages, whose fast is Claude's `speed`, has it turned into the tier the remote offers (`forwardTranslated`), so Claude Code's pick reaches the remote's vendor too (littlekk88 on Discord; `TestRemoteMagpieFastPick`, red without either half). A remote from before this sends no tiers, and its models are offered none, as before. The list gives every client the tiers, not only a magpie asking with `X-Magpie-Drawers`: Cindy shows its Fast switch on a model whose `service_tiers` hold `priority` (#1914, `TestModelsListTiersForEveryClient`). | [`codexcat.go`](../../internal/codexcat/codexcat.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`gateway.go`](../../internal/gateway/gateway.go), [`live.go`](../../internal/catalog/live.go) | diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 59f682420..7d8d3cf93 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -330,6 +330,7 @@ body.window .top.inrow .actions { margin-left: 0; } .top.cramped .seg button { padding: 0 8px; } .top.crowded .seg button { padding: 0 6px; font-size: 12px; } .top.crowded .brand { display: none; } +body:not(.side-nav) #nav button[data-view="groups"], body.side-nav .rt-togroups { display: none; } .top.packed .seg button { padding: 0 3px; font-size: 11.5px; } /* and when even that doesn't fit, the tabs scroll sideways rather than push the page wider */ .top.packed .seg { min-width: 0; flex: 0 1 auto; overflow-x: auto; overflow-y: hidden; scrollbar-width: none; } @@ -602,7 +603,7 @@ body.window .view { padding: 2px max(0px, calc(16px - var(--bar, 0px))) 8px 16px stretch them alone edge to edge while the others sit in the middle (面条 on Discord): their tables and charts lay out by the room they get. Masking too, which stretched alone (refeccd on Discord) */ -body.window :is(#view-agents, #view-sessions, #view-providers, #view-routing, #view-gateway, #view-usage, #view-masking, #view-library, #view-plugins, #view-settings) { padding-left: max(16px, calc(50% - 600px)); padding-right: max(0px, calc(max(16px, calc(50% - 600px)) - var(--bar, 0px))); } +body.window :is(#view-agents, #view-sessions, #view-providers, #view-routing, #view-groups, #view-gateway, #view-usage, #view-masking, #view-library, #view-plugins, #view-settings) { padding-left: max(16px, calc(50% - 600px)); padding-right: max(0px, calc(max(16px, calc(50% - 600px)) - var(--bar, 0px))); } /* a view takes focus (tabIndex -1) only so the keys scroll it after a click; a ring round the whole list there marks nothing a reader can act on (#1601) */ .view:focus { outline: none; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 9db55d242..80ed5d5dd 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -1838,13 +1838,13 @@ function guideCard(g) { add.onclick = (e) => { e.stopPropagation(); guideTemplate(tp, name); }; acts.append(add); } - const open = el("button", "text guide-open", t("Open Routing")); + const open = el("button", "text guide-open", t("Open routing groups")); open.type = "button"; open.dataset.feature = "routing"; open.onclick = (e) => { e.stopPropagation(); - if (mode === "window") show("routing"); - else api("window/main?view=routing", {}).catch(statusErr); + if (mode === "window") show("groups"); + else api("window/main?view=groups", {}).catch(statusErr); }; acts.append(open); three.body.append(acts); @@ -5652,7 +5652,7 @@ function keptNote(m) { act.onclick = (ev) => { ev.stopPropagation(); closePicker(); - if (mode !== "window") api("window/main?view=routing&newgroup=" + encodeURIComponent(m.id), {}).catch(statusErr); + if (mode !== "window") api("window/main?view=groups&newgroup=" + encodeURIComponent(m.id), {}).catch(statusErr); else window.newGroupWith?.(m.id, m.name, ev); }; } @@ -6001,6 +6001,7 @@ function loadProviders() { return p; } +const rtView = (v) => v === "routing" || v === "groups"; async function loadProvidersNow() { // The page's first opening (#1519, fatkun): a list is drawn at once, as // the Agents page draws the last state, and the fresh one replaces it @@ -6053,7 +6054,7 @@ async function loadProvidersNow() { magpie.call(view, "render", was); backAfterLoad($("#view-" + view)); // under Routing: drawn when opened (#4652) - } else if (view === "routing") { providersBehind = true; markNewPartners(); } + } else if (rtView(view)) { providersBehind = true; markNewPartners(); } else renderProviders(); renderArchive(); providersWhileFetching(); @@ -6070,7 +6071,7 @@ function providersWhileFetching() { clearTimeout(providersWhileFetching.timer); if (!providers?.fetching) return; providersWhileFetching.timer = setTimeout(async () => { - if (!(["providers", "routing"].includes(view) || providersPage(view)) || editing !== null || adding || document.hidden) return; + if (!(view === "providers" || rtView(view) || providersPage(view)) || editing !== null || adding || document.hidden) return; let next; try { next = await api("providers"); } catch { providersWhileFetching(); return; } const json = (p) => JSON.stringify({ ...p, fetching: false, gateway: { ...p.gateway, calls: 0 } }); @@ -11429,11 +11430,11 @@ function renderModels(p) { lost.hidden = !none.length; if (!none.length) return; lost.append(t("In no routing group, so no agent can use them now: {models}.", { models: none.slice(0, 8).join(", ") + (none.length > 8 ? " …" : "") })); - if (!p.unlisted) { lost.append(" " + t("Once saved, make a group of them in Routing.")); return; } + if (!p.unlisted) { lost.append(" " + t("Once saved, make a group of them in Routing groups.")); return; } for (const id of none.slice(0, 4)) { const b = el("button", "text action", t("Make a routing group of {model}", { model: id })); b.dataset.feature = "routing"; // made on the Routing page - b.onclick = (ev) => { if (mode !== "window") api("window/main?view=routing&newgroup=" + encodeURIComponent(p.id + "/" + id), {}); else window.newGroupWith?.(p.id + "/" + id, "", ev); }; + b.onclick = (ev) => { if (mode !== "window") api("window/main?view=groups&newgroup=" + encodeURIComponent(p.id + "/" + id), {}); else window.newGroupWith?.(p.id + "/" + id, "", ev); }; lost.append(b); } }; @@ -22877,7 +22878,7 @@ const readerAt = new WeakMap(); // took it out of sight, and it isn't brought back (backToReader) const scrolledFrom = new WeakMap(); // Where the reader is is the view's scrollTop, unless the view names a part -// to keep in place (keepInView, the Routing page's groups under parts that +// to keep in place (keepInView, the Routing page's lists under parts that // redraw on their own): then it is where that part is on screen as the // reader leaves it, and the view follows it (scroll anchoring WebKit lacked). const pinOf = new Map(), pinAt = new WeakMap(); @@ -23156,7 +23157,7 @@ async function show(v) { if (view === "library" && modalFormDirty() && !(await confirmDiscard())) return false; if (view === "library") magpie.call("library", "close"); else closeModal(); } - if (view === "routing" && magpie.call("routing", "dirty")) { + if (rtView(view) && magpie.call("routing", "dirty")) { if (!(await confirmDiscard())) return false; magpie.call("routing", "discard"); } @@ -23164,8 +23165,7 @@ async function show(v) { if (!(await confirmDiscard())) return false; magpie.call("library", "discard"); } - // the page left lets go of what was only for this visit (the Usage - // page's Requests, what a click filtered them by) + // the page left lets go of what was only for this visit magpie.call(view, "leave"); } view = v; @@ -23176,11 +23176,7 @@ async function show(v) { $("#pageTitle").dataset.en = title; $("#pageTitle").textContent = t(title); if (mode === "window") { - for (const b of $("#nav").querySelectorAll("button[data-view]")) { - const on = b.dataset.view === v; - b.classList.toggle("on", on); - if (on) b.setAttribute("aria-current", "page"); else b.removeAttribute("aria-current"); - } + markNav(v); if (!sideNav()) { slide($("#nav"), "nav"); navInSight(); } else navTopGo($("#nav").querySelector("button[data-view].on"), true); } @@ -23197,10 +23193,9 @@ async function show(v) { // a plugin's page loads what it shows; back once it has magpie.call(v, "open")?.then?.(back); if (v === "providers" && providersBehind) renderProviders(); - if (v === "providers" || v === "routing" || providersPage(v)) loadProviders().then(back, statusErr); - // Routing's accounts show their windows as the Usage page read them - // (#1833): what is kept, read in an ordinary way, never an asked read - if (v === "routing" && (!quotas || Date.now() - quotasAt > 60e3)) loadQuotas(); + if (v === "providers" || rtView(v) || providersPage(v)) loadProviders().then(back, statusErr); + // Routing's accounts' windows as Usage read them (#1833), never an asked read + if (rtView(v) && (!quotas || Date.now() - quotasAt > 60e3)) loadQuotas(); if (v === "settings") (settingsLoad = loadSettings()).then(back, statusErr); if (v === "plugins") window.loadPlugins?.()?.then(back); syncTitle(); @@ -23229,8 +23224,7 @@ if (mode === "window") for (const b of $("#nav").querySelectorAll("button[data-v b.onpointerleave = (e) => { if (e.buttons & 1) navTopGo(navTopOn(), true); }; b.onclick = () => { show(b.dataset.view).then((went) => { if (!went) navTopGo(navTopOn(), true); }); b.blur(); }; } -// setGatewayMode shows or leaves out gateway mode's pages' tabs; the page -// open, one of them, gives way to Providers +// gateway mode's pages' tabs; the page open, one of them, gives way to Providers function setGatewayMode(on) { gatewayMode = on; document.body.classList.toggle("gateway-mode", on); @@ -23509,6 +23503,17 @@ document.fonts?.ready.then(fitTop); // a font picked later (Settings' Font) can still be loading when it's applied document.fonts?.addEventListener("loadingdone", fitTop); +// the shown page's tab; Routing's for its groups in the header's row, +// which has no room for theirs (app.css) +function markNav(v) { + const tab = v === "groups" && !sideNav() ? "routing" : v; + for (const b of $("#nav").querySelectorAll("button[data-view]")) { + const on = b.dataset.view === tab; + b.classList.toggle("on", on); + if (on) b.setAttribute("aria-current", "page"); else b.removeAttribute("aria-current"); + } +} + // ---- the sidebar ---------------------------------------------------------- // A window wide enough has its pages down a sidebar, as a Mac app's: in // groups, the open page's own tabs under it, Settings at its foot and the @@ -23554,6 +23559,7 @@ function layoutNav() { $("#crumb").after(nav); $(".actions").insertBefore(prefs, $("#winclose")); } + markNav(view); navSubsAt = ""; // the sidebar coming or going isn't a list opening navSubs.quiet = true; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index eae2f5f11..c0a990a91 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3703,7 +3703,6 @@ const I18N = { "No {api} URL": "没有 {api} 地址", "This key is set to {api} only, but {name} has no {api} URL, so no request reaches {api} with it. Fill in the {api} URL, or set the key to Any protocol.": "这个 key 只用于 {api},但 {name} 没有填 {api} 地址,所以用这个 key 的请求到不了 {api}。请填上 {api} 地址,或者把 key 改回「任意协议」。", "any API": "任意 API", - "models agents pick as one": "Agent 当作一个模型来选", "Client": "客户端", "Unhide": "取消隐藏", "found by magpie": "magpie 自动发现", @@ -3993,6 +3992,7 @@ const I18N = { "At least: {k} replies read from session files, which don't say when their answers began, so time before that is counted too": "下限:{k} 次读自会话文件的回复。会话文件不记录正文何时开始,之前的时间也算在里面", "Protocol": "协议", "Upstream stop reason": "上游结束原因", + "Open routing groups": "打开路由组", "Open Routing": "打开路由", "{n} min": "{n} 分钟", "{n} h": "{n} 小时", @@ -4064,7 +4064,7 @@ const I18N = { "Agents don't see them: only the routing groups they are in use them.": "Agent 看不到这些模型,只有它们所在的路由分组会用到。", "Agents see the models picked.": "Agent 看到的是已勾选的模型。", "In no routing group, so no agent can use them now: {models}.": "不在任何路由分组中,暂无 Agent 能用:{models}。", - "Once saved, make a group of them in Routing.": "保存后可在「路由」里为它们建分组。", + "Once saved, make a group of them in Routing groups.": "保存后可在「路由组」里为它们建分组。", "Make a routing group of {model}": "用 {model} 建路由分组", "Make a routing group of it": "用它建路由分组", "Pick {group}": "选 {group}", @@ -8321,7 +8321,6 @@ const I18N = { "No {api} URL": "沒有 {api} 位址", "This key is set to {api} only, but {name} has no {api} URL, so no request reaches {api} with it. Fill in the {api} URL, or set the key to Any protocol.": "這個 key 只用於 {api},但 {name} 沒有填 {api} 位址,所以用這個 key 的請求到不了 {api}。請填上 {api} 位址,或把 key 改回「任意協議」。", "any API": "任意 API", - "models agents pick as one": "Agent 當作一個模型來選", "Client": "用戶端", "Unhide": "取消隱藏", "found by magpie": "magpie 自動發現", @@ -8608,6 +8607,7 @@ const I18N = { "At least: {k} replies read from session files, which don't say when their answers began, so time before that is counted too": "下限:{k} 次讀自會話檔案的回覆。會話檔案不記錄正文何時開始,之前的時間也算在裡面", "Protocol": "協議", "Upstream stop reason": "上游結束原因", + "Open routing groups": "開啟路由組", "Open Routing": "開啟路由", "{n} min": "{n} 分鐘", "{n} h": "{n} 小時", @@ -8677,7 +8677,7 @@ const I18N = { "Agents don't see them: only the routing groups they are in use them.": "Agent 看不到這些模型,只有它們所在的路由分組會用到。", "Agents see the models picked.": "Agent 看到的是已勾選的模型。", "In no routing group, so no agent can use them now: {models}.": "不在任何路由分組中,暫無 Agent 能用:{models}。", - "Once saved, make a group of them in Routing.": "儲存後可在「路由」裡為它們建分組。", + "Once saved, make a group of them in Routing groups.": "儲存後可在「路由組」裡為它們建分組。", "Make a routing group of {model}": "用 {model} 建路由分組", "Make a routing group of it": "用它建路由分組", "Pick {group}": "選 {group}", @@ -12951,7 +12951,6 @@ const I18N = { "No {api} URL": "{api} の URL がありません", "This key is set to {api} only, but {name} has no {api} URL, so no request reaches {api} with it. Fill in the {api} URL, or set the key to Any protocol.": "このキーは {api} 専用ですが、{name} には {api} の URL がないため、このキーでのリクエストは {api} に届きません。{api} の URL を入力するか、キーを「任意のプロトコル」に戻してください。", "any API": "任意の API", - "models agents pick as one": "エージェントが 1 つとして選ぶモデル群", "Client": "クライアント", "Unhide": "再表示", "found by magpie": "magpie が自動作成", @@ -13237,6 +13236,7 @@ const I18N = { "At least: {k} replies read from session files, which don't say when their answers began, so time before that is counted too": "下限:セッションファイルから読んだ {k} 件の応答。回答が始まった時刻がないため、その前の時間も含まれます", "Protocol": "プロトコル", "Upstream stop reason": "上流の終了理由", + "Open routing groups": "ルーティンググループを開く", "Open Routing": "ルーティングを開く", "{n} min": "{n} 分", "{n} h": "{n} 時間", @@ -13306,7 +13306,7 @@ const I18N = { "Agents don't see them: only the routing groups they are in use them.": "エージェントには見えません。所属するルーティンググループだけが使います。", "Agents see the models picked.": "エージェントには選択したモデルが表示されます。", "In no routing group, so no agent can use them now: {models}.": "どのルーティンググループにも入っていないため、現在どのエージェントも使えません:{models}。", - "Once saved, make a group of them in Routing.": "保存したら「ルーティング」でこれらのグループを作成してください。", + "Once saved, make a group of them in Routing groups.": "保存したら「ルーティンググループ」でこれらのグループを作成してください。", "Make a routing group of {model}": "{model} でルーティンググループを作成", "Make a routing group of it": "これでルーティンググループを作成", "Pick {group}": "{group} を選択", @@ -17592,7 +17592,6 @@ const I18N = { "No {api} URL": "Keine {api}-URL", "This key is set to {api} only, but {name} has no {api} URL, so no request reaches {api} with it. Fill in the {api} URL, or set the key to Any protocol.": "Dieser Schlüssel ist nur für {api} eingestellt, aber {name} hat keine {api}-URL, daher erreicht keine Anfrage mit ihm {api}. Trag die {api}-URL ein oder stell den Schlüssel auf Beliebiges Protokoll.", "any API": "beliebige API", - "models agents pick as one": "Modelle, die Agenten als eines wählen", "Client": "Client", "Unhide": "Einblenden", "found by magpie": "von magpie gefunden", @@ -17881,6 +17880,7 @@ const I18N = { "At least: {k} replies read from session files, which don't say when their answers began, so time before that is counted too": "Mindestens: {k} Antworten aus Sitzungsdateien. Sie sagen nicht, wann die Antworten begannen, also zählt die Zeit davor mit", "Protocol": "Protokoll", "Upstream stop reason": "Endgrund des Upstreams", + "Open routing groups": "Weiterleitungsgruppen öffnen", "Open Routing": "Weiterleitung öffnen", "{n} min": "{n} min", "{n} h": "{n} h", @@ -17950,7 +17950,7 @@ const I18N = { "Agents don't see them: only the routing groups they are in use them.": "Agenten sehen sie nicht: Nur die Weiterleitungsgruppen, in denen sie sind, nutzen sie.", "Agents see the models picked.": "Agenten sehen die gewählten Modelle.", "In no routing group, so no agent can use them now: {models}.": "In keiner Weiterleitungsgruppe, daher kann sie derzeit kein Agent nutzen: {models}.", - "Once saved, make a group of them in Routing.": "Erstellen Sie nach dem Speichern unter Weiterleitung eine Gruppe daraus.", + "Once saved, make a group of them in Routing groups.": "Erstellen Sie nach dem Speichern unter Weiterleitungsgruppen eine Gruppe daraus.", "Make a routing group of {model}": "Weiterleitungsgruppe aus {model} erstellen", "Make a routing group of it": "Weiterleitungsgruppe daraus erstellen", "Pick {group}": "{group} wählen", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index cb679e716..69de58d0a 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -72,6 +72,7 @@ Models + Insights diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index cc5f21a7b..36cd44aeb 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -21,8 +21,7 @@ magpie.plugin("routing", (ctx) => { title: "Routing", html: `
Routinglive, as the gateway decides - - +
@@ -36,6 +35,16 @@ magpie.plugin("routing", (ctx) => { return ready.then(() => routingPage(this)); }, }); + // Routing groups, a page of their own beside Routing (11-06): under the + // stage and every request they were a long scroll down, and New group + // with them. The same script draws them (routingPage), into this page. + ctx.slots.add("page", { + key: "groups", + title: "Routing groups", + html: `
`, + // Try again filled the page with its markup anew: the groups go back in + mount(main) { window.routingGroupsHome?.(main); }, + }); }); // The page, drawn once app.js is set up; part is its part, given the hooks @@ -43,14 +52,20 @@ magpie.plugin("routing", (ctx) => { function routingPage(part) { const box = $("#rt"); if (!box) return; + // the groups' way in where the header's row has no tab for them (markNav) + const toGroups = $("#rtToGroups"); + if (toGroups) toGroups.onclick = () => window.show("groups"); const NS = "http://www.w3.org/2000/svg"; const still = calm; const shown = () => !$("#view-routing").hidden && !document.hidden; + // the Routing groups page, which this script draws too (gsec) + const gView = () => $("#view-groups"); + const gShown = () => !gView().hidden && !document.hidden; // steady redraws a part of the page where the reader is: WebKit has no // scroll anchoring, and a part emptied and filled again, measured between, // pulls the page up to what was left of it for that moment - function steady(fn) { - const v = $("#view-routing"), top = v.scrollTop; + function steady(fn, v = $("#view-routing")) { + const top = v.scrollTop; try { return fn(); } finally { if (v.scrollTop !== top) v.scrollTop = top; } } @@ -2702,26 +2717,40 @@ function routingPage(part) { if (e.title !== title) e.title = title; } else for (const a of ["data-go", "tabindex", "role", "title"]) e.removeAttribute(a); } - function goRouting(e, go) { + async function goRouting(e, go) { const i = go.indexOf(":"), kind = go.slice(0, i), id = CSS.escape(go.slice(i + 1)); const row = kind === "group" ? gList.querySelector(`.rt-group[data-id="${id}"]`) : pList.querySelector(`.rt-pool[data-provider="${id}"]`); if (!row) return; - if (window.scrollOnPurpose?.(e)) row.scrollIntoView({ block: "center", behavior: still() ? "auto" : "smooth" }); + // they are on the Routing groups page: it opens, and the row comes + // into sight as the reader's click asked. A page just opened is at the + // row at once, and that is where the reader is in it (arrived): else + // the page put itself back where the reader last left it + const asked = window.scrollOnPurpose?.(e), opens = gView().hidden; + if (opens && !(await window.show("groups"))) return; + if (asked) { + readerScrolls(1000); + row.scrollIntoView({ block: "center", behavior: opens || still() ? "auto" : "smooth" }); + if (opens) window.arrived?.(gView()); + } row.classList.remove("rt-found"); void row.offsetWidth; row.classList.add("rt-found"); row.querySelector(".segs .opt.on")?.focus({ preventScroll: true }); } - $("#view-routing").addEventListener("click", (e) => { - const g = e.target.closest(".rt-go[data-go]"); - if (g) goRouting(e, g.dataset.go); - }); - $("#view-routing").addEventListener("keydown", (e) => { - const g = (e.key === "Enter" || e.key === " ") && e.target.closest?.(".rt-go[data-go]"); - if (!g) return; - e.preventDefault(); - goRouting(e, g.dataset.go); - }); + // on both pages: a request's group, and a group or provider named in + // another group's card + for (const v of [$("#view-routing"), gView()]) { + v?.addEventListener("click", (e) => { + const g = e.target.closest(".rt-go[data-go]"); + if (g) goRouting(e, g.dataset.go); + }); + v?.addEventListener("keydown", (e) => { + const g = (e.key === "Enter" || e.key === " ") && e.target.closest?.(".rt-go[data-go]"); + if (!g) return; + e.preventDefault(); + goRouting(e, g.dataset.go); + }); + } // lightRow lights a row and its wire: on for the one answering or that // answered the request shown, now and a flowing wire only while a @@ -5531,11 +5560,21 @@ function routingPage(part) { }; const gOffBox = el("div", "list rt-goffbox"); gOffBox.append(el("div", "rt-goffwhy", t("Routing groups are off in Plugins › Built-in: the groups magpie finds, one model several providers serve, still route, but your own can't be made or changed here.")), gOn); - gOff.append(el("div", "row-head", el("span", "label", t("Routing groups"))), gOffBox); - gsec.append(gHead, gFound, gNames, gList, gOff, pHead, pList); - // after the requests: a request picked in the list plays on the stage, - // so the list sits right under it - more.append(gsec); + gOff.append(gOffBox); + // the settings that hold for every group, under the list (11-06) + const sHead = el("div", "row-head rt-gset-head"); + sHead.dataset.feature = "groups"; + sHead.append(el("span", "label", t("Settings"))); + const gSet = el("div", "list rt-gset"); + gSet.dataset.feature = "groups"; + gSet.append(gFound, gNames); + gsec.append(gHead, gList, gOff, sHead, gSet, pHead, pList); + // on the Routing groups page, a page of their own; Try again on it puts + // them back in its markup made anew + const gHome = () => $("#rtGroups"); + window.routingGroupsHome = (main) => (main?.querySelector("#rtGroups") || gHome())?.append(gsec); + window.routingGroupsHome(); + if (gHome()) byWidth(gHome(), { max520: (w) => w <= 520 }); const ROUTE_OPTS = [["", "Smart"], ["order", "In order"], ["drain", "Until used up"], ["rotate", "In turn"], ["usage", "Least used"], ["pace", "Use before expiry"], ["free", "Free first"], ["fast", "Speed first"]]; // a group may also be routed by hand: every request to the member the // user picks on its card (provider.Manual, #317) — a provider's keys can't @@ -5675,8 +5714,8 @@ function routingPage(part) { // calling it on a row already in view would drop the hold the next editor // opens under (backToReader, app.js, guards the same way). const saved = body.id || body.from || ""; - const row = saved && document.querySelector(`#view-routing .rt-group[data-id="${CSS.escape(saved)}"]`); - const view = row && gFolded !== saved && document.getElementById("view-routing"); + const row = saved && gList.querySelector(`.rt-group[data-id="${CSS.escape(saved)}"]`); + const view = row && gFolded !== saved && gView(); if (view) { const rr = row.getBoundingClientRect(), vb = view.getBoundingClientRect(); if (rr.bottom > vb.bottom || rr.top < vb.top) { readerScrolls(1000); row.scrollIntoView({ block: "nearest" }); } @@ -5808,7 +5847,7 @@ function routingPage(part) { if (!groups) return; // not under a row being dragged: it is drawn when let go if (groupArranging) { groupRenderPending = true; return; } - steady(drawGroups); + steady(drawGroups, gView()); } // gSel: the groups picked to be removed together, while picking (lc on // Discord: they could only be removed one at a time); null otherwise @@ -5900,16 +5939,23 @@ function routingPage(part) { const shown = words.length ? all.filter((g) => gEdit?.id === g.id || groupMatches(g, words)) : all; if (gSel) gSel = new Set([...gSel].filter((id) => shown.some((g) => g.id === id))); if (gSel && !all.length) gSel = null; - const newBtn = el("button", "text rt-gnew"); + // the page's toolbar (11-06): the filter and how many there are on the + // left, what makes or picks groups on the right, New group the one + // filled button + const newBtn = el("button", "text primary rt-gnew"); newBtn.type = "button"; + newBtn.dataset.feature = "groups"; // off with them, as the note says newBtn.append(svg(PLUS, 11, 1.8), el("span", "", t("New group"))); + newBtn.title = t("Make a routing group of any models you like — agents pick it as one model"); newBtn.onclick = () => newGroup(); - const head = [el("span", "label", t("Routing groups")), el("span", "grow"), el("span", "note", t("models agents pick as one"))]; + const head = []; if (all.length > 1 || gQ.value) { gQ.placeholder = t("Filter groups and models"); gQ.setAttribute("aria-label", gQ.placeholder); head.push(gQ); } + if (all.length) head.push(el("span", "note rt-gcount", t("{n} groups · {m} on", { n: all.length, m: all.filter((g) => !g.disabled).length }))); + head.push(el("span", "grow")); // templates: a group for a common need made of the user's own models // in a click (provider.Templates). Cards while the user has no group of // their own, a menu by New group after @@ -5989,7 +6035,7 @@ function routingPage(part) { let gMorph = null, gSaved = null, gFolded = null; const slotKey = (n) => n.dataset?.gslot; function slotsOf() { - const m = new Map(), vt = document.getElementById("view-routing").getBoundingClientRect().top; + const m = new Map(), vt = gView().getBoundingClientRect().top; for (const n of gList.children) { const k = slotKey(n); if (k === undefined) continue; @@ -6001,7 +6047,7 @@ function routingPage(part) { function morphSlots(was) { const alias = gMorph, saved = gSaved; gMorph = gSaved = gFolded = null; - if (still() || !shown()) return; + if (still() || !gShown()) return; for (const n of gList.children) { const k = slotKey(n); if (k === undefined) continue; @@ -6043,7 +6089,7 @@ function routingPage(part) { // was above the window's; the page's scroll is read once the redraw // has put it back (steady). function foldInSight(n, grow, from, to, top) { - const view = document.getElementById("view-routing"); + const view = gView(); readerScrolls(1000); let s0, target; const step = () => { @@ -6712,7 +6758,7 @@ function routingPage(part) { const sfxSaid = el("span", "hint"); const sayLabel = () => { sfxSaid.textContent = t("Agents’ lists show “{label}”", { label: (d.name.trim() || t("New group")) + (suffixMode() === "on" ? " · routing group" : "") }) + - " · " + t("“· routing group” is set for every group above"); + " · " + t("“· routing group” is set for every group, under the list"); }; name.oninput = () => { d.name = name.value; showId(); sayLabel(); }; const nw = el("div"); @@ -8001,15 +8047,26 @@ function routingPage(part) { } // loaded when the view is shown, and again when the window comes back // back on the page, the same groups aren't drawn again either (#4652) - new MutationObserver(() => { if (!$("#view-routing").hidden) loadGroups(true); }).observe($("#view-routing"), { attributes: true, attributeFilter: ["hidden"] }); - window.addEventListener("focus", () => { if (shown()) loadGroups(true); }); + // on either page: Routing names the groups too (its stage, the story) + for (const v of [$("#view-routing"), gView()]) new MutationObserver(() => { if (!v.hidden) loadGroups(true); }).observe(v, { attributes: true, attributeFilter: ["hidden"] }); + window.addEventListener("focus", () => { if (shown() || gShown()) loadGroups(true); }); + // the groups' rows say what is left of their accounts, drawn again when + // the Usage page's readings come while the page is open (Routing's own + // second does it there); the page may be open already, from ?view=groups + let gTick = 0; + const gTicks = () => { + clearInterval(gTick); + gTick = gView().hidden ? 0 : setInterval(() => { if (gShown()) groupsReadAgain(); }, 1000); + }; + gTicks(); + new MutationObserver(gTicks).observe(gView(), { attributes: true, attributeFilter: ["hidden"] }); // newGroupWith: a new group's editor, opened with the model in it — a // model of a provider kept for routing groups that no group has, which // agents can reach no other way. The picker and the provider's editor // ask it (and the tray panel, by ?newgroup= on the window it opens). window.newGroupWith = async (id, name, ev) => { // app.js's show, the page's: this one's own show is the stage's caption - if (document.body.classList.contains("window") && $("#view-routing").hidden && !(await window.show("routing"))) return; + if (document.body.classList.contains("window") && gView().hidden && !(await window.show("groups"))) return; if (!groups) await loadGroups(); if (!groups) return; if (groupDirty() && !(await confirmDiscard())) return; @@ -8019,9 +8076,7 @@ function routingPage(part) { if (ed && window.scrollOnPurpose?.(ev)) ed.scrollIntoView({ block: "center", behavior: "smooth" }); ed?.querySelector("input")?.focus({ preventScroll: true }); }; - // newGroup: an empty new group's editor. The groups sit below the - // requests, out of sight on a first look, so the page's head has a New - // group too (mintonight, #944), which brings the editor into view. + // newGroup: an empty new group's editor, at the list's top async function newGroup(ev) { if (groupDirty() && !(await confirmDiscard())) return; gSel = null; @@ -8032,71 +8087,21 @@ function routingPage(part) { if (ed && window.scrollOnPurpose?.(ev)) ed.scrollIntoView({ block: "center", behavior: "smooth" }); ed?.querySelector("input")?.focus({ preventScroll: true }); } - const headNew = $("#rtNewGroup"); - if (headNew) headNew.onclick = async (ev) => { - if (!groups) await loadGroups(); - if (groups) newGroup(ev); - }; - // the head's Routing groups: the groups sit below the stage, the story - // and every request, a long scroll down with many models (shihh on - // Discord). Its click brings them to the top of the view, and the focus - // with them, so Tab goes on from there; the page is laid out as before - gsec.tabIndex = -1; - const headGo = $("#rtGoGroups"); - if (headGo) headGo.onclick = (ev) => { - if (!window.scrollOnPurpose?.(ev)) return; - gsec.scrollIntoView({ block: "start", behavior: still() ? "auto" : "smooth" }); - gsec.focus({ preventScroll: true }); - }; - // fitGo: it takes only room the head has spare, so nothing else in the - // head moves or wraps for it: named where its name fits, its arrow alone - // where only that does, and left out of a head with no room (a phone's) - const goHead = headGo?.parentElement, goGrow = goHead?.querySelector(".grow"); - function fitGo() { - if (!goGrow || !goHead.offsetParent) return; - headGo.dataset.fit = "none"; - const room = goGrow.getBoundingClientRect().width, gap = parseFloat(getComputedStyle(goHead).columnGap) || 0; - for (const fit of ["full", "icon"]) { - headGo.dataset.fit = fit; - if (room >= headGo.getBoundingClientRect().width + 6 + gap) return; - } - headGo.dataset.fit = "none"; - } - let goFitting = 0; - const fitGoSoon = () => { if (!goFitting) goFitting = requestAnimationFrame(() => { goFitting = 0; fitGo(); }); }; - if (goHead) { - const ro = new ResizeObserver(fitGoSoon); - for (const n of [goHead, ...goHead.querySelectorAll(".label, .note")]) ro.observe(n); - new MutationObserver(fitGoSoon).observe(document.documentElement, { attributes: true, attributeFilter: ["lang"] }); - } const askedGroup = document.body.classList.contains("window") && params.get("newgroup"); if (askedGroup) loadGroups().then(() => window.newGroupWith(askedGroup, "")); else loadGroups(); // ---------- where the reader is, as requests come ---------- - // Every request redraws what is above the routing groups: the stage gains - // or loses a row, the story a line, the lists theirs. The view kept its - // scrollTop, so all of it pushed the groups down or pulled them up under - // the reader, a group being edited too (Jerell.OvO on Discord). The view - // keeps a part of itself where it is on the screen instead (keepInView in - // app.js): the groups, while they are in the upper half of the view or a - // field in them has the focus, else the lists, while they are; with - // neither (the stage in sight at the top), the view stays as it is. - // The groups too while the pointer is on them, low in the view as they - // are at the page's foot: a manual group's card, its pick a click away, - // slid down from under the pointer as the requests list above it grew - // (cwfox67 on X). + // Every request redraws what is above the lists: the stage gains or + // loses a row, the story a line. The view keeps the lists where they are + // on the screen while they are in its upper half (keepInView in app.js); + // with the stage in sight at the top, the view stays as it is. The + // routing groups sat below them until they had a page of their own. const rv = $("#view-routing"); keepInView(rv, () => { const mid = rv.getBoundingClientRect().top + rv.clientHeight / 2; - if ((gsec.contains(document.activeElement) || gsec.matches(":hover")) && gsec.offsetParent) return gsec; - return [gsec, hist].find((p) => p.offsetParent && p.getBoundingClientRect().top <= mid) || null; + return hist.offsetParent && hist.getBoundingClientRect().top <= mid ? hist : null; }); - // the pointer coming onto the groups or off them changes the part kept, - // so where the reader is is taken again, as their scroll would - const repin = () => { if (held?.v !== rv && !rv.hidden) readerLeaves(rv); }; - gsec.addEventListener("pointerenter", repin); - gsec.addEventListener("pointerleave", repin); // ---------- the tray panel's Routing tab ---------- // The gateway's latest requests, as they come, from the same trace the diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.js index b2f90f657..c7ba8bed2 100644 --- a/internal/gui/assets/plugins/routing/i18n.js +++ b/internal/gui/assets/plugins/routing/i18n.js @@ -13,7 +13,7 @@ magpie.strings({ "magpie is masking this request before routing it (Settings › Privacy), so who takes it isn't picked yet.": "magpie 正在给这个请求脱敏(设置 › 隐私),脱敏完才路由,所以还没选出由谁处理。", "magpie hasn't routed this request yet, so who takes it isn't picked yet.": "magpie 还没开始路由这个请求,所以还没选出由谁处理。", "Nothing took this request: {error}": "没有谁处理这个请求:{error}", - "Go to the routing groups, below the requests": "跳到请求下方的路由组", + "{n} groups · {m} on": "{n} 个组 · {m} 个开启", "Filter, or type an agent's name…": "筛选,或输入 Agent 名称…", "the name its User-Agent begins with": "User-Agent 开头的名称", "heard from in the last 30 days": "近 30 天有请求", @@ -43,7 +43,7 @@ magpie.strings({ "In agents’ lists": "Agent 列表里的名称", "Names in agents’ lists": "Agent 列表里的名称", "Whether “· routing group” follows a group’s name in the agents’ lists: one setting for every group, and for the provider after each model’s name, as on Settings.": "Agent 的模型列表里,路由组名后面是否带「· routing group」。这是所有路由组共用的一个设置,也决定模型名后面是否带供应商,和「设置」里的是同一个。", - "“· routing group” is set for every group above": "是否带「· routing group」在上方统一设置,对所有路由组生效", + "“· routing group” is set for every group, under the list": "是否带「· routing group」在列表下方统一设置,对所有路由组生效", "{agent} guessed your next message for its composer by itself, reading the whole conversation again. Not a turn of the conversation; Codex composer predictions, under Settings in Codex's row on the Agents page, picks its model, and Codex's Settings › General › Show predictions turns it off.": "{agent} 自行为输入框猜测你的下一条消息,每次都把整段对话重读一遍。不属于对话轮次;在 Agent 页 Codex 那一行的设置里,用 Codex 输入框预测 选它用的模型,在 Codex 的 设置 › 常规 › 显示预测内容 里可以关掉。", "{name} is switched off: the group skips it until it is on again": "{name} 已关闭:开启前这个组会跳过它", "{n} switched off": "{n} 个已关闭", @@ -680,7 +680,7 @@ magpie.strings({ "magpie is masking this request before routing it (Settings › Privacy), so who takes it isn't picked yet.": "magpie 正在為這個請求脫敏(設定 › 隱私),脫敏完才路由,所以還沒選出由誰處理。", "magpie hasn't routed this request yet, so who takes it isn't picked yet.": "magpie 還沒開始路由這個請求,所以還沒選出由誰處理。", "Nothing took this request: {error}": "沒有誰處理這個請求:{error}", - "Go to the routing groups, below the requests": "跳到請求下方的路由組", + "{n} groups · {m} on": "{n} 個組 · {m} 個開啟", "Filter, or type an agent's name…": "篩選,或輸入 Agent 名稱…", "the name its User-Agent begins with": "User-Agent 開頭的名稱", "heard from in the last 30 days": "近 30 天有請求", @@ -721,7 +721,7 @@ magpie.strings({ "In agents’ lists": "Agent 列表裡的名稱", "Names in agents’ lists": "Agent 列表裡的名稱", "Whether “· routing group” follows a group’s name in the agents’ lists: one setting for every group, and for the provider after each model’s name, as on Settings.": "Agent 的模型列表裡,路由組名後面是否帶「· routing group」。這是所有路由組共用的一個設定,也決定模型名後面是否帶供應商,和「設定」裡的是同一個。", - "“· routing group” is set for every group above": "是否帶「· routing group」在上方統一設定,對所有路由組生效", + "“· routing group” is set for every group, under the list": "是否帶「· routing group」在列表下方統一設定,對所有路由組生效", "{name} is switched off: the group skips it until it is on again": "{name} 已關閉:開啟前這個組會跳過它", "{n} switched off": "{n} 個已關閉", "Off: agents aren't offered {name} and a request to it is turned away. Click to switch it on": "已關閉:Agent 列表裡沒有 {name},發給它的請求會被拒絕。點選開啟", @@ -1347,7 +1347,7 @@ magpie.strings({ "magpie is masking this request before routing it (Settings › Privacy), so who takes it isn't picked yet.": "magpie はルーティングの前にこのリクエストをマスクしています(設定 › プライバシー)。誰が処理するかはまだ決まっていません。", "magpie hasn't routed this request yet, so who takes it isn't picked yet.": "magpie はまだこのリクエストをルーティングしていないため、誰が処理するかはまだ決まっていません。", "Nothing took this request: {error}": "このリクエストを処理したものはありません: {error}", - "Go to the routing groups, below the requests": "リクエストの下にあるルーティンググループへ移動", + "{n} groups · {m} on": "{n} 個のグループ · {m} 個がオン", "Filter, or type an agent's name…": "絞り込み、またはエージェント名を入力…", "the name its User-Agent begins with": "User-Agent の先頭の名前", "heard from in the last 30 days": "過去 30 日にリクエストあり", @@ -1375,7 +1375,7 @@ magpie.strings({ "In agents’ lists": "エージェントの一覧での名前", "Names in agents’ lists": "エージェントの一覧での名前", "Whether “· routing group” follows a group’s name in the agents’ lists: one setting for every group, and for the provider after each model’s name, as on Settings.": "エージェントの一覧でグループ名の後に「· routing group」を付けるかどうか。すべてのグループに共通の設定で、モデル名の後のプロバイダ名にも効きます(「設定」と同じものです)。", - "“· routing group” is set for every group above": "「· routing group」を付けるかは上で全グループ共通に設定します", + "“· routing group” is set for every group, under the list": "「· routing group」を付けるかは一覧の下で全グループ共通に設定します", "{agent} guessed your next message for its composer by itself, reading the whole conversation again. Not a turn of the conversation; Codex composer predictions, under Settings in Codex's row on the Agents page, picks its model, and Codex's Settings › General › Show predictions turns it off.": "{agent} が入力欄に表示する次のメッセージの予測を自分で行い、そのたびに会話全体を読み直しました。会話のターンではありません。エージェントページの Codex の行にある設定の Codex の入力予測 でモデルを選べ、Codex の 設定 › 一般 › 予測候補を表示 でオフにできます。", "{name} is switched off: the group skips it until it is on again": "{name} はオフです。オンに戻すまでグループはスキップします", "{n} switched off": "{n} 件オフ", @@ -2014,7 +2014,7 @@ magpie.strings({ "magpie is masking this request before routing it (Settings › Privacy), so who takes it isn't picked yet.": "magpie maskiert diese Anfrage vor der Weiterleitung (Einstellungen › Datenschutz), daher steht noch nicht fest, wer sie übernimmt.", "magpie hasn't routed this request yet, so who takes it isn't picked yet.": "magpie hat diese Anfrage noch nicht weitergeleitet, daher steht noch nicht fest, wer sie übernimmt.", "Nothing took this request: {error}": "Niemand hat diese Anfrage übernommen: {error}", - "Go to the routing groups, below the requests": "Zu den Weiterleitungsgruppen unter den Anfragen springen", + "{n} groups · {m} on": "{n} Gruppen · {m} an", "Filter, or type an agent's name…": "Filtern oder Namen eines Agenten eingeben…", "the name its User-Agent begins with": "der Name, mit dem sein User-Agent beginnt", "heard from in the last 30 days": "in den letzten 30 Tagen gesehen", @@ -2042,7 +2042,7 @@ magpie.strings({ "In agents’ lists": "In den Listen der Agenten", "Names in agents’ lists": "Namen in den Listen der Agenten", "Whether “· routing group” follows a group’s name in the agents’ lists: one setting for every group, and for the provider after each model’s name, as on Settings.": "Ob in den Listen der Agenten „· routing group“ auf den Namen einer Gruppe folgt: eine Einstellung für alle Gruppen, und für den Anbieter nach jedem Modellnamen, wie in den Einstellungen.", - "“· routing group” is set for every group above": "„· routing group“ wird oben für alle Gruppen eingestellt", + "“· routing group” is set for every group, under the list": "„· routing group“ wird unter der Liste für alle Gruppen eingestellt", "{agent} guessed your next message for its composer by itself, reading the whole conversation again. Not a turn of the conversation; Codex composer predictions, under Settings in Codex's row on the Agents page, picks its model, and Codex's Settings › General › Show predictions turns it off.": "{agent} hat deine nächste Nachricht für sein Eingabefeld selbst vorhergesagt und dafür das ganze Gespräch erneut gelesen. Kein Zug des Gesprächs; das Modell wählst du mit Codex-Eingabevorhersagen unter Einstellungen in der Zeile von Codex auf der Seite Agenten, und in Codex unter Einstellungen › Allgemein › Textvorschläge anzeigen schaltest du es ab.", "{name} is switched off: the group skips it until it is on again": "{name} ist ausgeschaltet: Die Gruppe überspringt es, bis es wieder eingeschaltet ist", "{n} switched off": "{n} ausgeschaltet", diff --git a/internal/gui/assets/plugins/routing/routing.css b/internal/gui/assets/plugins/routing/routing.css index 411f94504..9d191ef70 100644 --- a/internal/gui/assets/plugins/routing/routing.css +++ b/internal/gui/assets/plugins/routing/routing.css @@ -270,20 +270,18 @@ .rt-accts:where(.max460, .max560) li > em { text-align: left; } :where(.rt.max560) .rt-stats { gap: 14px; } /* the Routing view */ -#view-routing .row-head { margin: 14px 0 6px; padding: 0 2px; gap: 0; } -#view-routing .row-head .note { font-size: 11px; color: var(--faint); margin-left: 8px; } +/* the Routing view, and the Routing groups view beside it */ +:is(#view-routing, #view-groups) .row-head { margin: 14px 0 6px; padding: 0 2px; gap: 0; } +:is(#view-routing, #view-groups) .row-head .note { font-size: 11px; color: var(--faint); margin-left: 8px; } #view-routing .row-head .rt-livedot + .note { margin-left: 8px; } -.rt-newgroup, .rt-gogroups { display: inline-flex; align-items: center; gap: 5px; } -.rt-newgroup svg, .rt-gogroups svg { width: 13px; height: 13px; flex: none; } -/* the routing groups, far below with many models: the head goes to them */ -.rt-gogroups { margin-right: 6px; flex: none; } -.rt-gogroups[data-fit="icon"] > span { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } -.rt-gogroups[data-fit="none"] { display: none; } -.rt-gsec:focus { outline: none; } -/* the routing groups' New group, at the top too: the groups sit below the - requests, out of sight on a first look (#944) */ -.rt-newgroup { margin-right: 6px; } .rt-gnew { display: inline-flex; align-items: center; gap: 4px; } +/* the groups page's toolbar: the filter first, then how many */ +.rt-gsec > .row-head:first-child .rt-gfilter { flex: 0 1 300px; width: auto; margin: 0; } +.rt-gsec > .row-head:first-child .rt-gcount { margin-left: 10px; white-space: nowrap; } +.rt-gsec > .row-head:first-child .rt-gfilter + .rt-gcount { margin-left: 10px; } +/* the settings for every group, a card under the list */ +.rt-gset > :is(.rt-gfound, .rt-gnames) { padding: 12px 14px; } +.rt-gset > .rt-gnames { border-top: 1px solid var(--line-2); } /* an email, hidden: stand-in letters of its shape, softly blurred — coming in out of focus when asked for */ .pii { filter: blur(2.2px); opacity: .5; user-select: none; } @@ -549,7 +547,7 @@ button.rt-session { cursor: pointer; } /* it pulses while a request is under way only (#2827) */ @media (prefers-reduced-motion: reduce) { .rt-livedot.on::after { animation: none; } } /* routing groups, and the providers routing over several of their own */ -.rt-gsec { display: grid; grid-template-columns: minmax(0, 1fr); gap: 6px; margin-top: 16px; } +.rt-gsec { display: grid; grid-template-columns: minmax(0, 1fr); gap: 6px; } .rt-gsec .row-head .note { margin-right: 6px; } /* the groups filtered by name and model, beside Select and New group */ .rt-gsec .rt-gfilter { width: 190px; min-width: 0; flex: 0 1 190px; height: 24px; margin: 0 6px 0 4px; } @@ -741,11 +739,11 @@ body.window .rt-gedit > .bar { --vfoot: 8px; } } .rt-gsec .segs .opt { white-space: nowrap; } /* the groups, in a page 520px wide or less */ -:where(.rt-more.max520) .rt-gsec .row-head .note { display: none; } -:where(.rt-more.max520) .rt-gsec .rt-gfilter { flex: 1 1 auto; width: auto; } -:where(.rt-more.max520) .rt-gedit { grid-template-columns: minmax(0, 1fr); gap: 4px; } -:where(.rt-more.max520) .rt-gedit label { text-align: left; padding-top: 8px; } -:where(.rt-more.max520) .rt-gedit .segs .opt { padding-left: 9px; padding-right: 9px; } +:where(.rt-gpage.max520) .rt-gsec .row-head .note { display: none; } +:where(.rt-gpage.max520) .rt-gsec .rt-gfilter { flex: 1 1 auto; width: auto; } +:where(.rt-gpage.max520) .rt-gedit { grid-template-columns: minmax(0, 1fr); gap: 4px; } +:where(.rt-gpage.max520) .rt-gedit label { text-align: left; padding-top: 8px; } +:where(.rt-gpage.max520) .rt-gedit .segs .opt { padding-left: 9px; padding-right: 9px; } /* the models and patterns take the column's width and no more: a grid's auto track grows to its widest row's content, so a long model name with its chips pushed the rows past the editor's edge, cut off there, and diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index c61063634..d973e6280 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -646,22 +646,31 @@ model's name (#968): a new group named "GPT 6.1 Sol" is said and sent as `group/gpt-6.1-sol`, and `groupSlug` folds a run of dots and trims them at the ends as `provider.GroupSlug` does, in English and Chinese, Chromium and WebKit. -`group-new-head.test.cjs` checks that a routing group of any models can be -made from the top of the Routing page, in Chromium and WebKit, English and +`group-new-head.test.cjs` checks that a routing group of any models is made +from the Routing groups page's toolbar, in Chromium and WebKit, English and Chinese (mintonight, #944: the groups' New group sat below the requests, so -only found groups were used). The page's head has New group with a plus and a -tooltip saying what a group is, in sight while the groups are below the fold; -its click opens an empty group's editor, brings it into view and focuses its -name. The groups' own New group has the plus too. No left-border accent. +only found groups were used). New group is in sight on arrival, with a plus +and a tooltip saying what a group is; its click opens an empty group's +editor, brings it into view and focuses its name, and a draft is replaced +only after Discard. No left-border accent. + +`routing-groups-page.test.cjs` checks that routing groups have a page of +their own, after Routing in the sidebar: its toolbar holds the filter, how +many groups there are and how many are on, Import, Select and New group as +the one filled button, in sight on arrival; the list follows, then Settings +(found groups, the names in agents' lists). The Routing page has no groups +and no jump to them. A request's group opens the groups page on its row, and +`?view=groups&newgroup=` opens a new group there. Every language, Chromium +and WebKit, at 1280px, 640px and 420px, with no sideways scroll. `name-suffix-where-named.test.cjs` checks the setting that says whether a provider's name or "· routing group" follows a name in the agents' lists (#868) where names are given, in Chromium and WebKit, English and Chinese. The provider editor's Names, prices & levels has its three choices and says what the lists -show. For the groups it is one setting for all of them, so it sits over the -groups on Routing (PAMI on Discord: in one group's editor it read as that -group's): a group's editor has no choices, only what its group will be called -and that it is set above; a pick there posts settings/plain-names once and the +show. For the groups it is one setting for all of them, so it sits under the +list on the Routing groups page (PAMI on Discord: in one group's editor it read +as that group's): a group's editor has no choices, only what its group will be +called and that it is set under the list; a pick there posts settings/plain-names once and the open editor's line follows it with its unsaved name. No click scrolls, nothing native, no left border, and every string has its Chinese, Japanese and German. @@ -714,13 +723,6 @@ back, neither click scrolls the page, the row is drawn in gateway mode, and nothing runs out of the row or the page sideways at 420px and 900px. Every language, Chromium and WebKit. -`routing-steady.test.cjs` scrolls the Routing page down to its routing groups, -opens one in its editor and types into its name, then streams six requests in -from the trace (new agents and accounts on the stage, failures and retries in -the story, the lists growing): the groups and the editor stay where they are -on the screen on every layout and scroll, the view's scrollTop moving by just -what grew above them, and the field keeps its focus and what was typed. - `routing-flood.test.cjs` takes the Routing page out of sight three ways (#302): the window hidden, the window covered and drawing no frames without saying it is hidden, and another tab open. Meanwhile 30 requests @@ -1977,9 +1979,9 @@ groups" (只通过路由分组使用; 悠悠哥 on Discord: hy4 vanished from th The model picker's filter, finding such a model, says why it isn't offered: hy3, in the group Mine, is reached by picking Mine ("Pick Mine" sets it); hy4, in no group, can't be used, and "Make a routing group of it" opens the -Routing page on a new group of it, added with `members: ["hunyuan/hy4"]`. +Routing groups page on a new group of it, added with `members: ["hunyuan/hy4"]`. The provider's editor names its models in no group under the tick (not once -unticked), each a click from a group; `?view=routing&newgroup=` opens the +unticked), each a click from a group; `?view=groups&newgroup=` opens the window on one, and the tray panel asks `window/main` for it. The page doesn't move, no left-border accent; English and Chinese, Chromium and WebKit. diff --git a/internal/gui/tests/builtins.test.cjs b/internal/gui/tests/builtins.test.cjs index 80a2c4c50..55b95b850 100644 --- a/internal/gui/tests/builtins.test.cjs +++ b/internal/gui/tests/builtins.test.cjs @@ -112,7 +112,10 @@ function server(lang, posts, broken) { const tabs = (page) => page.evaluate(() => [...document.querySelectorAll("#nav button[data-view]")].filter((b) => !b.hidden && b.offsetParent && getComputedStyle(b).display !== "none").map((b) => b.dataset.view)); const viewShown = (page) => page.evaluate(() => [...document.querySelectorAll("main.view")].filter((v) => !v.hidden).map((v) => v.id)); // the tabs with Sessions and Library off, the preset's masking on +// (Routing groups has a tab of its own in the sidebar only, from 1024 +// points; under it Routing's page opens them) const KEPT = ["agents", "providers", "routing", "gateway", "usage", "masking", "plugins"]; +const keptAt = (width) => (width >= 1024 ? KEPT.flatMap((k) => (k === "routing" ? [k, "groups"] : [k])) : KEPT); const rowsOf = (page) => page.evaluate(() => [...document.querySelectorAll("#builtinList .feat-row")].map((r) => { const b = r.querySelector('[role="switch"]'); return { id: r.dataset.id, name: r.querySelector(".name").textContent, on: b.getAttribute("aria-checked"), disabled: b.disabled, why: r.querySelector(".feat-why")?.textContent || "" }; @@ -145,7 +148,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.waitForSelector("#nav button.on"); const side = await page.evaluate(() => document.body.classList.contains("side-nav")); assert.equal(side, width >= 1024, `${where}: the layout`); - if (width >= 800) assert.deepEqual(await tabs(page), KEPT, `${where}: Sessions' and Library's tabs gone`); + if (width >= 800) assert.deepEqual(await tabs(page), keptAt(width), `${where}: Sessions' and Library's tabs gone`); // an address kept for a page switched off opens Agents assert.deepEqual(await viewShown(page), ["view-agents"], `${where}: ?view=sessions`); // Settings has no Features tab of its own, and Observability's is off @@ -206,7 +209,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.locator('#builtinList [data-id="library"] [role="switch"]').click(); await page.waitForSelector('#builtinList [data-id="library"] [aria-checked="true"]'); assert.deepEqual(posts, [["library", true]], where); - if (width >= 800) assert.deepEqual(await tabs(page), ["agents", "library", ...KEPT.slice(1)], `${where}: Library back`); + if (width >= 800) assert.deepEqual(await tabs(page), ["agents", "library", ...keptAt(width).slice(1)], `${where}: Library back`); assert.deepEqual(await viewShown(page), ["view-plugins"], `${where}: Plugins stays`); // Observability's, Routing's and Usage's rows can be below the fold: // the reader scrolls to them with the wheel, since the page puts back @@ -253,7 +256,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.locator('#builtinList [data-id="routing"] [role="switch"]').click(); await page.waitForSelector('#builtinList [data-id="routing"] [aria-checked="false"]'); assert.deepEqual(posts.at(-1), ["routing", false], where); - if (width >= 800) assert.deepEqual(await tabs(page), ["agents", "library", ...KEPT.slice(1).filter((k) => k !== "routing")], `${where}: Routing gone`); + if (width >= 800) assert.deepEqual(await tabs(page), ["agents", "library", ...keptAt(width).slice(1).filter((k) => k !== "routing" && k !== "groups")], `${where}: Routing gone`); assert.deepEqual(await viewShown(page), ["view-plugins"], `${where}: Plugins stays`); // and Usage: its tab goes const usageSwitch = page.locator('#builtinList [data-id="usage"] [role="switch"]'); @@ -262,7 +265,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await usageSwitch.click(); await page.waitForSelector('#builtinList [data-id="usage"] [aria-checked="false"]'); assert.deepEqual(posts.at(-1), ["usage", false], where); - if (width >= 800) assert.deepEqual(await tabs(page), ["agents", "library", ...KEPT.slice(1).filter((k) => k !== "routing" && k !== "usage")], `${where}: Usage gone`); + if (width >= 800) assert.deepEqual(await tabs(page), ["agents", "library", ...keptAt(width).slice(1).filter((k) => k !== "routing" && k !== "groups" && k !== "usage")], `${where}: Usage gone`); assert.deepEqual(await viewShown(page), ["view-plugins"], `${where}: Plugins stays`); // Discover brings the search back await pluginTabs(page, side).nth(1).click(); diff --git a/internal/gui/tests/drag-rows-shift.test.cjs b/internal/gui/tests/drag-rows-shift.test.cjs index cac78b99f..d3debd2dc 100644 --- a/internal/gui/tests/drag-rows-shift.test.cjs +++ b/internal/gui/tests/drag-rows-shift.test.cjs @@ -71,7 +71,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator(".rt-group[data-id=g]"); await card.waitFor(); const shift = (on) => page.evaluate((on) => { diff --git a/internal/gui/tests/filter-ime.test.cjs b/internal/gui/tests/filter-ime.test.cjs index 19c33f71b..6399e9f37 100644 --- a/internal/gui/tests/filter-ime.test.cjs +++ b/internal/gui/tests/filter-ime.test.cjs @@ -126,7 +126,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const typeIn = (page, text) => engine === "chromium" ? ime(page, text) : page.keyboard.type(text); test(`${engine} ${lang} ${width}px: the routing group filter takes one character a key`, async (t) => { - const { page, errors } = await open(t, "routing"); + const { page, errors } = await open(t, "groups"); const q = page.locator("input.rt-gfilter"); await q.waitFor(); await watch(page, "input.rt-gfilter"); @@ -135,7 +135,6 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.deepEqual(await field(page), { out: 0, same: true, value: "12", caret: [2, 2], connected: true }, "the filter after 1, 2"); // the groups follow it: only v12 has a 12 in it await page.waitForFunction(() => [...document.querySelectorAll(".rt-groups .rt-group")].map((r) => r.dataset.id).join() === "v12"); - assert.equal(await page.locator(".rt-gsec .row-head").first().locator(".label").textContent(), w.label); // a key in the middle goes where the caret is await page.keyboard.press("ArrowLeft"); await typeIn(page, "5"); @@ -147,8 +146,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // the row around it is still drawn again: in the other language // its words change, and the filter stays where it was await page.evaluate((l) => setLocale(l), w.other[0]); - await page.waitForFunction((s) => document.querySelector(".rt-gsec .row-head .label")?.textContent === s, w.other[1]); - assert.equal(await q.getAttribute("placeholder"), w.other[2]); + await page.waitForFunction((s) => document.querySelector("input.rt-gfilter")?.placeholder === s, w.other[2]); const f = await field(page); assert.equal(f.out, 0, "switching the language took the filter out"); assert.equal(f.value, "1"); diff --git a/internal/gui/tests/gateway-mode.test.cjs b/internal/gui/tests/gateway-mode.test.cjs index d207ee883..78ece32eb 100644 --- a/internal/gui/tests/gateway-mode.test.cjs +++ b/internal/gui/tests/gateway-mode.test.cjs @@ -85,7 +85,7 @@ const L = { // the Library stays, its MCP servers alone, for the router (treeman_26897) const HIDDEN = ["agents"]; // in the order the pages are grouped in (work, models, insights, extend) -const KEPT = ["sessions", "library", "providers", "routing", "gateway", "usage", "masking", "plugins"]; +const KEPT = ["sessions", "library", "providers", "routing", "groups", "gateway", "usage", "masking", "plugins"]; // the tabs shown, the page shown const tabs = (page) => page.evaluate(() => [...document.querySelectorAll("#nav button[data-view]")].filter((b) => !b.hidden && b.offsetParent).map((b) => b.dataset.view)); @@ -156,7 +156,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await clickStill(page, "#gatewayModeSegs .opt:nth-child(4)", `${where}: Off`); await page.waitForFunction(() => !document.querySelector('#nav button[data-view="agents"]').hidden); assert.deepEqual(posts.filter((p) => p[0] === "gateway-mode"), [["gateway-mode", "off"]], where); - assert.deepEqual(await tabs(page), ["agents", "sessions", "library", "providers", "routing", "gateway", "usage", "masking", "plugins"], `${where}: off`); + assert.deepEqual(await tabs(page), ["agents", "sessions", "library", "providers", "routing", "groups", "gateway", "usage", "masking", "plugins"], `${where}: off`); assert.deepEqual(await viewShown(page), ["view-settings"], `${where}: Settings stays`); assert.deepEqual(await agentRows(page), [true, true, true, true, true], `${where}: rows back`); assert.doesNotMatch(await page.locator("#gatewayModeSub").textContent(), new RegExp(L[lang].noAgents), where); @@ -190,7 +190,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.route("**/*", server(lang, [], { web, gateway: false, agents: true })); await page.goto("http://magpie.test/"); await page.waitForSelector("#nav button.on"); - assert.deepEqual(await tabs(page), ["agents", "sessions", "library", "providers", "routing", "gateway", "usage", "masking", "plugins"], where); + assert.deepEqual(await tabs(page), ["agents", "sessions", "library", "providers", "routing", "groups", "gateway", "usage", "masking", "plugins"], where); assert.deepEqual(await viewShown(page), ["view-agents"], where); await page.locator("#prefs").click(); await page.waitForSelector("#langPick span"); diff --git a/internal/gui/tests/grip-inset.test.cjs b/internal/gui/tests/grip-inset.test.cjs index f9d7d7556..7e7f7cc58 100644 --- a/internal/gui/tests/grip-inset.test.cjs +++ b/internal/gui/tests/grip-inset.test.cjs @@ -111,9 +111,9 @@ const kinds = [ { name: "Agents", mode: "window", view: "agents", row: '#agents > .row.agent[data-id="beta"]', grip: ".ag-handle" }, { name: "Providers", mode: "window", view: "providers", row: "#providers > .row.provider", grip: ".pv-handle" }, { name: "Usage", mode: "window", view: "usage", row: ".subscription-card", grip: ".us-handle" }, - { name: "Routing groups", mode: "window", view: "routing", row: '.rt-groups > .rt-group[data-id="g"]', grip: ".rt-ghandle" }, + { name: "Routing groups", mode: "window", view: "groups", row: '.rt-groups > .rt-group[data-id="g"]', grip: ".rt-ghandle" }, { - name: "a group's members", mode: "window", view: "routing", row: ".rt-gedit .fbrow:has(.rt-mhandle)", grip: ".rt-mhandle", + name: "a group's members", mode: "window", view: "groups", row: ".rt-gedit .fbrow:has(.rt-mhandle)", grip: ".rt-mhandle", open: async (page) => { await page.locator('.rt-groups > .rt-group[data-id="g"]').waitFor(); await page.evaluate(() => document.querySelector('.rt-groups > .rt-group[data-id="g"]').click()); diff --git a/internal/gui/tests/group-accounts.test.cjs b/internal/gui/tests/group-accounts.test.cjs index baafadc02..61374fcf7 100644 --- a/internal/gui/tests/group-accounts.test.cjs +++ b/internal/gui/tests/group-accounts.test.cjs @@ -81,7 +81,7 @@ async function open(engine, lang, width, members, held, t) { const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts, members, held)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator(".rt-group", { hasText: "Work" }); await card.waitFor(); return { page, card, errors, posts }; diff --git a/internal/gui/tests/group-arrange.test.cjs b/internal/gui/tests/group-arrange.test.cjs index e6d04ad7f..badca3003 100644 --- a/internal/gui/tests/group-arrange.test.cjs +++ b/internal/gui/tests/group-arrange.test.cjs @@ -95,7 +95,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-groups > .rt-group").nth(2).waitFor(); assert.deepEqual(await listed(page), ["one", "two", "auto-m"]); // a stack of logos is held whole in its handle, in its card, clear of diff --git a/internal/gui/tests/group-bulk-remove.test.cjs b/internal/gui/tests/group-bulk-remove.test.cjs index b6c3271e0..859e6da4d 100644 --- a/internal/gui/tests/group-bulk-remove.test.cjs +++ b/internal/gui/tests/group-bulk-remove.test.cjs @@ -83,7 +83,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = (name) => page.locator(".rt-groups .rt-group", { hasText: name }); await card("Model M").waitFor(); diff --git a/internal/gui/tests/group-classifier-failed.test.cjs b/internal/gui/tests/group-classifier-failed.test.cjs index 232e831b4..7337e75f4 100644 --- a/internal/gui/tests/group-classifier-failed.test.cjs +++ b/internal/gui/tests/group-classifier-failed.test.cjs @@ -64,7 +64,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator(".rt-group[data-id=local]"); await card.waitFor(); const line = card.locator(".mem.clsfail"); diff --git a/internal/gui/tests/group-context.test.cjs b/internal/gui/tests/group-context.test.cjs index 9f0d8b4f8..09e5034c6 100644 --- a/internal/gui/tests/group-context.test.cjs +++ b/internal/gui/tests/group-context.test.cjs @@ -80,7 +80,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator(".rt-group", { hasText: "Sol" }); await card.waitFor(); diff --git a/internal/gui/tests/group-decide-members.test.cjs b/internal/gui/tests/group-decide-members.test.cjs index ae3f9f30e..6df4f46c6 100644 --- a/internal/gui/tests/group-decide-members.test.cjs +++ b/internal/gui/tests/group-decide-members.test.cjs @@ -70,7 +70,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = (id) => page.locator(`.rt-group[data-id="${id}"]`); await card("g").waitFor(); const pop = page.locator("#pop"); diff --git a/internal/gui/tests/group-disabled-contrast.test.cjs b/internal/gui/tests/group-disabled-contrast.test.cjs index 020d97b3f..ba38f69c9 100644 --- a/internal/gui/tests/group-disabled-contrast.test.cjs +++ b/internal/gui/tests/group-disabled-contrast.test.cjs @@ -84,7 +84,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, theme, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const on = page.locator(".rt-group", { hasText: "Lit" }); const off = page.locator(".rt-group.disabled", { hasText: "Quiet" }); await off.waitFor(); diff --git a/internal/gui/tests/group-duplicate.test.cjs b/internal/gui/tests/group-duplicate.test.cjs index 08c3e049e..e014fae7f 100644 --- a/internal/gui/tests/group-duplicate.test.cjs +++ b/internal/gui/tests/group-duplicate.test.cjs @@ -90,7 +90,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // round is delivered on the next frame and nothing is painted wrong. page.on("pageerror", (e) => { if (!/^ResizeObserver loop completed with undelivered notifications/.test(e.message)) errors.push(e.message); }); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-groups > .rt-group").nth(1).waitFor(); // tall enough that the rows are in view unscrolled (1400: German // with the found groups' "leave out" line needs more than 1200): a scroll closes diff --git a/internal/gui/tests/group-editor-align.test.cjs b/internal/gui/tests/group-editor-align.test.cjs index 8522f1472..3ef4a5808 100644 --- a/internal/gui/tests/group-editor-align.test.cjs +++ b/internal/gui/tests/group-editor-align.test.cjs @@ -95,7 +95,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, withOne)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const w = await page.evaluate((lang) => Object.fromEntries(["New group", "Edit"].map((k) => [k, lang === "en" ? k : I18N[lang][k]])), lang); if (withOne) await page.locator(".rt-group", { hasText: "Glim" }).locator("button", { hasText: w.Edit }).click(); else await page.locator("button", { hasText: w["New group"] }).first().click(); diff --git a/internal/gui/tests/group-editor-fits.test.cjs b/internal/gui/tests/group-editor-fits.test.cjs index 571ca3913..1df6a7836 100644 --- a/internal/gui/tests/group-editor-fits.test.cjs +++ b/internal/gui/tests/group-editor-fits.test.cjs @@ -67,7 +67,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, web)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator(".rt-group", { hasText: "Free" }); await card.waitFor(); await card.locator("button.text").first().click(); diff --git a/internal/gui/tests/group-editor-selected.test.cjs b/internal/gui/tests/group-editor-selected.test.cjs index 04ae14b75..8ce138439 100644 --- a/internal/gui/tests/group-editor-selected.test.cjs +++ b/internal/gui/tests/group-editor-selected.test.cjs @@ -59,7 +59,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, theme, web)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator(".rt-group", { hasText: "Coding" }); await card.waitFor(); await card.locator("button.text").first().click(); diff --git a/internal/gui/tests/group-first-token.test.cjs b/internal/gui/tests/group-first-token.test.cjs index 22b81f36f..2c94871b3 100644 --- a/internal/gui/tests/group-first-token.test.cjs +++ b/internal/gui/tests/group-first-token.test.cjs @@ -83,7 +83,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator(".rt-group", { hasText: "Sol" }); await card.waitFor(); assert.equal(await card.locator(".tag", { hasText: w.tag }).count(), 0, "off by default"); diff --git a/internal/gui/tests/group-fold.test.cjs b/internal/gui/tests/group-fold.test.cjs index aa706cc3e..e0e40f549 100644 --- a/internal/gui/tests/group-fold.test.cjs +++ b/internal/gui/tests/group-fold.test.cjs @@ -74,7 +74,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator(".rt-group", { hasText: "Sol" }); const ed = page.locator(".rt-gedit"), head = ed.locator(".ehead"); const closed = () => page.waitForFunction(() => !document.querySelector(".rt-gedit") && document.querySelector(".rt-group")); diff --git a/internal/gui/tests/group-found-off.test.cjs b/internal/gui/tests/group-found-off.test.cjs index 574eff84a..bd9c00293 100644 --- a/internal/gui/tests/group-found-off.test.cjs +++ b/internal/gui/tests/group-found-off.test.cjs @@ -80,7 +80,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = (name) => page.locator(".rt-group", { hasText: name }); await card("Model M").waitFor(); const box = page.locator(".rt-gsec .rt-gfound"); @@ -89,13 +89,14 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.equal(await sw.getAttribute("aria-checked"), "true"); assert((await box.textContent()).includes(w.label)); assert((await box.textContent()).includes(w.onHint), "it says what found groups are"); - // by the list: right under the routing groups' head, over the cards + // under the list, in the page's Settings, the names in agents' lists + // (for every group) after it const order = await page.evaluate(() => { const s = document.querySelector(".rt-gsec"); - return [...s.children].map((c) => c.className); + return [...s.children].map((c) => c.className).filter((c) => c !== "rt-goff"); }); - // (the names in agents' lists, for every group, between them) - assert.deepEqual(order.slice(0, 4), ["row-head", "rt-gfound", "rt-gnames", "list rt-groups"]); + assert.deepEqual(order.slice(0, 4), ["row-head", "list rt-groups", "row-head rt-gset-head", "list rt-gset"]); + assert.deepEqual(await page.evaluate(() => [...document.querySelector(".rt-gset").children].map((c) => c.className)), ["rt-gfound", "rt-gnames"]); const border = await sw.evaluate((e) => { const c = getComputedStyle(e); return c.borderLeftWidth !== c.borderRightWidth || c.borderLeftColor !== c.borderRightColor; }); assert.equal(border, false, "no left-border accent"); diff --git a/internal/gui/tests/group-found-skip.test.cjs b/internal/gui/tests/group-found-skip.test.cjs index 8aa849709..d23fb33ec 100644 --- a/internal/gui/tests/group-found-skip.test.cjs +++ b/internal/gui/tests/group-found-skip.test.cjs @@ -86,7 +86,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator(".rt-group", { hasText: "Model M" }); await card.waitFor(); const pick = page.locator(".rt-gsec .rt-gfound .rt-skip-pick"); diff --git a/internal/gui/tests/group-from-model-add.test.cjs b/internal/gui/tests/group-from-model-add.test.cjs index 5fc24212f..c19b3a28d 100644 --- a/internal/gui/tests/group-from-model-add.test.cjs +++ b/internal/gui/tests/group-from-model-add.test.cjs @@ -64,8 +64,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts, refuse)); - await page.goto(`http://magpie.test/?view=routing&newgroup=${encodeURIComponent(MODEL)}`); - const ed = page.locator("#view-routing:not([hidden]) .rt-gedit"); + await page.goto(`http://magpie.test/?view=groups&newgroup=${encodeURIComponent(MODEL)}`); + const ed = page.locator("#view-groups:not([hidden]) .rt-gedit"); await ed.waitFor(); await ed.locator("input").first().fill("Hy4 preview"); // the reader wheels down until Add itself is under the pointer's @@ -93,7 +93,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const clickAdd = async () => { for (let i = 0; i < 80; i++) { const done = await page.evaluate(() => { - const v = document.querySelector("#view-routing"); + const v = document.querySelector("#view-groups"); return v.scrollTop + v.clientHeight >= v.scrollHeight - 1; }); if (done) break; diff --git a/internal/gui/tests/group-id-dots.test.cjs b/internal/gui/tests/group-id-dots.test.cjs index 6cb5542b1..5134b3938 100644 --- a/internal/gui/tests/group-id-dots.test.cjs +++ b/internal/gui/tests/group-id-dots.test.cjs @@ -58,7 +58,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], saved = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, saved)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-group", { hasText: "GPT-6.1 Sol" }).waitFor({ state: "attached" }); assert.deepEqual(await page.evaluate(() => ["GPT 6.1 Sol", "gpt-6.1-sol", "a..b", ".x.", "-.a.-", "claude/opus 5", "..."].map(groupSlug)), diff --git a/internal/gui/tests/group-import-replace.test.cjs b/internal/gui/tests/group-import-replace.test.cjs index 0eca7fbd7..25387cfaa 100644 --- a/internal/gui/tests/group-import-replace.test.cjs +++ b/internal/gui/tests/group-import-replace.test.cjs @@ -84,7 +84,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => { if (!/^ResizeObserver loop completed with undelivered notifications/.test(e.message)) errors.push(e.message); }); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-groups > .rt-group").nth(1).waitFor(); await page.waitForTimeout(500); await page.locator(".rt-gimportbtn").click(); diff --git a/internal/gui/tests/group-intent-sure.test.cjs b/internal/gui/tests/group-intent-sure.test.cjs index 32a9d2f03..8b8cdc2fe 100644 --- a/internal/gui/tests/group-intent-sure.test.cjs +++ b/internal/gui/tests/group-intent-sure.test.cjs @@ -62,7 +62,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const last = () => posts.filter((p) => p.path === "/api/groups/save").at(-1)?.body; const save = async (id) => { diff --git a/internal/gui/tests/group-member-drag.test.cjs b/internal/gui/tests/group-member-drag.test.cjs index e996a43de..0f42907df 100644 --- a/internal/gui/tests/group-member-drag.test.cjs +++ b/internal/gui/tests/group-member-drag.test.cjs @@ -71,7 +71,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator(".rt-group", { hasText: "G" }).first(); await card.waitFor(); await card.locator("button", { hasText: w.edit }).click(); diff --git a/internal/gui/tests/group-member-fast.test.cjs b/internal/gui/tests/group-member-fast.test.cjs index 1927fdf51..1fac7226d 100644 --- a/internal/gui/tests/group-member-fast.test.cjs +++ b/internal/gui/tests/group-member-fast.test.cjs @@ -84,7 +84,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator(".rt-group", { hasText: "Sol" }); await card.waitFor(); assert((await card.locator(".mem").textContent()).includes(w.label), "the card says the member is sent fast"); diff --git a/internal/gui/tests/group-member-free.test.cjs b/internal/gui/tests/group-member-free.test.cjs index c700b4b53..816f58ddc 100644 --- a/internal/gui/tests/group-member-free.test.cjs +++ b/internal/gui/tests/group-member-free.test.cjs @@ -70,7 +70,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator('.rt-group[data-id="g"]'); await card.waitFor(); diff --git a/internal/gui/tests/group-member-info.test.cjs b/internal/gui/tests/group-member-info.test.cjs index 060e20230..d1ce039ce 100644 --- a/internal/gui/tests/group-member-info.test.cjs +++ b/internal/gui/tests/group-member-info.test.cjs @@ -123,10 +123,10 @@ const rows = (page) => page.locator(".rt-gedit .fbrow").evaluateAll((rs) => rs.m // would: a scroll the reader didn't make (Playwright's own, before its // click) is put back (#1554), and the click lands on the window's foot async function reach(page, target) { - const view = await page.locator("#view-routing").boundingBox(); + const view = await page.locator("#view-groups").boundingBox(); await page.mouse.move(view.x + view.width / 2, view.y + view.height / 2); const rest = () => page.evaluate(() => new Promise((done) => { - const v = document.querySelector("#view-routing"); + const v = document.querySelector("#view-groups"); let last = -1; const look = () => { if (v.scrollTop === last) done(); else { last = v.scrollTop; setTimeout(look, 100); } }; look(); @@ -158,7 +158,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-group[data-id=g]").waitFor(); await page.locator(".rt-group[data-id=g]").click(); await page.locator(".rt-gedit .fbrow").first().waitFor(); @@ -210,7 +210,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-group[data-id=g3]").waitFor(); await page.locator(".rt-group[data-id=g3]").click(); await page.locator(".rt-gedit .fbrow").first().waitFor(); diff --git a/internal/gui/tests/group-member-levels.test.cjs b/internal/gui/tests/group-member-levels.test.cjs index 856b64090..d8dc2f6ae 100644 --- a/internal/gui/tests/group-member-levels.test.cjs +++ b/internal/gui/tests/group-member-levels.test.cjs @@ -78,7 +78,7 @@ async function open(engine, lang, width, members, t) { const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts, members)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator(".rt-group", { hasText: "Sol" }); await card.waitFor(); return { page, card, errors, posts }; diff --git a/internal/gui/tests/group-member-off.test.cjs b/internal/gui/tests/group-member-off.test.cjs index 46864e546..c3a568d03 100644 --- a/internal/gui/tests/group-member-off.test.cjs +++ b/internal/gui/tests/group-member-off.test.cjs @@ -69,7 +69,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator(".rt-group", { hasText: "Sol" }); await card.waitFor(); assert((await card.locator(".mem").textContent()).includes(w.off), "the card says the member is off"); diff --git a/internal/gui/tests/group-member-weight.test.cjs b/internal/gui/tests/group-member-weight.test.cjs index 2b1276e02..da5b1c0ac 100644 --- a/internal/gui/tests/group-member-weight.test.cjs +++ b/internal/gui/tests/group-member-weight.test.cjs @@ -77,7 +77,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const tr = (k, v = {}) => page.evaluate(([lang, k, v]) => (lang === "en" ? k : I18N[lang][k] || k).replace(/\{(\w+)\}/g, (_, n) => v[n]), [lang, k, v]); const card = page.locator(".rt-group", { hasText: "Sol" }); await card.waitFor(); diff --git a/internal/gui/tests/group-morph.test.cjs b/internal/gui/tests/group-morph.test.cjs index 655a91e57..2f15c854a 100644 --- a/internal/gui/tests/group-morph.test.cjs +++ b/internal/gui/tests/group-morph.test.cjs @@ -48,7 +48,7 @@ function serve(lang, saved) { // the height animation running on group b's slot, if any: its first and last // heights, and the slot's height now const slotMotion = (page) => page.evaluate(() => { - const n = document.querySelector('#view-routing [data-gslot="b"]'); + const n = document.querySelector('#view-groups [data-gslot="b"]'); const a = n?.getAnimations().find((x) => x.effect.getKeyframes().some((k) => k.height)); const ks = a?.effect.getKeyframes(); return { @@ -63,7 +63,7 @@ const slotMotion = (page) => page.evaluate(() => { // magpie moves the page only for the reader, so what is out of the window // is wheeled to as a reader would, then clicked async function reach(page, loc) { - const vb = await page.locator("#view-routing").boundingBox(); + const vb = await page.locator("#view-groups").boundingBox(); await page.mouse.move(vb.x + vb.width / 2, vb.y + vb.height / 2); for (let i = 0; i < 150; i++) { const b = await loc.boundingBox(); @@ -77,7 +77,7 @@ async function reach(page, loc) { const inSight = (page) => page.evaluate(() => { const r = document.querySelector('.rt-group[data-id="b"]').getBoundingClientRect(); - const v = document.querySelector("#view-routing").getBoundingClientRect(); + const v = document.querySelector("#view-groups").getBoundingClientRect(); return r.top >= v.top - 1 && r.bottom <= v.bottom + 1; }); @@ -93,7 +93,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", page.on("pageerror", (e) => errors.push(e.message)); let release; await page.route("**/*", serve(lang, new Promise((r) => { release = r; }))); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const row = page.locator(".rt-group[data-id=b]"); await row.waitFor(); const rowH = (await row.boundingBox()).height; @@ -155,7 +155,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", page.setDefaultTimeout(5000); page.setDefaultNavigationTimeout(60000); await page.route("**/*", serve("en", Promise.resolve())); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-group[data-id=b]").click(); await page.locator(".rt-gedit").waitFor(); assert.equal((await slotMotion(page)).from, null, "no height animation opening"); diff --git a/internal/gui/tests/group-new-head.test.cjs b/internal/gui/tests/group-new-head.test.cjs index fae10c314..fa250d9ee 100644 --- a/internal/gui/tests/group-new-head.test.cjs +++ b/internal/gui/tests/group-new-head.test.cjs @@ -2,11 +2,12 @@ // A routing group of any models is made with New group, which sat only at // the routing groups' head, below the requests: out of sight on a first // look, so a user used the found groups for days without knowing their -// own could be made (mintonight, #944). The Routing page's head has a New -// group too, by Hide accounts, with a plus and a tooltip saying what a -// group is; its click opens an empty group's editor and brings it into -// view, its name field focused. The groups' own New group has the plus as -// well. No left-border accent. In English and Chinese, Chromium and WebKit. +// own could be made (mintonight, #944). The groups have a page of their +// own since 11-06, and New group is its toolbar's filled button, in sight +// on arrival, with a plus and a tooltip saying what a group is; its click +// opens an empty group's editor and brings it into view, its name field +// focused. No left-border accent. In English and Chinese, Chromium and +// WebKit. const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); const path = require("node:path"); @@ -59,7 +60,7 @@ function serve(lang) { for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { for (const lang of ["en", "zh"]) { const w = words[lang]; - test(`${engine} ${lang}: New group in the Routing page's head`, async (t) => { + test(`${engine} ${lang}: New group on the groups page`, async (t) => { const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); const page = await (await browser.newContext({ viewport: { width: 1000, height: 560 }, reducedMotion: "reduce" })).newPage(); t.after(async () => { @@ -74,25 +75,20 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-group", { hasText: "Model M" }).waitFor({ state: "attached" }); - // the groups' own New group: with a plus - const inList = page.locator(".rt-gsec > .row-head button", { hasText: w.btn }); - assert.equal(await inList.count(), 1); - assert.equal(await inList.locator("svg").count(), 1, "the groups' New group has a plus"); - - // the page's head: a New group in sight on arrival, the groups not - const head = page.locator("#view-routing > .row-head #rtNewGroup"); + // the groups page's New group: in sight on arrival, with a plus + await page.evaluate(() => window.show("groups")); + const head = page.locator("#view-groups .rt-gsec > .row-head .rt-gnew"); await head.waitFor(); + assert.equal(await page.locator(".rt-gsec > .row-head button", { hasText: w.btn }).count(), 1); assert.equal((await head.textContent()).trim(), w.btn); assert.equal(await head.getAttribute("title"), w.tip); - assert.equal(await head.locator("svg").count(), 1); + assert.equal(await head.locator("svg").count(), 1, "New group has a plus"); const vh = await page.evaluate(() => innerHeight); const hb = await head.boundingBox(); - assert(hb && hb.y >= 0 && hb.y + hb.height <= vh, "the head's New group is in sight"); - const gTop = await page.locator(".rt-gsec").evaluate((e) => e.getBoundingClientRect().top); - assert(gTop > vh, `the groups are below the fold here (${gTop} > ${vh})`); + assert(hb && hb.y >= 0 && hb.y + hb.height <= vh, "New group is in sight"); const border = await head.evaluate((e) => { const c = getComputedStyle(e); return c.borderLeftWidth !== c.borderRightWidth || c.borderLeftColor !== c.borderRightColor; }); assert.equal(border, false, "no left-border accent"); @@ -107,10 +103,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", }); assert.equal(await ed.locator("input").first().inputValue(), ""); assert.equal(await ed.evaluate((e) => e.contains(document.activeElement) && document.activeElement.tagName), "INPUT"); - // Both New group entrances replace the same draft only after Discard. + // New group replaces the draft only after Discard. const name = ed.locator("input").first(); const ask = page.locator("dialog.action-confirm[open]"); - for (const entrance of [inList, head]) { + for (const entrance of [head]) { await name.fill("Unsaved group"); await page.mouse.move(500, 300); for (let i = 0; i < 20; i++) { @@ -128,7 +124,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.waitForFunction(() => document.querySelector(".rt-gedit input")?.value === ""); assert.equal(await ask.count(), 0, "Discard opens a clean new group"); } - // The model picker's entry must protect the same draft as both buttons. + // The model picker's entry protects the same draft as the button. await name.fill("Unsaved group"); const fromModel = () => page.evaluate(() => { window.newGroupWith("a/m", "Model A"); }); await fromModel(); diff --git a/internal/gui/tests/group-null-members.test.cjs b/internal/gui/tests/group-null-members.test.cjs index 5b4b2fbb6..8cda30d30 100644 --- a/internal/gui/tests/group-null-members.test.cjs +++ b/internal/gui/tests/group-null-members.test.cjs @@ -83,7 +83,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const row = (name) => page.locator(".rt-group", { has: page.locator(".nm b", { hasText: new RegExp("^" + name + "$") }) }); await row("Fast").waitFor(); assert.deepEqual(await page.locator(".rt-group .nm b").allTextContents(), ["Fast", "Plugin", "Odd", "Slow"], "every group is listed"); diff --git a/internal/gui/tests/group-patience.test.cjs b/internal/gui/tests/group-patience.test.cjs index b3f859a8b..64893e8a7 100644 --- a/internal/gui/tests/group-patience.test.cjs +++ b/internal/gui/tests/group-patience.test.cjs @@ -79,7 +79,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator(".rt-group", { hasText: "Sol" }); await card.waitFor(); diff --git a/internal/gui/tests/group-patterns.test.cjs b/internal/gui/tests/group-patterns.test.cjs index a96a40987..d8b03ea36 100644 --- a/internal/gui/tests/group-patterns.test.cjs +++ b/internal/gui/tests/group-patterns.test.cjs @@ -72,7 +72,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator(".rt-group", { hasText: "Free" }); await card.waitFor(); const pats = (await card.locator(".mem.pat").allTextContents()).map((x) => x.trim()); diff --git a/internal/gui/tests/group-pick-drawers.test.cjs b/internal/gui/tests/group-pick-drawers.test.cjs index 86d6420c3..a8d611994 100644 --- a/internal/gui/tests/group-pick-drawers.test.cjs +++ b/internal/gui/tests/group-pick-drawers.test.cjs @@ -65,7 +65,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator('.rt-group[data-id="g"]'); await card.waitFor(); await card.locator("button", { hasText: w.edit }).click(); diff --git a/internal/gui/tests/group-pick-filter.test.cjs b/internal/gui/tests/group-pick-filter.test.cjs index 13ee1498a..f0a617cb6 100644 --- a/internal/gui/tests/group-pick-filter.test.cjs +++ b/internal/gui/tests/group-pick-filter.test.cjs @@ -77,7 +77,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = (id) => page.locator(`.rt-group[data-id="${id}"]`); await card("g").waitFor(); await page.locator(".rt-gsec").evaluate((x) => x.scrollIntoView({ block: "center" })); // as the reader would diff --git a/internal/gui/tests/group-select-copy.test.cjs b/internal/gui/tests/group-select-copy.test.cjs index 26b757afa..1424b5d32 100644 --- a/internal/gui/tests/group-select-copy.test.cjs +++ b/internal/gui/tests/group-select-copy.test.cjs @@ -89,7 +89,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator(".rt-group", { hasText: "Free" }); await card.waitFor(); const ed = page.locator(".rt-gedit"); diff --git a/internal/gui/tests/group-share.test.cjs b/internal/gui/tests/group-share.test.cjs index 43cb9406d..e20e432c7 100644 --- a/internal/gui/tests/group-share.test.cjs +++ b/internal/gui/tests/group-share.test.cjs @@ -105,7 +105,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // page error; see group-duplicate.test.cjs page.on("pageerror", (e) => { if (!/^ResizeObserver loop completed with undelivered notifications/.test(e.message)) errors.push(e.message); }); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-groups > .rt-group").nth(1).waitFor(); // tall enough that the import box is in view unscrolled in every // language: a scroll closes the menu, and the page settles its own diff --git a/internal/gui/tests/group-switch-add-many.test.cjs b/internal/gui/tests/group-switch-add-many.test.cjs index 16eac3b1b..275bb7e0c 100644 --- a/internal/gui/tests/group-switch-add-many.test.cjs +++ b/internal/gui/tests/group-switch-add-many.test.cjs @@ -81,7 +81,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = (id) => page.locator(`.rt-group[data-id="${id}"]`); await card("g").waitFor(); await page.locator(".rt-gsec").evaluate((x) => x.scrollIntoView({ block: "center" })); // as the reader would diff --git a/internal/gui/tests/group-template.test.cjs b/internal/gui/tests/group-template.test.cjs index aed8f24d9..d2ae8d809 100644 --- a/internal/gui/tests/group-template.test.cjs +++ b/internal/gui/tests/group-template.test.cjs @@ -95,7 +95,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // WebKit's notice when a layout outruns its observers, not a fault page.on("pageerror", (e) => { if (!/^ResizeObserver loop completed with undelivered notifications/.test(e.message)) errors.push(e.message); }); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const cards = page.locator(".rt-gtpl-card"); await cards.nth(2).waitFor(); await page.waitForTimeout(500); @@ -159,7 +159,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // enough groups of the user's that the editor, last in the list, // opens below the window await page.route("**/*", serve(lang, posts, 12)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const btn = page.locator(".rt-gtplbtn"); await btn.waitFor(); await page.waitForTimeout(500); @@ -191,7 +191,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // WebKit's notice when a layout outruns its observers, not a fault page.on("pageerror", (e) => { if (!/^ResizeObserver loop completed with undelivered notifications/.test(e.message)) errors.push(e.message); }); await page.route("**/*", serve(lang, [])); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const smart = page.locator(".rt-gtpl-card[data-kind=smart]"); await smart.waitFor(); if (process.env.ARTIFACT_DIR) await page.locator(".rt-gtpl").screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-group-template-cards.png`) }); diff --git a/internal/gui/tests/group-unlists.test.cjs b/internal/gui/tests/group-unlists.test.cjs index ca74fb466..33a0bc9ac 100644 --- a/internal/gui/tests/group-unlists.test.cjs +++ b/internal/gui/tests/group-unlists.test.cjs @@ -70,7 +70,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator(".rt-group", { hasText: "Glim" }); await card.waitFor(); const w = await page.evaluate(([keys, lang]) => Object.fromEntries(keys.map((k) => [k, lang === "en" ? k : I18N[lang][k]])), [KEYS, lang]); diff --git a/internal/gui/tests/menu-input-scroll.test.cjs b/internal/gui/tests/menu-input-scroll.test.cjs index ad503c25b..81cd4b187 100644 --- a/internal/gui/tests/menu-input-scroll.test.cjs +++ b/internal/gui/tests/menu-input-scroll.test.cjs @@ -70,7 +70,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const group = page.locator(".rt-group").first(); await group.waitFor(); await press(page, group.locator("button", { hasText: words[lang].edit })); diff --git a/internal/gui/tests/model-same-name-tell.test.cjs b/internal/gui/tests/model-same-name-tell.test.cjs index a2f3aa101..bca45b17b 100644 --- a/internal/gui/tests/model-same-name-tell.test.cjs +++ b/internal/gui/tests/model-same-name-tell.test.cjs @@ -135,10 +135,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", ]); await page.keyboard.press("Escape"); - // the Routing page's card of a group of two alike says each one's source + // the groups page's card of a group of two alike says each one's source await page.evaluate(() => document.querySelector("#tellAnchor")?.remove()); - await page.goto("http://magpie.test/?view=routing"); - const mem = page.locator("#view-routing .mem", { hasText: "DeepSeek-V4.1-Flash" }).first(); + await page.goto("http://magpie.test/?view=groups"); + const mem = page.locator("#view-groups .mem", { hasText: "DeepSeek-V4.1-Flash" }).first(); await mem.waitFor(); const said = await mem.textContent(); assert.ok(said.includes("DeepSeek-V4.1-Flash · buddy") && said.includes("DeepSeek-V4.1-Flash · cline"), said); diff --git a/internal/gui/tests/mono-icon-redraw.test.cjs b/internal/gui/tests/mono-icon-redraw.test.cjs index 2f6d7fdce..21f05a020 100644 --- a/internal/gui/tests/mono-icon-redraw.test.cjs +++ b/internal/gui/tests/mono-icon-redraw.test.cjs @@ -94,7 +94,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", } }); }); await page.route("**/*", serve(lang, asked)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator(".rt-group", { hasText: "DeepSeek V4" }); await card.waitFor(); await card.locator("button", { hasText: words[lang].edit }).click(); diff --git a/internal/gui/tests/name-suffix-no-names.test.cjs b/internal/gui/tests/name-suffix-no-names.test.cjs index d45aa540d..e0a9bbcfd 100644 --- a/internal/gui/tests/name-suffix-no-names.test.cjs +++ b/internal/gui/tests/name-suffix-no-names.test.cjs @@ -92,7 +92,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await sub.waitFor(); assert.equal(await sub.textContent(), said[lang]); assert.equal(await overflows(page), false, "the page scrolls sideways"); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const note = page.locator(".rt-gnames .no-names"); await note.waitFor(); assert.equal(await note.textContent(), said[lang]); @@ -123,7 +123,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const note = page.locator(".mnames:not([hidden]) .msuffix .no-names"); await note.waitFor(); assert.equal(await note.textContent(), said.en); - for (const [view, sel] of [["routing", ".rt-gnames .no-names"], ["settings", ".row.pref .sub.no-names"]]) { + for (const [view, sel] of [["groups", ".rt-gnames .no-names"], ["settings", ".row.pref .sub.no-names"]]) { await page.goto(`http://magpie.test/?view=${view}`); await page.locator(sel).waitFor(); assert.equal(await page.locator(sel).textContent(), said.en); @@ -135,7 +135,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.goto("http://magpie.test/?view=settings"); await page.locator("#plainNamesSegs .opt").first().waitFor(); assert.equal(await page.locator(".row.pref", { has: page.locator("#plainNamesSegs") }).locator(".sub").count(), 0); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-gnames .segs").waitFor(); assert.equal(await page.locator(".rt-gnames .no-names:visible").count(), 0); assert.deepEqual(errors, []); diff --git a/internal/gui/tests/name-suffix-saved.test.cjs b/internal/gui/tests/name-suffix-saved.test.cjs index e6d0f1a07..752f941c4 100644 --- a/internal/gui/tests/name-suffix-saved.test.cjs +++ b/internal/gui/tests/name-suffix-saved.test.cjs @@ -96,7 +96,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", test(`${engine} ${lang} ${width}px: Routing opened first shows the saved Off, and Settings and back keep it`, async (t) => { const posts = []; const { page, errors, tr } = await launch(t, engine, lang, width, OFF, {}, posts); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-group", { hasText: "Fast" }).waitFor(); const set = page.locator(".rt-gnames"); await set.locator(".segs").waitFor(); @@ -105,12 +105,15 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // a group's editor says what its group is called there: no suffix await page.locator(".rt-group", { hasText: "Fast" }).locator("button", { hasText: await tr("Edit") }).click(); const row = page.locator(".rt-gedit label", { hasText: new RegExp(`^${await tr("In agents’ lists")}$`) }).locator("xpath=following-sibling::div[1]"); - await says(row.locator(".hint"), (await tr("Agents’ lists show “{label}”", { label: "Fast" })) + " · " + (await tr("“· routing group” is set for every group above"))); + await says(row.locator(".hint"), (await tr("Agents’ lists show “{label}”", { label: "Fast" })) + " · " + (await tr("“· routing group” is set for every group, under the list"))); // Settings says the same, and coming back still does await page.locator("#prefs").click(); await page.locator("#plainNamesSegs .opt.on").waitFor(); await picked(page.locator("#plainNamesSegs .opt.on"), await tr("Off")); - await page.locator('#nav button[data-view="routing"]').click(); + // the groups tab is the sidebar's; the header's row reaches them from Routing + const tab = page.locator('#nav button[data-view="groups"]'); + if (await tab.isVisible()) await tab.click(); + else { await page.locator('#nav button[data-view="routing"]').click(); await page.locator("#rtToGroups").click(); } await picked(page.locator(".rt-gnames .opt.on"), await tr("Off")); assert.deepEqual(posts, [], "nothing is written"); assert.deepEqual(errors, []); @@ -119,7 +122,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", test(`${engine} ${lang} ${width}px: Routing drawn before the state comes in follows the saved "Not on names I set"`, async (t) => { const posts = []; const { page, errors, tr } = await launch(t, engine, lang, width, OWN, { stateDelay: 600 }, posts); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const set = page.locator(".rt-gnames"); await set.locator(".segs").waitFor(); await picked(set.locator(".opt.on"), await tr("Not on names I set")); diff --git a/internal/gui/tests/name-suffix-where-named.test.cjs b/internal/gui/tests/name-suffix-where-named.test.cjs index bb89b863d..4047a6a18 100644 --- a/internal/gui/tests/name-suffix-where-named.test.cjs +++ b/internal/gui/tests/name-suffix-where-named.test.cjs @@ -21,9 +21,9 @@ const { chromium, webkit } = require("playwright"); const assets = path.resolve(__dirname, "../assets"); const words = { en: { names: "Names, prices & levels", edit: "Edit", general: "General", global: "“Provider in model names” is one setting for every provider", change: "Change in Settings", own: "Not on names I set", on: "On", off: "Off", label: "In agents’ lists", - shows: (l) => `Agents’ lists show “${l}”`, above: " · “· routing group” is set for every group above", setting: "Names in agents’ lists" }, + shows: (l) => `Agents’ lists show “${l}”`, above: " · “· routing group” is set for every group, under the list", setting: "Names in agents’ lists" }, zh: { names: "名称、价格与推理档位", edit: "编辑", general: "常规", global: "「模型名带供应商」是全局设置,对所有供应商生效", change: "在设置中修改", own: "自定义名称不带供应商", on: "开启", off: "关闭", label: "Agent 列表里的名称", - shows: (l) => `Agent 的模型列表里显示为「${l}」`, above: " · 是否带「· routing group」在上方统一设置,对所有路由组生效", setting: "Agent 列表里的名称" }, + shows: (l) => `Agent 的模型列表里显示为「${l}」`, above: " · 是否带「· routing group」在列表下方统一设置,对所有路由组生效", setting: "Agent 列表里的名称" }, }; function serve(lang, posts) { @@ -135,16 +135,16 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", test(`${engine} ${lang}: "· routing group" is set over the groups, for all of them, and a group's editor says what it shows`, async (t) => { const posts = []; const { page, errors } = await launch(t, engine, lang, posts); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator(".rt-group", { hasText: "Fast" }); await card.waitFor(); - // the setting is over the groups, before the first card + // the setting is under the groups, in the page's Settings (11-06) const set = page.locator(".rt-gnames"); await set.waitFor(); assert.equal((await set.locator("b").textContent()).trim(), w.setting); assert.deepEqual((await set.locator(".segs .opt").allTextContents()).map((s) => s.trim()), [w.off, w.own, w.on]); assert.equal((await set.locator(".opt.on").textContent()).trim(), w.on); - assert.ok(await set.evaluate((s) => !!(s.compareDocumentPosition(document.querySelector(".rt-group")) & Node.DOCUMENT_POSITION_FOLLOWING)), "the setting is over the groups"); + assert.ok(await set.evaluate((s) => !!(s.compareDocumentPosition(document.querySelector(".rt-group")) & Node.DOCUMENT_POSITION_PRECEDING)), "the setting is under the groups"); await card.locator("button", { hasText: w.edit }).click(); const ed = page.locator(".rt-gedit"); const row = ed.locator("label", { hasText: new RegExp(`^${w.label}$`) }).locator("xpath=following-sibling::div[1]"); @@ -155,6 +155,16 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // the name typed is the name shown await ed.locator("input").first().fill("Fast lane"); assert.equal(await row.locator(".hint").textContent(), w.shows("Fast lane · routing group") + w.above); + // the setting, under the open editor, brought into sight by the wheel + // first, as a reader would: what is measured is the click alone + const vp = page.viewportSize(); + await page.mouse.move(vp.width / 2, vp.height / 2); + for (let i = 0; i < 40; i++) { + const r = await set.boundingBox(); + if (r.y >= 0 && r.y + r.height <= vp.height) break; + await page.mouse.wheel(0, r.y + r.height - vp.height + 40); + await page.waitForTimeout(60); + } const before = await scrolls(page); await set.locator(".opt", { hasText: w.own }).click(); await page.locator(".rt-gnames .opt.on", { hasText: w.own }).waitFor(); @@ -164,12 +174,12 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.deepEqual(posts, [{ mode: "own" }]); assert.deepEqual(await scrolls(page), before, "the click scrolled the page"); // nothing native, no stripe down the side - assert.equal(await page.locator("#view-routing select").count(), 0); + assert.equal(await page.locator("#view-groups select").count(), 0); assert.equal(await set.evaluate((e) => getComputedStyle(e).borderLeftWidth), "0px"); assert.equal(await row2.evaluate((e) => getComputedStyle(e).borderLeftWidth), "0px"); const missing = await page.evaluate(() => ["Agents’ lists show “{label}”", "In agents’ lists", "“Provider in model names” is one setting for every provider", "Change in Settings", "Not on names I set", "Provider in model names", - "Names in agents’ lists", "“· routing group” is set for every group above", + "Names in agents’ lists", "“· routing group” is set for every group, under the list", "Whether “· routing group” follows a group’s name in the agents’ lists: one setting for every group, and for the provider after each model’s name, as on Settings."] .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/own-requests.test.cjs b/internal/gui/tests/own-requests.test.cjs index 0002dbaad..3457a3d21 100644 --- a/internal/gui/tests/own-requests.test.cjs +++ b/internal/gui/tests/own-requests.test.cjs @@ -231,7 +231,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.route("**/*", serveRouting(lang)); try { const open = async (i) => { - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const g = page.locator(".rt-group").nth(i); await g.waitFor(); const edit = g.locator("button", { hasText: await page.evaluate(() => t("Edit")) }); diff --git a/internal/gui/tests/rate-limited-sink.test.cjs b/internal/gui/tests/rate-limited-sink.test.cjs index ba90f1ad9..ca109c774 100644 --- a/internal/gui/tests/rate-limited-sink.test.cjs +++ b/internal/gui/tests/rate-limited-sink.test.cjs @@ -144,7 +144,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.match(await stage.textContent(), new RegExp(w.row)); await page.waitForFunction((s) => document.body.innerText.includes(s), zh ? "已排到最后" : "so it went to the back"); - // the providers with several accounts: set at once + // the providers with several accounts, on the Routing groups page: + // set at once + await page.evaluate(() => window.show("groups")); const pool = page.locator(".rt-pool", { hasText: "WorkBuddy AI" }); await pool.waitFor(); // the pool sits under the window's foot: wheeled to, as the reader diff --git a/internal/gui/tests/removed-groups-menu-scroll.test.cjs b/internal/gui/tests/removed-groups-menu-scroll.test.cjs index a73bc281c..f36214ca2 100644 --- a/internal/gui/tests/removed-groups-menu-scroll.test.cjs +++ b/internal/gui/tests/removed-groups-menu-scroll.test.cjs @@ -71,7 +71,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const line = page.locator(".rt-ghidden"); await line.waitFor(); assert.equal((await line.textContent()).trim(), words[lang]); diff --git a/internal/gui/tests/routing-classifier-above.test.cjs b/internal/gui/tests/routing-classifier-above.test.cjs index 27c10327a..50f0775be 100644 --- a/internal/gui/tests/routing-classifier-above.test.cjs +++ b/internal/gui/tests/routing-classifier-above.test.cjs @@ -84,7 +84,7 @@ async function open(t, engine, lang, width) { page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, routeOf())); await page.goto("http://magpie.test/?view=routing"); - await page.locator(".rt-group").first().waitFor(); + await page.locator("#view-routing .rt-stage").waitFor(); return { page, errors }; } diff --git a/internal/gui/tests/routing-classifier-said.test.cjs b/internal/gui/tests/routing-classifier-said.test.cjs index c8dd72a4d..d64437977 100644 --- a/internal/gui/tests/routing-classifier-said.test.cjs +++ b/internal/gui/tests/routing-classifier-said.test.cjs @@ -80,7 +80,7 @@ async function open(t, engine, lang, width, said) { page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, routeOf(said))); await page.goto("http://magpie.test/?view=routing"); - await page.locator(".rt-group").first().waitFor(); + await page.locator("#view-routing .rt-stage").waitFor(); return { page, errors }; } diff --git a/internal/gui/tests/routing-compact.test.cjs b/internal/gui/tests/routing-compact.test.cjs index 8994f5b3b..8118c8238 100644 --- a/internal/gui/tests/routing-compact.test.cjs +++ b/internal/gui/tests/routing-compact.test.cjs @@ -73,7 +73,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", test(`${engine} ${lang}: a rule for compacting`, async (t) => { const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); t.after(() => browser.close()); - const page = await (await browser.newContext({ viewport: { width: 1100, height: 1400 } })).newPage(); + const page = await (await browser.newContext({ viewport: { width: 1100, height: 1400 }, reducedMotion: "reduce" })).newPage(); page.setDefaultTimeout(5000); page.setDefaultNavigationTimeout(60000); const errors = [], posts = []; @@ -81,14 +81,16 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.route("**/*", serve(lang, posts)); await page.goto("http://magpie.test/?view=routing"); const group = page.locator(".rt-group").first(); - await group.waitFor(); + await group.waitFor({ state: "attached" }); // the compaction in the trace, told as one await page.waitForFunction((s) => document.documentElement.innerText.includes(s), w.story); const said = await page.evaluate(() => document.documentElement.innerText); assert(said.includes(w.small), "the model passed over is named"); - // the group's rule, in words + // the group's rule, in words, on the groups page + await page.evaluate(() => window.show("groups")); + await group.waitFor(); const title = await group.evaluate((g) => [...g.querySelectorAll("[title]")].map((e) => e.title).join("\n")); assert(title.includes(`1. ${w.cond} →`), `the rule reads as compacting: ${title}`); diff --git a/internal/gui/tests/routing-days-fit.test.cjs b/internal/gui/tests/routing-days-fit.test.cjs index 9280ae2d2..d50722ada 100644 --- a/internal/gui/tests/routing-days-fit.test.cjs +++ b/internal/gui/tests/routing-days-fit.test.cjs @@ -17,7 +17,9 @@ const ymd = (d) => [d.getFullYear(), d.getMonth() + 1, d.getDate()].map((n) => S const allDays = Array.from({ length: 30 }, (_, i) => ({ day: ymd(new Date(now.getTime() - i * 864e5)), requests: 100 + i })); const at = (i) => new Date(now.getTime() - (i + 1) * 60e3).toISOString(); const who = { id: "fixture-key", provider: "fixture", name: "Fixture", who: "key-1", kind: "key", model: "model-a", routing: "", used: 0 }; -const routes = Array.from({ length: 4 }, (_, i) => ({ +// a day's requests fill the window, as a day of 100 or more does: the bar +// held when a day comes in needs the room under it to scroll into +const routes = Array.from({ length: 12 }, (_, i) => ({ id: 100 - i, seq: 100 - i, time: at(i), agent: "fixture", model: "model-a", provider: "fixture", order: [who], tries: [{ id: who.id, model: "model-a", start: at(i), done: true, status: 200, ms: 1200 }], done: true, status: 200, ms: 1200, tokens: 3000, diff --git a/internal/gui/tests/routing-editor-foot.test.cjs b/internal/gui/tests/routing-editor-foot.test.cjs index 57f0d88af..429860319 100644 --- a/internal/gui/tests/routing-editor-foot.test.cjs +++ b/internal/gui/tests/routing-editor-foot.test.cjs @@ -3,7 +3,7 @@ // the editor runs on below it (Jiabubu on Discord): the Scroll to top and // Scroll to bottom capsule (scrollends.js) sat over Add, and under the bar's // ground the view's own foot padding showed as a gap above the window's -// edge. Here a New group editor on a long Routing page is scrolled so its +// edge. Here the editor of a group far down the Routing groups page is scrolled so its // bar is held: the bar's ground reaches the window's edge, and the capsule, // once in, is above the bar and over none of its buttons. Chromium and // WebKit, the desktop window and the browser page, wide and narrow, @@ -20,7 +20,7 @@ const ids = models.map((m) => m.id); // enough groups above for the page to be scrolled a screen down const groups = { models, pools: [], - groups: Array.from({ length: 16 }, (_, i) => ({ id: `g${i}`, name: `group ${i}`, routing: "order", members: ids, ready: true, memberInfo: ids.map((id) => ({ id, ready: true })), offers: [], shared: [] })), + groups: Array.from({ length: 40 }, (_, i) => ({ id: `g${i}`, name: `group ${i}`, routing: "order", members: ids, ready: true, memberInfo: ids.map((id) => ({ id, ready: true })), offers: [], shared: [] })), }; function serve(lang, web) { @@ -61,25 +61,32 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, web)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-group").nth(15).waitFor(); - await page.locator(".rt-newgroup:visible").first().click(); + // a group far down the list, its editor opened in its place + await page.evaluate(() => [...document.querySelectorAll(".rt-group")[20].querySelectorAll("button")].find((b) => b.textContent === t("Edit")).click()); await page.locator(".rt-gedit").waitFor(); // the editor's top just under the window's: the page a screen - // down, the editor running on below, its bar held at the foot - await page.evaluate(() => { - const v = document.querySelector("#view-routing"), e = document.querySelector(".rt-gedit"); - v.scrollTop += e.getBoundingClientRect().top - v.getBoundingClientRect().top - 20; - if (v.scrollTop <= v.clientHeight) { // the editor near the top: groups go above it - v.scrollTop = v.clientHeight + 40; - } + // down, the editor running on below, its bar held at the foot; + // by the wheel, as a reader scrolls (a scroll by code is put back) + const want = await page.evaluate(() => { + const v = document.querySelector("#view-groups"), e = document.querySelector(".rt-gedit"); + return Math.max(v.scrollTop + e.getBoundingClientRect().top - v.getBoundingClientRect().top - 20, v.clientHeight + 40); }); + const vb = await page.locator("#view-groups").boundingBox(); + await page.mouse.move(vb.x + vb.width / 2, vb.y + vb.height / 2); + for (let i = 0; i < 40; i++) { + const now = await page.evaluate(() => document.querySelector("#view-groups").scrollTop); + if (Math.abs(now - want) < 2) break; + await page.mouse.wheel(0, want - now); + await page.waitForTimeout(60); + } // the capsule comes on the window's scroll, a frame later await page.waitForFunction(() => document.querySelector(".view-ends.on")); await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => setTimeout(r, 250))))); const m = await page.evaluate(() => { const box = (e) => { const b = e.getBoundingClientRect(); return { top: b.top, bottom: b.bottom, left: b.left, right: b.right }; }; - const v = document.querySelector("#view-routing"), e = document.querySelector(".rt-gedit"), bar = e.querySelector(":scope > .bar"); + const v = document.querySelector("#view-groups"), e = document.querySelector(".rt-gedit"), bar = e.querySelector(":scope > .bar"); return { view: box(v), ed: box(e), bar: box(bar), ends: box(document.querySelector(".view-ends")), buttons: [...bar.querySelectorAll("button")].map((b) => ({ text: b.textContent, ...box(b) })), scrolled: v.scrollTop > v.clientHeight }; }); assert(m.scrolled && m.ed.bottom > m.view.bottom + 40, `${at}: the page a screen down and the editor running on below the window: ${JSON.stringify([m.ed, m.view])}`); diff --git a/internal/gui/tests/routing-folder.test.cjs b/internal/gui/tests/routing-folder.test.cjs index e420f85ed..e858b079f 100644 --- a/internal/gui/tests/routing-folder.test.cjs +++ b/internal/gui/tests/routing-folder.test.cjs @@ -73,7 +73,7 @@ function serve(lang, posts) { async function open(t, engine, lang, width) { const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); t.after(() => browser.close()); - const page = await (await browser.newContext({ viewport: { width, height: 1400 } })).newPage(); + const page = await (await browser.newContext({ viewport: { width, height: 1400 }, reducedMotion: "reduce" })).newPage(); page.setDefaultTimeout(5000); page.setDefaultNavigationTimeout(60000); const errors = [], posts = []; @@ -81,7 +81,7 @@ async function open(t, engine, lang, width) { await page.route("**/*", serve(lang, posts)); await page.goto("http://magpie.test/?view=routing"); const group = page.locator(".rt-group").first(); - await group.waitFor(); + await group.waitFor({ state: "attached" }); return { page, group, errors, posts }; } @@ -115,6 +115,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.waitForFunction((s) => document.documentElement.innerText.includes(s), w.dir); const said = await page.evaluate(() => document.documentElement.innerText); assert(said.includes(w.cond), `the rule's folders are told: ${said.slice(0, 2000)}`); + await page.evaluate(() => window.show("groups")); + await group.waitFor(); // the group's rule, in words const title = await group.evaluate((g) => [...g.querySelectorAll("[title]")].map((e) => e.title).join("\n")); @@ -154,6 +156,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", test(`${engine} ${lang}: a rule by folder at a phone's width`, async (t) => { const { page, group, errors } = await open(t, engine, lang, 390); + await page.evaluate(() => window.show("groups")); await press(page, group.locator("button", { hasText: w.edit })); // the group is below the fold here const fd = page.locator(".rt-gedit .rt-rule").first().locator(".rt-cond.fd"); await fd.waitFor(); diff --git a/internal/gui/tests/routing-group-strategy.test.cjs b/internal/gui/tests/routing-group-strategy.test.cjs index d336e50bf..593c80b47 100644 --- a/internal/gui/tests/routing-group-strategy.test.cjs +++ b/internal/gui/tests/routing-group-strategy.test.cjs @@ -86,7 +86,7 @@ async function open(t, engine, { lang, theme = "light", web = true, width = 1100 const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, theme, web, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-group", { hasText: "Auto" }).waitFor(); return { page, errors, posts }; } @@ -94,7 +94,7 @@ async function open(t, engine, { lang, theme = "light", web = true, width = 1100 // the reader wheels the row into the middle of the view (code that scrolls // is put back: only the reader moves the view) async function wheelTo(page, row, width) { - const dy = await row.evaluate((g) => { const v = document.querySelector("#view-routing"); + const dy = await row.evaluate((g) => { const v = document.querySelector("#view-groups"); return Math.round(g.getBoundingClientRect().top - v.getBoundingClientRect().top - v.clientHeight / 2); }); await page.mouse.move(width / 2, 400); await page.mouse.wheel(0, dy); @@ -124,8 +124,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.equal(await page.locator(".rt-group select, select").count(), 0, "no native select"); // the reader scrolls the card to the middle, then opens its routing - const view = page.locator("#view-routing"); - const dy = await card().evaluate((g) => { const v = document.querySelector("#view-routing"); + const view = page.locator("#view-groups"); + const dy = await card().evaluate((g) => { const v = document.querySelector("#view-groups"); return Math.round(g.getBoundingClientRect().top - v.getBoundingClientRect().top - v.clientHeight / 2); }); await page.mouse.move(550, 400); await page.mouse.wheel(0, dy); diff --git a/internal/gui/tests/routing-groups-jump.test.cjs b/internal/gui/tests/routing-groups-jump.test.cjs deleted file mode 100644 index 227fb6766..000000000 --- a/internal/gui/tests/routing-groups-jump.test.cjs +++ /dev/null @@ -1,172 +0,0 @@ -// Run with Node's test runner and Playwright on the module path; see README.md. -// The routing groups sit at the Routing page's foot, below the stage, the -// story and every request: with many models a long scroll down (shihh on -// Discord). The page's head has a Routing groups beside New group, with a -// down arrow and a tooltip saying where they are; its click brings the -// groups' heading to the top of the view (or the view to its foot) and the -// focus into them, and nothing else moves: the groups stay where they were -// in the page, and a click no reader made scrolls nothing. It takes only -// room the head has spare: named where that fits, its arrow alone (still -// named to a screen reader) where only that does, left out where nothing -// does, and every other part of the head is where it is without it. Every -// language, Chromium and WebKit, wide, a phone's width and a narrow window. -const assert = require("node:assert/strict"); -const fs = require("node:fs/promises"); -const path = require("node:path"); -const { test } = require("node:test"); -const { chromium, webkit } = require("playwright"); - -const assets = path.resolve(process.env.MAGPIE_ROUTING_ASSETS || path.join(__dirname, "../assets")); -const models = [ - { id: "a/m", name: "m", providerName: "A", icon: "generic" }, - { id: "b/m", name: "m", providerName: "B", icon: "generic" }, -]; -const info = (ids) => ids.map((id) => ({ id, ready: true })); -const found = { id: "auto-m", name: "Model M", members: ["a/m", "b/m"], auto: true, ready: true, memberInfo: info(["a/m", "b/m"]) }; - -const words = { - en: { btn: "Routing groups", tip: "Go to the routing groups, below the requests" }, - zh: { btn: "路由组", tip: "跳到请求下方的路由组" }, - "zh-TW": { btn: "路由組", tip: "跳到請求下方的路由組" }, - ja: { btn: "ルーティンググループ", tip: "リクエストの下にあるルーティンググループへ移動" }, - de: { btn: "Weiterleitungsgruppen", tip: "Zu den Weiterleitungsgruppen unter den Anfragen springen" }, -}; - -// requests enough to put the groups well below the window's fold -const now = Date.now(); -const routes = Array.from({ length: 60 }, (_, i) => ({ - id: "r" + i, seq: i + 1, at: new Date(now - i * 60000).toISOString(), agent: "claude", asked: "group/auto-m", - model: "a/m", provider: "a", status: 200, ms: 900, ttft: 300, in: 100, out: 20, done: true, -})); - -function serve(lang, web) { - const state = { agents: [{ id: "claude", name: "Claude Code", path: "/test/claude", fields: [] }], profiles: [], settings: { lang, theme: "light" } }; - return async (r) => { - const url = new URL(r.request().url()); - const json = (data) => r.fulfill({ json: data }); - if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${web}};` }); - if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); - if (url.pathname === "/api/state") return json(state); - if (url.pathname === "/api/plugins") return json({ plugins: [] }); - if (url.pathname === "/api/gateway/trace") { - if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes - return json({ mine: true, now: new Date().toISOString(), seq: routes.length, totals: { requests: routes.length, rerouted: 0, errors: 0 }, routes }); - } - if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); - if (url.pathname === "/api/groups") return json({ models, pools: [], deciders: [], found: true, groups: [found] }); - if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); - if (url.pathname.startsWith("/api/")) return json({}); - const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); - const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; - await r.fulfill({ body: await fs.readFile(file), contentType }); - }; -} - -// Under the whole suite's load webkit en once waited past the 5s default -// for the head button's fit (#3478): the page sizes the button a frame -// after the head's layout, and a loaded machine serves those first frames -// late, the fit with them. The waits that span the page's boot (the rows -// it fills, the head and the fit it gets in the first frames) get 15s; -// the goto keeps the minute every page's load has (#4470), and the waits -// inside a loaded page (the click's jump and its settle) the quick 5s. -const boot = 15000; - -for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { - for (const lang of Object.keys(words)) { - for (const { width, web } of [{ width: 1000, web: true }, { width: 480, web: true }, { width: 640, web: false }]) { - const w = words[lang]; - test(`${engine} ${lang} ${width}px${web ? " web" : " window"}: Routing groups in the Routing page's head goes to them`, async (t) => { - const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); - const page = await (await browser.newContext({ viewport: { width, height: 600 }, reducedMotion: "reduce" })).newPage(); - t.after(async () => { - if (process.env.ARTIFACT_DIR) { - await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); - await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}${web ? "-web" : ""}-routing-groups-jump.png`) }); - } - await browser.close(); - }); - page.setDefaultTimeout(5000); - page.setDefaultNavigationTimeout(60000); - const errors = []; - page.on("pageerror", (e) => errors.push(e.message)); - await page.route("**/*", serve(lang, web)); - await page.goto("http://magpie.test/?view=routing"); - await page.locator(".rt-group", { hasText: "Model M" }).waitFor({ state: "attached", timeout: boot }); - await page.locator(".rt-reqs > *").first().waitFor({ state: "attached", timeout: boot }); - - const view = page.locator("#view-routing"); - const go = page.locator("#view-routing > .row-head #rtGoGroups"); - await go.waitFor({ state: "attached", timeout: boot }); - await page.waitForFunction(() => document.getElementById("rtGoGroups").dataset.fit, null, { timeout: boot }); - await page.waitForTimeout(100); // the fit settles in the frame after a resize - const fit = await go.getAttribute("data-fit"); - if (width === 1000) assert.equal(fit, "full", "a wide head names it"); - assert.equal(await go.getAttribute("title"), w.tip); - assert.equal(await go.evaluate((e) => e.tagName), "BUTTON", "a button, no native select"); - assert.equal(await go.locator("svg").count(), 1, "a down arrow"); - // nothing else in the head moves for it, or wraps, at this width (the - // spacer gives it its room) - const apart = await page.evaluate(() => { - const b = document.getElementById("rtGoGroups"), h = b.parentElement; - const at = () => JSON.stringify([h.getBoundingClientRect().height, ...[...h.children].filter((c) => c !== b && !c.classList.contains("grow")).map((c) => { const r = c.getBoundingClientRect(); return [c.className, Math.round(r.left), Math.round(r.top), Math.round(r.width), Math.round(r.height)]; })]); - const withIt = at(); - b.style.setProperty("display", "none", "important"); - const without = at(); - b.style.removeProperty("display"); - return { withIt, without, over: h.scrollWidth - h.clientWidth }; - }); - assert.equal(apart.withIt, apart.without, "the head is laid out as without it"); - assert(apart.over <= 0, `nothing overflows the head (${apart.over}px)`); - const vw = await page.evaluate(() => document.documentElement.scrollWidth - innerWidth); - assert(vw <= 0, `no sideways scroll (${vw}px)`); - if (fit === "none") { - assert.equal(await go.isVisible(), false, "left out where the head has no room"); - assert.deepEqual(errors, []); - return; - } - await go.waitFor(); - // named on screen, or to a screen reader where only the arrow shows - assert.equal(await page.getByRole("button", { name: w.btn, exact: true }).count(), 1); - const label = go.locator("span"); - if (fit === "full") assert.equal((await label.textContent()).trim(), w.btn); - else assert((await label.boundingBox()).width <= 1, "the arrow alone"); - const border = await go.evaluate((e) => { const c = getComputedStyle(e); return c.borderLeftWidth !== c.borderRightWidth || c.borderLeftColor !== c.borderRightColor; }); - assert.equal(border, false, "no left-border accent"); - const hb = await go.boundingBox(); - assert(hb.x >= 0 && hb.x + hb.width <= width && hb.y >= 0, "in sight on arrival"); - - // the layout as before: the groups after every request, below the fold - assert.equal(await page.evaluate(() => { - const more = document.getElementById("rtMore"), g = more.querySelector(".rt-gsec"), reqs = more.querySelector(".rt-reqs"); - return g.parentElement === more && more.lastElementChild === g && !!(reqs.compareDocumentPosition(g) & Node.DOCUMENT_POSITION_FOLLOWING); - }), true, "the groups stay at the page's foot, after the requests"); - const vh = await view.evaluate((v) => v.getBoundingClientRect().bottom); - const gTop = () => page.locator(".rt-gsec").evaluate((e) => e.getBoundingClientRect().top); - assert(await gTop() > vh, "the groups are below the fold on arrival"); - assert.equal(await view.evaluate((v) => v.scrollTop), 0, "the page opens at its top"); - - // a click no reader made (code's own) scrolls nothing - await go.evaluate((b) => b.click()); - await page.waitForTimeout(300); - assert.equal(await view.evaluate((v) => v.scrollTop), 0, "an untrusted click doesn't move the page"); - - // the reader's click: the groups' heading at the top of the view, the focus in them - await go.click(); - // at the top of the view, or the view at its foot where the page ends first - await page.waitForFunction(() => { - const v = document.getElementById("view-routing"), g = document.querySelector(".rt-gsec"); - const top = g.getBoundingClientRect().top - v.getBoundingClientRect().top; - return (top >= -1 && top < 40) || (top > 0 && v.scrollTop > 0 && v.scrollTop + v.clientHeight >= v.scrollHeight - 1); - }); - assert.equal(await page.evaluate(() => document.querySelector(".rt-gsec").contains(document.activeElement)), true, "the focus goes with them"); - const gh = await page.locator(".rt-gsec > .row-head .label").first().boundingBox(); - assert(gh && gh.y >= 0 && gh.y + gh.height <= vh, "the groups' heading is in sight"); - // and stays there: a moment later the view hasn't been pulled away - const at = await view.evaluate((v) => v.scrollTop); - await page.waitForTimeout(400); - assert.equal(await view.evaluate((v) => v.scrollTop), at, "the view stays where the click took it"); - assert.deepEqual(errors, []); - }); - } - } -} diff --git a/internal/gui/tests/routing-groups-off.test.cjs b/internal/gui/tests/routing-groups-off.test.cjs index ca037013b..e294c6f49 100644 --- a/internal/gui/tests/routing-groups-off.test.cjs +++ b/internal/gui/tests/routing-groups-off.test.cjs @@ -82,7 +82,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, false, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const note = page.locator(".rt-gsec .rt-goff"); await note.waitFor(); @@ -90,7 +90,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert(text.includes(w.why), text); const btn = note.locator("button", { hasText: w.on }); assert(await btn.isVisible()); - assert.equal(await page.locator("#rtNewGroup").isVisible(), false, "New group is off with them"); + assert.equal(await page.locator(".rt-gnew").isVisible(), false, "New group is off with them"); assert.equal(await page.locator(".rt-group", { hasText: "Mine" }).isVisible(), false); assert(await note.evaluate((n) => n.getBoundingClientRect().right <= innerWidth + 1), "the note fits the window"); assert(await btn.evaluate((b) => b.getBoundingClientRect().right <= innerWidth + 1), "so does its button"); @@ -99,7 +99,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await note.waitFor({ state: "hidden" }); assert.deepEqual(posts, [{ id: "groups", on: true }]); await page.locator(".rt-group", { hasText: "Mine" }).waitFor({ state: "visible" }); - await page.locator("#rtNewGroup").waitFor({ state: "visible" }); + await page.locator(".rt-gnew").waitFor({ state: "visible" }); await page.waitForFunction((m) => document.querySelector("#status").textContent.includes(m), w.done); assert.deepEqual(errors, []); }); @@ -110,10 +110,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, true, [])); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-group", { hasText: "Mine" }).waitFor({ state: "visible" }); assert.equal(await page.locator(".rt-goff").isVisible(), false); - assert(await page.locator("#rtNewGroup").isVisible()); + assert(await page.locator(".rt-gnew").isVisible()); assert.deepEqual(errors, []); }); } @@ -121,7 +121,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", test(`${engine}: the note's strings are in every language`, async (t) => { const page = await open(engine, 900, t, `${engine}-routing-groups-off-i18n.png`); await page.route("**/*", serve("en", false, [])); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-goff").waitFor(); const missing = await page.evaluate((ks) => ["zh", "zh-TW", "ja", "de"].flatMap((l) => ks.filter((k) => !I18N[l]?.[k]).map((k) => `${l}: ${k}`)), keys); assert.deepEqual(missing, []); diff --git a/internal/gui/tests/routing-groups-page.test.cjs b/internal/gui/tests/routing-groups-page.test.cjs new file mode 100644 index 000000000..3b0d7bafb --- /dev/null +++ b/internal/gui/tests/routing-groups-page.test.cjs @@ -0,0 +1,261 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Routing groups have a page of their own beside Routing (11-06): below the +// stage and every request they were a long scroll down, New group with +// them. The sidebar names the page under Models, after Routing; its +// toolbar is the filter, how many groups there are and how many are on, +// then Templates, Import, Select and New group, the one filled button; +// the list follows, then Settings (found groups, the names in agents' +// lists). The Routing page keeps the stage and the requests, and a +// request's group opens the groups page on its row. Every language, +// Chromium and WebKit, wide, a narrow window and a phone's width. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(process.env.MAGPIE_ROUTING_ASSETS || path.join(__dirname, "../assets")); +const models = [ + { id: "a/m", name: "m", providerName: "A", icon: "generic" }, + { id: "b/m", name: "m", providerName: "B", icon: "generic" }, + { id: "a/n", name: "n", providerName: "A", icon: "generic" }, +]; +const info = (ids) => ids.map((id) => ({ id, ready: true })); +const groups = [ + { id: "auto-m", name: "Model M", members: ["a/m", "b/m"], auto: true, ready: true, memberInfo: info(["a/m", "b/m"]) }, + { id: "mine", name: "Mine", members: ["a/n", "b/m"], ready: true, memberInfo: info(["a/n", "b/m"]) }, + { id: "off", name: "Off one", members: ["a/n"], disabled: true, ready: true, memberInfo: info(["a/n"]) }, +]; + +const words = { + en: { nav: "Routing groups", count: "3 groups · 2 on", fresh: "New group", settings: "Settings" }, + zh: { nav: "路由组", count: "3 个组 · 2 个开启", fresh: "新建组", settings: "设置" }, + "zh-TW": { nav: "路由組", count: "3 個組 · 2 個開啟", fresh: "新增組", settings: "設定" }, + ja: { nav: "ルーティンググループ", count: "3 個のグループ · 2 個がオン", fresh: "新しいグループ", settings: "設定" }, + de: { nav: "Weiterleitungsgruppen", count: "3 Gruppen · 2 an", fresh: "Neue Gruppe", settings: "Einstellungen" }, +}; + +// enough requests that the Routing page scrolls +const now = Date.now(); +const routes = Array.from({ length: 30 }, (_, i) => ({ + id: "r" + i, seq: i + 1, at: new Date(now - i * 60000).toISOString(), agent: "claude", asked: "group/mine", + model: "a/n", provider: "a", status: 200, ms: 900, ttft: 300, in: 100, out: 20, done: true, + group: { id: "mine", name: "Mine" }, +})); + +function serve(lang, web) { + const state = { agents: [{ id: "claude", name: "Claude Code", path: "/test/claude", fields: [] }], profiles: [], settings: { lang, theme: "light" } }; + return async (r) => { + const url = new URL(r.request().url()); + const json = (data) => r.fulfill({ json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${web}};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes + return json({ mine: true, now: new Date().toISOString(), seq: routes.length, totals: { requests: routes.length, rerouted: 0, errors: 0 }, routes }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/groups") return json({ models, pools: [], deciders: [], found: true, groups }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await r.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +// the page's boot under the whole suite's load (#3478) +const boot = 15000; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + for (const { width, web } of [{ width: 1280, web: false }, { width: 640, web: false }, { width: 420, web: true }]) { + const w = words[lang]; + test(`${engine} ${lang} ${width}px${web ? " web" : " window"}: Routing groups is a page of its own`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage(); + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}${web ? "-web" : ""}-routing-groups-page.png`) }); + } + await browser.close(); + }); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, web)); + await page.goto("http://magpie.test/?view=routing"); + await page.locator(".rt-reqs > *").first().waitFor({ state: "attached", timeout: boot }); + await page.locator(".rt-group", { hasText: "Mine" }).waitFor({ state: "attached", timeout: boot }); + + // the Routing page: the stage and the requests, no groups, no jump + assert.equal(await page.locator("#view-routing .rt-gsec, #view-routing .rt-group").count(), 0, "no groups on the Routing page"); + assert.equal(await page.locator("#rtGoGroups, #rtNewGroup").count(), 0, "its head has no way down to them"); + assert.equal(await page.locator("#view-groups .rt-gsec").count(), 1, "the groups are on their own page"); + + // the sidebar (or the header's tabs) names the page, after Routing + const nav = page.locator('button[data-view="groups"]'); + assert.equal(await nav.count(), 1); + assert.equal((await nav.textContent()).trim(), w.nav); + assert.equal(await page.evaluate(() => { + const r = document.querySelector('button[data-view="routing"]'); + return r.nextElementSibling === document.querySelector('button[data-view="groups"]'); + }), true, "right after Routing"); + + // the sidebar has the tab; the header's row has no room for it (at + // 860px it pushed the logo out), so there Routing's head opens the + // page and Routing's tab stands for both + const side = await page.evaluate(() => document.body.classList.contains("side-nav")); + const into = page.locator("#rtToGroups"); + assert.equal(side, width >= 1024, "the sidebar from 1024 points"); + assert.equal(await nav.isVisible(), side, "the tab where there is room"); + assert.equal(await into.isVisible(), !side, "Routing's head opens them where there is no tab"); + if (side) await nav.click(); + else { + assert.equal((await into.textContent()).replace("›", "").trim(), w.nav); + await into.click(); + } + const view = page.locator("#view-groups"); + await view.waitFor(); + const on = await page.evaluate(() => [...document.querySelectorAll("#nav button[data-view].on")].map((b) => b.dataset.view)); + assert.deepEqual(on, [side ? "groups" : "routing"], "the tab shown as the page's"); + assert.equal(await page.locator("#view-routing").isHidden(), true); + const rows = view.locator(".rt-group"); + await rows.first().waitFor({ timeout: boot }); + assert.equal(await rows.count(), 3); + + // the toolbar: the filter, how many, then New group, the filled one + const head = view.locator(".rt-gsec > .row-head").first(); + assert.equal(await head.locator(".rt-gfilter").count(), 1, "the filter"); + assert.equal((await head.locator(".rt-gcount").textContent()).trim(), w.count); + const fresh = head.locator(".rt-gnew"); + assert.equal((await fresh.textContent()).trim(), w.fresh); + assert.equal(await fresh.evaluate((e) => e.classList.contains("primary")), true, "New group is the filled button"); + assert.equal(await head.locator(".rt-gimportbtn").count(), 1, "Import"); + assert.equal(await head.locator(".rt-gselect").count(), 1, "Select"); + assert.equal(await head.locator("select").count(), 0, "no native select"); + const fb = await fresh.boundingBox(); + assert(fb && fb.x >= 0 && fb.x + fb.width <= width && fb.y >= 0 && fb.y + fb.height <= 700, "New group in sight on arrival"); + // the list right under the toolbar, Settings under the list + const order = await page.evaluate(() => { + const s = document.querySelector("#view-groups .rt-gsec"), kids = [...s.children]; + const at = (q) => kids.findIndex((k) => k.matches(q)); + return [at(".row-head"), at(".rt-groups"), at(".rt-gset-head"), at(".rt-gset")]; + }); + assert.deepEqual(order, [0, 1, 3, 4], "toolbar, list, (off), Settings, its card"); + assert.equal((await view.locator(".rt-gset-head .label").textContent()).trim(), w.settings); + assert.equal(await view.locator(".rt-gset .rt-gfound").count(), 1, "found groups in Settings"); + assert.equal(await view.locator(".rt-gset .rt-gnames").count(), 1, "the names in Settings"); + const gb = await view.locator(".rt-groups").boundingBox(), hb = await head.boundingBox(); + assert(gb.y >= hb.y + hb.height - 1 && gb.y - (hb.y + hb.height) < 24, "the list right below the toolbar"); + const over = await page.evaluate(() => document.documentElement.scrollWidth - innerWidth); + assert(over <= 0, `no sideways scroll (${over}px)`); + const headOver = await head.evaluate((h) => h.scrollWidth - h.clientWidth); + assert(headOver <= 0, `nothing overflows the toolbar (${headOver}px)`); + const border = await fresh.evaluate((e) => { const c = getComputedStyle(e); return c.borderLeftWidth !== c.borderRightWidth || c.borderLeftColor !== c.borderRightColor; }); + assert.equal(border, false, "no left-border accent"); + + // New group opens its editor at the list's top, on this page + await fresh.click(); + await view.locator(".rt-gedit").first().waitFor(); + assert.equal(await page.locator("#view-routing .rt-gedit").count(), 0); + assert.deepEqual(errors, []); + }); + } + } +} + +// a request's group on the Routing page opens the groups page on its row +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(`${engine}: a request's group goes to its row on the groups page`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width: 1280, height: 700 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve("en", false)); + await page.goto("http://magpie.test/?view=routing"); + await page.locator(".rt-group", { hasText: "Mine" }).waitFor({ state: "attached", timeout: boot }); + const go = page.locator('#view-routing .rt-go[data-go="group:mine"]').first(); + await go.waitFor({ timeout: boot }); + await go.click(); + await page.locator("#view-groups").waitFor(); + assert.equal(await page.locator("#view-routing").isHidden(), true, "Routing is left"); + const row = page.locator('#view-groups .rt-group[data-id="mine"]'); + await row.waitFor(); + const rb = await row.boundingBox(); + assert(rb.y >= 0 && rb.y + rb.height <= 700, "its row in sight"); + // the window opened on a new group of a model: the groups page + await page.goto("http://magpie.test/?view=groups&newgroup=a%2Fn"); + await page.locator("#view-groups .rt-gedit").first().waitFor({ timeout: boot }); + assert.equal(await page.locator("#view-groups").isVisible(), true); + assert.deepEqual(errors, []); + }); +} + +// The groups page draws itself again each second when the accounts' quotas +// change, as the Routing page did under streaming requests (routing-steady +// and routing-pointer-pin, gone with the groups' move): the quota line +// comes in under a group by itself, and with a group open in its editor +// and a name being typed, the field keeps its focus and what was typed, +// and the list stays where it is. +const withProvider = { models, pools: [], deciders: [], found: true, groups: groups.map((g) => ({ ...g, memberInfo: g.memberInfo.map((i) => ({ ...i, provider: i.id.split("/")[0], name: i.id.split("/")[0].toUpperCase() })) })) }; +// two accounts: the line is what they have left together +const card = (amount) => ["a1@example.com", "a2@example.com"].map((user) => ({ provider: "a", name: "A", kind: "subscription", icon: "generic", plan: "Pro", user, readAt: new Date().toISOString(), + windows: [{ name: "Credits", amount, limit: 500, unit: "credits", used: (100 * amount) / 500, resetsAt: new Date(Date.now() + 9 * 864e5).toISOString() }] })); +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const width of [1280, 420]) { + test(`${engine} ${width}px: the groups page draws new quotas by itself, an open editor left alone`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 500 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const base = serve("en", width < 600); + await page.route("**/*", (r) => { + const at = new URL(r.request().url()).pathname; + if (at === "/api/groups") return r.fulfill({ json: withProvider }); + if (at === "/api/usage/quotas") return r.fulfill({ json: [] }); + return base(r); + }); + await page.goto("http://magpie.test/?view=groups"); + const row = page.locator('#view-groups .rt-group[data-id="mine"]'); + await row.waitFor({ timeout: boot }); + await page.waitForFunction(() => Array.isArray(quotas), null, { timeout: boot }); + // quotas come in: the line shows with no click and no reload + await page.evaluate((q) => { quotas = q; }, card(400)); + await row.locator(".rt-gquota").waitFor({ timeout: 5000 }); + + await row.getByRole("button", { name: "Edit", exact: true }).click(); + const name = page.locator("#view-groups .rt-gedit input").first(); + await name.waitFor(); + // focus, not a click: at a phone's height the editor's Save bar can + // sit over it, and what is asked here is the redraw, not the reach + await name.focus(); + await page.keyboard.type("Opus and more"); + const typed = await name.inputValue(); + const top = async () => (await name.boundingBox()).y; + const before = await top(), scrolled = await page.locator("#view-groups").evaluate((v) => v.scrollTop); + // new quotas twice, each a tick's redraw were the editor not open + for (const amount of [300, 200]) { + await page.evaluate((q) => { quotas = q; }, card(amount)); + await page.waitForTimeout(1300); + } + assert.equal(await name.evaluate((e) => e === document.activeElement), true, "the field kept its focus"); + assert.equal(await name.inputValue(), typed); + assert.equal(await page.locator("#view-groups").evaluate((v) => v.scrollTop), scrolled, "the view didn't scroll"); + assert(Math.abs((await top()) - before) < 1, "the field stayed where it was"); + await page.keyboard.type("!"); + assert.equal(await name.inputValue(), typed + "!"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/gui/tests/routing-groups-wide.test.cjs b/internal/gui/tests/routing-groups-wide.test.cjs index fb38d436f..b109f1e00 100644 --- a/internal/gui/tests/routing-groups-wide.test.cjs +++ b/internal/gui/tests/routing-groups-wide.test.cjs @@ -62,7 +62,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, web)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-group").nth(2).waitFor(); const settle = () => page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => setTimeout(r, 100))))); for (const width of web ? [1440, 1100, 700, 440, 360] : [1440, 1100, 900, 700, 560]) { @@ -70,7 +70,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.setViewportSize({ width, height: 900 }); await settle(); const m = await page.evaluate(() => { - const v = document.querySelector("#view-routing"), de = document.documentElement; + const v = document.querySelector("#view-groups"), de = document.documentElement; const rows = [...document.querySelectorAll(".rt-groups > .rt-group")].map((g) => { const b = g.getBoundingClientRect(), list = g.parentElement.getBoundingClientRect(); const kids = [...g.querySelectorAll(".mem, .tags, .switch, button")].map((e) => e.getBoundingClientRect()).filter((k) => k.width > 0); diff --git a/internal/gui/tests/routing-intent-entry.test.cjs b/internal/gui/tests/routing-intent-entry.test.cjs index 8a0063943..1b803a74c 100644 --- a/internal/gui/tests/routing-intent-entry.test.cjs +++ b/internal/gui/tests/routing-intent-entry.test.cjs @@ -90,7 +90,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const group = page.locator(".rt-group").first(); await group.waitFor(); diff --git a/internal/gui/tests/routing-intent-fallback.test.cjs b/internal/gui/tests/routing-intent-fallback.test.cjs index a87ba523d..050ac48c9 100644 --- a/internal/gui/tests/routing-intent-fallback.test.cjs +++ b/internal/gui/tests/routing-intent-fallback.test.cjs @@ -86,7 +86,7 @@ async function open(t, engine, lang, width, kept) { page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, routeOf(kept))); await page.goto("http://magpie.test/?view=routing"); - await page.locator(".rt-group").first().waitFor(); + await page.locator(".rt-group").first().waitFor({ state: "attached" }); return { page, errors }; } diff --git a/internal/gui/tests/routing-levels.test.cjs b/internal/gui/tests/routing-levels.test.cjs index bf053aca8..e35f5a892 100644 --- a/internal/gui/tests/routing-levels.test.cjs +++ b/internal/gui/tests/routing-levels.test.cjs @@ -64,13 +64,13 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", test(`${engine} ${lang}: a group names the reasoning levels agents are offered`, async (t) => { const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); t.after(() => browser.close()); - const page = await (await browser.newContext({ viewport: { width: 1100, height: 1400 } })).newPage(); + const page = await (await browser.newContext({ viewport: { width: 1100, height: 1400 }, reducedMotion: "reduce" })).newPage(); page.setDefaultTimeout(5000); page.setDefaultNavigationTimeout(60000); const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-group").first().waitFor(); const ed = page.locator(".rt-gedit"); // the editor's Levels row: the field after its label diff --git a/internal/gui/tests/routing-manual.test.cjs b/internal/gui/tests/routing-manual.test.cjs index 23e80dabb..5b107110f 100644 --- a/internal/gui/tests/routing-manual.test.cjs +++ b/internal/gui/tests/routing-manual.test.cjs @@ -82,7 +82,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator(".rt-group", { hasText: "Hand" }); await card.waitFor(); @@ -99,8 +99,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // the reader scrolls the card to the middle, then picks luna: saved // with the group's other fields as they were, nothing moves, the // editor stays shut - const view = page.locator("#view-routing"); - const dy = await card.evaluate((g) => { const v = document.querySelector("#view-routing"); + const view = page.locator("#view-groups"); + const dy = await card.evaluate((g) => { const v = document.querySelector("#view-groups"); return Math.round(g.getBoundingClientRect().top - v.getBoundingClientRect().top - v.clientHeight / 2); }); await page.mouse.move(550, 400); await page.mouse.wheel(0, dy); @@ -133,7 +133,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const wheelTo = async (x) => { // the distance is read once the editor has stopped moving await settled(page); - const d = await x.evaluate((e) => { const v = document.querySelector("#view-routing"); + const d = await x.evaluate((e) => { const v = document.querySelector("#view-groups"); return Math.round(e.getBoundingClientRect().top - v.getBoundingClientRect().top - v.clientHeight / 2); }); await page.mouse.move(550, 400); await page.mouse.wheel(0, d); diff --git a/internal/gui/tests/routing-many-keys.test.cjs b/internal/gui/tests/routing-many-keys.test.cjs index 6b246bcbc..612412db5 100644 --- a/internal/gui/tests/routing-many-keys.test.cjs +++ b/internal/gui/tests/routing-many-keys.test.cjs @@ -168,10 +168,13 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert(rows.wires >= 800, `${rows.wires} wires: each key has one, in the list or not`); assert.deepEqual(rows.unwired, [], "a wire ends at each key in sight"); // scrolled to the foot, the last key is there, drawn, with its wire - await page.mouse.move(700, 500); // by the wheel, as a reader would: on until the last key is in the - // list, then to it + // list, then to it. The wheel turns over the keys: at the page's foot + // the requests list sits below them, and a wheel over it scrolls it + // and stops there (overscroll-behavior: contain), as it should + const overKeys = () => page.evaluate(() => { const r = document.querySelector("#view-routing .rt-accts").getBoundingClientRect(); return [r.left + Math.min(40, r.width / 2), (Math.max(60, r.top) + Math.min(innerHeight - 20, r.bottom)) / 2]; }).then(([x, y]) => page.mouse.move(x, y)); for (let k = 0; k < 80; k++) { + await overKeys(); const at = await page.evaluate(() => [...document.querySelectorAll("#view-routing .rt-accts > li")].find((li) => li.title === "solpool2#k299")?.getBoundingClientRect().top); if (at !== undefined && Math.abs(at - 400) < 150) break; await page.mouse.wheel(0, at === undefined ? 3000 : Math.max(-3000, Math.min(3000, at - 400))); @@ -189,6 +192,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", for (let k = 0; k < 80; k++) { const f = await fold2(); if (f && Math.abs(f.top - 300) < 150) break; + await overKeys(); await page.mouse.wheel(0, !f ? -3000 : Math.max(-3000, Math.min(3000, f.top - 300))); await page.waitForTimeout(!f ? 50 : 300); } diff --git a/internal/gui/tests/routing-mode-goes.test.cjs b/internal/gui/tests/routing-mode-goes.test.cjs index 2966a9c49..f41935f83 100644 --- a/internal/gui/tests/routing-mode-goes.test.cjs +++ b/internal/gui/tests/routing-mode-goes.test.cjs @@ -96,7 +96,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const { page, errors } = await open(engine, lang, "lone", width, t); await page.waitForFunction((s) => document.querySelector(".rt-mode")?.textContent.trim() === s, lone[lang]); // the groups are in, and the chip still names no routing - await page.locator(".rt-group").first().waitFor(); + await page.locator("#view-groups .rt-group").first().waitFor({ state: "attached" }); await page.waitForTimeout(150); assert.equal(await page.locator(".rt-hub i").isHidden(), true, "the chip names no routing"); assert.equal((await page.locator(".rt-mode").textContent()).trim(), lone[lang]); @@ -120,18 +120,24 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.equal((await head.textContent()).trim(), smart[lang]); assert.equal(await head.getAttribute("data-go"), "pool:relay"); - const view = page.locator("#view-routing"); + // the pools are on the Routing groups page: the chip opens it, with + // the pool in sight + const groups = page.locator("#view-groups"); const pool = page.locator('.rt-pool[data-provider="relay"]'); await pool.waitFor({ state: "attached" }); - const inView = () => pool.evaluate((p) => { const v = document.querySelector("#view-routing").getBoundingClientRect(), r = p.getBoundingClientRect(); - return r.top >= v.top && r.bottom <= v.bottom; }); + const inView = () => pool.evaluate((p) => { const v = document.querySelector("#view-groups"), b = v.getBoundingClientRect(), r = p.getBoundingClientRect(); + return !v.hidden && r.height > 0 && r.top >= b.top && r.bottom <= b.bottom; }); assert.equal(await inView(), false, "the pool starts out of view"); - const top = await view.evaluate((v) => v.scrollTop); + const back = async () => { + await page.evaluate(() => window.show("routing")); + await page.waitForFunction(() => !document.querySelector("#view-routing").hidden); + await pool.evaluate((p) => p.classList.remove("rt-found")); + }; // a click takes the reader there: in view, marked, its routing focused await chip.click(); await page.waitForFunction(() => document.querySelector('.rt-pool[data-provider="relay"]')?.classList.contains("rt-found")); - assert.ok(await view.evaluate((v) => v.scrollTop) > top, "the view went down to it"); + assert.equal(await groups.isVisible(), true, "the groups page opened"); assert.equal(await inView(), true); assert.equal(await page.evaluate(() => document.activeElement?.closest(".rt-pool")?.dataset.provider), "relay"); assert.equal(await page.evaluate(() => document.activeElement?.classList.contains("on")), true); @@ -140,8 +146,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // a press held over the head's redraw is still a click (#2151): the // chip is not written over under the pointer, which WebKit takes // for a press that never ends where it began - await view.evaluate((v) => { v.scrollTop = 0; }); - await pool.evaluate((p) => p.classList.remove("rt-found")); + await back(); const box = await chip.boundingBox(); await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2); await page.mouse.down(); @@ -151,11 +156,11 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.waitForFunction(() => document.querySelector('.rt-pool[data-provider="relay"]')?.classList.contains("rt-found")); assert.equal(await inView(), true); - // the keyboard does the same from the top - await view.evaluate((v) => { v.scrollTop = 0; }); + // the keyboard does the same + await back(); await chip.focus(); await page.keyboard.press("Enter"); - await page.waitForFunction(() => document.querySelector("#view-routing").scrollTop > 0); + await page.waitForFunction(() => document.querySelector('.rt-pool[data-provider="relay"]')?.classList.contains("rt-found")); assert.equal(await inView(), true); // nothing is drawn wider than the window assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true); diff --git a/internal/gui/tests/routing-pause-folder.test.cjs b/internal/gui/tests/routing-pause-folder.test.cjs index bab37a2d5..ba235b344 100644 --- a/internal/gui/tests/routing-pause-folder.test.cjs +++ b/internal/gui/tests/routing-pause-folder.test.cjs @@ -88,7 +88,7 @@ function serve(lang, posts, route) { async function open(t, engine, lang, width, folder) { const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); t.after(() => browser.close()); - const page = await (await browser.newContext({ viewport: { width, height: 1400 } })).newPage(); + const page = await (await browser.newContext({ viewport: { width, height: 1400 }, reducedMotion: "reduce" })).newPage(); page.setDefaultTimeout(5000); page.setDefaultNavigationTimeout(60000); const errors = [], posts = []; @@ -96,7 +96,7 @@ async function open(t, engine, lang, width, folder) { await page.route("**/*", serve(lang, posts, routeFrom(folder))); await page.goto("http://magpie.test/?view=routing"); const group = page.locator(".rt-group").first(); - await group.waitFor(); + await group.waitFor({ state: "attached" }); return { page, group, errors, posts }; } @@ -125,6 +125,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const said = await page.evaluate(() => document.documentElement.innerText); assert(said.includes(w.cond), `the pause's folders are told: ${said.slice(0, 2000)}`); if (w.aside) assert(said.includes(w.aside), `the paused reason: ${said.slice(0, 2000)}`); + await page.evaluate(() => window.show("groups")); + await group.waitFor(); // the group's rule, in words const title = await group.evaluate((g) => [...g.querySelectorAll("[title]")].map((e) => e.title).join("\n")); @@ -189,6 +191,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", test(`${engine} ${lang}: a pause outside a folder at a phone's width, the agent saying none`, async (t) => { const { page, group, errors } = await open(t, engine, lang, 390, ""); await page.waitForFunction((s) => document.documentElement.innerText.includes(s), w.none); + await page.evaluate(() => window.show("groups")); + await group.waitFor(); await press(page, group.locator("button", { hasText: w.edit })); // the group is below the fold here const row = page.locator(".rt-gedit .rt-rule").first(); const xf = row.locator(".rt-cond.xf"); diff --git a/internal/gui/tests/routing-pause.test.cjs b/internal/gui/tests/routing-pause.test.cjs index cc97cb448..f3d61e606 100644 --- a/internal/gui/tests/routing-pause.test.cjs +++ b/internal/gui/tests/routing-pause.test.cjs @@ -86,7 +86,7 @@ async function open(engine, lang, width, t) { await page.route("**/*", serve(lang, posts)); await page.goto("http://magpie.test/?view=routing"); const group = page.locator(".rt-group").first(); - await group.waitFor(); + await group.waitFor({ state: "attached" }); return { page, group, errors, posts }; } // a click as the reader's: wheeled into the middle of the view first (a @@ -96,11 +96,11 @@ async function press(page, x) { // a group opening into its editor moves its height and parts for ~700ms // (91b0be836): where x will be is read once that has stopped await page.waitForFunction(() => !document.getAnimations().some((a) => a.playState === "running" && Number.isFinite(a.effect?.getComputedTiming().endTime))); - const d = await x.evaluate((e) => { const v = document.querySelector("#view-routing"); + const d = await x.evaluate((e) => { const v = document.querySelector("#view-groups"); return Math.round(e.getBoundingClientRect().top - v.getBoundingClientRect().top - v.clientHeight / 2); }); if (Math.abs(d) > 100) { // over the view, not the sidebar beside it - const v = await page.locator("#view-routing").boundingBox(); + const v = await page.locator("#view-groups").boundingBox(); await page.mouse.move(v.x + 10, 300); await page.mouse.wheel(0, d); await page.waitForTimeout(400); @@ -123,6 +123,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // the trace: the model paused, by which rule and when await page.waitForFunction((s) => document.documentElement.innerText.includes(s), w.aside); + await page.evaluate(() => window.show("groups")); + await group.waitFor(); // the group's rule, in words const title = await group.evaluate((g) => [...g.querySelectorAll("[title]")].map((e) => e.title).join("\n")); @@ -192,6 +194,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", for (const lang of Object.keys(words)) { test(`${engine} ${lang}: a pause rule at a narrow width`, async (t) => { const { page, group, errors } = await open(engine, lang, 420, t); + await page.evaluate(() => window.show("groups")); + await group.waitFor(); await press(page, group.locator("button", { hasText: EDIT[lang] })); const row = page.locator(".rt-gedit .rt-rule").first(); await row.waitFor(); diff --git a/internal/gui/tests/routing-pointer-pin.test.cjs b/internal/gui/tests/routing-pointer-pin.test.cjs deleted file mode 100644 index 81a4df433..000000000 --- a/internal/gui/tests/routing-pointer-pin.test.cjs +++ /dev/null @@ -1,107 +0,0 @@ -// Run with Node's test runner and Playwright on the module path; see README.md. -// Routing: the groups stay under the pointer as requests come in (cwfox67 on -// X: picking a manual group's model meant fighting the page, which shook as -// it updated). With the groups low in the view, as they are at the page's -// foot, the requests list above them kept its place and grew, so a group's -// card slid down from under the pointer with each request. With the pointer -// on a manual group's card and requests streaming in, the card stays where -// it is on the screen. In Chromium and WebKit, at a phone's width and a -// desk's. -const assert = require("node:assert/strict"); -const { test } = require("node:test"); -const fs = require("node:fs/promises"); -const path = require("node:path"); -const { chromium, webkit } = require("playwright"); - -const assets = path.resolve(__dirname, "../assets"); -const now = Date.now(), iso = (ms) => new Date(ms).toISOString(); -const seat = { id: "codex@me", provider: "codex", name: "ChatGPT", who: "me@example.com", kind: "account", model: "gpt-6.1-sol", known: true, plan: "Pro" }; -const prompt = (n) => ({ window: 272000, tokens: 90000 + n * 8000, counted: true, turns: n, parts: [ - { kind: "system", tokens: 9000, items: [{ name: "prompt", tokens: 9000 }] }, - { kind: "files", tokens: 30000 + n * 4000, items: Array.from({length: 1 + (n % 5)}, (_, i) => ({ name: "/work/f" + i + ".js", tag: "read", tokens: 3000 })) }, - { kind: "chat", tokens: 19000 + n * 2000, items: [{ name: "turn", tag: "turns", n, tokens: 19000 + n * 2000 }] } ] }); -function req(id, step) { - const t0 = now - (400 - id) * 1000, done = step === "done"; - return { id, seq: id * 10 + ({ start: 0, read: 1, done: 2 })[step], time: iso(t0), agent: "codex", session: "019a-session", model: "gpt-6.1-sol", provider: "codex", - order: [seat], tries: [{ id: seat.id, model: seat.model, start: iso(t0), done, ...(done ? { status: 200, ms: 4000 } : {}) }], - done, ...(done ? { status: 200, ms: 4000, tokens: 2000, cost: 0.05, priced: true, usage: [{ in: 3000, cache_read: 87000, out: 400 }] } : {}), - ...(step === "start" ? {} : { prompt: prompt(id - 100) }) }; -} -const first = [101, 102, 103].map((i) => req(i, "done")); -const models = [{ id: "a/sol", name: "sol", providerName: "A", icon: "generic" }, { id: "b/flash", name: "flash", providerName: "B", icon: "generic" }]; -const base = { members: ["a/sol", "b/flash"], ready: true, memberInfo: [{ id: "a/sol", ready: true }, { id: "b/flash", ready: true }], offers: [], shared: [] }; -const groups = { models, pools: [], groups: [{ ...base, id: "hand", name: "Hand", routing: "manual", pick: "a/sol", picked: "a/sol" }, { ...base, id: "auto", name: "Auto", routing: "order" }] }; -function serve(feed) { - const state = { agents: [{ id: "codex", name: "Codex", path: "/test/codex", fields: [] }], profiles: [], settings: { lang: "en", theme: "light" } }; - return async (route) => { - const url = new URL(route.request().url()); const json = (d) => route.fulfill({ json: d }); - if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: 'window.bootPrefs = {lang:"en",theme:"light",web:true};' }); - if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); - if (url.pathname === "/api/state") return json(state); - if (url.pathname === "/api/gateway/trace") { - const trace = (routes) => json({ mine: true, now: new Date().toISOString(), seq: routes.length ? routes[routes.length - 1].seq : Number(url.searchParams.get("after")), totals: { requests: 0, rerouted: 0, errors: 0 }, routes }); - if (!url.searchParams.get("wait")) return trace(first); - return trace([await new Promise((res) => { feed.next = res; })]); - } - if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); - if (url.pathname === "/api/groups") return json(groups); - if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); - if (url.pathname.startsWith("/api/")) return json({}); - const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); - const ct = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; - await route.fulfill({ body: await fs.readFile(file).catch(() => ""), contentType: ct }); - }; -} -for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { - test(`${engine}: a group under the pointer stays put as requests come in`, async (t) => { - const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); - t.after(() => browser.close()); - for (const [w, h] of [[420, 760], [1100, 760]]) { - await t.test(`${w}x${h}`, async () => { - const context = await browser.newContext({ viewport: { width: w, height: h } }); - const page = await context.newPage(); - page.setDefaultTimeout(5000); - page.setDefaultNavigationTimeout(60000); - const errors = []; - page.on("pageerror", (e) => errors.push(e.message)); - const feed = {}; - await page.route("**/*", serve(feed)); - await page.goto("http://magpie.test/?view=routing"); - await page.locator(".rt-group").first().waitFor(); - await page.waitForTimeout(1500); - // the reader wheels down to the groups, then puts the pointer on the - // manual group's card - // over the view, not the sidebar beside it - const v = await page.locator("#view-routing").boundingBox(); - await page.mouse.move(v.x + 8, h / 2); - for (let i = 0; i < 80; i++) { - const top = await page.evaluate(() => document.querySelector(".rt-group").getBoundingClientRect().top); - if (top < 300) break; - await page.mouse.wheel(0, Math.min(200, top - 250)); - await page.waitForTimeout(60); - } - await page.waitForTimeout(300); - const b = await page.locator(".rt-group").first().boundingBox(); - await page.mouse.move(b.x + 40, b.y + 10); - await page.waitForTimeout(100); - const at = () => page.evaluate(() => [document.querySelector(".rt-group").getBoundingClientRect().top, document.querySelector(".rt-reqs").offsetHeight, document.querySelector("#rt").offsetHeight]); - const was = await at(), seen = []; - for (let id = 104; id < 112; id++) for (const s of ["start", "read", "done"]) { - for (let i = 0; i < 60 && !feed.next; i++) await page.waitForTimeout(50); - const next = feed.next; - assert(next, "the page asks for the next trace"); - feed.next = null; - next(req(id, s)); - await page.waitForTimeout(250); - seen.push(await at()); - } - const last = seen[seen.length - 1]; - assert(last[1] + last[2] - was[1] - was[2] > 50 || w < 760, `what is above the groups really changed: ${JSON.stringify([was, last])}`); - for (const s of seen) assert(Math.abs(s[0] - was[0]) <= 1.5, `the card stayed under the pointer: ${was[0]} → ${seen.map((x) => Math.round(x[0])).join(" ")}`); - assert.deepEqual(errors, []); - feed.next?.(req(999, "done")); - await context.close(); - }); - } - }); -} diff --git a/internal/gui/tests/routing-pool-tooltip.test.cjs b/internal/gui/tests/routing-pool-tooltip.test.cjs index 374be23bc..0f309401c 100644 --- a/internal/gui/tests/routing-pool-tooltip.test.cjs +++ b/internal/gui/tests/routing-pool-tooltip.test.cjs @@ -49,7 +49,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const row = page.locator(".rt-pool"); await row.waitFor(); assert.equal(await row.getAttribute("title"), null, "the row itself carries no tooltip"); diff --git a/internal/gui/tests/routing-provider-off.test.cjs b/internal/gui/tests/routing-provider-off.test.cjs index a387d3ef8..d347f89b1 100644 --- a/internal/gui/tests/routing-provider-off.test.cjs +++ b/internal/gui/tests/routing-provider-off.test.cjs @@ -69,7 +69,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const say = (key, vars = {}) => page.evaluate(([lang, key, vars]) => { const s = (lang !== "en" && I18N[lang]?.[key]) || key; return s.replace(/\{(\w+)\}/g, (_, k) => vars[k] ?? `{${k}}`); diff --git a/internal/gui/tests/routing-return-cost.test.cjs b/internal/gui/tests/routing-return-cost.test.cjs index f1f3e309b..4c4c86680 100644 --- a/internal/gui/tests/routing-return-cost.test.cjs +++ b/internal/gui/tests/routing-return-cost.test.cjs @@ -70,7 +70,7 @@ const watch = () => { new MutationObserver((ms) => { for (const m of ms) if (set(m.oldValue) !== set(m.target.getAttribute("class"))) w.flips.push(m.target.className); }) .observe(document.querySelector("#view-routing"), { subtree: true, attributes: true, attributeFilter: ["class"], attributeOldValue: true }); new MutationObserver((ms) => { w.providers += ms.length; }).observe(document.querySelector("#view-providers"), { subtree: true, childList: true }); - new MutationObserver((ms) => { w.groups += ms.length; }).observe(document.querySelector("#view-routing .rt-groups"), { subtree: true, childList: true }); + new MutationObserver((ms) => { w.groups += ms.length; }).observe(document.querySelector("#view-groups .rt-groups"), { subtree: true, childList: true }); // the picked request's story: its head, its steps and its context card for (const s of [".rt-log-head", ".rt-steps", ".ctx-card"]) new MutationObserver((ms) => { w.story += ms.length; }).observe(document.querySelector("#view-routing " + s), { subtree: true, childList: true, characterData: true }); // the stage's nodes as they are now diff --git a/internal/gui/tests/routing-rows-fit.test.cjs b/internal/gui/tests/routing-rows-fit.test.cjs index 7e5b59909..e5aa6a362 100644 --- a/internal/gui/tests/routing-rows-fit.test.cjs +++ b/internal/gui/tests/routing-rows-fit.test.cjs @@ -64,7 +64,7 @@ function serve(lang, web) { // what sticks out: the page past the window, and a row's controls past the row const measure = (page) => page.evaluate(() => { - const v = document.querySelector("#view-routing"), de = document.documentElement; + const v = document.querySelector("#view-groups"), de = document.documentElement; const out = []; for (const row of document.querySelectorAll(".rt-groups > *, .rt-pools > *")) { const rb = row.getBoundingClientRect(); @@ -91,7 +91,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, web)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-group").nth(2).waitFor(); const memLine = await page.locator(".rt-group[data-id=g1] .mem").first().textContent(); assert(memLine.includes("WorkBuddy AI · Hy3"), `the reporter's member line: ${memLine}`); diff --git a/internal/gui/tests/routing-rule-agent-typed.test.cjs b/internal/gui/tests/routing-rule-agent-typed.test.cjs index 4a45abc66..cec73e1cb 100644 --- a/internal/gui/tests/routing-rule-agent-typed.test.cjs +++ b/internal/gui/tests/routing-rule-agent-typed.test.cjs @@ -81,13 +81,13 @@ function serve(lang, posts, asked) { async function open(t, engine, lang, width) { const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); t.after(() => browser.close()); - const page = await (await browser.newContext({ viewport: { width, height: 1400 } })).newPage(); + const page = await (await browser.newContext({ viewport: { width, height: 1400 }, reducedMotion: "reduce" })).newPage(); page.setDefaultTimeout(5000); page.setDefaultNavigationTimeout(60000); const errors = [], posts = [], asked = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts, asked)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const group = page.locator(".rt-group").first(); await group.waitFor(); return { page, group, errors, posts, asked }; diff --git a/internal/gui/tests/routing-rule-columns.test.cjs b/internal/gui/tests/routing-rule-columns.test.cjs index b4d2f7dc8..bb2df6f74 100644 --- a/internal/gui/tests/routing-rule-columns.test.cjs +++ b/internal/gui/tests/routing-rule-columns.test.cjs @@ -134,7 +134,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const ed = await openEditor(page, lang); for (const width of [1100, 900, 700]) { await page.setViewportSize({ width, height: 1400 }); diff --git a/internal/gui/tests/routing-rule-drag.test.cjs b/internal/gui/tests/routing-rule-drag.test.cjs index 2ee4b5e2b..2c2ab0b01 100644 --- a/internal/gui/tests/routing-rule-drag.test.cjs +++ b/internal/gui/tests/routing-rule-drag.test.cjs @@ -71,7 +71,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator(".rt-group").first(); await card.waitFor(); await card.locator("button", { hasText: w.edit }).click(); @@ -93,7 +93,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // wheeled to the rules, as the reader would (a scroll no reader asked // for is put back) - const v = await page.locator("#view-routing").boundingBox(); + const v = await page.locator("#view-groups").boundingBox(); await page.mouse.move(v.x + 10, 300); for (let n = 0; n < 40; n++) { const b = await ed.locator(".rt-rules").boundingBox(); diff --git a/internal/gui/tests/routing-rule-effort.test.cjs b/internal/gui/tests/routing-rule-effort.test.cjs index 58b743e05..3f968777d 100644 --- a/internal/gui/tests/routing-rule-effort.test.cjs +++ b/internal/gui/tests/routing-rule-effort.test.cjs @@ -70,7 +70,7 @@ async function open(engine, lang, width, t) { const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const group = page.locator(".rt-group").first(); await group.waitFor(); return { page, group, errors, posts }; @@ -81,10 +81,10 @@ async function press(page, x) { // a group opening into its editor moves its height and parts for ~700ms // (91b0be836): where x will be is read once that has stopped await page.waitForFunction(() => !document.getAnimations().some((a) => a.playState === "running" && Number.isFinite(a.effect?.getComputedTiming().endTime))); - const d = await x.evaluate((e) => { const v = document.querySelector("#view-routing"); + const d = await x.evaluate((e) => { const v = document.querySelector("#view-groups"); return Math.round(e.getBoundingClientRect().top - v.getBoundingClientRect().top - v.clientHeight / 2); }); if (Math.abs(d) > 100) { - const v = await page.locator("#view-routing").boundingBox(); + const v = await page.locator("#view-groups").boundingBox(); await page.mouse.move(v.x + 10, 300); await page.mouse.wheel(0, d); await page.waitForTimeout(400); diff --git a/internal/gui/tests/routing-rule-example.test.cjs b/internal/gui/tests/routing-rule-example.test.cjs index 2de6e4627..ff2510760 100644 --- a/internal/gui/tests/routing-rule-example.test.cjs +++ b/internal/gui/tests/routing-rule-example.test.cjs @@ -110,14 +110,14 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", test(`${engine} ${lang} ${width}: a group with no rule offers an example rule`, async (t) => { const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); t.after(() => browser.close()); - const page = await (await browser.newContext({ viewport: { width, height: 1400 } })).newPage(); + const page = await (await browser.newContext({ viewport: { width, height: 1400 }, reducedMotion: "reduce" })).newPage(); page.setDefaultTimeout(5000); page.setDefaultNavigationTimeout(60000); const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); shape = {}; - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); let ed = await openEditor(page, w); const tryIt = ed.locator("button.rt-try"); diff --git a/internal/gui/tests/routing-rule-models.test.cjs b/internal/gui/tests/routing-rule-models.test.cjs index fbb2f4b05..22a61c182 100644 --- a/internal/gui/tests/routing-rule-models.test.cjs +++ b/internal/gui/tests/routing-rule-models.test.cjs @@ -109,7 +109,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", test(`${engine} ${lang} ${width}: a rule names several models`, async (t) => { const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); t.after(() => browser.close()); - const page = await (await browser.newContext({ viewport: { width, height: 1400 } })).newPage(); + const page = await (await browser.newContext({ viewport: { width, height: 1400 }, reducedMotion: "reduce" })).newPage(); page.setDefaultTimeout(5000); page.setDefaultNavigationTimeout(60000); const errors = [], posts = []; @@ -117,10 +117,12 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.route("**/*", serve(lang, posts)); await page.goto("http://magpie.test/?view=routing"); const group = page.locator(".rt-group").first(); - await group.waitFor(); + await group.waitFor({ state: "attached" }); // the trace: the rule's next went first await page.waitForFunction((s) => document.documentElement.innerText.includes(s), w.why); + await page.evaluate(() => window.show("groups")); + await group.waitFor(); await press(page, group.locator("button", { hasText: w.edit })); const ed = page.locator(".rt-gedit"); diff --git a/internal/gui/tests/routing-rule-remove.test.cjs b/internal/gui/tests/routing-rule-remove.test.cjs index 23fecd011..c55bc66ad 100644 --- a/internal/gui/tests/routing-rule-remove.test.cjs +++ b/internal/gui/tests/routing-rule-remove.test.cjs @@ -122,13 +122,13 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", test(`${engine} ${lang} ${width}: a rule's ⋯ is there to remove it, and a rule with no condition says how`, async (t) => { const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); t.after(() => browser.close()); - const page = await (await browser.newContext({ viewport: { width, height: 1400 } })).newPage(); + const page = await (await browser.newContext({ viewport: { width, height: 1400 }, reducedMotion: "reduce" })).newPage(); page.setDefaultTimeout(5000); page.setDefaultNavigationTimeout(60000); const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); // the ⋯ is drawn with the pointer off the rule, and Remove rule // under it takes the rule out diff --git a/internal/gui/tests/routing-rules-line.test.cjs b/internal/gui/tests/routing-rules-line.test.cjs index a83a8880d..c1db258a4 100644 --- a/internal/gui/tests/routing-rules-line.test.cjs +++ b/internal/gui/tests/routing-rules-line.test.cjs @@ -118,13 +118,13 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", test(`${engine} ${lang} ${width}: a rule reads as one line, its conditions added from a menu`, async (t) => { const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); t.after(() => browser.close()); - const page = await (await browser.newContext({ viewport: { width, height: 1400 } })).newPage(); + const page = await (await browser.newContext({ viewport: { width, height: 1400 }, reducedMotion: "reduce" })).newPage(); page.setDefaultTimeout(5000); page.setDefaultNavigationTimeout(60000); const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); // saved untouched: the rules as loaded, field for field let ed = await openEditor(page, w); diff --git a/internal/gui/tests/routing-save-blank.test.cjs b/internal/gui/tests/routing-save-blank.test.cjs index 688227327..f68f8d216 100644 --- a/internal/gui/tests/routing-save-blank.test.cjs +++ b/internal/gui/tests/routing-save-blank.test.cjs @@ -59,7 +59,7 @@ function serve(lang) { // What the reader sees: whether any group row is in the view's own box, and how // much of the view's foot is the room kept for a click. const seen = (page) => page.evaluate(() => { - const v = document.querySelector("#view-routing"); + const v = document.querySelector("#view-groups"); const vr = v.getBoundingClientRect(); const rows = [...v.querySelectorAll(".rt-group")]; const inSight = rows.filter((r) => { const b = r.getBoundingClientRect(); return b.bottom > vr.top && b.top < vr.bottom; }).length; @@ -92,14 +92,14 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-group[data-id=big]").waitFor(); // the editor, from the row await page.locator(".rt-group[data-id=big]").click(); const save = page.locator(".rt-gedit button", { hasText: new RegExp(`^${w.save}$`) }); await save.waitFor(); - const view = page.locator("#view-routing"); + const view = page.locator("#view-groups"); const box = await view.boundingBox(); // the reader scrolls down to the editor's foot: the editor is taller // than the window (its Save stays in sight on the way, held at the diff --git a/internal/gui/tests/routing-save-keeps-the-row.test.cjs b/internal/gui/tests/routing-save-keeps-the-row.test.cjs index e1329655c..c8479f5a6 100644 --- a/internal/gui/tests/routing-save-keeps-the-row.test.cjs +++ b/internal/gui/tests/routing-save-keeps-the-row.test.cjs @@ -56,7 +56,7 @@ function serve(lang) { // What the reader sees: whether the row saved is in the view's own box, how many // rows are at all, and how much of the view's foot is the room kept for a click. const seen = (page) => page.evaluate(() => { - const v = document.querySelector("#view-routing"); + const v = document.querySelector("#view-groups"); const vr = v.getBoundingClientRect(); const rows = [...v.querySelectorAll(".rt-group")]; const inBox = (r) => { const b = r.getBoundingClientRect(); return b.bottom > vr.top && b.top < vr.bottom; }; @@ -89,13 +89,13 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-group[data-id=big]").waitFor(); // narrow, the row is below the window's foot; magpie moves the page // only for the reader, so it is wheeled to as a reader would const row = page.locator(".rt-group[data-id=big]"); - const vb = await page.locator("#view-routing").boundingBox(); + const vb = await page.locator("#view-groups").boundingBox(); await page.mouse.move(vb.x + vb.width / 2, vb.y + vb.height / 2); for (let i = 0; i < 100; i++) { const b = await row.boundingBox(); @@ -108,7 +108,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const saveText = await page.evaluate(() => t("Save")); const save = page.locator(".rt-gedit button", { hasText: new RegExp(`^${saveText}$`) }); await save.waitFor(); - const view = page.locator("#view-routing"); + const view = page.locator("#view-groups"); const box = await view.boundingBox(); // the reader scrolls down to the editor's foot: the editor is taller // than the window (its Save stays in sight on the way, held at the diff --git a/internal/gui/tests/routing-smart-intent.test.cjs b/internal/gui/tests/routing-smart-intent.test.cjs index 05724fad2..91b11b9e2 100644 --- a/internal/gui/tests/routing-smart-intent.test.cjs +++ b/internal/gui/tests/routing-smart-intent.test.cjs @@ -81,7 +81,7 @@ async function open(t, engine, lang, width, how) { page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, routeOf(how))); await page.goto("http://magpie.test/?view=routing"); - await page.locator(".rt-group").first().waitFor(); + await page.locator("#view-routing .rt-stage").waitFor(); return { page, errors }; } diff --git a/internal/gui/tests/routing-steady.test.cjs b/internal/gui/tests/routing-steady.test.cjs deleted file mode 100644 index ab239392c..000000000 --- a/internal/gui/tests/routing-steady.test.cjs +++ /dev/null @@ -1,180 +0,0 @@ -// Run with Node's test runner and Playwright on the module path; see README.md. -// Requests coming in never move the Routing page (Jerell.OvO on Discord -// #general: as the request log refreshed, the page kept scrolling up, so -// the routing groups further down could not be read or edited). With the -// view scrolled down to the groups and one open in its editor, a name being -// typed, new requests stream in from the trace — new agents and accounts on -// the stage, a failure and a retry in the story, the list growing — and the -// groups stay where they are on the screen, the view's scrollTop with them, -// and the field keeps its focus and what was typed. -const assert = require("node:assert/strict"); -const fs = require("node:fs/promises"); -const path = require("node:path"); -const { test } = require("node:test"); -const { chromium, webkit } = require("playwright"); - -const assets = path.resolve(__dirname, "../assets"); -const now = new Date(); -const iso = (ms) => new Date(ms).toISOString(); -const acct = (n) => ({ id: `acct-${n}`, provider: `prov${n}`, name: `Provider ${n}`, who: `user${n}@example.com`, kind: "account", model: `model-${n}`, known: true, used: 10 * n, plan: "Pro" }); -const agentsOf = ["codex", "claude", "opencode", "kimi"]; - -// a request: from an agent, weighing some accounts, answered by the last -// of them after the others failed (more tries, a longer story) -function req(id, agent, ids, fails) { - const t0 = now.getTime() - (200 - id) * 1000; - const order = ids.map(acct); - const tries = order.slice(0, fails + 1).map((w, i) => ({ - id: w.id, model: w.model, start: iso(t0 + i * 100), done: true, ms: 800, - ...(i < fails ? { status: 429, fail: "rate", again: true, error: "rate limited, try again later" } : { status: 200 }), - })); - return { id, seq: id, time: iso(t0), agent, model: order[0].model, provider: order[0].provider, order, tries, done: true, status: 200, ms: 900 + fails * 800, tokens: 1500 }; -} -const first = [req(100, "codex", [1], 0), req(101, "codex", [1, 2], 0)]; -const later = [ - req(102, "claude", [3, 4, 5], 2), - req(103, "opencode", [6, 1, 2, 3], 3), - req(104, "kimi", [7, 8], 1), - req(105, "codex", [1, 2, 3, 4, 5, 6], 4), - req(106, "claude", [2], 0), - req(107, "opencode", [8, 7, 6, 5, 4], 3), -]; - -const models = [1, 2, 3].map((n) => ({ id: `prov${n}/model-${n}`, name: `model-${n}`, providerName: `Provider ${n}`, icon: "generic" })); -const groups = { - models, - groups: [ - { id: "opus-anywhere", name: "Opus anywhere", members: [models[0].id, models[1].id], routing: "", ready: true }, - { id: "cheap", name: "Cheap", members: [models[2].id], routing: "order", ready: true }, - ], - pools: [1, 2, 3].map((n) => ({ provider: `prov${n}`, name: `Provider ${n}`, kind: "account", who: ["a", "b"], routing: "", affinity: "" })), -}; - -function serve(feed) { - const state = { agents: agentsOf.map((id) => ({ id, name: id[0].toUpperCase() + id.slice(1), path: `/test/${id}`, fields: [] })), profiles: [], settings: { lang: "en", theme: "light" } }; - return async (route) => { - const url = new URL(route.request().url()); - const json = (data) => route.fulfill({ json: data }); - if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: 'window.bootPrefs = {lang:"en",theme:"light",web:true};' }); - if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); - if (url.pathname === "/api/state") return json(state); - if (url.pathname === "/api/gateway/trace") { - const trace = (routes) => json({ mine: true, now: new Date().toISOString(), seq: routes.length ? routes[routes.length - 1].seq : Number(url.searchParams.get("after")), totals: { requests: 0, rerouted: 0, errors: 0 }, routes }); - if (!url.searchParams.get("wait")) return trace(first); - // the long poll: answered when the test feeds a request - const r = await new Promise((res) => { feed.next = res; }); - return trace([r]); - } - if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); - if (url.pathname === "/api/groups") return json(groups); - if (url.pathname === "/api/providers") return json({ providers: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); - if (url.pathname.startsWith("/api/")) return json({}); - const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); - const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; - await route.fulfill({ body: await fs.readFile(file), contentType }); - }; -} - -const view = "#view-routing"; - -for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { - test(`${engine}: requests coming in leave the routing groups where they are`, async (t) => { - const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); - const context = await browser.newContext({ viewport: { width: 1100, height: 760 } }); - const page = await context.newPage(); - page.setDefaultTimeout(5000); - page.setDefaultNavigationTimeout(60000); - const errors = []; - page.on("pageerror", (e) => errors.push(e.message)); - const feed = { next: null }; - await page.route("**/*", serve(feed)); - t.after(async () => { - if (process.env.ARTIFACT_DIR) { - await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); - await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-steady.png`) }); - } - feed.next?.(req(999, "codex", [1], 0)); - await browser.close(); - }); - await page.goto("http://magpie.test/?view=routing"); - await page.locator(".rt-req").nth(first.length - 1).waitFor(); - await page.locator(".rt-group").first().waitFor(); - await page.waitForTimeout(2000); // the first request's play - - // down to the groups with the wheel (the view moves only for the - // reader), the second group in the middle of the view; then the first - // opened in its editor and a name typed into it - const dy = await page.locator(view).evaluate((v) => { - const g = [...document.querySelectorAll(".rt-group")].pop(); - return Math.round(g.getBoundingClientRect().top - v.getBoundingClientRect().top - v.clientHeight / 2); - }); - await page.mouse.move(550, 400); - await page.mouse.wheel(0, dy); - await page.waitForTimeout(400); - const scrolled = await page.locator(view).evaluate((v) => v.scrollTop); - assert(scrolled > 200, `the view must be scrolled down to the groups (${scrolled})`); - await page.locator(".rt-group").first().locator("button", { hasText: "Edit" }).click(); - const name = page.locator(".rt-gedit input").first(); - await name.click(); - await name.press("End"); - await page.keyboard.type(" and more"); - const typed = await name.inputValue(); - assert.equal(typed, "Opus anywhere and more"); - await page.waitForTimeout(300); - - // where things are: on the screen, and the groups' place in the page - // (which moves as what's above them grows or shrinks) - const where = () => page.evaluate((sel) => { - const v = document.querySelector(sel), vt = v.getBoundingClientRect().top; - const top = (e) => e.getBoundingClientRect().top - vt; - const gsec = document.querySelector(".rt-gsec"); - return { - scrollTop: v.scrollTop, - inPage: gsec.getBoundingClientRect().top - vt + v.scrollTop, - onScreen: { head: top(gsec), editor: top(document.querySelector(".rt-gedit")), group: top([...document.querySelectorAll(".rt-group")].pop()) }, - }; - }, view); - const before = await where(); - - // every layout and every scroll while they come, after the page has - // had its say (these observers and listeners come after the page's): - // what the reader could see, not only where it ends - await page.evaluate((sel) => { - // (to a pixel and a half: WebKit scrolls by whole pixels, the - // parts above are laid out in fractions of one) - const v = document.querySelector(sel), ed = () => document.querySelector(".rt-gedit").getBoundingClientRect().top; - const want = ed(); - window.__moves = []; - const look = (why) => { const at = ed(); if (Math.abs(at - want) > 1.5) window.__moves.push(`${why}: the editor at ${at}, not ${want}`); }; - window.__ro = new ResizeObserver(() => look("layout")); - for (const e of [v, ...v.children, ...document.querySelector("#rtMore").children]) window.__ro.observe(e); - v.addEventListener("scroll", () => look("scroll")); - }, view); - for (const r of later) { - for (let i = 0; i < 50 && !feed.next; i++) await page.waitForTimeout(50); - const next = feed.next; - feed.next = null; - next(r); - await page.waitForTimeout(900); - } - await page.waitForTimeout(2500); // the plays end, the countdowns tick - assert.equal(await page.locator(".rt-req").count(), first.length + later.length, "every request must be listed"); - const moves = await page.evaluate(() => { window.__ro.disconnect(); return window.__moves; }); - const after = await where(); - - // what's above the groups did change: new agents and accounts on the - // stage, a longer story, more rows in the lists - assert(Math.abs(after.inPage - before.inPage) > 50, `the part above the groups must have changed (${before.inPage} → ${after.inPage})`); - // and the groups stayed where they were on the screen, the view - // scrolling by just what grew above them, on every frame - for (const k of Object.keys(before.onScreen)) assert(Math.abs(after.onScreen[k] - before.onScreen[k]) <= 1.5, `the ${k} moved: ${JSON.stringify([before, after])}`); - assert(Math.abs((after.scrollTop - before.scrollTop) - (after.inPage - before.inPage)) < 2, `scrollTop must follow the groups: ${JSON.stringify([before, after])}`); - assert.deepEqual(moves, [], "the page moved while the requests came"); - // the field kept its focus and what was typed, and goes on taking it - assert.equal(await name.evaluate((e) => e === document.activeElement), true, "the field lost its focus"); - assert.equal(await name.inputValue(), typed); - await page.keyboard.type("!"); - assert.equal(await name.inputValue(), typed + "!"); - assert.deepEqual(errors, []); - }); -} diff --git a/internal/gui/tests/routing-time-zone.test.cjs b/internal/gui/tests/routing-time-zone.test.cjs index 40dc51d1f..ce90c6214 100644 --- a/internal/gui/tests/routing-time-zone.test.cjs +++ b/internal/gui/tests/routing-time-zone.test.cjs @@ -79,7 +79,7 @@ async function open(t, engine, lang, clock, width) { const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, clock, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const group = page.locator(".rt-group").first(); await group.waitFor(); const titles = () => group.evaluate((g) => [...g.querySelectorAll("[title]")].map((e) => e.title).join("\n")); diff --git a/internal/gui/tests/routing-time.test.cjs b/internal/gui/tests/routing-time.test.cjs index 14ce6d7ca..151dd860e 100644 --- a/internal/gui/tests/routing-time.test.cjs +++ b/internal/gui/tests/routing-time.test.cjs @@ -84,12 +84,14 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.route("**/*", serve(lang, posts)); await page.goto("http://magpie.test/?view=routing"); const group = page.locator(".rt-group").first(); - await group.waitFor(); + await group.waitFor({ state: "attached" }); // the trace: the rule that matched, told by its hours await page.waitForFunction((s) => document.documentElement.innerText.includes(s), w.cond); const said = await page.evaluate(() => document.documentElement.innerText); assert(said.includes(w.story), `the rule that matched is told: ${said.slice(0, 400)}`); + await page.evaluate(() => window.show("groups")); + await group.waitFor(); // the group's rule, in words const title = await group.evaluate((g) => [...g.querySelectorAll("[title]")].map((e) => e.title).join("\n")); @@ -111,7 +113,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // reader wheels Add a rule into view first: the editor runs past the // fold since the hints under Routing (a click's scroll is put back) const wheelTo = async (x) => { - const d = await x.evaluate((e) => { const v = document.querySelector("#view-routing"); + const d = await x.evaluate((e) => { const v = document.querySelector("#view-groups"); return Math.round(e.getBoundingClientRect().top - v.getBoundingClientRect().top - v.clientHeight / 2); }); await page.mouse.move(550, 400); await page.mouse.wheel(0, d); diff --git a/internal/gui/tests/sidebar.test.cjs b/internal/gui/tests/sidebar.test.cjs index b170ba98a..34fda99b2 100644 --- a/internal/gui/tests/sidebar.test.cjs +++ b/internal/gui/tests/sidebar.test.cjs @@ -61,7 +61,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.equal(await page.locator(".top #nav").count(), 0, "and not in the header"); assert.deepEqual(await page.locator("#nav .nav-gl:visible").allTextContents(), w.groups); assert.deepEqual(await page.locator("#nav button[data-view]").evaluateAll((bs) => bs.map((b) => b.dataset.view)), - ["agents", "sessions", "library", "providers", "routing", "gateway", "usage", "masking", "plugins"]); + ["agents", "sessions", "library", "providers", "routing", "groups", "gateway", "usage", "masking", "plugins"]); assert.ok(await page.locator("#side .side-foot #prefs").isVisible(), "Settings at the sidebar's foot"); assert.equal((await page.locator("#prefs .side-l").textContent()).trim(), w.settings); // no page's name or group cut, and nothing scrolls sideways diff --git a/internal/gui/tests/stays-strict.test.cjs b/internal/gui/tests/stays-strict.test.cjs index aa0e9ec2b..658869170 100644 --- a/internal/gui/tests/stays-strict.test.cjs +++ b/internal/gui/tests/stays-strict.test.cjs @@ -114,7 +114,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], posts = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, posts)); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const pool = page.locator(".rt-pool", { hasText: "Codex" }); await pool.waitFor(); const strict = pool.locator(".segs .opt", { hasText: new RegExp(`^${await tr(page, "Strict")}$`) }); diff --git a/internal/gui/tests/unlisted-models.test.cjs b/internal/gui/tests/unlisted-models.test.cjs index fc04b20e4..7cc190d23 100644 --- a/internal/gui/tests/unlisted-models.test.cjs +++ b/internal/gui/tests/unlisted-models.test.cjs @@ -127,7 +127,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // the list's own choices are still the ones the keys move over assert.equal(await page.locator("#list li[data-i]").count(), 1, "only “use as typed” is a choice"); await kept.getByRole("button", { name: w.make }).click(); - const ed = page.locator("#view-routing:not([hidden]) .rt-gedit"); + const ed = page.locator("#view-groups:not([hidden]) .rt-gedit"); await ed.waitFor(); assert.equal(await ed.locator("input").first().inputValue(), "hy4", "named after the model"); await ed.getByRole("button", { name: w.save, exact: true }).click(); @@ -149,12 +149,12 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert(await lost.isHidden(), "said only while kept for groups"); await page.locator(".editor label", { hasText: lang === "zh" ? "只通过路由分组使用" : "Only through routing groups" }).locator("input").check(); await lost.getByRole("button", { name: w.makeOf }).click(); - const ed2 = page.locator("#view-routing:not([hidden]) .rt-gedit"); + const ed2 = page.locator("#view-groups:not([hidden]) .rt-gedit"); await ed2.waitFor(); assert.equal(await ed2.locator("input").first().inputValue(), "hy4"); // opened with ?newgroup=, as the tray panel asks the window - page = await open("http://magpie.test/?view=routing&newgroup=hunyuan%2Fhy4", posts); + page = await open("http://magpie.test/?view=groups&newgroup=hunyuan%2Fhy4", posts); await page.locator(".rt-gedit").waitFor(); assert.equal(await page.locator(".rt-gedit input").first().inputValue(), "hy4"); @@ -166,10 +166,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await filterFor(page, page.locator(`${row} .ag-open .field[data-key="model"]`), "hy4"); await page.locator("#list li.kept").getByRole("button", { name: w.make }).click(); for (let i = 0; i < 40 && !posts.some((p) => p.path.startsWith("/api/window/main")); i++) await page.waitForTimeout(50); - assert.equal(posts.find((p) => p.path.startsWith("/api/window/main"))?.path, "/api/window/main?view=routing&newgroup=hunyuan%2Fhy4"); + assert.equal(posts.find((p) => p.path.startsWith("/api/window/main"))?.path, "/api/window/main?view=groups&newgroup=hunyuan%2Fhy4"); const missing = await page.evaluate((ks) => ks.filter((k) => !I18N.zh[k]), [ - "In no routing group, so no agent can use them now: {models}.", "Once saved, make a group of them in Routing.", + "In no routing group, so no agent can use them now: {models}.", "Once saved, make a group of them in Routing groups.", "Make a routing group of {model}", "Make a routing group of it", "Pick {group}", "{provider} is used only through routing groups: agents reach {model} by picking {group}.", "{provider} is used only through routing groups, and {model} is in none, so no agent can use it. Make a group of it, or untick “Only through routing groups” in {provider}'s models.", diff --git a/internal/gui/tests/usage-all-accounts.test.cjs b/internal/gui/tests/usage-all-accounts.test.cjs index 89f3402cb..e4ac99cd5 100644 --- a/internal/gui/tests/usage-all-accounts.test.cjs +++ b/internal/gui/tests/usage-all-accounts.test.cjs @@ -152,7 +152,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.locator("#quotaMode .opt").nth(0).click(); // a routing group's row - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const line = page.locator('.rt-groups > .rt-group[data-id="glm"] .rt-gquota'); await line.waitFor(); const said = await line.textContent(); diff --git a/internal/gui/tests/usage-focus-steady.test.cjs b/internal/gui/tests/usage-focus-steady.test.cjs index 27e3b51b9..3035e1e8e 100644 --- a/internal/gui/tests/usage-focus-steady.test.cjs +++ b/internal/gui/tests/usage-focus-steady.test.cjs @@ -176,9 +176,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.deepEqual(await flashes(panel), [], "the panel's chart isn't dimmed or blanked"); assert.deepEqual(await kept(panel, PCOL), Array.from({ length: pcols }, (_, i) => i + 1), "the same columns stay"); - // the Routing page's groups: the same cards stay - await p.locator('[data-view="routing"]').first().click(); - const GRP = "#view-routing .rt-group"; + // the Routing groups page: the same cards stay + await p.locator('[data-view="groups"]').first().click(); + const GRP = "#view-groups .rt-group"; await p.locator(GRP).first().waitFor(); await p.waitForTimeout(300); await watch(p, GRP); diff --git a/internal/gui/tests/view-ends-relayout.test.cjs b/internal/gui/tests/view-ends-relayout.test.cjs index 94156a9bc..b28f203ae 100644 --- a/internal/gui/tests/view-ends-relayout.test.cjs +++ b/internal/gui/tests/view-ends-relayout.test.cjs @@ -26,7 +26,7 @@ const groups = { // a pool in the list, as on a real page: an empty one's list is hidden // again on every draw, which happened to place the capsule again pools: [{ provider: "workbuddy-ai", name: "WorkBuddy AI", icon: "generic", kind: "account", who: ["a", "b", "c"], routing: "order" }], - groups: Array.from({ length: 16 }, (_, i) => ({ id: `g${i}`, name: `group ${i}`, routing: "order", members: ids, ready: true, memberInfo: ids.map((id) => ({ id, ready: true })), offers: [], shared: [] })), + groups: Array.from({ length: 30 }, (_, i) => ({ id: `g${i}`, name: `group ${i}`, routing: "order", members: ids, ready: true, memberInfo: ids.map((id) => ({ id, ready: true })), offers: [], shared: [] })), }; const AGENTS = Array.from({ length: 40 }, (_, i) => ({ id: "a" + i, name: "Agent " + i, path: "/t/a" + i + ".json", icon: "generic", wired: true, @@ -100,13 +100,15 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", page.on("pageerror", (e) => { if (!/^ResizeObserver loop/.test(e.message)) errors.push(e.message); }); await page.route("**/*", serve(lang, web)); - // Routing: a screen down, the capsule in sight - await page.goto("http://magpie.test/?view=routing"); + // Routing groups: a screen down, the capsule in sight (with the + // page to themselves, the groups need more rows to be a screen + // and more down) + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-group").nth(15).waitFor(); - const v = "#view-routing"; + const v = "#view-groups"; await page.mouse.move(width / 2, 300); const down = await page.evaluate(() => { - const v = document.querySelector("#view-routing"), g = document.querySelectorAll(".rt-group")[9]; + const v = document.querySelector("#view-groups"), g = document.querySelectorAll(".rt-group")[20]; return Math.round(g.getBoundingClientRect().top - v.getBoundingClientRect().top - v.clientHeight / 2); }); await page.mouse.wheel(0, down); diff --git a/internal/gui/tests/view-scrollbar.test.cjs b/internal/gui/tests/view-scrollbar.test.cjs index 9b6eb7c57..b3ff19c5f 100644 --- a/internal/gui/tests/view-scrollbar.test.cjs +++ b/internal/gui/tests/view-scrollbar.test.cjs @@ -48,7 +48,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve()); - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); await page.locator(".rt-group").nth(30).waitFor(); const bar = () => page.evaluate(() => { const v = [...document.querySelectorAll(".view")].find((x) => x.offsetParent && x.scrollHeight > x.clientHeight); @@ -66,7 +66,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // its foot (#1623, fanbuz: Usage's was the engine's 15-17px one, twice // the side's, as only the side's width was set) const foot = await page.evaluate(() => { - const v = document.querySelector("#view-routing"), wide = document.createElement("div"); + const v = document.querySelector("#view-groups"), wide = document.createElement("div"); wide.style.cssText = "width: 3000px; height: 1px"; v.append(wide); v.style.display = "none"; v.offsetWidth; v.style.display = ""; @@ -76,7 +76,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", return h; }); assert.equal(foot, 8, "a wide page's bar across its foot is as thin as the one at its side"); - const thumb = await page.evaluate(() => getComputedStyle(document.querySelector("#view-routing"), "::-webkit-scrollbar-thumb").backgroundColor); + const thumb = await page.evaluate(() => getComputedStyle(document.querySelector("#view-groups"), "::-webkit-scrollbar-thumb").backgroundColor); assert.notEqual(thumb, "rgba(0, 0, 0, 0)", "the thumb is drawn in no colour"); assert.deepEqual(errors, []); }); diff --git a/internal/gui/tests/zero-priced-free.test.cjs b/internal/gui/tests/zero-priced-free.test.cjs index 4066e22f0..c9b335b8a 100644 --- a/internal/gui/tests/zero-priced-free.test.cjs +++ b/internal/gui/tests/zero-priced-free.test.cjs @@ -128,7 +128,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.locator("#modal").waitFor({ state: "hidden" }); // a routing group's Add a model picker - await page.goto("http://magpie.test/?view=routing"); + await page.goto("http://magpie.test/?view=groups"); const card = page.locator('.rt-group[data-id="g"]'); await card.waitFor(); await card.locator("button", { hasText: w.edit }).click(); diff --git a/internal/gui/trace.go b/internal/gui/trace.go index 796008e82..01ca3a802 100644 --- a/internal/gui/trace.go +++ b/internal/gui/trace.go @@ -325,8 +325,9 @@ func mainView(q url.Values) string { } } // the panel's picker making a routing group of a model kept for groups - // and in none: the window opens on a new group of it - if m := q.Get("newgroup"); view == "routing" && m != "" { + // and in none: the window opens on a new group of it, on the Routing + // groups page (routing, from a build before it, still does) + if m := q.Get("newgroup"); (view == "routing" || view == "groups") && m != "" { view += "&newgroup=" + url.QueryEscape(m) } return view diff --git a/internal/gui/unlisted_test.go b/internal/gui/unlisted_test.go index 0eda8bffb..6ef962e1d 100644 --- a/internal/gui/unlisted_test.go +++ b/internal/gui/unlisted_test.go @@ -55,6 +55,9 @@ func TestUnlistedModelsSaid(t *testing.T) { if v := mainView(url.Values{"view": {"routing"}, "newgroup": {"hunyuan/hy4"}}); v != "routing&newgroup=hunyuan%2Fhy4" { t.Fatalf("window view %q", v) } + if v := mainView(url.Values{"view": {"groups"}, "newgroup": {"hunyuan/hy4"}}); v != "groups&newgroup=hunyuan%2Fhy4" { + t.Fatalf("window view %q", v) + } if v := mainView(url.Values{"view": {"settings"}, "newgroup": {"x/y"}}); v != "settings" { t.Fatalf("window view %q", v) }