From 3c9d79d28234ee233657a0bd316eef1306065c8b Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 20 Nov 2026 15:00:00 +0800 Subject: [PATCH] gateway: a key can set how the routing groups it asks for route (justforlxz on X) justforlxz asked on X for a routing strategy among a gateway key's options. A key now has Routing: unset follows each group's own (the default), "smart" is the default Quota first, or any built-in routing (order, drain, rotate, usage, pace, weight, free, fast, cheap, expiring, fit) or a plugin's /. Manual is refused, and a Manual group still goes to its pick. A provider or nested group with its own routing keeps it (#576), as under the group's own. - access: Key.Routing, Identity.Routing, the routing-key action (CleanRouting). An issued key that sets none follows its issuer's. - provider: GroupRouting is the list of routings a group takes. SaveGroup and CleanRouting both use it. - gateway: keyRouted is applied wherever a request's group is resolved: handle (Chat, Messages, Responses, and the masked-route move), embeddings/rerank, draw, video, a System One decision group and relayed search. count_tokens plans no group. planned carries the routing the plan was made by, so leastHeld weighs members the same way and the trace's group shows it. - CLI: magpie gateway-key routing [follow|smart|...]. - GUI: a "Group routing" badge on the key row, hidden until hover like the tier and masking badges, opens the app's menu (openProtoMenu). The routings the rotation plugin serves are left out when it is off. zh, zh-TW, ja and de strings are included. - docs/subsystems/gateway-routing.md: the paragraph after ServiceTier. Run (at cf5840a37 rebased on eb1da1572): - gofmt -l: clean. On mote: go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., and go build for darwin, linux (nogui) and windows: all ok. - On mote, go test -count=1 -timeout 45m for internal/access, cli, provider, gui and gateway: access, cli and provider ok. internal/gui red only on TestBuiltinsTranslated (#7257) and TestSettingsSaveKeepsWhatItDoesNotSend (#7240), both red on main. internal/gateway red only on TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes (#7117, red on main). A doneHold "close of closed channel" panic was logged by the HTTP server (#6690). - On mica, the GUI files gateway-key-*, gateway-keys-*, gateway-caller-keys, i18n-keys, i18n-en-no-cjk and key-row-chips-fit in Chromium and WebKit, 5 languages, 1100/420 widths: 549 of 550 pass. The one red is gateway-key-account-groups (rename typed as "DayDaytime"). It is red alone 2 of 3 on origin/main eb1da1572 too, filed as #7316. - Red on the old code, broken by hand: TestKeyGroupRouting fails on Chat, Messages and Responses with keyRouted made a no-op (the Free first key goes to the paid member first). TestKeyRouting, TestGatewayKeyRoutingCLI and gateway-key-routing.test.cjs don't build or find their field, action or badge on the old code. - TestKeyGroupRouting's Manual case stays green with keyRouted's Manual guard removed, because a Manual group is sent to its pick before routing. The guard is held by TestKeyRoutedCases. - Rebased on 6635dec7c (it changes i18n.js and the core budget). At this head on mote: internal/gui -run Budget|I18n|Strings|Keys ok, the access/cli Routing tests ok, and gateway-key-routing, gateway-key-tier, i18n-keys and i18n-en-no-cjk in both engines: 48 of 48 pass. Not run or tried: the full go test ./... and the whole GUI suite (both mote and mica were running other sessions' GUI suites, at load 27/18 and 70/12). Windows and Linux test runs. A real gateway with a real key and real accounts. --- docs/subsystems/gateway-routing.md | 20 ++++ internal/access/access.go | 50 +++++++- internal/access/issue.go | 5 +- internal/access/routing_test.go | 55 +++++++++ internal/cli/gateway_keys_cli.go | 37 +++++- internal/cli/gateway_keys_cli_test.go | 39 +++++++ internal/gateway/affinity.go | 7 +- internal/gateway/codex_search.go | 3 +- internal/gateway/decide_group.go | 3 +- internal/gateway/draw.go | 3 +- internal/gateway/embeddings.go | 3 +- internal/gateway/fallback.go | 2 +- internal/gateway/gateway.go | 4 +- internal/gateway/key_routing.go | 23 ++++ internal/gateway/key_routing_test.go | 108 ++++++++++++++++++ internal/gateway/trace.go | 4 + internal/gateway/video.go | 3 +- internal/gui/admin.go | 2 +- internal/gui/assets/app.css | 10 +- internal/gui/assets/i18n.js | 20 ++++ internal/gui/assets/plugins/gateway/keys.js | 38 +++++- internal/gui/tests/fixtures/caller-keys.cjs | 1 + .../gui/tests/gateway-key-routing.test.cjs | 72 ++++++++++++ internal/provider/group.go | 2 +- internal/provider/routing.go | 10 ++ 25 files changed, 504 insertions(+), 20 deletions(-) create mode 100644 internal/access/routing_test.go create mode 100644 internal/gateway/key_routing.go create mode 100644 internal/gateway/key_routing_test.go create mode 100644 internal/gui/tests/gateway-key-routing.test.cjs diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index d3d08572c..47bf0d21c 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -991,6 +991,26 @@ that honours no service tier is sent none, and Anthropic-protocol requests `TestKeyTieredChat`, `TestKeyServiceTier` in `internal/access`, `TestGatewayKeyTierCLI`, `gateway-key-tier.test.cjs`. +A key's `Routing` (justforlxz on X; `access.Key`, set by the `routing-key` +action, the key row's routing badge or `magpie gateway-key routing +follow|smart|order|drain|rotate|usage|pace|weight|free|fast|cheap|expiring|fit|/`; stored as +"", "smart", a built-in routing or a plugin's) is how a routing group its +requests ask for picks among its members' keys and accounts: the group is +planned with that routing in place of its own (`keyRouted` in +`key_routing.go`, applied where the request's group is resolved: `handle` for +Chat, Messages and Responses, the masked-route move there too, embeddings +and rerank, drawing, video, a System One group and a relayed search's +order). Unset follows the group. A Manual group still sends to its pick, and +a group in the group or a provider in it routed its own way keeps its own +routing (#576), as under the group's own; a member left on the default is +weighed with the key's routing, as with the group's. The plan carries the +routing it was made by (`planned.routing`), so `leastHeld` judges the +members the same way, and the trace's group shows it. count_tokens plans no +group, so it is untouched. An issued key that sets none follows its +issuer's (`Identity.Routing`). Tests: `TestKeyGroupRouting`, +`TestKeyRouting` in `internal/access`, `TestGatewayKeyRoutingCLI`, +`gateway-key-routing.test.cjs`. + A key's `Redact` (y0ngb1n on X; `access.Key`, set by the `redact-key` action, the key row's masking badge or `magpie gateway-key redact follow|on|off`; stored as "", "on" or "off") decides whether Settings › diff --git a/internal/access/access.go b/internal/access/access.go index 887c7c554..9c39e4673 100644 --- a/internal/access/access.go +++ b/internal/access/access.go @@ -217,6 +217,42 @@ type Key struct { // are, for a device the user trusts. A request with no key (this // computer's own) always follows the setting. Redact string `json:"redact,omitempty"` + // Routing is how a routing group the key asks for picks among its + // members' accounts and keys for the key's requests (justforlxz on + // X): RoutingSmart, one of provider's group routings but Manual, or a + // plugin's + // "/"; "" follows the group's own. A manual group + // still sends to its pick, and a group in the group, or a provider + // routed its own way in it, keeps its own routing, as always. + Routing string `json:"routing,omitempty"` +} + +// RoutingSmart is a key's Routing for Smart: a group's own routing "" +// is Smart, and a key's "" follows the group. +const RoutingSmart = "smart" + +// keyRoutings are the built-in routings a key can set, besides Smart. +var keyRoutings = []string{provider.Ordered, provider.Drain, provider.Rotate, provider.LeastUsed, provider.Pace, provider.Weighted, provider.FreeFirst, provider.Fastest, provider.Cheapest, provider.FreeExpiring, provider.SmallFirst} + +// CleanRouting is a key's group routing as it is kept: "" to follow the +// group, RoutingSmart, a built-in routing or a plugin's. +func CleanRouting(v string) (string, error) { + r := strings.TrimSpace(v) + switch strings.ToLower(r) { + case "", "follow", "group", "default": + return "", nil + case RoutingSmart: + return RoutingSmart, nil + case provider.Manual: // a group's own pick: a key has none to send to + default: + if l := strings.ToLower(r); provider.GroupRouting(l) { + return l, nil + } + if provider.PluginRouting(r) { + return r, nil + } + } + return "", fmt.Errorf("Routing: follow, smart, one of %s or a plugin's /, not %q", strings.Join(keyRoutings, ", "), v) } // A key's Redact. @@ -308,6 +344,9 @@ type Identity struct { ServiceTier string // Redact is Key.Redact; an issued key is held on by its issuer's on. Redact string + // Routing is Key.Routing; an issued key that sets none follows its + // issuer's. + Routing string // Default: the key is the sharing key magpie made itself (Default), // the one it writes into this computer's own agents that reach the // gateway from beyond loopback, never one the user made for someone @@ -526,6 +565,9 @@ type Change struct { ServiceTier string `json:"serviceTier,omitempty"` // Redact is what "redact-key" sets (Key.Redact): "", "on" or "off". Redact string `json:"redact,omitempty"` + // Routing is what "routing-key" sets (Key.Routing), "" to follow the + // group's own. + Routing string `json:"routing,omitempty"` // Secret is the value "add-key" gives the new key, one its clients // already send (love1sbug on X: keys handed out from another gateway), // or "rotate-key" gives the key; "" for one magpie makes. @@ -708,6 +750,12 @@ func Update(action string, in Change) (string, error) { return "", err } keys[i].ServiceTier = tier + case "routing-key": + routing, err := CleanRouting(in.Routing) + if err != nil { + return "", err + } + keys[i].Routing = routing case "redact-key": mode, err := CleanRedact(in.Redact) if err != nil { @@ -796,7 +844,7 @@ func Update(action string, in Change) (string, error) { default: return "", fmt.Errorf("unknown key action %q", action) } - if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "aliases-key" && action != "accounts-key" && action != "mcp-key" && action != "quotas-key" && action != "concurrency-key" && action != "tier-key" && action != "redact-key" && action != "access-key" && action != "issuer-key" && action != "admin-key" && action != "memory-key" && action != "move-key" { + if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "aliases-key" && action != "accounts-key" && action != "mcp-key" && action != "quotas-key" && action != "concurrency-key" && action != "tier-key" && action != "routing-key" && action != "redact-key" && action != "access-key" && action != "issuer-key" && action != "admin-key" && action != "memory-key" && action != "move-key" { mirror = &keys[i] } } diff --git a/internal/access/issue.go b/internal/access/issue.go index 9c8d35d33..f74ecfb76 100644 --- a/internal/access/issue.go +++ b/internal/access/issue.go @@ -353,7 +353,7 @@ func identityOf(k Key, keys []Key, now time.Time) (Identity, error) { return Identity{}, &Refused{Why: fmt.Sprintf("the gateway key %q names an account group, and magpie can't read its account groups now: %v", k.Name, err)} } k.Accounts = accounts - who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), Aliases: k.Aliases, AccountModels: len(k.Models) == 0 && picksAccounts(k.Accounts), Accounts: k.Accounts, MCP: k.MCP, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Browser: k.Browser, Admin: adminOf(k), Memory: memoryOf(k), Expires: k.Expires, Issues: k.Issues && k.Issuer == "" && !k.Browser, MaxConcurrency: k.MaxConcurrency, ServiceTier: k.ServiceTier, Redact: k.Redact} + who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), Aliases: k.Aliases, AccountModels: len(k.Models) == 0 && picksAccounts(k.Accounts), Accounts: k.Accounts, MCP: k.MCP, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Browser: k.Browser, Admin: adminOf(k), Memory: memoryOf(k), Expires: k.Expires, Issues: k.Issues && k.Issuer == "" && !k.Browser, MaxConcurrency: k.MaxConcurrency, ServiceTier: k.ServiceTier, Redact: k.Redact, Routing: k.Routing} // the default key as Default tells it: marked LAN, or the id the // settings name (settings read only for an unmarked key) who.Default = k.LAN || (k.ID != "" && settings.Shared().LANKeyID == k.ID) @@ -386,6 +386,9 @@ func identityOf(k Key, keys []Key, now time.Time) (Identity, error) { if p.Redact == RedactOn { who.Redact = RedactOn } + if who.Routing == "" { + who.Routing = p.Routing + } if !p.Expires.IsZero() && (who.Expires.IsZero() || p.Expires.Before(who.Expires)) { who.Expires = p.Expires } diff --git a/internal/access/routing_test.go b/internal/access/routing_test.go new file mode 100644 index 000000000..eb63e4536 --- /dev/null +++ b/internal/access/routing_test.go @@ -0,0 +1,55 @@ +package access + +import ( + "testing" + "time" +) + +// justforlxz on X: a gateway key can set how the routing groups it asks +// for route its requests. routing-key sets it, Authenticate tells it, +// "follow" takes it off, and Manual (a group's own pick) or a word it +// doesn't know is refused with the key left as it was. A key issued under +// it that sets none follows its issuer's, and one that sets its own keeps +// it. +func TestKeyRouting(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + clockAt(t, time.Date(2026, 11, 20, 9, 0, 0, 0, time.UTC)) + id, secret := addKey(t, "Team") + if who, _ := Authenticate(secret); who.Routing != "" { + t.Fatal("a new key has a routing:", who.Routing) + } + for in, want := range map[string]string{"rotate": "rotate", "Usage": "usage", "smart": "smart", "free": "free", "fit": "fit", "drain": "drain", "acme/sticky": "acme/sticky", "follow": "", "": ""} { + if _, err := Update("routing-key", Change{Key: id, Routing: in}); err != nil { + t.Fatal(in, err) + } + if who, ok := Authenticate(secret); !ok || who.Routing != want { + t.Fatalf("%q: routing %q, want %q", in, who.Routing, want) + } + } + Update("routing-key", Change{Key: id, Routing: "rotate"}) + for _, bad := range []string{"manual", "sideways", "a/b/c"} { + if _, err := Update("routing-key", Change{Key: id, Routing: bad}); err == nil { + t.Fatalf("%q was taken", bad) + } + } + if who, _ := Authenticate(secret); who.Routing != "rotate" { + t.Fatal("a refused word changed the key:", who.Routing) + } + + if _, err := Update("issuer-key", Change{Key: id, Issues: true}); err != nil { + t.Fatal(err) + } + child, err := IssueKey(Issue{TTL: time.Hour, Issuer: id}) + if err != nil { + t.Fatal(err) + } + if who, _ := Authenticate(child.Key); who.Routing != "rotate" { + t.Fatal("issued, setting none, doesn't follow its issuer:", who.Routing) + } + if _, err := Update("routing-key", Change{Key: child.ID, Routing: "order"}); err != nil { + t.Fatal(err) + } + if who, _ := Authenticate(child.Key); who.Routing != "order" { + t.Fatal("issued, its own lost to its issuer's:", who.Routing) + } +} diff --git a/internal/cli/gateway_keys_cli.go b/internal/cli/gateway_keys_cli.go index 74b982078..2bddfcf09 100644 --- a/internal/cli/gateway_keys_cli.go +++ b/internal/cli/gateway_keys_cli.go @@ -1,6 +1,7 @@ package cli import ( + "cmp" "encoding/json" "fmt" "io" @@ -58,6 +59,10 @@ func gatewayKeysTo(out io.Writer, args []string) error { access.MigrateLegacyLANKeyBestEffort() return gatewayKeyTier(out, args[1:]) } + if action == "routing" { + access.MigrateLegacyLANKeyBestEffort() + return gatewayKeyRouting(out, args[1:]) + } if action == "redact" || action == "masking" { access.MigrateLegacyLANKeyBestEffort() return gatewayKeyRedact(out, args[1:]) @@ -123,7 +128,7 @@ func gatewayKeysTo(out io.Writer, args []string) error { args = args[:2] } if (action == "list" && len(args) != 1) || (action != "list" && len(args) != 2) { - return fmt.Errorf("usage: magpie gateway-key list | add [--key | --key -] [--read-only] | rotate [--key | --key -] | remove | limit [list | off | reset [] | remove | [add] day|week|month|total|d|h|account [--account / --window ] [--tokens N] [--cost USD] [--cache-reads] [--model /|/* ...]] | models [all | /|/*|re: ...] | aliases [none | =/ ...] | accounts [all | /|/ ...] | quotas [on | off] | concurrency [ | off] | tier [follow | standard | fast | ultrafast] | redact [follow | on | off] | mcp [all | none | |/ ...] | access [read-only | full] | move | issue --ttl [--name ] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from ] | issuer [on | off] | oidc [list | add --key --repo owner/name … | remove ]") + return fmt.Errorf("usage: magpie gateway-key list | add [--key | --key -] [--read-only] | rotate [--key | --key -] | remove | limit [list | off | reset [] | remove | [add] day|week|month|total|d|h|account [--account / --window ] [--tokens N] [--cost USD] [--cache-reads] [--model /|/* ...]] | models [all | /|/*|re: ...] | aliases [none | =/ ...] | accounts [all | /|/ ...] | quotas [on | off] | concurrency [ | off] | tier [follow | standard | fast | ultrafast] | routing [follow | smart | order | drain | rotate | usage | pace | weight | free | fast | cheap | expiring | fit | /] | redact [follow | on | off] | mcp [all | none | |/ ...] | access [read-only | full] | move | issue --ttl [--name ] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from ] | issuer [on | off] | oidc [list | add --key --repo owner/name … | remove ]") } switch action { case "list", "add", "rotate", "remove": @@ -905,6 +910,36 @@ func gatewayKeyTier(out io.Writer, args []string) error { return err } +// gatewayKeyRouting shows or sets how a routing group a key's requests +// ask for picks its members' accounts and keys for them (access.Key.Routing, +// justforlxz on X): +// +// magpie gateway-key routing its routing +// magpie gateway-key routing follow|smart|order|drain|rotate|usage|pace|weight|free|fast|cheap|expiring|fit|/ +func gatewayKeyRouting(out io.Writer, args []string) error { + if len(args) == 0 || len(args) > 2 { + return fmt.Errorf("usage: magpie gateway-key routing [follow | smart | order | drain | rotate | usage | pace | weight | free | fast | cheap | expiring | fit | /]") + } + id := args[0] + if len(args) == 2 { + if _, err := access.Update("routing-key", access.Change{Key: id, Routing: args[1]}); err != nil { + return err + } + } + keys, err := access.List() + if err != nil { + return err + } + i := slices.IndexFunc(keys, func(k access.Key) bool { return k.ID == id }) + if i < 0 { + return fmt.Errorf("Key not found") + } + k := keys[i] + word := cmp.Or(map[string]string{"": "follows each routing group's own", access.RoutingSmart: "smart"}[k.Routing], k.Routing) + _, err = fmt.Fprintf(out, "%s: group routing %s\n", k.Name, word) + return err +} + // gatewayKeyRedact shows or sets whether Settings › Privacy's masking // applies to a key's requests (access.Key.Redact, y0ngb1n on X): // diff --git a/internal/cli/gateway_keys_cli_test.go b/internal/cli/gateway_keys_cli_test.go index b948b7d2c..db847dbd9 100644 --- a/internal/cli/gateway_keys_cli_test.go +++ b/internal/cli/gateway_keys_cli_test.go @@ -817,3 +817,42 @@ func TestGatewayKeyRedactCLI(t *testing.T) { t.Fatalf("a refused call changed it: %q", keys[0].Redact) } } + +// justforlxz on X: `gateway-key routing [follow|smart|order|…]` shows +// or sets how the routing groups a key asks for route its requests. +func TestGatewayKeyRoutingCLI(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", os.Getenv("HOME")) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + if err := settings.Save(settings.Settings{LAN: true}); err != nil { + t.Fatal(err) + } + call := func(args ...string) (string, error) { + var out bytes.Buffer + err := gatewayKeysTo(&out, append([]string{"gateway-key"}, args...)) + return out.String(), err + } + if _, err := call("add", "Team"); err != nil { + t.Fatal(err) + } + keys, _ := access.List() + id := keys[0].ID + for _, c := range [][2]string{{"", "follows each routing group's own"}, {"rotate", "rotate"}, {"smart", "smart"}, {"usage", "usage"}, {"follow", "follows each routing group's own"}} { + args := []string{"routing", id} + if c[0] != "" { + args = append(args, c[0]) + } + if got, err := call(args...); err != nil || got != "Team: group routing "+c[1]+"\n" { + t.Fatalf("%v: %q %v", args, got, err) + } + } + call("routing", id, "rotate") + for _, args := range [][]string{{"routing"}, {"routing", id, "manual"}, {"routing", id, "--help"}, {"routing", id, "rotate", "x"}, {"routing", "missing", "rotate"}, {"routing", "missing"}} { + if _, err := call(args...); err == nil { + t.Error("accepted", args) + } + } + if keys, _ = access.List(); keys[0].Routing != "rotate" { + t.Fatalf("a refused call changed it: %q", keys[0].Routing) + } +} diff --git a/internal/gateway/affinity.go b/internal/gateway/affinity.go index 96dae7477..d7c1fae70 100644 --- a/internal/gateway/affinity.go +++ b/internal/gateway/affinity.go @@ -492,7 +492,7 @@ func strictKeep(scope, mode string, in http.Header, body []byte, cs []candidate, } if len(back) > 0 { pl.capped = slices.DeleteFunc(slices.Clone(pl.capped), func(c candidate) bool { return c.sameVendor(st.who, st.model) }) - return append(back, cs...), planned{order: append(order, pl.order...), left: pl.left, held: pl.held, capped: pl.capped}, nil + return append(back, cs...), planned{order: append(order, pl.order...), left: pl.left, held: pl.held, capped: pl.capped, routing: pl.routing, grouped: pl.grouped}, nil } var held []Weighed for _, c := range pl.held { @@ -506,7 +506,7 @@ func strictKeep(scope, mode string, in http.Header, body []byte, cs []candidate, if len(held) > 0 { // only its own reset, should it spend one by itself, brings it back pl.held = slices.DeleteFunc(slices.Clone(pl.held), func(c candidate) bool { return !c.sameVendor(st.who, st.model) }) - return nil, planned{order: nil, left: pl.left, held: pl.held, capped: pl.capped}, held[:1] + return nil, planned{order: nil, left: pl.left, held: pl.held, capped: pl.capped, routing: pl.routing, grouped: pl.grouped}, held[:1] } return cs, pl, nil } @@ -858,6 +858,9 @@ func leastHeld(scope, key string, cs []candidate, pl planned, ready bool) ([]can } if strings.HasPrefix(scope, provider.GroupPrefix) { if g, ms, ok := provider.FindGroup(scope); ok { + if pl.grouped { // as it was planned: by the calling key's routing, it may be + g.Routing = pl.routing + } for _, m := range ms { // a group in the group, or a provider routed its own way: // its own routing orders its models or keys (#576) diff --git a/internal/gateway/codex_search.go b/internal/gateway/codex_search.go index 3b3772755..1a56b3f53 100644 --- a/internal/gateway/codex_search.go +++ b/internal/gateway/codex_search.go @@ -12,6 +12,7 @@ import ( "strings" "time" + "github.com/yetone/magpie/internal/access" "github.com/yetone/magpie/internal/provider" ) @@ -140,7 +141,7 @@ func (s *Server) relaySearchers(r *http.Request, model string) []searchTarget { keep := groupKeeps(who, g, ms) ms = slices.DeleteFunc(slices.Clone(ms), func(m provider.Member) bool { return !keep[m.Provider.ID+"/"+m.Model] }) } - cs, _ = s.planGroup(g.Live(), ms, provider.Responses) + cs, _ = s.planGroup(keyRouted(access.Caller(r.Context()), g.Live()), ms, provider.Responses) } else { p, bare, ok := provider.Resolve(model) if !ok || keyHeld && !modelAllowed(who, p, bare) { diff --git a/internal/gateway/decide_group.go b/internal/gateway/decide_group.go index 0aee50f5b..d57cf5f4e 100644 --- a/internal/gateway/decide_group.go +++ b/internal/gateway/decide_group.go @@ -90,7 +90,8 @@ func (s *Server) serveDecisionGroup(w http.ResponseWriter, r *http.Request, body if refuseOff(w, provider.Chat, asked) { // every model of it disabled (#1867) return } - g = g.Live() + // routed as the calling key says, where it says (justforlxz on X) + g = keyRouted(access.Caller(r.Context()), g.Live()) r = heldByGroup(r, g) // held to the group's accounts, if it is keyWho, keyHeld := keyHolds(r) accWho, accHeld := accountHolds(r) diff --git a/internal/gateway/draw.go b/internal/gateway/draw.go index ecdecc3ca..0f56d887a 100644 --- a/internal/gateway/draw.go +++ b/internal/gateway/draw.go @@ -21,6 +21,7 @@ import ( "sync" "time" + "github.com/yetone/magpie/internal/access" "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/settings" @@ -781,7 +782,7 @@ func (s *Server) images(edit bool) http.HandlerFunc { if keyHeld { keeps = groupKeeps(keyWho, g, ms) } - t := s.drawingTries(g, ms, keeps, drawsModel) + t := s.drawingTries(keyRouted(access.Caller(r.Context()), g), ms, keeps, drawsModel) if len(t) == 0 && keeps != nil { fail(keyGroupRefusal(w, keyWho, d.Model, ms)) return diff --git a/internal/gateway/embeddings.go b/internal/gateway/embeddings.go index 3fea7c1ee..602ad3be4 100644 --- a/internal/gateway/embeddings.go +++ b/internal/gateway/embeddings.go @@ -12,6 +12,7 @@ import ( "strings" "time" + "github.com/yetone/magpie/internal/access" "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/usage" ) @@ -161,7 +162,7 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op // (429) or one whose vendor fails; a model is asked on its own tries := []candidate{{p: p, model: model}} if isGroup { - cs, pl := s.planGroup(g.Live(), ms, provider.Chat) + cs, pl := s.planGroup(keyRouted(access.Caller(r.Context()), g.Live()), ms, provider.Chat) if len(cs) > 0 { tries = cs } else if slices.ContainsFunc(pl.left, func(w Weighed) bool { return w.HeldBy != "" }) { diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index 9c33a4ac2..ec6f29f4f 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -699,7 +699,7 @@ func planFallbackGroup(g provider.Group, ms []provider.Member, from provider.Pro // too, within its own order (#2255), before g's Sink orders the whole. // A member's fallbacks are not the group's. func (s *Server) planGroup(g provider.Group, ms []provider.Member, from provider.Protocol) ([]candidate, planned) { - var pl planned + pl := planned{routing: g.Routing, grouped: true} var asides []candidate var wAsides []Weighed out := planLevel(g, ms, 0, from, &pl, &asides, &wAsides, nil) diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index f1d49a76f..fad8ff3a6 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -2947,6 +2947,8 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // before any image is taken out of the request: one may be for images g, ms, isGroup := provider.FindGroup(asked) g = g.Live() // a manual group's rules wait + // routed as the calling key says, where it says (justforlxz on X) + g = keyRouted(access.Caller(r.Context()), g) // a model on this machine or the local network that the user set to // go unmasked gets the request as written (lc on Discord), and it // isn't masked on its way, the request archive on or not: the archive @@ -2976,7 +2978,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro log.Printf("gateway: %d value(s) masking would change, sent as written to %s (Settings › Privacy)", hits.n, to) p, model, _ = provider.Resolve(to) g, ms, isGroup = provider.FindGroup(to) - g = g.Live() + g = keyRouted(access.Caller(r.Context()), g.Live()) sentWhole = true move(to, movedPrivacy) } else { diff --git a/internal/gateway/key_routing.go b/internal/gateway/key_routing.go new file mode 100644 index 000000000..c4cac414a --- /dev/null +++ b/internal/gateway/key_routing.go @@ -0,0 +1,23 @@ +package gateway + +import ( + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/provider" +) + +// keyRouted is g as a request with who's gateway key routes it: by the +// key's own routing (access.Key.Routing, justforlxz on X) when it sets +// one, else by the group's. A manual group sends to the member picked on +// its card whatever the key says, and a group in g, or a provider in it +// routed its own way, keeps its own routing as it always does (planLevel): +// the key's routing, as the group's, picks between them. +func keyRouted(who access.Identity, g provider.Group) provider.Group { + switch { + case who.Routing == "" || g.Routing == provider.Manual: + case who.Routing == access.RoutingSmart: + g.Routing = "" + default: + g.Routing = who.Routing + } + return g +} diff --git a/internal/gateway/key_routing_test.go b/internal/gateway/key_routing_test.go new file mode 100644 index 000000000..d172e96a2 --- /dev/null +++ b/internal/gateway/key_routing_test.go @@ -0,0 +1,108 @@ +package gateway + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/provider" +) + +// justforlxz on X: a gateway key can set how a routing group it asks for +// routes its requests. The group here is In order with the paid member +// listed first; a key set to Free first sends its requests to the free one +// first on Chat, Messages and Responses alike, while a key that sets none, +// and this computer's own request, keep the group's order. A Manual group +// still sends to its pick whatever the key says. +func TestKeyGroupRouting(t *testing.T) { + fresh(t) + vendor := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if b, _ := io.ReadAll(r.Body); strings.Contains(string(b), `"stream":true`) { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, "data: {\"id\":\"ok\",\"object\":\"chat.completion.chunk\",\"model\":\"m\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"hi\"},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":1,\"completion_tokens\":1}}\n\ndata: [DONE]\n\n") + return + } + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"id":"ok","object":"chat.completion","model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}`)) + }) + serveOn(t, "freev", "sk-free", []string{"m"}, vendor) + serveOn(t, "paidv", "sk-paid", []string{"m"}, vendor) + liveModels(t, "freev", `{"models":[{"id":"m","free":true}]}`) + liveModels(t, "paidv", `{"models":[{"id":"other"},{"id":"m"}]}`) + if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"paidv/m", "freev/m"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + keys, secrets := newCaller(t, "Free", "Plain") + if _, err := access.Update("routing-key", access.Change{Key: keys[0].ID, Routing: provider.FreeFirst}); err != nil { + t.Fatal(err) + } + s := New() + first := func(path, secret, body string) string { + t.Helper() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + if secret != "" { + req.Header.Set("Authorization", "Bearer "+secret) + req.RemoteAddr = "192.168.1.20:5000" + } else { + req.RemoteAddr = "127.0.0.1:5000" + } + n := len(s.trace.routes) + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("%s: %d %s", path, rec.Code, rec.Body.String()) + } + if len(s.trace.routes) == n { + t.Fatalf("%s: nothing routed", path) + } + last := s.trace.routes[len(s.trace.routes)-1] + if len(last.Order) == 0 { + t.Fatalf("%s: no order: %+v", path, last) + } + return last.Order[0].Provider + } + asks := map[string]string{ + "/v1/chat/completions": `{"model":"group/g","messages":[{"role":"user","content":"x"}]}`, + "/v1/messages": `{"model":"group/g","max_tokens":10,"messages":[{"role":"user","content":"x"}]}`, + "/v1/responses": `{"model":"group/g","input":"x"}`, + } + for path, body := range asks { + if got := first(path, secrets[0], body); got != "freev" { + t.Errorf("%s: the Free first key went to %s first, want freev", path, got) + } + if got := first(path, secrets[1], body); got != "paidv" { + t.Errorf("%s: a key that sets none went to %s first, want paidv (the group's order)", path, got) + } + if got := first(path, "", body); got != "paidv" { + t.Errorf("%s: this computer's own request went to %s first, want paidv", path, got) + } + } + + // Manual: the group's pick, whatever the key says + if err := provider.SaveGroup(provider.Group{ID: "g", Name: "G", Members: []string{"paidv/m", "freev/m"}, Routing: provider.Manual, Pick: "paidv/m"}); err != nil { + t.Fatal(err) + } + if got := first("/v1/chat/completions", secrets[0], asks["/v1/chat/completions"]); got != "paidv" { + t.Errorf("a Manual group went to %s for the Free first key, want its pick paidv", got) + } +} + +// keyRouted's own cases: unset follows, smart is the group's default (""), +// a Manual group keeps Manual. +func TestKeyRoutedCases(t *testing.T) { + for _, c := range []struct{ key, group, want string }{ + {"", provider.Ordered, provider.Ordered}, + {"smart", provider.Ordered, ""}, + {provider.Rotate, "", provider.Rotate}, + {provider.Rotate, provider.Manual, provider.Manual}, + {"acme/sticky", provider.LeastUsed, "acme/sticky"}, + } { + if got := keyRouted(access.Identity{Routing: c.key}, provider.Group{Routing: c.group}).Routing; got != c.want { + t.Errorf("key %q on a group %q: %q, want %q", c.key, c.group, got, c.want) + } + } +} diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index 2960c1c4b..7e7589b49 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -619,6 +619,10 @@ type planned struct { // model is, though no other can read it unlisted []candidate unlistedW []Weighed + // routing, when grouped, is the routing a group was planned by: its + // own, or the calling key's (keyRouted) + routing string + grouped bool } func weighed(c candidate, p provider.Provider, wg weighing, fallback bool, from provider.Protocol) Weighed { diff --git a/internal/gateway/video.go b/internal/gateway/video.go index 3c134a6e9..2e8c2f2af 100644 --- a/internal/gateway/video.go +++ b/internal/gateway/video.go @@ -21,6 +21,7 @@ import ( "strings" "time" + "github.com/yetone/magpie/internal/access" "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/lazyre" "github.com/yetone/magpie/internal/provider" @@ -1157,7 +1158,7 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) { if keyHeld { keeps = groupKeeps(keyWho, g, ms) } - t := s.drawingTries(g, ms, keeps, servesKind(provider.KindVideo)) + t := s.drawingTries(keyRouted(access.Caller(r.Context()), g), ms, keeps, servesKind(provider.KindVideo)) if len(t) == 0 && keeps != nil { fail(keyGroupRefusal(w, keyWho, f.Model, ms)) return diff --git a/internal/gui/admin.go b/internal/gui/admin.go index a690c87f5..d1f72aca8 100644 --- a/internal/gui/admin.go +++ b/internal/gui/admin.go @@ -85,7 +85,7 @@ var adminProviderActions = []string{ var adminKeyActions = []string{ "add-key", "rotate-key", "rename-key", "limit-key", "reset-limit-key", "models-key", "aliases-key", "accounts-key", "mcp-key", "quotas-key", - "concurrency-key", "tier-key", "redact-key", "issuer-key", "access-key", + "concurrency-key", "tier-key", "routing-key", "redact-key", "issuer-key", "access-key", "on-key", "off-key", "remove-key", "move-key", } diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 4e34be5a4..87dece9e5 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -3381,16 +3381,16 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } #gatewayKeys .amodels.key-models { display: inline-block; flex: 0 1 auto; min-width: 24px; max-width: 180px; line-height: 20px; overflow: hidden; text-overflow: ellipsis; } /* a key's quotas and concurrency badges (#2216) take no room until the row is hovered, and give way before the row runs past a narrow window */ -#gatewayKeys .amodels:is(.key-quotas, .key-conc, .key-tier, .key-redact) { display: inline-block; flex: 0 1 auto; min-width: 0; line-height: 20px; overflow: hidden; text-overflow: ellipsis; } +#gatewayKeys .amodels:is(.key-quotas, .key-conc, .key-tier, .key-routing, .key-redact) { display: inline-block; flex: 0 1 auto; min-width: 0; line-height: 20px; overflow: hidden; text-overflow: ellipsis; } /* unset, shown by a hover, they give way before the masked key does: the key squeezed by them on a narrow window slid its copy button under the pointer that came to drag the row */ -#gatewayKeys .acc > :is(.key-quotas, .key-conc, .key-tier, .key-redact):not(.set) { flex-shrink: 8; } +#gatewayKeys .acc > :is(.key-quotas, .key-conc, .key-tier, .key-routing, .key-redact):not(.set) { flex-shrink: 8; } /* On a narrow window they keep that room when not hovered, only faded out: four of them (key-redact made four) took ~90px on hover, the key gave it up and its copy button slid under the pointer that came to drag the row, so the drag never started (#6268) */ -@media (min-width: 521px) { #gatewayKeys .acc:not(:hover) > :is(.key-quotas, .key-conc, .key-tier, .key-redact):not(.set, .open, :focus) { max-width: 0; padding: 0; margin-left: -9px; box-shadow: none; } } +@media (min-width: 521px) { #gatewayKeys .acc:not(:hover) > :is(.key-quotas, .key-conc, .key-tier, .key-routing, .key-redact):not(.set, .open, :focus) { max-width: 0; padding: 0; margin-left: -9px; box-shadow: none; } } /* the MCP servers a key held to some may use: cut, and gives way first */ #gatewayKeys .amodels.key-mcp { display: inline-block; flex: 0 1 auto; min-width: 24px; max-width: 180px; line-height: 20px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } /* a read-only key's tag, always shown, never a button */ @@ -4980,8 +4980,8 @@ body.panel .modal { padding: 16px 12px; } body.web .accts.keys .acc > :is(.amodels, .proto, .alane, .aspend, .abal):not(.set) { margin-left: 0 !important; } body.web .accts.keys .acc > .abal.abal-many { flex-shrink: 1 !important; padding-block: 2px !important; } body.web .accts.keys .key-acts > .text.quiet { margin-right: 0 !important; } - body.web #gatewayKeys .acc > :is(.key-quotas, .key-conc, .key-tier, .key-redact) { max-width: none !important; padding: 0 7px !important; margin-left: 0 !important; flex-shrink: 0; } - body.web #gatewayKeys .acc > :is(.key-quotas, .key-conc, .key-tier, .key-redact):not(.set) { box-shadow: inset 0 0 0 1px var(--line) !important; } + body.web #gatewayKeys .acc > :is(.key-quotas, .key-conc, .key-tier, .key-routing, .key-redact) { max-width: none !important; padding: 0 7px !important; margin-left: 0 !important; flex-shrink: 0; } + body.web #gatewayKeys .acc > :is(.key-quotas, .key-conc, .key-tier, .key-routing, .key-redact):not(.set) { box-shadow: inset 0 0 0 1px var(--line) !important; } } /* Import from other apps: a checklist per app */ diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index b8e8de02d..27c44caa9 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3026,6 +3026,11 @@ const I18N = { "This key's requests go at this service tier, whatever they ask": "这个密钥的请求按此服务层级发出,无论请求指定什么", "This key's requests keep the service tier they ask for": "这个密钥的请求保持各自指定的服务层级", "{who}: service tier {tier}": "{who}:服务层级 {tier}", + "Group routing": "分组路由", + "As the group routes": "按分组自己的方式", + "Routing groups this key asks for route its requests this way, not by their own": "这个密钥请求的路由分组按这种方式分配它的请求,而不按分组自己的方式", + "Routing groups route this key's requests by their own routing": "路由分组按各自的路由方式分配这个密钥的请求", + "{who}: group routing {routing}": "{who}:分组路由 {routing}", "Masking on": "脱敏:开", "Masking off": "脱敏:关", "Follow Settings": "跟随设置", @@ -8537,6 +8542,11 @@ const I18N = { "This key's requests go at this service tier, whatever they ask": "這個金鑰的請求依此服務層級送出,無論請求指定什麼", "This key's requests keep the service tier they ask for": "這個金鑰的請求保持各自指定的服務層級", "{who}: service tier {tier}": "{who}:服務層級 {tier}", + "Group routing": "分組路由", + "As the group routes": "依分組自己的方式", + "Routing groups this key asks for route its requests this way, not by their own": "這個金鑰請求的路由分組依這種方式分配它的請求,而不依分組自己的方式", + "Routing groups route this key's requests by their own routing": "路由分組依各自的路由方式分配這個金鑰的請求", + "{who}: group routing {routing}": "{who}:分組路由 {routing}", "Masking on": "脫敏:開", "Masking off": "脫敏:關", "Follow Settings": "跟隨設定", @@ -14019,6 +14029,11 @@ const I18N = { "This key's requests go at this service tier, whatever they ask": "このキーのリクエストは、指定にかかわらずこのサービス階層で送られます", "This key's requests keep the service tier they ask for": "このキーのリクエストは、指定されたサービス階層のまま送られます", "{who}: service tier {tier}": "{who}:サービス階層 {tier}", + "Group routing": "グループのルーティング", + "As the group routes": "グループの設定どおり", + "Routing groups this key asks for route its requests this way, not by their own": "このキーが指定するルーティンググループは、グループ自身の設定ではなくこの方法でリクエストを振り分けます", + "Routing groups route this key's requests by their own routing": "ルーティンググループは、このキーのリクエストをグループ自身のルーティングで振り分けます", + "{who}: group routing {routing}": "{who}:グループのルーティング {routing}", "Masking on": "マスク オン", "Masking off": "マスク オフ", "Follow Settings": "設定に従う", @@ -19544,6 +19559,11 @@ const I18N = { "This key's requests go at this service tier, whatever they ask": "Anfragen dieses Schlüssels laufen in dieser Service-Stufe, egal was sie anfordern", "This key's requests keep the service tier they ask for": "Anfragen dieses Schlüssels behalten die Service-Stufe, die sie anfordern", "{who}: service tier {tier}": "{who}: Service-Stufe {tier}", + "Group routing": "Gruppen-Routing", + "As the group routes": "Wie die Gruppe routet", + "Routing groups this key asks for route its requests this way, not by their own": "Routing-Gruppen, die dieser Schlüssel anfragt, verteilen seine Anfragen so statt nach ihrem eigenen Routing", + "Routing groups route this key's requests by their own routing": "Routing-Gruppen verteilen die Anfragen dieses Schlüssels nach ihrem eigenen Routing", + "{who}: group routing {routing}": "{who}: Gruppen-Routing {routing}", "Masking on": "Maskierung an", "Masking off": "Maskierung aus", "Follow Settings": "Wie in den Einstellungen", diff --git a/internal/gui/assets/plugins/gateway/keys.js b/internal/gui/assets/plugins/gateway/keys.js index 2fe9dc00a..b63787353 100644 --- a/internal/gui/assets/plugins/gateway/keys.js +++ b/internal/gui/assets/plugins/gateway/keys.js @@ -234,7 +234,7 @@ function renderGatewayKeys() { tick.onclick = () => gatewayKeyAction(k.off ? "on-key" : "off-key", { key: k.id }); // the copy sits by the key it copies (the owner: stranded among the // badges it read as nobody's); Rotate and Remove wait in the row's menu - row.append(tick, gatewayRename(k), el("span", "plan mono", k.masked), copyCallerKeyBtn(k), el("span", "grow"), ...(k.browser ? [gatewayBrowserTag()] : k.readOnly ? [gatewayReadOnlyTag()] : k.admin && gatewayKeyCanAdmin(k) ? [gatewayAdminTag(k)] : []), ...(k.memory && gatewayKeyCanAdmin(k) ? [gatewayMemoryTag()] : []), gatewayModelsBadge(k), ...gatewayKeptOutBadge(k), ...gatewayMCPBadge(k), gatewayQuotasBadge(k), ...(k.browser || k.readOnly ? [] : [gatewayConcurrencyBadge(k), gatewayTierBadge(k), gatewayRedactBadge(k)]), gatewayLimitBadge(k), gatewayKeyMore(k)); + row.append(tick, gatewayRename(k), el("span", "plan mono", k.masked), copyCallerKeyBtn(k), el("span", "grow"), ...(k.browser ? [gatewayBrowserTag()] : k.readOnly ? [gatewayReadOnlyTag()] : k.admin && gatewayKeyCanAdmin(k) ? [gatewayAdminTag(k)] : []), ...(k.memory && gatewayKeyCanAdmin(k) ? [gatewayMemoryTag()] : []), gatewayModelsBadge(k), ...gatewayKeptOutBadge(k), ...gatewayMCPBadge(k), gatewayQuotasBadge(k), ...(k.browser || k.readOnly ? [] : [gatewayConcurrencyBadge(k), gatewayTierBadge(k), gatewayRoutingBadge(k), gatewayRedactBadge(k)]), gatewayLimitBadge(k), gatewayKeyMore(k)); const under = gatewayLimit?.id === k.id ? [gatewayLimitEditor(k)] : keyUsed(k).map((u) => gatewayLimitLine(k, u)); if (under.length) row.classList.add("with-limit"), row.append(...under); list.append(row); @@ -1060,6 +1060,42 @@ function gatewayTierBadge(k) { return b; } +// how a routing group the key asks for routes its requests (justforlxz on +// X): as the group does, or by a routing of the key's own; a Manual group +// still sends to its pick. The built-in rotation's routings leave the menu +// while it is off (ROTATION), one the key has kept. +const KEY_ROUTINGS = [ + ["", "As the group routes"], ["smart", "Quota first"], ["order", "In order"], ["drain", "Until used up"], + ["rotate", "In turn"], ["usage", "Least used first"], ["pace", "Use before expiry"], ["weight", "By weight"], + ["free", "Free first"], ["fast", "Speed first"], ["cheap", "Cheapest first"], ["expiring", "Free quota by expiry"], + ["fit", "Small context first"], +]; +function gatewayRoutingBadge(k) { + const own = k.routing || ""; + const opts = KEY_ROUTINGS.filter(([v]) => v === own || !(ROTATION.has(v) && featuresOff.has("rotation"))) + .map(([v, name]) => ({ v, name })) + .concat(jsRoutings(own).filter(([v]) => !KEY_ROUTINGS.some(([id]) => id === v)).map(([v, name]) => ({ v, name, literalName: true }))); + const cur = opts.find((o) => o.v === own) || opts[0]; + const word = (o) => o.literalName ? o.name : t(o.name); + const b = el("button", "amodels key-routing" + (own ? " set" : "")); + b.type = "button"; + b.textContent = own ? word(cur) : t("Group routing"); + b.title = t(own ? "Routing groups this key asks for route its requests this way, not by their own" : "Routing groups route this key's requests by their own routing"); + b.setAttribute("aria-label", t("Group routing")); + b.setAttribute("aria-haspopup", "menu"); + b.setAttribute("aria-expanded", "false"); + b.onclick = (e) => { + e.stopPropagation(); + if (b.classList.contains("open")) return closeProtoMenu(); + openProtoMenu(b, opts, cur.v, async (v) => { + if (v === cur.v) return; + const out = await gatewayKeyAction("routing-key", { key: k.id, routing: v }); + if (out) status(t("{who}: group routing {routing}", { who: k.name, routing: word(opts.find((o) => o.v === v)) }), "ok"); + }, "Group routing", "sess-menu"); + }; + return b; +} + // A key's masking (y0ngb1n on X): as Settings › Privacy says, always on, or // off for a device the user trusts. A request with no key (this // computer's own) follows the settings. diff --git a/internal/gui/tests/fixtures/caller-keys.cjs b/internal/gui/tests/fixtures/caller-keys.cjs index a29c2fe3e..f6850d953 100644 --- a/internal/gui/tests/fixtures/caller-keys.cjs +++ b/internal/gui/tests/fixtures/caller-keys.cjs @@ -237,6 +237,7 @@ function fixture(lang, theme, events, options = {}) { k.maxConcurrency = body.maxConcurrency || undefined; } if (action === "tier-key") k.serviceTier = body.serviceTier || undefined; + if (action === "routing-key") k.routing = body.routing || undefined; if (action === "redact-key") k.redact = body.redact === "on" || body.redact === "off" ? body.redact : undefined; if (action === "access-key") k.readOnly = body.readOnly || undefined; // a key put at a place in the list, as access.Update keeps it; diff --git a/internal/gui/tests/gateway-key-routing.test.cjs b/internal/gui/tests/gateway-key-routing.test.cjs new file mode 100644 index 000000000..b28b5850d --- /dev/null +++ b/internal/gui/tests/gateway-key-routing.test.cjs @@ -0,0 +1,72 @@ +// A gateway key's group routing (justforlxz on X): a badge on the key's +// row, shown always while set and on hover while not, opens the app's +// menu (no native select): as the group routes, or one of the routings a +// group can take but Manual. It sends "routing-key"; a read-only key has +// none. +const assert = require("node:assert/strict"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); +const { fixture } = require("./fixtures/caller-keys.cjs"); + +const words = { + en: { label: "Group routing", follow: "As the group routes", turn: "In turn", smart: "Quota first" }, + zh: { label: "分组路由", follow: "按分组自己的方式", turn: "轮流", smart: "额度优先" }, + "zh-TW": { label: "分組路由", follow: "依分組自己的方式", turn: "輪流", smart: "額度優先" }, + ja: { label: "グループのルーティング", follow: "グループの設定どおり", turn: "交互", smart: "枠優先" }, + de: { label: "Gruppen-Routing", follow: "Wie die Gruppe routet", turn: "Abwechselnd", smart: "Kontingent zuerst" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const width of [1100, 420]) { + for (const [lang, w] of Object.entries(words)) { + test(`${engine} ${width} ${lang}: a key's group routing is set from the app's 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: 700 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(6000); + page.setDefaultNavigationTimeout(60000); + const events = [], errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", fixture(lang, "light", events, { lan: true, keyHolds: { server: { routing: "rotate" }, laptop: { readOnly: true } } })); + await page.goto("http://magpie.test/?view=gateway"); + await page.locator("#gatewayKeys .acc[data-key]").last().waitFor(); + const row = (id) => page.locator(`#gatewayKeys .acc[data-key="${id}"]`); + const badge = (id) => row(id).locator(".key-routing"); + const item = (name) => page.locator(".proto-menu .pm-item", { has: page.locator(".pm-name", { hasText: new RegExp(`^${name}$`) }) }); + const sent = () => events.filter((e) => e.action === "routing-key").map((e) => e.body); + const reads = (id, text) => page.waitForFunction(([id, text]) => document.querySelector(`#gatewayKeys .acc[data-key="${id}"] .key-routing`)?.textContent === text, [id, text]); + + // set: said always, not only on hover; a read-only key has none + await page.mouse.move(0, 0); + assert.equal(await badge("server").textContent(), w.turn); + assert.equal(await badge("server").evaluate((b) => getComputedStyle(b).opacity), "1"); + assert.equal(await badge("server").getAttribute("aria-label"), w.label); + assert.equal(await badge("laptop").count(), 0); + // unset: on hover only + assert.equal(await badge("work").evaluate((b) => getComputedStyle(b).opacity), "0"); + await row("work").hover(); + assert.equal(await badge("work").textContent(), w.label); + + await badge("work").click(); + await page.locator(".proto-menu").waitFor(); + assert.equal(await page.locator(".proto-menu .pm-head").textContent(), w.label); + // a key has no pick of its own to send to: no Manual + assert.equal(await item("Manual").count(), 0); + await item(w.smart).click(); + await reads("work", w.smart); + assert.deepEqual(sent(), [{ key: "work", routing: "smart" }]); + + await row("server").hover(); + await badge("server").click(); + await item(w.follow).click(); + await reads("server", w.label); + assert.deepEqual(sent().at(-1), { key: "server", routing: "" }); + + const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + assert.ok(over <= 0, `the page scrolls sideways by ${over}px`); + assert.equal(await page.locator("select").count(), 0, "no native select"); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/provider/group.go b/internal/provider/group.go index 73a6091d0..90589217e 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -2063,7 +2063,7 @@ func SaveGroup(g Group) error { if err := cleanDecisionGroup(&g, groupsIn(entries)); err != nil { return err } - if g.Routing != Ordered && g.Routing != Rotate && g.Routing != LeastUsed && g.Routing != Pace && g.Routing != Weighted && g.Routing != FreeFirst && g.Routing != Fastest && g.Routing != Cheapest && g.Routing != Drain && g.Routing != FreeExpiring && g.Routing != SmallFirst && g.Routing != Manual && !PluginRouting(g.Routing) { + if !GroupRouting(g.Routing) { g.Routing = "" } if !slices.Contains(Affinities, g.Affinity) { diff --git a/internal/provider/routing.go b/internal/provider/routing.go index 2369970d9..ed8fd4bec 100644 --- a/internal/provider/routing.go +++ b/internal/provider/routing.go @@ -89,6 +89,16 @@ var pluginRouting = lazyre.New(`^[A-Za-z0-9._-]+/[A-Za-z0-9][A-Za-z0-9._-]*$`) // its listed order. func PluginRouting(routing string) bool { return pluginRouting.MatchString(routing) } +// GroupRouting says whether routing is one a routing group can be routed +// by besides Smart (""): a built-in one, Manual, or a plugin's. +func GroupRouting(routing string) bool { + switch routing { + case Ordered, Rotate, LeastUsed, Pace, Weighted, FreeFirst, Fastest, Cheapest, Drain, FreeExpiring, SmallFirst, Manual: + return true + } + return PluginRouting(routing) +} + // SetRouting changes how a provider's requests spread over its keys or // accounts. func SetRouting(id, routing string) error {