routing: a member behind another by weight or order isn't told as kept for last (Creat.wu)

Creat.wu on Discord (#general, 10-24): in a group routed by weight, a
sub-group whose accounts are all near their limit "is skipped however
high its weight". The screenshot is the Routing page's line
"<account> 已用 91%,其他账号都无法响应时才用。"

Cause: the routing itself already gives such a member its share.
weightedUnits leaves a unit out of the round only when its head is
resting; Smart's 90% band orders accounts inside the sub-group and
nothing in the parent reads it. A sandbox probe with the reporter's
shape (parent weighted, group/sb:4 with two Codex accounts at 91% and
92%, a key at 1) sent 16 of 20 new conversations to the sub-group and 4
to the key. What was wrong is the explanation. On a request whose turn
went to the key, the sub-group's accounts are listed after it, and the
page's asides (client.js) said of each one "used 91%, kept for when the
others can't", which reads as the member being passed over.

Change:
- client.js: memberSplit finds where a later account parts from the
  first one in the group tree. When that level is routed by weight (the
  first has the round's turn) or by order (no affinity kept, no rule),
  a low or not-yet-known account there gets one line per member instead:
  "{member} isn't passed over for being near its limit: by weight this
  request was {first}'s share, and {member} takes its own share of the
  requests while it can answer." or "... it comes after {first} in
  {group}'s order." Spent and resting lines are unchanged, and inside a
  Smart sub-group the low line stays, since the band does order those
  accounts.
- i18n.js: both strings in zh, zh-TW, ja and de.
- weighted_low_test.go: TestWeightedGroupGivesALowGroupItsShare holds
  the share (16/4 over 20, only the account with most left inside, and
  the sub-group's accounts behind the key not resting).
- routing-weight-member-low.test.cjs: weight, inner-Smart, order and
  plain Smart scenes, chromium and webkit, every language.
- gateway-routing.md: the weighted sentence says a unit near its limit
  keeps its share, and points at memberSplit.

Siblings: Smart, usage and pace parents weigh a nested group by its
head, so a low head goes later there by design and its line stays.
Manual picks a member and sorts the rest smartly (line stays). Rotate
is account-level.

Run (worktree at origin/main 7d9165d84; rebased on c30af359b, which changes
nothing under the routing plugin, weighted.go or fallback.go, and run
again there: go test ./internal/gui (budgets) ok, the new Go test ok,
routing-weight-member-low and i18n-keys 44/44):
- the new Go test -count=3 with the weighted tests: ok
- go test ./internal/gui/...: ok (112s)
- node --test routing-*, i18n-*, group-member-weight GUI files, both
  engines, all languages, at load 40 to 110: 1227 of 1285 pass. The 58
  reds are in the rule editor and manual and steady files
  (routing-pause, -rule-effort, -rule-remove, -intent-entry, -manual,
  -steady, -time, -rules-line, -busy-frames), all click timeouts.
  busy-frames and rules-line pass when rerun one at a time. The rest are
  red the same way on a clean origin/main 5a85a2a91 worktree, and are
  filed: #3408, #3409, #3410, #3411, #3412, #3094, #3096, and #3465
  (routing-time, new). routing-weight-member-low: 40/40.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./...: clean; gofmt -l on the changed files: clean
- go test ./internal/gateway/... -timeout 45m: ok (408s)

Broken by hand:
- weightedUnits with `|| heads[i].p.Account != nil` added to the skip:
  the Go test is red (0 of 20 to the sub-group). Restored.
- the old client.js: the weight and order scenes are red (10 failures
  on chromium), the inner-Smart and Smart scenes stay green.

Not tried: real accounts, or the reporter's own config (not shared);
the full ./... suite (another session's full suite held the machine).
This commit is contained in:
yetone
2026-10-24 17:38:26 +08:00
parent c30af359b4
commit 6d707af083
5 changed files with 271 additions and 1 deletions
+1 -1
View File
@@ -32,7 +32,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md).
| Model resolution | `serve` resolves the model the agent asked for: Claude tier stand-ins, a routing group (`provider.GroupFor`: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id; the user's own groups only while the `groups` plugin is on, [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)), auto stand-ins, the agent's own stand-in (`StandIn`: Codex's config.toml `model` when magpie is its provider, for a name it sends that magpie doesn't serve, such as its auto-review's `codex-auto-review`), itself taken through `GroupFor` and auto stand-ins so a config naming a group bare reaches it, then `provider.Resolve`. A Codex memory call or auto-review (`x-openai-subagent: guardian`, or `codex-auto-review`) that still names no served model goes to the model Codex's last turn was answered on (`codexMemoryStandIn`, per agent and gateway key), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, `TestCodexAutoReviewReachesItsTurnsModel`). A bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api) is never refused: with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-<slug>`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, `Resolve` takes the first provider in the Providers order that exposes it, with no fallback. magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. `/v1/models` lists bare ids only when the user asks for them ([Model ids without the provider](#model-ids-without-the-provider)). Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) |
| 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/<model>`: 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`, preferring a spelling models.dev lists), so a client that looks the part after the slash up on models.dev finds it (ZeroClover on X). Its old id `group/auto-<slug>` is served forever. Inside magpie the group keeps that one id: `validateModel` takes `auto/<model>` (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/<model>` by the old id. An agent field magpie set to `group/auto-<slug>` moves to `auto/<model>` on the next `SyncCatalog` (`agent.renameFoundGroups`), but only while its value is still what applied.json says magpie wrote; a value the user set or changed stays. A pick of the group by its old id written now (`Agent.Apply`) is written as `auto/<model>`. 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/<x>` is its model and found groups list as `group/auto-<slug>` (`autoRefsOn`). Hand-made groups stay `group/<id>`. | [`internal/provider/autoref.go`](../../internal/provider/autoref.go), [`key_models.go`](../../internal/gateway/key_models.go), [`internal/agent/autoref.go`](../../internal/agent/autoref.go) |
| Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576). 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` or `free` (free first). `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. `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 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. 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/<id>`, 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, and a kept conversation moves the round's charge to the member that kept it (`wrrSeat`, `routes.MoveRound`). 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`). 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` or `free` (free first). `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. `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 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. 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/<id>`, 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`). 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`). 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`). `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`); a fallback is never asked for want of either. 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) |
| 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. 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) |
| Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. Volcengine Ark (`isArk`: an `ark.*.volces.com` base, the preset's plans or one added by hand) is asked at `/images/generations` only, as its doc (https://www.volcengine.com/docs/82379/1541523) takes it (`drawArk`): `watermark: false`, since it marks every image otherwise; reference images as JSON `image` (a URL or data URL, an array for several), never a multipart edit; no `n`, so one request per image (`eachDrawing`); no ratio as `size`, so a ratio its doc lists is sent as that ratio's 2K size and any other is a 400 that says to put it in the prompt; no mask, no quality (JL on Discord, `TestArkDrawsWithoutWatermarkOncePerImage`). A routing group named for a drawing or a video (`drawingGroup`: `group/<id>`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). Pause rules and a gateway key's group hold apply as for a chat. Nothing rests for a failed drawing. `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. An account's own list of models (#474) never bars a ChatGPT account's GPT Image, a Grok subscription's Grok Imagine or a WorkBuddy plan's image models (`listsCantName`): the list is picked from the editor's chat models, which they are never among, so a list kept for some chat models had every drawing refused as "set not to be served by any account" (heyiwei5 on X). A key's list, picked from models that include its image ones, still bars them. `TestCodexDrawsPastAccountModelLists`. A drawing is given Settings → Images → Image generation timeout (`imageTimeout`, 1 to 60 minutes, 5 when unset; neighbads on X: a slow image endpoint needed more) as its context's deadline (`drawTimeout`, `drawWithin`), and so is downloading an image answered as a link (`imageLongest`, never under `ImageLongest`). A drawing's request goes through a transport with no `ResponseHeaderTimeout` (`drawsApart`), since an images API sends its headers only once it has drawn, and every other request keeps `upstreamHeaderWait` (10 minutes). A video's submit, status and download calls keep 5 minutes each (`videoTimeout`). The `magpie mcp image` process, which may not read these settings (WSL), waits on a call up to `callLongest` (two hours and a minute), so it never cuts one the gateway still waits on. `TestLongImageTimeoutLetsASlowVendorFinish`, `TestImageTimeoutSettingReachesTheVendor`, `TestOnlyDrawingsWaitPastTheHeaderWait`. | [`draw.go`](../../internal/gateway/draw.go), [`draw_volcengine.go`](../../internal/gateway/draw_volcengine.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.go) |
+80
View File
@@ -0,0 +1,80 @@
package gateway
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// A group routed by weight with a Smart group in it whose every account is
// near its limit (91% and 92%, not out, not resting) and a key beside it
// (Creat.wu on Discord): the group in it weighing 4 and the key 1 take 16
// and 4 of 20 new conversations. Being near its limit doesn't pass the
// member over in its parent's round; inside it, Smart sends its share to
// the account with the most left.
func TestWeightedGroupGivesALowGroupItsShare(t *testing.T) {
codexSignedIn(t, "spare@example.com")
b := newResetBackend(t)
capUsage(t, map[string]float64{"me@example.com": 91, "spare@example.com": 92})
var keyed atomic.Int32
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
keyed.Add(1)
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, grokAnswer)
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "xai", Name: "X", Key: "k", Models: []string{"gpt-5.5"}, Chat: up.URL + "/v1"}); err != nil {
t.Fatal(err)
}
if err := provider.SaveGroup(provider.Group{ID: "sb", Name: "SB", Members: []string{"codex/gpt-5.5"}}); err != nil {
t.Fatal(err)
}
if err := provider.SaveGroup(provider.Group{ID: "pa", Name: "PA", Members: []string{"group/sb", "xai/gpt-5.5"}, Routing: provider.Weighted,
Weights: map[string]int{"group/sb": 4, "xai/gpt-5.5": 1}}); err != nil {
t.Fatal(err)
}
s := New()
for i := range 20 {
// a new conversation each: nothing is kept for affinity
body := fmt.Sprintf(`{"model":"group/pa","stream":true,"input":[{"role":"user","content":[{"type":"input_text","text":"hi %d"}]}]}`, i)
if rec := codexOn(s, "/v1/responses", body); rec.Code != 200 {
t.Fatalf("request %d: %d %s", i, rec.Code, rec.Body.String())
}
}
tried, _ := b.seen()
if n := strings.Count(tried, "acct-"); n != 16 || keyed.Load() != 4 || strings.Contains(tried, "acct-2") {
t.Fatalf("4 : 1 over 20: the group in it took %d (%s), the key %d", n, tried, keyed.Load())
}
// the trace: when the round gives a request to the group in it, its
// account with the most left goes first; when to the key, the group's
// accounts are after it, not resting
var sb, key int
for _, r := range s.Trace(t.Context(), 0, 0).Routes {
if len(r.Order) != 3 || !r.Order[0].Turn {
t.Fatalf("order: %+v", r.Order)
}
switch r.Order[0].Who {
case "me@example.com":
sb++
case "":
key++
for _, w := range r.Order[1:] {
if w.Rest != nil || len(w.Via) != 1 || w.Via[0] != "sb" {
t.Fatalf("behind the key: %+v", w)
}
}
default:
t.Fatalf("first: %+v", r.Order[0])
}
}
if sb != 16 || key != 4 {
t.Fatalf("traced: the group in it first %d, the key %d", sb, key)
}
}
@@ -651,9 +651,38 @@ function routingPage(part) {
return t("{who} goes first, in the order given: when its allowance renews isn't known.", { who: w });
}
// memberSplit: the group that put x behind f, when it is one that takes
// its members whole (by weight, in order) and f and x are of different
// members of it — with the names of those members and the group; null
// when they are of one member, or of a group that pools its members'
// accounts (Smart and the rest), where what x has left is why
function memberSplit(r, f, x) {
if (!r.group) return null;
const fv = f.via || [], xv = x.via || [];
const subOf = (id) => r.group.subs?.find((s) => s.id === id);
const at = (w, v, i) => i < v.length ? "group/" + v[i] : `${w.provider}/${w.model}${w.fixed ? ":" + w.fixed : ""}`;
const named = (w, v, i) => i < v.length ? subOf(v[i])?.name || v[i] : w.name || w.provider;
let g = r.group;
for (let i = 0; i <= Math.max(fv.length, xv.length); i++) {
const a = at(f, fv, i), b = at(x, xv, i);
if (a !== b) {
const routing = g?.routing || "";
if (routing !== "weight" && routing !== "order") return null;
// the first there by the round's pick, or by the order, not kept
// on for its conversation or sent there by a rule
if (routing === "weight" ? !f.turn : r.affinity?.kept || r.rule && !r.rule.bare) return null;
return { routing, member: named(x, xv, i), first: named(f, fv, i), group: g.name || g.id };
}
if (i >= fv.length || i >= xv.length) return null; // one member
g = subOf(fv[i]);
}
return null;
}
// asides: the others' places, where they say something
function asides(r) {
const out = [];
const told = new Set(); // the members told as behind by weight or order
const aff = affWhy(r, true) ? null : affWhy(r, false);
if (aff) out.push(aff);
const cls = classWhy(r.rule);
@@ -676,7 +705,21 @@ function routingPage(part) {
}
const smart = (x) => !x.routing && (x.kind === "account" || x.known);
const someKnown = r.order.some((x) => x.known);
const f0 = r.order[0];
for (const x of r.order.slice(1)) {
// behind the first by a group's weights or its order, which take
// each member whole: not by what x has left (Creat.wu: a group in
// a group by weight, its accounts at 91%, read as passed over)
const by = !x.rest && !x.sunk && f0 ? memberSplit(r, f0, x) : null;
if (by && smart(x) && (x.known ? group(x) === "low" : someKnown)) {
if (!told.has(by.member)) {
told.add(by.member);
out.push(by.routing === "weight"
? t("{member} isn't passed over for being near its limit: by weight this request was {first}'s share, and {member} takes its own share of the requests while it can answer.", { member: by.member, first: by.first })
: t("{member} isn't passed over for being near its limit: it comes after {first} in {group}'s order.", { member: by.member, first: by.first, group: by.group }));
}
continue;
}
if (x.sunk && !x.rest) out.push(t("{who} was rate limited at {time} while it had quota left, so it went to the back: it comes round again once those ahead of it are rate limited in turn.", { who: who(x), time: clock(x.sunk) }));
else if (x.rest) out.push(t("{who} is resting — {why}, {when} — so it waits at the back.", { who: who(x), why: `${x.rest.status} · ${failWord(x.rest.why)}`, when: restWhen(x.rest, at(r.time)) }));
else if (smart(x) && x.known && group(x) === "spent" && x.credits) out.push(t("{who} is at {n} of its allowance but goes on on its credits — ahead of those used up with nothing to go on with, after those with allowance left.", { who: who(x), n: pct(x.used) }));
@@ -413,6 +413,8 @@ magpie.strings({
"{who} is resting — {why}, {when} — so it waits at the back.": "{who} 正在休息({why},{when}),排在最后。",
"{who} is at {n} — all but used up, it answers only when nothing else can.": "{who} 已用 {n},几乎用尽,仅在其他都无法响应时使用。",
"{who} is at {n} — kept for when the others can't.": "{who} 已用 {n},其他账号都无法响应时才用。",
"{member} isn't passed over for being near its limit: by weight this request was {first}'s share, and {member} takes its own share of the requests while it can answer.": "{member} 不会因为快用完而被跳过:按权重,这次请求轮到 {first},{member} 只要还能响应,就照样按权重分到它那份请求。",
"{member} isn't passed over for being near its limit: it comes after {first} in {group}'s order.": "{member} 不会因为快用完而被跳过:它按 {group} 的顺序排在 {first} 之后。",
"{who}: what it has left isn't known yet, so it goes after those known.": "{who}:剩余额度未知,排在已知的之后。",
"{who}: what it has left isn't known yet, and its answer tells, so it goes before those known.": "{who}:剩余额度未知,回答一次即可得知,因此排在已知的之前。",
"{who} goes first: what it has left isn't known yet, and its answer tells — kept behind those known, it would never answer and never be known.": "{who} 排第一:剩余额度未知,回答一次即可得知;若排在已知的之后,就永远轮不到,也永远无法得知。",
@@ -955,6 +957,8 @@ magpie.strings({
"{who} is resting — {why}, {when} — so it waits at the back.": "{who} 正在休息({why},{when}),排在最後。",
"{who} is at {n} — all but used up, it answers only when nothing else can.": "{who} 已用 {n},幾乎用盡,僅在其他都無法回應時使用。",
"{who} is at {n} — kept for when the others can't.": "{who} 已用 {n},其他帳號都無法回應時才用。",
"{member} isn't passed over for being near its limit: by weight this request was {first}'s share, and {member} takes its own share of the requests while it can answer.": "{member} 不會因為快用完而被跳過:按權重,這次請求輪到 {first},{member} 只要還能回應,就照樣按權重分到它那份請求。",
"{member} isn't passed over for being near its limit: it comes after {first} in {group}'s order.": "{member} 不會因為快用完而被跳過:它按 {group} 的順序排在 {first} 之後。",
"{who}: what it has left isn't known yet, so it goes after those known.": "{who}:剩餘額度未知,排在已知的之後。",
"{who}: what it has left isn't known yet, and its answer tells, so it goes before those known.": "{who}:剩餘額度未知,回答一次即可得知,因此排在已知的之前。",
"{who} goes first: what it has left isn't known yet, and its answer tells — kept behind those known, it would never answer and never be known.": "{who} 排第一:剩餘額度未知,回答一次即可得知;若排在已知的之後,就永遠輪不到,也永遠無法得知。",
@@ -1495,6 +1499,8 @@ magpie.strings({
"{who} is resting — {why}, {when} — so it waits at the back.": "{who} は休止中です — {why}、{when} — そのため最後尾で待ちます。",
"{who} is at {n} — all but used up, it answers only when nothing else can.": "{who} は {n} — ほぼ使い切っており、他に応答できる相手がいないときだけ応答します。",
"{who} is at {n} — kept for when the others can't.": "{who} は {n} — 他が応答できないときのために取っておきます。",
"{member} isn't passed over for being near its limit: by weight this request was {first}'s share, and {member} takes its own share of the requests while it can answer.": "{member} は上限に近いからといって飛ばされません。重みにより今回のリクエストは {first} の番で、{member} も応答できる限り重みどおりの分を受け持ちます。",
"{member} isn't passed over for being near its limit: it comes after {first} in {group}'s order.": "{member} は上限に近いからといって飛ばされません。{group} の順番で {first} の後にあるだけです。",
"{who}: what it has left isn't known yet, so it goes after those known.": "{who}:残りがまだ不明なため、判明しているものの後になります。",
"{who}: what it has left isn't known yet, and its answer tells, so it goes before those known.": "{who}:残りがまだ不明で、応答すれば判明するため、判明しているものの前になります。",
"{who} goes first: what it has left isn't known yet, and its answer tells — kept behind those known, it would never answer and never be known.": "{who} が先です:残りがまだ不明で、応答すれば判明します — 判明しているものの後ろに置くと、応答する機会も判明する機会もありません。",
@@ -2037,6 +2043,8 @@ magpie.strings({
"{who} is resting — {why}, {when} — so it waits at the back.": "{who} pausiert – {why}, {when} – und wartet daher hinten.",
"{who} is at {n} — all but used up, it answers only when nothing else can.": "{who} liegt bei {n} – fast aufgebraucht, es antwortet nur, wenn nichts anderes kann.",
"{who} is at {n} — kept for when the others can't.": "{who} liegt bei {n} – aufgehoben für den Fall, dass die anderen nicht können.",
"{member} isn't passed over for being near its limit: by weight this request was {first}'s share, and {member} takes its own share of the requests while it can answer.": "{member} wird nicht übergangen, weil es fast am Limit ist: nach Gewicht war diese Anfrage der Anteil von {first}, und {member} bekommt seinen eigenen Anteil der Anfragen, solange es antworten kann.",
"{member} isn't passed over for being near its limit: it comes after {first} in {group}'s order.": "{member} wird nicht übergangen, weil es fast am Limit ist: es kommt in der Reihenfolge von {group} nach {first}.",
"{who}: what it has left isn't known yet, so it goes after those known.": "{who}: Sein Rest ist noch unbekannt, daher kommt es nach den bekannten.",
"{who}: what it has left isn't known yet, and its answer tells, so it goes before those known.": "{who}: Sein Rest ist noch unbekannt, und seine Antwort verrät ihn, daher kommt es vor den bekannten.",
"{who} goes first: what it has left isn't known yet, and its answer tells — kept behind those known, it would never answer and never be known.": "{who} kommt zuerst: Sein Rest ist noch unbekannt, und seine Antwort verrät ihn – hinter den bekannten würde es nie antworten und nie bekannt werden.",
@@ -0,0 +1,139 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A group routed by weight, or in order, takes each member whole: a member
// behind the first is there by the group's round or its order, not by
// what its accounts have left. The Routing page told a group in a group by
// weight, its accounts at 91%, as "kept for when the others can't" when
// the round gave the request to the other member (Creat.wu on Discord),
// and it read as passed over. Now it says the member isn't passed over
// and takes its share, once for the member. Within one member, and in a
// Smart group that pools its members' accounts, the low line stays. In
// all five languages, in Chromium and WebKit.
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 ago = (minutes) => new Date(now.getTime() - minutes * 60e3).toISOString();
const ahead = (hours) => new Date(now.getTime() + hours * 36e5).toISOString();
const acct = (user, used, extra = {}) => ({ id: "codex#" + user, provider: "codex", name: "Codex", who: user, kind: "account", agent: "codex", model: "gpt-6-astra",
known: true, used, renews: [ahead(3), ahead(90)], ...extra });
const key = (extra = {}) => ({ id: "xai", provider: "xai", name: "XKey", kind: "provider", model: "gpt-6-astra", ...extra });
const sub = { id: "sb", name: "Pool B", routing: "", in: "pa" };
const scenes = {
// the round gave this request to the key: the group in it, all near
// its limit, is behind by weight
weight: { group: { id: "pa", name: "Parent", routing: "weight", subs: [sub] },
order: [key({ turn: true }), acct("me@example.com", 91, { via: ["sb"] }), acct("spare@example.com", 92, { via: ["sb"] })] },
// the round gave it to the group in it: its second account is behind
// its first by Smart, within the member
weightInner: { group: { id: "pa", name: "Parent", routing: "weight", subs: [sub] },
order: [acct("me@example.com", 91, { via: ["sb"], turn: true }), acct("spare@example.com", 92, { via: ["sb"] }), key()] },
// in order: the account's member comes after the key's
order: { group: { id: "pa", name: "Parent", routing: "order" },
order: [key(), acct("me@example.com", 91)] },
// Smart pools the members' accounts: low is why
smart: { group: { id: "pa", name: "Parent", routing: "" },
order: [key(), acct("me@example.com", 91)] },
};
function serve(lang, scene) {
const s = scenes[scene];
const route = {
id: 1, seq: 1, time: ago(1), agent: "codex", model: "gpt-6-astra", provider: s.order[0].provider, done: true, status: 200, ms: 900, tokens: 1200,
group: s.group, order: s.order,
tries: [{ id: s.order[0].id, model: "gpt-6-astra", start: ago(1), done: true, status: 200, ms: 900 }],
};
return async (request) => {
const url = new URL(request.request().url());
const json = (data) => request.fulfill({ json: data });
if (url.pathname === "/boot.js") return request.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return request.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes
return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 1 }, routes: [route] });
}
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 } });
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 request.fulfill({ body: await fs.readFile(file), contentType });
};
}
async function open(t, engine, lang, scene, width = 1100) {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await browser.newPage({ viewport: { width, height: 900 }, reducedMotion: "reduce" });
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (error) => errors.push(error.message));
await page.route("**/*", serve(lang, scene));
await page.goto("http://magpie.test/?view=routing");
const req = page.locator(".rt-req").first();
await req.waitFor();
if (await req.getAttribute("aria-pressed") !== "true") await req.click();
await page.locator(".rt-steps li.why").first().waitFor();
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}}`);
}, [lang, key, vars]);
const steps = () => page.locator(".rt-steps li").allTextContents();
return { page, errors, say, steps };
}
const LOW = "{who} is at {n} — kept for when the others can't.";
const WEIGHT = "{member} isn't passed over for being near its limit: by weight this request was {first}'s share, and {member} takes its own share of the requests while it can answer.";
const ORDER = "{member} isn't passed over for being near its limit: it comes after {first} in {group}'s order.";
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
test(`${engine} ${lang}: a group in a group by weight, near its limit, is told as taking its share`, async (t) => {
const { errors, say, steps } = await open(t, engine, lang, "weight");
const all = await steps();
const want = await say(WEIGHT, { member: "Pool B", first: "XKey" });
if (lang !== "en") assert.ok(!want.startsWith("Pool B isn't"), `not translated: ${want}`);
assert.equal(all.filter((s) => s.includes(want)).length, 1, all.join("\n"));
for (const [user, n] of [["me@example.com", "91%"], ["spare@example.com", "92%"]]) {
const low = await say(LOW, { who: user, n });
assert.ok(!all.some((s) => s.includes(low)), `told as kept for last: ${low}\n${all.join("\n")}`);
}
assert.deepEqual(errors, []);
});
test(`${engine} ${lang}: within the member by weight, its second account is still told as kept for last`, async (t) => {
const { errors, say, steps } = await open(t, engine, lang, "weightInner");
const all = await steps();
const low = await say(LOW, { who: "spare@example.com", n: "92%" });
assert.ok(all.some((s) => s.includes(low)), all.join("\n"));
const head = (await say(WEIGHT, { member: "Pool B", first: "XKey" })).slice(0, 12);
assert.ok(!all.some((s) => s.startsWith(head)), all.join("\n"));
assert.deepEqual(errors, []);
});
test(`${engine} ${lang}: a member behind another in order is told by the order`, async (t) => {
const { errors, say, steps } = await open(t, engine, lang, "order");
const all = await steps();
const want = await say(ORDER, { member: "Codex", first: "XKey", group: "Parent" });
assert.ok(all.some((s) => s.includes(want)), `want ${want}\n${all.join("\n")}`);
const low = await say(LOW, { who: "me@example.com", n: "91%" });
assert.ok(!all.some((s) => s.includes(low)), all.join("\n"));
assert.deepEqual(errors, []);
});
test(`${engine} ${lang}: a Smart group that pools its members still says low is why`, async (t) => {
const { errors, say, steps } = await open(t, engine, lang, "smart");
const all = await steps();
const low = await say(LOW, { who: "me@example.com", n: "91%" });
assert.ok(all.some((s) => s.includes(low)), all.join("\n"));
assert.deepEqual(errors, []);
});
}
}