gateway: a provider's fallback can be a routing group, routed as the group

01huadalang on Discord: "还有备用模型增加路由组的选择,现在只能选模型". A
provider's Fallback list held models only; a "group/<id>" entry resolved
to the group's first member alone. Now such an entry is served through the
group, as a request to the group would be:

- plan → planPaused: a fallback naming a group (provider.FallbackGroup,
  the group as routed, Live) hands its members to planLevel
  (planFallbackGroup): the group's own routing, its sink and asides, and
  its pause rules (serve passes provider.PausedOut for the agent's folder).
  Its trace rows are marked Fallback with the group in Via.
- No loop, each provider/model once a round: a member that is the primary,
  a model named earlier, or another fallback group's member is left out
  where it comes second. Groups have no fallbacks of their own and a
  member's fallbacks are not followed, so nothing leads back. A group that
  is gone or off is passed over, as a model none serves is.
- Every sibling that reads p.Fallback now reads a group's members through
  provider.FallbackModels: redaction (unredactedRoute: an unmasked
  provider with a fallback group holding a remote model is masked),
  careful accounts (carefulOf), native compaction, Codex's own turns
  (codexFallsBack) and Claude's auto-mode review (claudeReviewed, which
  moves from provider.Resolve to ResolveRoute, as the gateway reads
  fallbacks).
- CLI: `magpie provider fallback` already took group/<id> (Resolve knows
  groups); its usage and error now say so. Pinned by
  TestFallbackCmdTakesGroup.
- GUI: the provider editor's Fallback picker lists the routing groups
  (providers.gateway.groups) beside the models as chips with the Routing
  fan and a muted "routing group" tell; a picked group's row has the same
  fan and tell, and a gone one says "No routing group {id} now; it is
  skipped". A filter matches a group's name, id and its members'
  providers. New strings in zh, zh-TW, ja and de.
- app.js budget raised 187 bytes on main (1,311,922; core 1,531,060), the core's
  own editor, no room added; the addition was cut from ~900 bytes first.
- docs/subsystems/gateway-routing.md: the Candidates row says all this.

Not done: a fallback group's turn rules (ruleFor/ruleOver, which can ask
a classifier) are not applied. The plan is made before the primary is
tried, so they would cost a classifier call on every request the primary
answers. Its routing order, sink and pause rules are applied.

Run (at f6e7214af; after the rebase, the last bullet):
- gofmt -l: clean. mote: go build ./...; go vet on the touched packages;
  GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...: ok.
