DD asked for weighted round robin as a group routing, next to In turn.
A provider's keys could already route by weight (#841). Groups could not.
What changes:
- provider: Group.Weights maps a member's spelling to its weight, 1 to
1000. A member left out, or set to 0, weighs 1. SaveGroup accepts
routing "weight". It also cleans weights the way it cleans fast and
off: it strips :fast, drops weights of members that are gone and of
members weighing 1, and refuses a weight below 0 or above 1000.
Weights follow a member when it is renamed (RenameMember, Rename,
RenameGroup) and survive Share/Import.
- gateway: planLevel treats each member of a weight-routed group as one
unit: a model with its keys in its provider's order, or a nested group
routed its own way. weightedUnits orders the units by smooth WRR on a
round per group ("group/<id>"), sharing wrrPick with the keys. The
round's pick goes first and the rest stay in member order for
failover. A unit whose head is resting leaves the round. When a
conversation is kept on another member (session/turn/cache/strict),
the charge moves to that member (wrrSeat, wrrMove).
- cli: routing=weight (also weighted, wrr). weight=<model>=<n>[,...]
sets weights and keeps the rest; weight= on its own clears them. The
group view shows "· weight N" for each member.
- tui: By weight is in the group routing list.
- gui: the group editor offers By weight. Each member then shows
"Weight N · S%", its share among the members that are on. Clicking it
edits the number in place: Enter or blur keeps it, Escape cancels,
and a value outside 1 to 1000 shows a warning. The trace header uses
group wording for a weight-routed group. Strings are added in zh,
zh-TW, ja and de.
- docs: reference.md, gateway-routing.md, and site start pages in en,
zh and ja.
Run:
- go test -tags nogui ./internal/provider ./internal/cli ./internal/tui:
ok.
- ./internal/gateway: ok in 988s with -timeout 45m. The first run hit
the default 10m timeout at load average ~170. The test running at
that moment had been running for 2s; it was not a hang.
- go vet -tags nogui on those packages, for darwin, GOOS=linux and
GOOS=windows: clean. gofmt -l: clean.
- New group-member-weight.test.cjs: 8/8 in Chromium and WebKit, en and
zh at 1100, en and de at 420. The WebKit de 420 case also passed six
runs at once.
- gui-zh-tw, gui-ja, gui-de, i18n-keys, routing-*, group-*,
panel-routing*, settings-groups and agent-model-groups: all green
except two.
- routing-steady (WebKit) is #1804. It is red 2/3 alone on origin/main
e1b70c13d too.
- routing-save-blank (chromium en) was red under load only, and 3/3
green alone. The overshoot in its wheel loop is filed as #1924.
Broken by hand, each red, then restored:
- byWeight forced false:
--- FAIL: TestWeightedGroup (weighted_group_test.go:69 its turn ...)
- cleanWeights call skipped:
--- FAIL: TestSaveGroupWeights (groupweight_test.go:39 weights map[...
an/claude-opus-5-5:0 ... oa/gpt-6.1-sol:high:fast:3 ...])
- CLI weight case renamed:
--- FAIL: TestGroupWeightCLI (unknown field "weight")
- GUI chip not appended: group-member-weight chromium en 1100 timed out
on the weight button.
- Not red: the test's "moved nothing" check. A scroll forced on click,
or padding added above, did not turn it red, because the view's own
scroll guard and scroll anchoring hold the clicked row in place. It
only shows that the row stays under the pointer.
Not tried: real accounts through a running gateway. The routing is
proven by the plan-level test with synthetic providers only.
267 lines
8.8 KiB
Go
267 lines
8.8 KiB
Go
package provider
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"slices"
|
|
"strings"
|
|
)
|
|
|
|
// A routing group shared as text (laincatx on X): one group's routing,
|
|
// rules and members, copied from one magpie and pasted into another. It
|
|
// says what it is (ShareMark) and in which format (ShareVersion), so a
|
|
// magpie can tell it from any other text and one made by a newer magpie
|
|
// from one it can read.
|
|
const (
|
|
ShareMark = "routing-group"
|
|
ShareVersion = 1
|
|
)
|
|
|
|
// SharedGroup is the text a group is shared as.
|
|
type SharedGroup struct {
|
|
Magpie string `json:"magpie"`
|
|
Version int `json:"version"`
|
|
Group Group `json:"group"`
|
|
}
|
|
|
|
// ShareGroup is group id as text to paste into another magpie: its
|
|
// members as it names them, its patterns, routing, rules, classifier,
|
|
// effort, context, levels, fast and off members. A group holds no key or
|
|
// account of its own, only provider/model ids, so nothing secret goes with
|
|
// it; what is derived (the models its patterns match now, found, hidden,
|
|
// switched off) stays behind, and so do the rules that hold by a folder,
|
|
// in it or outside it:
|
|
// a folder is a path on the sharer's own machine, which names their
|
|
// projects and means nothing on another.
|
|
func ShareGroup(id string) (string, error) {
|
|
all := Groups()
|
|
i := slices.IndexFunc(all, func(g Group) bool { return g.ID == id && !g.Hidden })
|
|
if i < 0 {
|
|
return "", fmt.Errorf("no group %q", id)
|
|
}
|
|
// a copy shares nothing with the group read: the rules' time windows
|
|
// are pointers
|
|
raw, err := json.Marshal(all[i])
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
var g Group
|
|
if err := json.Unmarshal(raw, &g); err != nil {
|
|
return "", err
|
|
}
|
|
g.Members, g.Match = ownMembers(g)
|
|
g.Matched = nil
|
|
g.Auto, g.Hidden, g.Disabled = false, false, false
|
|
g.Rules = slices.DeleteFunc(g.Rules, Rule.ByFolder)
|
|
out, err := json.Marshal(SharedGroup{Magpie: ShareMark, Version: ShareVersion, Group: g})
|
|
return string(out), err
|
|
}
|
|
|
|
// ShareError is why a text can't be imported as a group, by Why, for the
|
|
// GUI to say in the reader's language: "not_shared" (no group shared from
|
|
// magpie), "newer" (a format past ShareVersion, in Format), "no_format",
|
|
// "unreadable" (Err), "none_here" (none of its models here, in Models).
|
|
type ShareError struct {
|
|
Why string
|
|
Format int
|
|
Models []string
|
|
Err error
|
|
}
|
|
|
|
func (e *ShareError) Error() string {
|
|
switch e.Why {
|
|
case "newer":
|
|
return fmt.Sprintf("this group was shared from a newer magpie (format %d): update magpie to import it", e.Format)
|
|
case "no_format":
|
|
return "this shared group says no format it is in: copy it again with Copy to share"
|
|
case "unreadable":
|
|
return fmt.Sprintf("this shared group can't be read: %v", e.Err)
|
|
case "none_here":
|
|
return "none of the group's models is in your magpie: " + strings.Join(e.Models, ", ")
|
|
}
|
|
return "this is not a routing group shared from magpie: copy one with Copy to share in a group's menu"
|
|
}
|
|
|
|
func (e *ShareError) Unwrap() error { return e.Err }
|
|
|
|
// Imported is what ImportGroup made of a shared group.
|
|
type Imported struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
// Missing are the models and groups the text names that this magpie
|
|
// has none of, left out of the group: members, and the classifier.
|
|
Missing []string `json:"missing,omitempty"`
|
|
// Instead are the members this magpie has under another provider: the
|
|
// same model (AutoGroupOf), "shared → here".
|
|
Instead []string `json:"instead,omitempty"`
|
|
// Rules is how many of the group's rules were left out with the
|
|
// member they send to, or the classifier their intent needs, or for
|
|
// holding by a folder of the sharer's.
|
|
Rules int `json:"rules,omitempty"`
|
|
}
|
|
|
|
// ReadShared reads a shared group's text, as copied or pasted from a chat:
|
|
// the object may have words or a code fence around it.
|
|
func ReadShared(text string) (SharedGroup, error) {
|
|
var s SharedGroup
|
|
start, end := strings.Index(text, "{"), strings.LastIndex(text, "}")
|
|
notOne := &ShareError{Why: "not_shared"}
|
|
if start < 0 || end < start {
|
|
return s, notOne
|
|
}
|
|
var probe struct {
|
|
Magpie string `json:"magpie"`
|
|
Version int `json:"version"`
|
|
Group json.RawMessage `json:"group"`
|
|
}
|
|
if err := json.Unmarshal([]byte(text[start:end+1]), &probe); err != nil || probe.Magpie != ShareMark {
|
|
return s, notOne
|
|
}
|
|
switch {
|
|
case probe.Version > ShareVersion:
|
|
return s, &ShareError{Why: "newer", Format: probe.Version}
|
|
case probe.Version < 1:
|
|
return s, &ShareError{Why: "no_format"}
|
|
}
|
|
if err := json.Unmarshal(probe.Group, &s.Group); err != nil {
|
|
return s, &ShareError{Why: "unreadable", Err: err}
|
|
}
|
|
s.Magpie, s.Version = probe.Magpie, probe.Version
|
|
return s, nil
|
|
}
|
|
|
|
// ImportGroup adds the group a shared text holds as a group of the
|
|
// user's, named as it was shared and numbered past a name or id in use,
|
|
// so it never replaces a group there is. It is listed last. A member this
|
|
// magpie has no provider of is the same model under one it has, where it
|
|
// serves it (Instead), else left out (Missing), and with it the rules that
|
|
// send to it and its place among the fast and off members. Nothing is
|
|
// added when none of its members is left.
|
|
func ImportGroup(text string) (Imported, error) {
|
|
s, err := ReadShared(text)
|
|
if err != nil {
|
|
return Imported{}, err
|
|
}
|
|
g := s.Group
|
|
entries := providerEntries()
|
|
all := Groups()
|
|
var res Imported
|
|
// what each member the text names is here: itself, another provider's
|
|
// same model, or "" for none
|
|
here := map[string]string{}
|
|
place := func(m string) string {
|
|
m = strings.TrimSpace(m)
|
|
if to, ok := here[m]; ok {
|
|
return to
|
|
}
|
|
to := memberHere(entries, all, m)
|
|
here[m] = to
|
|
switch {
|
|
case to == "":
|
|
res.Missing = append(res.Missing, m)
|
|
case to != m:
|
|
res.Instead = append(res.Instead, m+" → "+to)
|
|
}
|
|
return to
|
|
}
|
|
members, match := ownMembers(g)
|
|
g.Members = nil
|
|
for _, m := range members {
|
|
if to := place(m); to != "" && !slices.Contains(g.Members, to) {
|
|
g.Members = append(g.Members, to)
|
|
}
|
|
}
|
|
g.Match, g.Matched = match, nil
|
|
if len(g.Members) == 0 && len(g.Match) == 0 {
|
|
return res, &ShareError{Why: "none_here", Models: res.Missing}
|
|
}
|
|
kept := func(list []string) []string {
|
|
var out []string
|
|
for _, m := range list {
|
|
if to := here[strings.TrimSpace(m)]; to != "" && !slices.Contains(out, to) {
|
|
out = append(out, to)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
g.Off, g.Fast = kept(g.Off), slices.DeleteFunc(kept(g.Fast), func(f string) bool {
|
|
// the same model under another provider may have no fast mode
|
|
model, _ := memberEffortIn(entries, f)
|
|
p, id, ok := resolveIn(entries, model)
|
|
return ok && !CanFast(p, id)
|
|
})
|
|
g.Weights = renamedWeights(g.Weights, func(m string) string { return here[strings.TrimSpace(m)] })
|
|
if g.Routing != Manual && len(g.Off) == len(g.Members) {
|
|
g.Off = nil // the ones it sent to are gone: those left are on
|
|
}
|
|
g.Pick = here[strings.TrimSpace(g.Pick)]
|
|
if c := strings.TrimSpace(g.Classifier); c != "" {
|
|
if g.Classifier = place(c); g.Classifier == GroupPrefix+g.ID {
|
|
g.Classifier = ""
|
|
}
|
|
}
|
|
// a rule sends to a model the group names, or one its patterns match
|
|
// here
|
|
in := append(slices.Clone(g.Members), matchesIn(entries, g)...)
|
|
var rules []Rule
|
|
for _, r := range g.Rules {
|
|
use := here[strings.TrimSpace(r.Use)]
|
|
if _, named := here[strings.TrimSpace(r.Use)]; !named && !IsPattern(r.Use) {
|
|
// a rule may send to a model a pattern matches: one this
|
|
// magpie has, or none
|
|
use = memberHere(entries, all, r.Use)
|
|
}
|
|
// a folder is the sharer's path, never this machine's
|
|
if use == "" || !slices.Contains(in, use) || (r.Intent != "" && g.Classifier == "") || r.ByFolder() {
|
|
res.Rules++
|
|
continue
|
|
}
|
|
r.Use = use
|
|
rules = append(rules, r)
|
|
}
|
|
g.Rules = rules
|
|
if g.Classifier == "" {
|
|
g.Effort = "" // nothing to rate a turn with
|
|
}
|
|
name := strings.TrimSpace(g.Name)
|
|
if name == "" {
|
|
name = "Shared group"
|
|
}
|
|
g.Name, g.ID = freeGroupName(all, name, "")
|
|
g.Auto, g.Hidden, g.Disabled = false, false, false
|
|
if err := SaveGroup(g); err != nil {
|
|
return res, err
|
|
}
|
|
res.ID, res.Name = g.ID, g.Name
|
|
return res, nil
|
|
}
|
|
|
|
// memberHere is what member m of a shared group is in this magpie: m
|
|
// itself when it has the provider (or the group), else the same model
|
|
// (AutoGroupOf) under the first provider here that serves it, in the
|
|
// Providers order; "" when none does. A member's own effort goes with it.
|
|
func memberHere(entries []Entry, all []Group, m string) string {
|
|
m = strings.TrimPrefix(strings.TrimSpace(m), "magpie/")
|
|
model, effort := memberEffortIn(entries, m)
|
|
if gid, ok := strings.CutPrefix(model, GroupPrefix); ok {
|
|
if slices.ContainsFunc(all, func(g Group) bool { return g.ID == gid && !g.Hidden }) {
|
|
return m
|
|
}
|
|
return ""
|
|
}
|
|
pid, id, ok := strings.Cut(model, "/")
|
|
if !ok {
|
|
return ""
|
|
}
|
|
if _, err := Find(pid); err == nil || isModel(entries, model) {
|
|
return m
|
|
}
|
|
same := AutoGroupOf(pid, id)
|
|
for _, e := range entries {
|
|
if e.Group == "" && AutoGroupOf(e.Provider.ID, e.Model) == same {
|
|
return WithMemberEffort(e.ID, effort)
|
|
}
|
|
}
|
|
return ""
|
|
}
|