- mote: go test -timeout 45m ./...: every package ok except internal/gui:
  TestCoreScriptBudget (fixed above, then ok) and ten AppKit window tests
  (TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt, TestMainWindowCorners
  …) killed at their 30s bars while four other sessions' GUI suites held
  mote at load 70-110. Run alone, all ten
  pass (TestDockJoinLeadsCommandTab skips) except TestMainWindowCorners,
  red at base f6e7214af too (#3949); the load kills are #2645.
- GUI: the whole suite (962 files, node --test --test-concurrency=8) on the
  Linux box (WSL magpie-desktop, chromium + webkit): 14,217
  tests, 305 red in 99 files. Those 99 files rerun at base f6e7214af: 156
  red; at this head: 159; the ~20 that differ either way are flakes (the
  head-only ones, key-replace and vertex-editor, rerun twice on each: the
  same reds at base). Filed as #4120.
  fallback-group.test.cjs (new), fallback-more and i18n-keys: ok in
  chromium and webkit on mote and on Linux.
  After the app.js cut, at the final head: the three files 12 of 12 on
  Linux; webkit ok on mote, chromium there failed only at browser launch
  under load.
- Broken by hand, each red, then restored:
  - the group branch in planPaused off: all five gateway group tests red
    (TestFallbackToGroupServedByMember is red on the old code: only the
    first member was tried).
  - the dedup off: TestFallbackGroupWithThePrimaryTriesItOnce and
    TestFallbackGroupSharedModelTriedOnce red.
  - the pause filter off: TestFallbackGroupPauseHolds red.
  - redact.go from origin/main: TestFallbackGroupKeepsMasking red.
  - the GUI's group list off: fallback-group.test.cjs red in all four
    (chromium/webkit × en/zh).
- After the rebase onto 0daf36332 (18 commits, gateway.go among them;
  the budget test conflicted, kept main's and measured again): gofmt -l
  clean; mote: go build ./..., vet of the touched packages, linux and
  windows vet ok; go test internal/provider, internal/cli, internal/agent
  ok, and internal/gateway and internal/gui -run with Fallback, Redact,
  Unredacted, Careful, Compaction, CodexFalls, Budget, Rest and Probe ok; fallback-group, fallback-more, i18n-keys
  and rest-probed 52 of 52 on Linux.

Not tried: a real request through a real group fallback with real
accounts (the tests use fake upstreams); the Windows GUI; the TUI has no
fallback editor.
This commit is contained in:
yetone
2026-10-29 05:19:28 +08:00
parent 0daf363325
commit b4267de595
17 changed files with 456 additions and 44 deletions
File diff suppressed because one or more lines are too long
+2 -3
View File
@@ -332,9 +332,8 @@ func claudeReviewed(catalogs []string, models ...string) bool {
if gateway.AutoModeReviewable(p, model) {
return true
}
return slices.ContainsFunc(p.Fallback, func(id string) bool {
fp, fm, ok := provider.Resolve(id)
return ok && gateway.AutoModeReviewable(fp, fm)
return slices.ContainsFunc(provider.FallbackModels(p), func(m provider.Member) bool {
return gateway.AutoModeReviewable(m.Provider, m.Model)
})
}
find := provider.GroupFinder()
+44
View File
@@ -0,0 +1,44 @@
package cli
import (
"slices"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// magpie provider fallback takes a routing group's id ("group/<id>") as a
// fallback beside models (01huadalang on Discord); a group that isn't
// there is an error, as a model none serves is.
func TestFallbackCmdTakesGroup(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
t.Setenv("DSH_HOME", "")
for _, p := range []provider.Provider{
{ID: "plan", Name: "Plan", Key: "kp", Models: []string{"m"}, Chat: "http://127.0.0.1:1/v1"},
{ID: "a", Name: "A", Key: "ka", Models: []string{"x"}, Chat: "http://127.0.0.1:2/v1"},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
if err := provider.SaveGroup(provider.Group{ID: "backup", Name: "Backup", Members: []string{"a/x"}}); err != nil {
t.Fatal(err)
}
if err := providerCmd([]string{"provider", "fallback", "plan", "group/backup", "a/x"}); err != nil {
t.Fatal(err)
}
p, err := provider.Find("plan")
if err != nil {
t.Fatal(err)
}
if want := []string{"group/backup", "a/x"}; !slices.Equal(p.Fallback, want) {
t.Fatalf("fallback %v, want %v", p.Fallback, want)
}
if err := providerCmd([]string{"provider", "fallback", "plan", "group/nothing"}); err == nil {
t.Fatal("a group that isn't there was taken")
}
}
+4 -2
View File
@@ -511,7 +511,7 @@ func providerCmd(args []string) error {
// where requests go when this provider is out of quota, rate
// limited or down; "none" clears the list
if len(rest) < 1 {
return fmt.Errorf("magpie provider fallback <id> [provider/model… | none]")
return fmt.Errorf("magpie provider fallback <id> [provider/model… | group/<id>… | none]")
}
p, err := provider.Find(rest[0])
if err != nil {
@@ -521,8 +521,10 @@ func providerCmd(args []string) error {
p.Fallback = nil
if !(len(rest) == 2 && rest[1] == "none") {
for _, id := range rest[1:] {
// a routing group's id ("group/<id>") resolves too: the
// gateway sends the request through the group
if _, _, ok := provider.Resolve(id); !ok {
return fmt.Errorf("magpie knows no model %q (magpie models lists them)", id)
return fmt.Errorf("magpie knows no model or group %q (magpie models lists them)", id)
}
p.Fallback = append(p.Fallback, id)
}
+2 -4
View File
@@ -128,10 +128,8 @@ func carefulOf(p provider.Provider, model string, ms []provider.Member) ([]provi
return ps, models
}
ps, models = append(ps, p), append(models, model)
for _, id := range p.Fallback {
if fp, fm, ok := provider.ResolveRoute(id); ok {
ps, models = append(ps, fp), append(models, fm)
}
for _, m := range provider.FallbackModels(p) {
ps, models = append(ps, m.Provider), append(models, m.Model)
}
return ps, models
}
+1 -6
View File
@@ -1424,12 +1424,7 @@ func (s *Server) codexFallsBack(model string, body []byte) bool {
if !ok || p.Account == nil || p.Account.Agent != "codex" {
return false
}
for _, id := range p.Fallback {
if _, _, ok := provider.ResolveRoute(id); ok {
return true
}
}
return false
return len(provider.FallbackModels(p)) > 0
}
// codexFallBack serves Codex's turn on its own sign-in, which the backend
+56
View File
@@ -405,6 +405,13 @@ func (s *Server) candidates(p provider.Provider, model string, from provider.Pro
// plan is candidates, and for the routing trace what each stood where it
// did by, and those left out.
func (s *Server) plan(p provider.Provider, model string, from provider.Protocol) ([]candidate, planned) {
return s.planPaused(p, model, from, nil)
}
// planPaused is plan, a routing group among the fallbacks (01huadalang on
// Discord) less the models paused leaves out of it: its pause rules, as
// a request to the group would have them; nil pauses none.
func (s *Server) planPaused(p provider.Provider, model string, from provider.Protocol, paused func(provider.Group, []provider.Member) []provider.Member) ([]candidate, planned) {
var pl planned
add := func(q provider.Provider, m string, fallback bool) []candidate {
cs, aside, left, barred := perKeyBarred(q, m, from)
@@ -436,6 +443,25 @@ func (s *Server) plan(p provider.Provider, model string, from provider.Protocol)
}
seen := map[string]bool{p.ID + "/" + model: true}
for _, id := range p.Fallback {
if g, ms, ok := provider.FallbackGroup(id); ok {
// a routing group: its members as a request to it has them,
// in its order, routing and sink, less any model tried
// already (this provider's own, another fallback's); a
// member's fallbacks are not followed, so nothing leads back
if paused != nil {
ms = paused(g, ms)
}
ms = slices.DeleteFunc(ms, func(m provider.Member) bool {
k := m.Provider.ID + "/" + m.Model
if seen[k] {
return true
}
seen[k] = true
return false
})
out = append(out, planFallbackGroup(g, ms, from, &pl)...)
continue
}
fp, fm, ok := provider.ResolveRoute(id)
if !ok || seen[fp.ID+"/"+fm] {
continue
@@ -446,6 +472,36 @@ func (s *Server) plan(p provider.Provider, model string, from provider.Protocol)
return restLast(out, pl)
}
// planFallbackGroup is planGroup for a routing group a provider falls back
// to, its rows added to pl as fallbacks reached through g: the group's
// keys and accounts in its own order, sunk by its own Sink, those set
// aside after them.
func planFallbackGroup(g provider.Group, ms []provider.Member, from provider.Protocol, pl *planned) []candidate {
if len(ms) == 0 {
return nil
}
at, leftAt, unlistedAt := len(pl.order), len(pl.left), len(pl.unlistedW)
var asides []candidate
var wAsides []Weighed
out := planLevel(g, ms, 0, from, pl, &asides, &wAsides)
if sinks(g.Sink, g.Routing) {
var order []Weighed
out, order = sinkPlanned(out, pl.order[at:])
pl.order = append(pl.order[:at], order...)
}
out, pl.order = append(out, asides...), append(pl.order, wAsides...)
via := func(ws []Weighed) {
for i := range ws {
ws[i].Fallback = true
ws[i].Via = append([]string{g.ID}, ws[i].Via...)
}
}
via(pl.order[at:])
via(pl.left[leftAt:])
via(pl.unlistedW[unlistedAt:])
return out
}
// planGroup is plan for a routing group: every member's keys or accounts
// weighed together as the group's routing says — in order, member by
// member, each as its own provider's routing orders it; else all as one,
+160
View File
@@ -0,0 +1,160 @@
package gateway
import (
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// fallbackToGroup saves a provider "plan" whose key kp answers 429 (out of
// quota) and falls back to the routing group "backup" of members, served
// by a (key ka, model x) and b (key kb, model x).
func fallbackToGroup(t *testing.T, g provider.Group) (plan, a, b *keyed) {
t.Helper()
fresh(t)
plan, a, b = &keyed{fail: map[string]int{"kp": 429}}, &keyed{}, &keyed{}
serveOn(t, "a", "ka", []string{"x"}, a)
serveOn(t, "b", "kb", []string{"x"}, b)
up := httptest.NewServer(plan)
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Key: "kp", Models: []string{"m"}, Chat: up.URL + "/v1", Fallback: []string{"group/backup"}}); err != nil {
t.Fatal(err)
}
g.ID, g.Name = "backup", "Backup"
if err := provider.SaveGroup(g); err != nil {
t.Fatal(err)
}
return plan, a, b
}
// A provider's fallback can be a routing group, not only a model
// (01huadalang on Discord): with the primary out of quota, the request
// goes through the group, its members in the group's own order.
func TestFallbackToGroupServedByMember(t *testing.T) {
plan, a, b := fallbackToGroup(t, provider.Group{Members: []string{"a/x", "b/x"}, Routing: provider.Ordered})
a.fail = map[string]int{"ka": 429}
code, body := postAs(t, New(), "", `{"model":"plan/m","messages":[{"role":"user","content":"hi"}]}`)
if code != 200 || !strings.Contains(body, "from kb") {
t.Fatalf("plan/m out of quota, falling back to group/backup: %d %s", code, body)
}
if len(plan.tried) != 1 || len(a.tried) != 1 || len(b.tried) != 1 {
t.Fatalf("each tried once, the group's order: plan %v, a %v, b %v", plan.tried, a.tried, b.tried)
}
}
// The group's own order holds: In order with b first sends to b, a never
// asked once b answers.
func TestFallbackGroupKeepsItsOrder(t *testing.T) {
_, a, b := fallbackToGroup(t, provider.Group{Members: []string{"b/x", "a/x"}, Routing: provider.Ordered})
code, body := postAs(t, New(), "", `{"model":"plan/m","messages":[{"role":"user","content":"hi"}]}`)
if code != 200 || !strings.Contains(body, "from kb") || len(a.tried) != 0 || len(b.tried) != 1 {
t.Fatalf("group b, a: %d %s, a %v, b %v", code, body, a.tried, b.tried)
}
}
// A group holding the provider's own model is no loop: the model is tried
// once, as the primary, and the group's other members after it.
func TestFallbackGroupWithThePrimaryTriesItOnce(t *testing.T) {
plan, a, b := fallbackToGroup(t, provider.Group{Members: []string{"plan/m", "a/x", "b/x"}, Routing: provider.Ordered})
a.fail = map[string]int{"ka": 500}
b.fail = map[string]int{"kb": 500}
if code, _ := postAs(t, New(), "", `{"model":"plan/m","messages":[{"role":"user","content":"hi"}]}`); code == 200 {
t.Fatalf("every one failing answered 200")
}
// every one failing, the request is asked again as many times as
// magpie's patience has it; each round asks each model once
if len(plan.tried) == 0 || len(a.tried) != len(plan.tried) || len(b.tried) != len(plan.tried) {
t.Fatalf("each tried once a round: plan %v, a %v, b %v", plan.tried, a.tried, b.tried)
}
}
// A model named both as a fallback and in a fallback group is tried once,
// where it was named first; so is a model two fallback groups share.
func TestFallbackGroupSharedModelTriedOnce(t *testing.T) {
plan, a, b := fallbackToGroup(t, provider.Group{Members: []string{"a/x", "b/x"}, Routing: provider.Ordered})
if err := provider.SaveGroup(provider.Group{ID: "more", Name: "More", Members: []string{"b/x", "a/x"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
p, err := provider.Find("plan")
if err != nil {
t.Fatal(err)
}
p.Fallback = []string{"a/x", "group/backup", "group/more"}
if err := provider.Save(*p); err != nil {
t.Fatal(err)
}
a.fail = map[string]int{"ka": 500}
b.fail = map[string]int{"kb": 500}
postAs(t, New(), "", `{"model":"plan/m","messages":[{"role":"user","content":"hi"}]}`)
// every one failing, the request is asked again as many times as
// magpie's patience has it; each round asks each model once
if len(plan.tried) == 0 || len(a.tried) != len(plan.tried) || len(b.tried) != len(plan.tried) {
t.Fatalf("each tried once a round: plan %v, a %v, b %v", plan.tried, a.tried, b.tried)
}
}
// A member the group's pause rule holds now is out of the group as a
// fallback too, as it is for a request to the group.
func TestFallbackGroupPauseHolds(t *testing.T) {
now := time.Date(2026, 9, 29, 10, 0, 0, 0, time.Local) // a Tuesday, in peak
ruleClock = func() time.Time { return now }
t.Cleanup(func() { ruleClock = time.Now })
_, a, b := fallbackToGroup(t, provider.Group{Members: []string{"a/x", "b/x"}, Routing: provider.Ordered,
Rules: []provider.Rule{{Use: "a/x", Pause: true, Time: peak}}})
code, body := postAs(t, New(), "", `{"model":"plan/m","messages":[{"role":"user","content":"hi"}]}`)
if code != 200 || !strings.Contains(body, "from kb") || len(a.tried) != 0 {
t.Fatalf("a/x paused: %d %s, a %v, b %v", code, body, a.tried, b.tried)
}
}
// A fallback group that is gone is passed over, as a model none serves is.
func TestFallbackGroupGoneIsSkipped(t *testing.T) {
plan, a, b := fallbackToGroup(t, provider.Group{Members: []string{"a/x"}, Routing: provider.Ordered})
p, err := provider.Find("plan")
if err != nil {
t.Fatal(err)
}
p.Fallback = []string{"group/nothing", "b/x"}
if err := provider.Save(*p); err != nil {
t.Fatal(err)
}
code, body := postAs(t, New(), "", `{"model":"plan/m","messages":[{"role":"user","content":"hi"}]}`)
if code != 200 || !strings.Contains(body, "from kb") || len(a.tried) != 0 || len(plan.tried) != 1 {
t.Fatalf("group/nothing then b/x: %d %s, a %v, b %v", code, body, a.tried, b.tried)
}
}
// A provider set to go unmasked stays masked when a routing group among
// its fallbacks may send the request to a model that isn't: the group's
// members are its fallbacks as much as a model named alone is.
func TestFallbackGroupKeepsMasking(t *testing.T) {
fresh(t)
for _, p := range []provider.Provider{
{ID: "near", Name: "Near", Key: "k1", Models: []string{"m"}, Chat: "http://127.0.0.1:1/v1", Unredacted: true, Fallback: []string{"group/backup"}},
{ID: "near2", Name: "Near2", Key: "k2", Models: []string{"m"}, Chat: "http://127.0.0.1:2/v1", Unredacted: true},
{ID: "far", Name: "Far", Key: "k3", Models: []string{"m"}, Chat: "https://api.example.com/v1"},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
if err := provider.SaveGroup(provider.Group{ID: "backup", Name: "Backup", Members: []string{"near2/m"}}); err != nil {
t.Fatal(err)
}
near, err := provider.Find("near")
if err != nil {
t.Fatal(err)
}
if !unredactedRoute(*near, false, nil) {
t.Fatal("a group of unmasked local models masked the request")
}
if err := provider.SaveGroup(provider.Group{ID: "backup", Name: "Backup", Members: []string{"near2/m", "far/m"}}); err != nil {
t.Fatal(err)
}
if unredactedRoute(*near, false, nil) {
t.Fatal("a fallback group with a remote member left the request unmasked")
}
}
+10 -1
View File
@@ -2226,7 +2226,16 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
scope += "|" + words
}
} else {
cands, pl = s.plan(p, model, from)
// a routing group among the fallbacks is routed as a request to it
// would be, its pause rules too (pausedOut's)
cands, pl = s.planPaused(p, model, from, func(fg provider.Group, fms []provider.Member) []provider.Member {
folder := ""
if provider.PausesByFolder(fg, fms) {
folder = factsOf(from, body).dir
}
kept, _ := provider.PausedOut(fg, fms, agent, folder, ruleClock())
return kept
})
if handedOnOf(r) != nil {
// Codex's own sign-in, asked as often as it is asked: only
// the fallbacks are left (codexFallBack)
+2 -8
View File
@@ -116,14 +116,8 @@ func (s *Server) nativeCompactionFor(asked string) bool {
if s.plannedCarrier(p, model) {
return true
}
seen := map[string]bool{p.ID + "/" + model: true}
for _, id := range p.Fallback {
fp, fm, ok := provider.ResolveRoute(id)
if !ok || seen[fp.ID+"/"+fm] {
continue
}
seen[fp.ID+"/"+fm] = true
if s.plannedCarrier(fp, fm) {
for _, m := range provider.FallbackModels(p) {
if (m.Provider.ID != p.ID || m.Model != model) && s.plannedCarrier(m.Provider, m.Model) {
return true
}
}
+4 -3
View File
@@ -303,9 +303,10 @@ func unredactedRoute(p provider.Provider, isGroup bool, ms []provider.Member) bo
if !p.SkipsRedaction() {
return false
}
for _, id := range p.Fallback {
// one that resolves to nothing isn't tried (plan)
if fp, _, ok := provider.ResolveRoute(id); ok && !fp.SkipsRedaction() {
// one that resolves to nothing isn't tried (plan); a routing group
// among them is each of its members
for _, m := range provider.FallbackModels(p) {
if !m.Provider.SkipsRedaction() {
return false
}
}
+3
View File
@@ -2868,6 +2868,9 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
.fbrow { display: flex; align-items: center; gap: 8px; min-height: 28px; font-size: 12.5px; }
.fbrow .i { width: 14px; color: var(--muted); font-variant-numeric: tabular-nums; }
.fbrow .grow { flex: 1; }
/* a routing group among the fallbacks: its fan, then the muted word */
.fbrow .mtell { color: var(--muted); font-size: 11px; flex: none; }
.fbrow > svg { flex: none; color: var(--muted); }
.fallback .mchips:empty { display: none; }
.after-list { display: flex; align-items: center; gap: 8px; padding: 8px 4px 0; flex: none; }
/* the Providers page's add button stays at the view's foot over a long list;
+10 -6
View File
@@ -11849,13 +11849,16 @@ function renderFallback(p) {
const box = el("div", "fallback");
const list = el("div", "fbl");
const sugg = el("div", "mchips");
const q = input("", t("add a model: filter, or type provider/model…"));
const q = input("", t("add a model or routing group: filter, or type provider/model…"));
const all = [];
// a routing group too, routed as itself (01huadalang)
for (const g of providers.gateway?.groups || []) all.push({ id: g.id, label: g.name, g: g.providers?.join(" ") || "" });
for (const o of providers.providers) {
if (!o.ready || o.off) continue;
const tells = modelTells(o.models.filter((m) => m.on));
for (const m of o.models) if (m.on) all.push({ id: o.id + "/" + m.id, label: o.name + " · " + (m.name || m.id) + (tells.has(m.id) ? " · " + tells.get(m.id) : ""), icon: o.icon });
}
const tell = () => el("span", "mtell", t("routing group"));
let open = false;
const add = (id) => { if (id && !draft.fallback.includes(id)) draft.fallback.push(id); q.value = ""; draw(); };
const draw = () => {
@@ -11863,8 +11866,9 @@ function renderFallback(p) {
draft.fallback.forEach((id, i) => {
const known = all.find((x) => x.id === id);
const row = el("div", "fbrow");
row.append(el("span", "i", String(i + 1)), icon(known?.icon || "generic"), el("span", "n", known ? known.label : id), el("span", "grow"));
if (!known) row.title = t("No provider serves {id} now; it is skipped", { id });
const g = id.startsWith("group/");
row.append(el("span", "i", String(i + 1)), g ? svg(FAN, 16, 1.5) : icon(known?.icon || "generic"), el("span", "n", known ? known.label : id), ...(g ? [tell()] : []), el("span", "grow"));
if (!known) row.title = t(g ? "No routing group {id} now; it is skipped" : "No provider serves {id} now; it is skipped", { id });
if (i) {
const up = el("button", "text", t("Up"));
up.onclick = () => { draft.fallback.splice(i - 1, 0, draft.fallback.splice(i, 1)[0]); draw(); };
@@ -11878,10 +11882,10 @@ function renderFallback(p) {
sugg.replaceChildren();
if (!open && !q.value.trim()) return;
const f = q.value.trim().toLowerCase();
const hits = all.filter((x) => !draft.fallback.includes(x.id) && !x.id.startsWith(p.id + "/") && (x.id + " " + x.label).toLowerCase().includes(f));
const hits = all.filter((x) => !draft.fallback.includes(x.id) && !x.id.startsWith(p.id + "/") && (x.id + " " + x.label + " " + (x.g ?? "")).toLowerCase().includes(f));
for (const x of hits.slice(0, 12)) {
const c = el("button", "mchip");
c.append(el("span", "", x.label));
c.append(...(x.g != null ? [svg(FAN, 12, 1.5), el("span", "", x.label), tell()] : [el("span", "", x.label)]));
c.title = x.id;
c.onmousedown = (e) => e.preventDefault(); // keep the box focused
c.onclick = () => add(x.id);
@@ -11889,7 +11893,7 @@ function renderFallback(p) {
}
// only the first dozen are drawn: the rest are said to be there
if (hits.length > 12) sugg.append(el("span", "hint", t("{n} more — type to narrow", { n: hits.length - 12 })));
if (!hits.length && f) sugg.append(el("span", "hint", f.includes("/") ? t("Enter adds {id}", { id: q.value.trim() }) : t("No model matches")));
if (!hits.length && f) sugg.append(el("span", "hint", f.includes("/") ? t("Enter adds {id}", { id: q.value.trim() }) : t("No model or routing group matches")));
};
q.onfocus = () => { open = true; draw(); };
q.onblur = () => { open = false; draw(); };
+12 -8
View File
@@ -1543,14 +1543,15 @@ const I18N = {
"e.g. 500k · or deepseek-v4-flash=272k, comma separated": "如 500k · 或 deepseek-v4-flash=272k,逗号分隔",
"Where Codex, Claude Code and Grok Build compact a long conversation on these models; empty follows Long conversations, in their settings on the Agents page (else in Settings), and a size at or above a model's window runs it to its whole window": "Codex、Claude Code 和 Grok Build 在这些模型上压缩长对话的位置;留空按 Agent 页里它们设置中的「长对话」(否则在「设置」里),大于等于模型窗口则用完整窗口",
"Compact at: {v} is not a number of tokens like 272k": "压缩阈值:{v} 不是 272k 这样的 token 数",
"add a model: filter, or type provider/model…": "添加模型:筛选,或输入 provider/model…",
"add a model or routing group: filter, or type provider/model…": "添加模型或路由组:筛选,或输入 provider/model…",
"No provider serves {id} now; it is skipped": "现在没有供应商提供 {id},会跳过它",
"No routing group {id} now; it is skipped": "现在没有路由组 {id},会跳过它",
"Up": "上移",
"Down": "下移",
"switched off": "已关闭",
"Move {name}": "移动 {name}",
"Enter adds {id}": "回车添加 {id}",
"No model matches": "没有匹配的模型",
"No model or routing group matches": "没有匹配的模型或路由组",
"When {name} is out of quota, rate limited or down, a request goes to these instead, top first. It only happens before any of the reply is sent, and {name} then sits out a minute.": "{name} 额度用完、限流或不可用时,请求按从上到下的顺序改发给这些模型。仅在回复开始前切换,之后 {name} 暂停使用一分钟。",
"{agent} and the gateway use the one in use. Sessions already running keep theirs until restarted.": "{agent} 和网关使用标记为「使用中」的账号。已在运行的会话保持原账号,重启后切换。",
"The gateway uses the first. Tick more and it moves on to the next when the one before it is out of quota. {agent} itself stays signed in as it is.": "网关优先用第一个账号;勾选多个时,前一个额度用完自动换下一个。{agent} 本身的登录不变。",
@@ -5593,14 +5594,15 @@ const I18N = {
"e.g. 500k · or deepseek-v4-flash=272k, comma separated": "如 500k · 或 deepseek-v4-flash=272k,逗號分隔",
"Where Codex, Claude Code and Grok Build compact a long conversation on these models; empty follows Long conversations, in their settings on the Agents page (else in Settings), and a size at or above a model's window runs it to its whole window": "Codex、Claude Code 和 Grok Build 在這些模型上壓縮長對話的位置;留空按 Agent 頁裡它們設定中的「長對話」(否則在「設定」裡),大於等於模型視窗則用完整視窗",
"Compact at: {v} is not a number of tokens like 272k": "壓縮閾值:{v} 不是 272k 這樣的 token 數",
"add a model: filter, or type provider/model…": "新增模型:篩選,或輸入 provider/model…",
"add a model or routing group: filter, or type provider/model…": "新增模型或路由組:篩選,或輸入 provider/model…",
"No provider serves {id} now; it is skipped": "現在沒有供應商提供 {id},會跳過它",
"No routing group {id} now; it is skipped": "現在沒有路由組 {id},會跳過它",
"Up": "上移",
"Down": "下移",
"switched off": "已關閉",
"Move {name}": "移動 {name}",
"Enter adds {id}": "回車新增 {id}",
"No model matches": "沒有匹配的模型",
"No model or routing group matches": "沒有匹配的模型或路由組",
"When {name} is out of quota, rate limited or down, a request goes to these instead, top first. It only happens before any of the reply is sent, and {name} then sits out a minute.": "{name} 額度用完、限流或不可用時,請求按從上到下的順序改發給這些模型。僅在回覆開始前切換,之後 {name} 暫停使用一分鐘。",
"{agent} and the gateway use the one in use. Sessions already running keep theirs until restarted.": "{agent} 和閘道使用標記為「使用中」的帳號。已在執行的會話保持原帳號,重啟後切換。",
"The gateway uses the first. Tick more and it moves on to the next when the one before it is out of quota. {agent} itself stays signed in as it is.": "閘道優先用第一個帳號;勾選多個時,前一個額度用完自動換下一個。{agent} 本身的登入不變。",
@@ -9620,14 +9622,15 @@ const I18N = {
"e.g. 500k · or deepseek-v4-flash=272k, comma separated": "例:500k · または deepseek-v4-flash=272k(カンマ区切り)",
"Where Codex, Claude Code and Grok Build compact a long conversation on these models; empty follows Long conversations, in their settings on the Agents page (else in Settings), and a size at or above a model's window runs it to its whole window": "Codex、Claude Code、Grok Build がこれらのモデルで長い会話を圧縮する位置です。空欄ならエージェントページのそれぞれの設定にある「長い会話」(なければ「設定」)に従い、モデルのウィンドウ以上ならウィンドウ全体を使います",
"Compact at: {v} is not a number of tokens like 272k": "圧縮しきい値:{v} は 272k のようなトークン数ではありません",
"add a model: filter, or type provider/model…": "モデルを追加:絞り込み、または provider/model を入力…",
"add a model or routing group: filter, or type provider/model…": "モデルまたはルーティンググループを追加:絞り込み、または provider/model を入力…",
"No provider serves {id} now; it is skipped": "現在 {id} を提供しているプロバイダはないため、スキップされます",
"No routing group {id} now; it is skipped": "現在ルーティンググループ {id} はないため、スキップされます",
"Up": "上へ",
"Down": "下へ",
"switched off": "オフ",
"Move {name}": "{name} を移動",
"Enter adds {id}": "Enter で {id} を追加",
"No model matches": "一致するモデルはありません",
"No model or routing group matches": "一致するモデルやルーティンググループはありません",
"When {name} is out of quota, rate limited or down, a request goes to these instead, top first. It only happens before any of the reply is sent, and {name} then sits out a minute.": "{name} のクォータ切れ、レート制限、ダウン時には、リクエストは代わりにこれらへ上から順に送られます。応答が送られ始める前にのみ切り替わり、その後 {name} は 1 分間休止します。",
"{agent} and the gateway use the one in use. Sessions already running keep theirs until restarted.": "{agent} とゲートウェイは使用中のアカウントを使います。実行中のセッションは再起動するまで元のアカウントのままです。",
"The gateway uses the first. Tick more and it moves on to the next when the one before it is out of quota. {agent} itself stays signed in as it is.": "ゲートウェイは最初のアカウントを使います。複数にチェックを入れると、前のアカウントのクォータが切れたときに次へ移ります。{agent} 自身のサインインはそのままです。",
@@ -13677,14 +13680,15 @@ const I18N = {
"e.g. 500k · or deepseek-v4-flash=272k, comma separated": "z. B. 500k · oder deepseek-v4-flash=272k, durch Kommas getrennt",
"Where Codex, Claude Code and Grok Build compact a long conversation on these models; empty follows Long conversations, in their settings on the Agents page (else in Settings), and a size at or above a model's window runs it to its whole window": "Wo Codex, Claude Code und Grok Build eine lange Unterhaltung bei diesen Modellen komprimieren; leer folgt Lange Unterhaltungen in ihren Einstellungen auf der Seite Agenten (sonst unter Einstellungen), ein Wert ab dem Fenster des Modells nutzt das ganze Fenster",
"Compact at: {v} is not a number of tokens like 272k": "Komprimieren ab: {v} ist keine Token-Zahl wie 272k",
"add a model: filter, or type provider/model…": "Modell hinzufügen: filtern oder provider/model eingeben…",
"add a model or routing group: filter, or type provider/model…": "Modell oder Weiterleitungsgruppe hinzufügen: filtern oder provider/model eingeben…",
"No provider serves {id} now; it is skipped": "Derzeit stellt kein Anbieter {id} bereit; es wird übersprungen",
"No routing group {id} now; it is skipped": "Derzeit gibt es keine Weiterleitungsgruppe {id}; sie wird übersprungen",
"Up": "Nach oben",
"Down": "Nach unten",
"switched off": "ausgeschaltet",
"Move {name}": "{name} verschieben",
"Enter adds {id}": "Enter fügt {id} hinzu",
"No model matches": "Kein Modell passt",
"No model or routing group matches": "Kein Modell und keine Weiterleitungsgruppe passt",
"When {name} is out of quota, rate limited or down, a request goes to these instead, top first. It only happens before any of the reply is sent, and {name} then sits out a minute.": "Hat {name} kein Kontingent mehr, wird gedrosselt oder fällt aus, geht eine Anfrage stattdessen an diese, von oben nach unten. Das geschieht nur, bevor ein Teil der Antwort gesendet wurde, und {name} pausiert dann eine Minute.",
"{agent} and the gateway use the one in use. Sessions already running keep theirs until restarted.": "{agent} und der Zugangspunkt verwenden das Konto „In Verwendung“. Laufende Sitzungen behalten ihres bis zum Neustart.",
"The gateway uses the first. Tick more and it moves on to the next when the one before it is out of quota. {agent} itself stays signed in as it is.": "Der Zugangspunkt verwendet das erste. Haken Sie weitere an, wechselt er zum nächsten, sobald das vorherige kein Kontingent mehr hat. {agent} selbst bleibt angemeldet wie bisher.",
File diff suppressed because one or more lines are too long
+103
View File
@@ -0,0 +1,103 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A provider's Fallback can be a routing group, not only a model (01huadalang
// on Discord: "备用模型增加路由组的选择,现在只能选模型"). The picker lists
// the groups beside the models, each with the Routing fan and the words
// "routing group"; a group picked is a row with the same tell, and Save sends
// "group/<id>". A group that is gone says it is skipped. In English and
// Chinese; every new string has its zh, zh-TW, ja and de.
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 base = { chat: "", responses: "", anthropic: "", catalog: "", agents: [], fallback: [], headers: {}, keyList: [], key: { set: true }, ready: true };
const acme = { ...base, id: "acme", name: "Acme", icon: "generic", models: [{ id: "a1", name: "A1", on: true }], fallback: ["group/gone"] };
const wb = { ...base, id: "wb", name: "WorkBuddy", icon: "generic", models: [{ id: "m1", name: "WB Model 1", on: true }] };
const backup = { id: "group/backup", name: "Backup Lane", icons: ["generic"], providers: ["WorkBuddy"], members: ["wb/m1"], efforts: [] };
function serve(lang, posts) {
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
const providers = { providers: [acme, wb], presets: [], excluded: [], gateway: { running: true, window: true, groups: [backup] } };
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:"${lang}",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/providers") return json(providers);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (route.request().method() === "POST" && url.pathname.startsWith("/api/provider")) {
posts.push({ path: url.pathname, body: route.request().postDataJSON() });
return json(providers);
}
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 words = {
en: { tell: "routing group", gone: "No routing group group/gone now; it is skipped", none: "No model or routing group matches", save: "Save" },
zh: { tell: "路由组", gone: "现在没有路由组 group/gone,会跳过它", none: "没有匹配的模型或路由组", save: "保存" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
test(`${engine} ${lang}: a routing group can be picked as a fallback`, 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: 900, height: 760 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
const errors = [], posts = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, posts));
await page.goto("http://magpie.test/?view=providers");
const W = words[lang];
const missing = await page.evaluate(() => {
const keys = ["add a model or routing group: filter, or type provider/model…", "No routing group {id} now; it is skipped", "No model or routing group matches", "routing group"];
return ["zh", "zh-TW", "ja", "de"].flatMap((l) => keys.filter((k) => !I18N[l]?.[k]).map((k) => l + ": " + k));
});
assert.deepEqual(missing, [], "every new string in every language");
await page.locator(".row.provider", { hasText: "Acme" }).first().click();
{ const adv = page.locator(".editor details.advanced"); await adv.waitFor({ state: "attached" }); if (!(await adv.evaluate((d) => d.open))) await adv.locator(":scope > summary").click(); }
const box = page.locator(".editor .fallback");
// a group that is gone: its fan, its id, the tell, and why it is skipped
const gone = box.locator(".fbrow").first();
assert.equal(await gone.getAttribute("title"), W.gone);
assert.equal((await gone.locator(".mtell").textContent()).trim(), W.tell);
assert.equal(await gone.locator(":scope > svg").count(), 1, "the group's fan, not a provider icon");
// the picker lists the group beside the models, with its fan and tell
await box.locator("input").focus();
const chip = box.locator(".mchips .mchip", { hasText: "Backup Lane" });
await chip.waitFor();
assert.equal(await chip.getAttribute("title"), "group/backup");
assert.equal((await chip.locator(".mtell").textContent()).trim(), W.tell);
assert.equal(await chip.locator("svg").count(), 1);
assert.equal(await box.locator(".mchips .mchip", { hasText: "WB Model 1" }).count(), 1, "the models are still there");
assert.equal(await box.locator("select").count(), 0, "never a native select");
// a filter finds a group by its member providers too, and says when nothing matches
await box.locator("input").fill("workbuddy");
assert.equal(await chip.count(), 1);
await box.locator("input").fill("zzz");
assert.equal((await box.locator(".mchips .hint").textContent()).trim(), W.none);
await box.locator("input").fill("");
await box.locator("input").focus();
await chip.click();
const row = box.locator(".fbrow").nth(1);
assert.equal((await row.locator(".n").textContent()).trim(), "Backup Lane");
assert.equal((await row.locator(".mtell").textContent()).trim(), W.tell);
assert.equal(await row.getAttribute("title"), null);
// no coloured left-border accent on a group row
assert.equal(await row.evaluate((e) => getComputedStyle(e).borderLeftWidth), "0px");
const sent = page.waitForRequest((r) => r.method() === "POST" && new URL(r.url()).pathname.startsWith("/api/provider"));
await page.getByRole("button", { name: W.save, exact: true }).click();
await sent;
assert.deepEqual(posts.at(-1).body.fallback, ["group/gone", "group/backup"]);
assert.deepEqual(errors, []);
});
}
}
+40
View File
@@ -784,6 +784,46 @@ func FindGroup(id string) (Group, []Member, bool) {
return GroupFinder()(id)
}
// FallbackGroup is the routing group a provider's fallback entry names
// ("group/<id>", 01huadalang on Discord), as the gateway routes it (Live),
// with its members ready now. ok is false for an entry naming a model,
// and for a group removed or switched off: such an entry is passed over.
func FallbackGroup(id string) (Group, []Member, bool) {
if _, ok := GroupIDOf(id); !ok {
return Group{}, nil, false
}
g, ms, ok := FindGroup(id)
return g.Live(), ms, ok
}
// FallbackModels are the models p's fallbacks reach, in order: an entry
// naming a model, that model as routing reaches it (ResolveRoute); one
// naming a routing group, the group's members. An entry that reaches
// nothing is left out, as the gateway passes it over, and a model met
// again is listed where it was met first.
func FallbackModels(p Provider) []Member {
var out []Member
seen := map[string]bool{}
add := func(m Member) {
if k := m.Provider.ID + "/" + m.Model; !seen[k] {
seen[k] = true
out = append(out, m)
}
}
for _, id := range p.Fallback {
if _, ms, ok := FallbackGroup(id); ok {
for _, m := range ms {
add(m)
}
continue
}
if fp, fm, ok := ResolveRoute(id); ok {
add(Member{ID: id, Path: []string{id}, Provider: fp, Model: fm})
}
}
return out
}
// GroupFor is the group a model's id without a provider in it names, as
// "group/<id>": the group of that id, else the group of that model however
// a vendor spells it ("grok-4.7" is the group grok-4-7 or auto-grok-4-7).