routing: every group follows a default for rate limits, slow starts and busy members unless it sets its own
jiezhengj on Discord asked to set the per-group policies once instead of
in each group. The Routing groups page's Settings card, under the list,
now has three rows: Rate limited (keeps its place / goes to the back),
Slow to start (wait / 30 s ... 4 min) and Every member busy (off / 1 min
... 4 min). They are saved in settings.json as groupSink, groupFirstToken
and groupPatience (settings.SetGroupDefaults, POST /api/groups/defaults).
A group follows the default for each value it leaves unset, and its own
value always wins:
- Sinks() is the group's Sink, or else the default unless NoSink, a new
field for an explicit "Keeps its place".
- FirstTokenOr() is the group's own FirstToken (-1, FirstTokenWait, is an
explicit Wait), or else the default. The gateway reads it where it
reads a group's first-token time.
- Waits() reads the default when Patience is 0. 60 is an explicit 1 min.
Groups saved before have 0 and no NoSink, so they follow the default,
which starts at magpie's own (keep its place, wait, 60s). Nothing a user
set changes. The group editor's three rows gain a Default option, on for
a group that sets none, and its hint names the value it follows. Segments
only, with no native select.
Run on mote, at 06b2daeff rebased on origin/main 2dac9b84e:
- go test on the new tests TestGroupDefaultsUnlessItsOwn,
TestGroupFirstTokenFollowsTheDefault, TestGroupSinkFollowsTheDefault
and TestGroupDefaultsSaved, plus TestKeysAreWhatTheSaveWrites and the
existing first-token and sink tests: ok.
- Broken by hand (Waits, FirstTokenOr and Sinks ignoring settings): the
three provider/gateway tests went red.
- GUI: group-defaults (new), group-patience, group-first-token,
group-found-off and rate-limited-sink, in Chromium and WebKit, in en,
zh, zh-TW, ja and de, at 1100 and 420: 56/56 pass. With the old
client.js and routing.css, group-defaults, group-patience and
group-first-token fail 44 of 44.
- GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./...:
clean. gofmt -l: clean.
Still running when this was pushed (owner: never hold a verified commit
behind the suite): go test -timeout 45m on internal/provider,
internal/gateway, internal/gui, internal/settings and
internal/settingsapi, then the whole GUI suite under suite.lock. Any red
they show gets its own issue.
Not tried: the real app with real groups under real rate limits. Only
the gateway tests' fakes exercise the default sink and first-token paths.
Reported-by: jiezhengj on Discord
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -590,7 +590,7 @@ func planFallbackGroup(g provider.Group, ms []provider.Member, from provider.Pro
|
||||
var asides []candidate
|
||||
var wAsides []Weighed
|
||||
out := planLevel(g, ms, 0, from, pl, &asides, &wAsides, []provider.Group{g})
|
||||
if sinks(g.Sink, g.Routing) {
|
||||
if sinks(g.Sinks(), g.Routing) {
|
||||
var order []Weighed
|
||||
out, order = sinkPlanned(out, pl.order[at:])
|
||||
pl.order = append(pl.order[:at], order...)
|
||||
@@ -625,7 +625,7 @@ func (s *Server) planGroup(g provider.Group, ms []provider.Member, from provider
|
||||
var asides []candidate
|
||||
var wAsides []Weighed
|
||||
out := planLevel(g, ms, 0, from, &pl, &asides, &wAsides, nil)
|
||||
if sinks(g.Sink, g.Routing) {
|
||||
if sinks(g.Sinks(), g.Routing) {
|
||||
out, pl.order = sinkPlanned(out, pl.order)
|
||||
}
|
||||
out, pl.order = append(out, asides...), append(pl.order, wAsides...)
|
||||
@@ -652,10 +652,11 @@ func placed(ms []provider.Member, cs []candidate) {
|
||||
}
|
||||
|
||||
// innerFirstToken is the FirstToken of the innermost group m is in
|
||||
// (m.Via, the outermost first) that sets one, 0 for none.
|
||||
// (m.Via, the outermost first) that sets one, 0 for none:
|
||||
// provider.FirstTokenWait counts as set, so an inner Wait waits.
|
||||
func innerFirstToken(m provider.Member) int {
|
||||
for i := len(m.Via) - 1; i >= 0; i-- {
|
||||
if m.Via[i].FirstToken > 0 {
|
||||
if m.Via[i].FirstToken != 0 {
|
||||
return m.Via[i].FirstToken
|
||||
}
|
||||
}
|
||||
@@ -875,7 +876,7 @@ func planLevel(g provider.Group, ms []provider.Member, depth int, from provider.
|
||||
// (#576) and rules, and its Sink was left unread, only the group the
|
||||
// agent asked for sinking.
|
||||
func sinkOwn(sub provider.Group, cs []candidate, order []Weighed) ([]candidate, []Weighed) {
|
||||
if !sinks(sub.Sink, sub.Routing) {
|
||||
if !sinks(sub.Sinks(), sub.Routing) {
|
||||
return cs, order
|
||||
}
|
||||
return sinkPlanned(cs, order)
|
||||
|
||||
@@ -3433,8 +3433,12 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
hw.reloop = reloops < loopReasks && !pass
|
||||
}
|
||||
// a member of a group in the group is timed by the innermost
|
||||
// group that sets a FirstToken (#2246), else by the group asked for
|
||||
firstToken := cmp.Or(c.firstToken, g.FirstToken)
|
||||
// group that sets a FirstToken (#2246), else by the group asked
|
||||
// for, which follows the default for every group when it sets none
|
||||
firstToken := c.firstToken
|
||||
if firstToken == 0 && isGroup {
|
||||
firstToken = g.FirstTokenOr()
|
||||
}
|
||||
if isGroup && firstToken > 0 && !last && streams && !pass {
|
||||
// slow to start, the next member is asked (Group.FirstToken)
|
||||
hw.firstWait = time.Duration(firstToken) * time.Second
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
func setGroupDefaults(t *testing.T, sink bool, firstToken, patience int) {
|
||||
t.Helper()
|
||||
if err := settings.SetGroupDefaults(sink, firstToken, patience); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// A group that sets no first-token time of its own follows the default for
|
||||
// every group (jiezhengj on Discord: set once, not in each group); one
|
||||
// that picked Wait itself waits, whatever the default.
|
||||
func TestGroupFirstTokenFollowsTheDefault(t *testing.T) {
|
||||
fresh(t)
|
||||
setGroupDefaults(t, false, 1, 0)
|
||||
a := &slowStart{wait: 10 * time.Second}
|
||||
b := &scripted{replies: []reply{{200, "text/event-stream", chatStreamOK}}}
|
||||
slowOn(t, "a", a)
|
||||
scriptedOn(t, "b", provider.Chat, b)
|
||||
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := New()
|
||||
began := time.Now()
|
||||
code, body := postAs(t, s, "", `{"model":"group/g","stream":true,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
if took := time.Since(began); took > 5*time.Second {
|
||||
t.Fatalf("took %s", took)
|
||||
}
|
||||
if code != 200 || !strings.Contains(body, "from b") || a.n != 1 || b.n != 1 {
|
||||
t.Fatalf("default: %d %s (a %d, b %d)", code, body, a.n, b.n)
|
||||
}
|
||||
|
||||
// the group's own Wait wins over the default
|
||||
fresh(t)
|
||||
setGroupDefaults(t, false, 1, 0)
|
||||
a = &slowStart{wait: 2 * time.Second}
|
||||
b = &scripted{replies: []reply{{200, "text/event-stream", chatStreamOK}}}
|
||||
slowOn(t, "a", a)
|
||||
scriptedOn(t, "b", provider.Chat, b)
|
||||
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered, FirstToken: provider.FirstTokenWait}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g, _, _ := provider.FindGroup("group/g")
|
||||
if g.FirstToken != provider.FirstTokenWait {
|
||||
t.Fatalf("Wait not kept: %d", g.FirstToken)
|
||||
}
|
||||
s = New()
|
||||
if code, body := postAs(t, s, "", `{"model":"group/g","stream":true,"messages":[{"role":"user","content":"hi"}]}`); code != 200 || !strings.Contains(body, "slow answer") || b.n != 0 {
|
||||
t.Fatalf("own wait: %d %s (b %d)", code, body, b.n)
|
||||
}
|
||||
}
|
||||
|
||||
// A group that sets nothing for one rate limited with quota left follows
|
||||
// the default for every group; its own Keeps its place (NoSink) or Goes to
|
||||
// the back (Sink) wins.
|
||||
func TestGroupSinkFollowsTheDefault(t *testing.T) {
|
||||
fresh(t)
|
||||
forgetSinks(t)
|
||||
s := &Server{}
|
||||
mem := func(id string) provider.Member {
|
||||
return provider.Member{ID: id + "/m", Path: []string{id + "/m"}, Provider: provider.Provider{ID: id, Chat: "http://127.0.0.1:1/v1", Key: "k-" + id}, Model: "m"}
|
||||
}
|
||||
ms := []provider.Member{mem("a"), mem("b"), mem("c")}
|
||||
ids := func(cs []candidate) []string {
|
||||
var out []string
|
||||
for _, c := range cs {
|
||||
out = append(out, c.p.ID)
|
||||
}
|
||||
return out
|
||||
}
|
||||
rate := []byte(`{"error":{"message":"Too many requests"}}`)
|
||||
cs, _ := s.planGroup(provider.Group{ID: "g", Routing: provider.Ordered}, ms, provider.Chat)
|
||||
s.restAfter(cs[0], 429, http.Header{}, rate)
|
||||
rested(cs[0].restKey())
|
||||
order := func(g provider.Group) []string {
|
||||
out, _ := s.planGroup(g, ms, provider.Chat)
|
||||
return ids(out)
|
||||
}
|
||||
back, kept := []string{"b", "c", "a"}, []string{"a", "b", "c"}
|
||||
if got := order(provider.Group{ID: "g", Routing: provider.Ordered}); !slices.Equal(got, kept) {
|
||||
t.Fatalf("no default: %v", got)
|
||||
}
|
||||
setGroupDefaults(t, true, 0, 0)
|
||||
if got := order(provider.Group{ID: "g", Routing: provider.Ordered}); !slices.Equal(got, back) {
|
||||
t.Fatalf("default to the back: %v", got)
|
||||
}
|
||||
if got := order(provider.Group{ID: "g", Routing: provider.Ordered, NoSink: true}); !slices.Equal(got, kept) {
|
||||
t.Fatalf("own keeps its place: %v", got)
|
||||
}
|
||||
setGroupDefaults(t, false, 0, 0)
|
||||
if got := order(provider.Group{ID: "g", Routing: provider.Ordered, Sink: true}); !slices.Equal(got, back) {
|
||||
t.Fatalf("own to the back: %v", got)
|
||||
}
|
||||
}
|
||||
@@ -273,7 +273,7 @@ type NestedRule struct {
|
||||
|
||||
// groupRef is the trace's g, with its models ms.
|
||||
func groupRef(g provider.Group, ms []provider.Member) *GroupRef {
|
||||
ref := &GroupRef{ID: g.ID, Ref: g.Ref(), Name: g.Name, Routing: g.Routing, Affinity: g.Affinity, Auto: g.Auto, Sink: sinks(g.Sink, g.Routing)}
|
||||
ref := &GroupRef{ID: g.ID, Ref: g.Ref(), Name: g.Name, Routing: g.Routing, Affinity: g.Affinity, Auto: g.Auto, Sink: sinks(g.Sinks(), g.Routing)}
|
||||
seen := map[string]bool{}
|
||||
for _, m := range ms {
|
||||
ref.Members = append(ref.Members, m.Spelled())
|
||||
|
||||
@@ -5640,8 +5640,12 @@ function routingPage(part) {
|
||||
// for the providers' models), so it sits over the groups rather than in
|
||||
// one group's editor (PAMI on Discord)
|
||||
const gNames = el("div", "rt-gnames");
|
||||
// what every group does that sets none of its own when one is rate
|
||||
// limited, slow to start, or every member is busy (jiezhengj on Discord:
|
||||
// set once rather than in each group); a group's editor sets its own
|
||||
const gDefs = [el("div", "rt-gdef rt-gdef-sink"), el("div", "rt-gdef rt-gdef-first"), el("div", "rt-gdef rt-gdef-patience")];
|
||||
// the groups go with the routing groups built-in plugin; the pools stay
|
||||
for (const n of [gHead, gFound, gNames, gList]) n.dataset.feature = "groups";
|
||||
for (const n of [gHead, gFound, gNames, ...gDefs, gList]) n.dataset.feature = "groups";
|
||||
// and off (the Essentials preset leaves it off), where they were
|
||||
// the page says so and turns it on (bigbenniu on X: past the requests
|
||||
// there was nothing, and no word of where New group had gone). The
|
||||
@@ -5673,7 +5677,7 @@ function routingPage(part) {
|
||||
sHead.append(el("span", "label", t("Settings")));
|
||||
const gSet = el("div", "list rt-gset");
|
||||
gSet.dataset.feature = "groups";
|
||||
gSet.append(gFound, gNames);
|
||||
gSet.append(gFound, gNames, ...gDefs);
|
||||
gsec.append(gHead, gList, gOff, sHead, gSet, pHead, pList);
|
||||
// on the Routing groups page, a page of their own; Try again on it puts
|
||||
// them back in its markup made anew
|
||||
@@ -5701,16 +5705,35 @@ function routingPage(part) {
|
||||
sink: "One rate limited (429) while it still has quota goes to the back of the order, behind every one not rate limited since, and comes round again once those ahead of it are rate limited in turn — so the load goes round rather than back to the first each time. Out of quota, it rests as usual. Kept until magpie restarts.",
|
||||
};
|
||||
// in turn goes round already, and a manual group sends to one member
|
||||
// how long a group's member may take to its first token (provider.Group.FirstToken)
|
||||
// how long a group's member may take to its first token, as the default
|
||||
// for every group has it (settings' groupFirstToken: 0 waits)
|
||||
const FIRST_OPTS = [[0, "Wait"], [30, "30 s"], [60, "1 min"], [120, "2 min"]];
|
||||
// how long a request waits for a group whose every member is busy
|
||||
// (provider.Group.Patience: 0 is the 60s default, -1 off)
|
||||
// how long a request waits for a group whose every member is busy, as
|
||||
// the default for every group has it (settings' groupPatience: 0 is the
|
||||
// 60s default, -1 off)
|
||||
const PATIENCE_OPTS = [[-1, "Off"], [0, "1 min"], [120, "2 min"], [240, "4 min"]];
|
||||
const patienceOf = (n) => n === 60 ? 0 : n || 0;
|
||||
// a group's own (provider.Group): 0 follows the default for every group,
|
||||
// so Wait is -1 (FirstTokenWait), 1 min a Patience of 60, and Keeps its
|
||||
// place NoSink (jiezhengj on Discord: set once, not in each group)
|
||||
const G_FIRST_OPTS = [[0, "Default"], [-1, "Wait"], ...FIRST_OPTS.slice(1)];
|
||||
const G_PATIENCE_OPTS = [[0, "Default"], [-1, "Off"], [60, "1 min"], ...PATIENCE_OPTS.slice(2)];
|
||||
const G_SINK_OPTS = [["def", "Default"], ...SINK_OPTS];
|
||||
const sinkModeOf = (g) => g.sink ? "sink" : g.noSink ? "" : "def";
|
||||
// the default for every group (groups.defaults), each value checked
|
||||
const groupDefaults = () => {
|
||||
const d = groups?.defaults || {};
|
||||
return { sink: d.sink === true, firstToken: Number.isInteger(d.firstToken) && d.firstToken > 0 ? d.firstToken : 0,
|
||||
patience: Number.isInteger(d.patience) && d.patience >= -1 ? d.patience : 0 };
|
||||
};
|
||||
const patienceWord = (n) => {
|
||||
if (n === 60) n = 0;
|
||||
const o = PATIENCE_OPTS.find(([v]) => v === (n || 0));
|
||||
return o ? t(o[1]) : took(n * 1000);
|
||||
};
|
||||
const firstWord = (n) => {
|
||||
const o = FIRST_OPTS.find(([v]) => v === Math.max(n || 0, 0));
|
||||
return o ? t(o[1]) : took(n * 1000);
|
||||
};
|
||||
const sinkable = (routing) => routing !== "rotate" && routing !== "weight" && routing !== "manual";
|
||||
const AFF_HINT = {
|
||||
"": "A conversation stays with the account or key that answered it while what the vendor cached of it is worth keeping — within a turn always, across turns while it's fresh.",
|
||||
@@ -5908,7 +5931,7 @@ function routingPage(part) {
|
||||
// there, rather than leaving the slot empty.
|
||||
const openGroupEditor = async (g) => {
|
||||
if (groupDirty() && !(await confirmDiscard())) return false;
|
||||
gEdit = { id: g.id, draft: { name: g.name, members: [...g.members], match: [...(g.match || [])], matched: [...(g.matched || [])], fast: [...(g.fast || [])], off: [...(g.off || [])], weights: { ...(g.weights || {}) }, effortMaps: Object.fromEntries(Object.entries(g.effortMaps || {}).map(([id, m]) => [id, { ...m }])), accounts: [...(g.accounts || [])], routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink, unlists: !!g.unlists, firstToken: g.firstToken || 0, patience: patienceOf(g.patience), context: g.context || 0, classifier: g.classifier || "", intentSure: g.intentSure ?? null, effort: g.effort || "", levels: [...(g.levels || [])], rules: (g.rules || []).map((r) => ({ ...r, ...(r.more?.length ? { more: [...r.more] } : {}), intent: r.intent || "", agents: [...(r.agents || [])], folders: [...(r.folders || [])], exceptFolders: [...(r.exceptFolders || [])], time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } };
|
||||
gEdit = { id: g.id, draft: { name: g.name, members: [...g.members], match: [...(g.match || [])], matched: [...(g.matched || [])], fast: [...(g.fast || [])], off: [...(g.off || [])], weights: { ...(g.weights || {}) }, effortMaps: Object.fromEntries(Object.entries(g.effortMaps || {}).map(([id, m]) => [id, { ...m }])), accounts: [...(g.accounts || [])], routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: sinkModeOf(g), unlists: !!g.unlists, firstToken: g.firstToken || 0, patience: g.patience || 0, context: g.context || 0, classifier: g.classifier || "", intentSure: g.intentSure ?? null, effort: g.effort || "", levels: [...(g.levels || [])], rules: (g.rules || []).map((r) => ({ ...r, ...(r.more?.length ? { more: [...r.more] } : {}), intent: r.intent || "", agents: [...(r.agents || [])], folders: [...(r.folders || [])], exceptFolders: [...(r.exceptFolders || [])], time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } };
|
||||
renderGroups();
|
||||
return true;
|
||||
};
|
||||
@@ -6096,6 +6119,7 @@ function routingPage(part) {
|
||||
replaceKeeping(gHead, head);
|
||||
drawFound();
|
||||
drawNames();
|
||||
drawDefaults();
|
||||
const rows = [];
|
||||
if (!gSel && !own && !words.length && tpls.length) rows.push(templateCards(tpls));
|
||||
if (gSel) rows.push(selectBar(shown));
|
||||
@@ -6538,6 +6562,41 @@ function routingPage(part) {
|
||||
// an open editor says what its group will be called: drawn again with it
|
||||
gNames.replaceChildren(txt, suffixSegs(() => renderGroups()));
|
||||
}
|
||||
// drawDefaults: the default for every group that sets none of its own,
|
||||
// saved at once as it is picked (settings' groupSink, groupFirstToken,
|
||||
// groupPatience)
|
||||
function drawDefaults() {
|
||||
const def = groupDefaults();
|
||||
const row = (box, label, hint, opts, cur, key) => {
|
||||
const txt = el("div", "txt");
|
||||
txt.append(el("b", "", t(label)), el("small", "", hint));
|
||||
// a value set elsewhere (magpie settings set) that no option names
|
||||
if (!opts.some(([v]) => v === cur)) opts = [...opts, [cur, key === "firstToken" ? firstWord(cur) : patienceWord(cur)]];
|
||||
const pick = segs(opts.map(([v, n]) => [v, t(n)]), cur, (v) => setDefaults({ ...def, [key]: v }));
|
||||
pick.setAttribute("aria-label", t(label));
|
||||
box.replaceChildren(txt, pick);
|
||||
};
|
||||
row(gDefs[0], "Rate limited", t(SINK_HINT[def.sink ? "sink" : ""]), SINK_OPTS, def.sink ? "sink" : "", "sink");
|
||||
row(gDefs[1], "Slow to start", def.firstToken > 0
|
||||
? t("A member that hasn't begun answering after {n} — no text, reasoning or tool call yet — is let go and the next one asked, before any of it reaches the agent. Let go once, it doesn't rest; let go twice in a row, its model rests on that account, a minute and longer each time, until it answers again. The last one left is always waited for. Only for streamed requests.", { n: took(def.firstToken * 1000) })
|
||||
: t("Every member is waited for, however long it takes to begin answering."), FIRST_OPTS, def.firstToken, "firstToken");
|
||||
row(gDefs[2], "Every member busy", def.patience < 0
|
||||
? t("When every member has failed, the agent gets the last one's error at once.")
|
||||
: t("When every member has failed with an error that may pass — overloaded, unavailable, rate limited for a moment — and nothing of the reply has reached the agent, each is asked again after a pause, longer each time and never shorter than the vendor asks, for up to {n} more. A streaming agent is kept waiting meanwhile.", { n: patienceWord(def.patience) }),
|
||||
PATIENCE_OPTS, def.patience === 60 ? 0 : def.patience, "patience");
|
||||
}
|
||||
async function setDefaults(d) {
|
||||
try {
|
||||
const next = groupsFrom(await api("groups/defaults", { sink: d.sink === true || d.sink === "sink", firstToken: d.firstToken, patience: d.patience }));
|
||||
groups.defaults = next.defaults;
|
||||
drawDefaults();
|
||||
// an open editor's Default rows say the value they follow
|
||||
if (gEdit) renderGroups();
|
||||
} catch (e) {
|
||||
status(e.message, "err");
|
||||
drawDefaults();
|
||||
}
|
||||
}
|
||||
async function setFound(on, s) {
|
||||
if (groupDirty() && !(await confirmDiscard())) return;
|
||||
s.classList.toggle("on", on);
|
||||
@@ -6669,7 +6728,7 @@ function routingPage(part) {
|
||||
closeProtoMenu();
|
||||
if (v === cur || (groupDirty() && !(await confirmDiscard()))) return b.focus({ preventScroll: true });
|
||||
const n = opts.find(([id]) => id === v)?.[1] || v;
|
||||
await groupAction("save", { id: g.id, name: g.name, members: namedOf(g), match: g.match || [], routing: v, pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink && sinkable(v), firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", intentSure: g.intentSure ?? null, context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [], weights: g.weights || {}, effortMaps: g.effortMaps || {}, accounts: g.accounts || [], unlists: !!g.unlists },
|
||||
await groupAction("save", { id: g.id, name: g.name, members: namedOf(g), match: g.match || [], routing: v, pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink && sinkable(v), noSink: !!g.noSink, firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", intentSure: g.intentSure ?? null, context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [], weights: g.weights || {}, effortMaps: g.effortMaps || {}, accounts: g.accounts || [], unlists: !!g.unlists },
|
||||
t("{name}: {routing}", { name: g.name, routing: t(n) }));
|
||||
// the rows were drawn anew: the keyboard stays on this one's routing
|
||||
gList.querySelector(`.rt-group[data-id="${CSS.escape(g.id)}"] .rt-groute`)?.focus({ preventScroll: true });
|
||||
@@ -6802,7 +6861,7 @@ function routingPage(part) {
|
||||
b.onclick = (e) => {
|
||||
e.stopPropagation(); // the card opens the editor; this picks
|
||||
if (on) return;
|
||||
groupAction("save", { id: g.id, name: g.name, members: namedOf(g), match: g.match || [], routing: "manual", pick: id, affinity: g.affinity || "", sink: !!g.sink, firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", intentSure: g.intentSure ?? null, context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [], weights: g.weights || {}, effortMaps: g.effortMaps || {}, accounts: g.accounts || [], unlists: !!g.unlists },
|
||||
groupAction("save", { id: g.id, name: g.name, members: namedOf(g), match: g.match || [], routing: "manual", pick: id, affinity: g.affinity || "", sink: !!g.sink, noSink: !!g.noSink, firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", intentSure: g.intentSure ?? null, context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [], weights: g.weights || {}, effortMaps: g.effortMaps || {}, accounts: g.accounts || [], unlists: !!g.unlists },
|
||||
t("{name}: every request to {model}", { name: g.name, model: memberName(id) }));
|
||||
};
|
||||
box.append(b);
|
||||
@@ -7317,11 +7376,14 @@ function routingPage(part) {
|
||||
ed.append(el("label", "", t("Routing")), rw);
|
||||
// one rate limited with quota left: its place, or the back
|
||||
const kHint = el("div", "hint"), kw = el("div", "sink-wrap"), kLab = el("label", "", t("Rate limited"));
|
||||
// Default follows the setting for every group, under the list
|
||||
const drawSink = () => {
|
||||
kHint.textContent = t(SINK_HINT[d.sink ? "sink" : ""]);
|
||||
const mode = d.sink ?? "def", def = mode === "def";
|
||||
const sinks = def ? groupDefaults().sink : mode === "sink";
|
||||
kHint.textContent = (def ? t("As set for every group under the list: {v}.", { v: t(SINK_OPTS[sinks ? 1 : 0][1]) }) + " " : "") + t(SINK_HINT[sinks ? "sink" : ""]);
|
||||
kLab.hidden = kw.hidden = !sinkable(d.routing);
|
||||
};
|
||||
const kPick = segs(SINK_OPTS.map(([id, n]) => [id, t(n)]), d.sink ? "sink" : "", (v) => { d.sink = v === "sink"; drawSink(); });
|
||||
const kPick = segs(G_SINK_OPTS.map(([id, n]) => [id, t(n)]), d.sink ?? "def", (v) => { d.sink = v; drawSink(); });
|
||||
kPick.classList.add("sink-pick");
|
||||
kw.append(kPick, kHint);
|
||||
ed.append(kLab, kw);
|
||||
@@ -7337,17 +7399,18 @@ function routingPage(part) {
|
||||
firstIn.setAttribute("aria-describedby", fHint.id);
|
||||
const firstUnit = el("span", "first-unit", t("min"));
|
||||
const firstMins = (s) => String(+(s / 60).toFixed(2));
|
||||
let firstMode = FIRST_OPTS.some(([n]) => n === (d.firstToken || 0)) ? d.firstToken || 0 : "custom";
|
||||
let firstMode = G_FIRST_OPTS.some(([n]) => n === (d.firstToken || 0)) ? d.firstToken || 0 : "custom";
|
||||
if (firstMode === "custom") firstIn.value = firstMins(d.firstToken);
|
||||
let firstErr = "";
|
||||
const drawFirst = () => {
|
||||
firstIn.hidden = firstUnit.hidden = firstMode !== "custom";
|
||||
firstIn.setAttribute("aria-invalid", String(!!firstErr));
|
||||
fHint.textContent = firstErr || (d.firstToken
|
||||
? t("A member that hasn't begun answering after {n} — no text, reasoning or tool call yet — is let go and the next one asked, before any of it reaches the agent. Let go once, it doesn't rest; let go twice in a row, its model rests on that account, a minute and longer each time, until it answers again. The last one left is always waited for. Only for streamed requests.", { n: took(d.firstToken * 1000) })
|
||||
const own = d.firstToken || 0, first = own || groupDefaults().firstToken;
|
||||
fHint.textContent = firstErr || (own ? "" : t("As set for every group under the list: {v}.", { v: firstWord(first) }) + " ") + (first > 0
|
||||
? t("A member that hasn't begun answering after {n} — no text, reasoning or tool call yet — is let go and the next one asked, before any of it reaches the agent. Let go once, it doesn't rest; let go twice in a row, its model rests on that account, a minute and longer each time, until it answers again. The last one left is always waited for. Only for streamed requests.", { n: took(first * 1000) })
|
||||
: t("Every member is waited for, however long it takes to begin answering."));
|
||||
};
|
||||
fw.append(segs([...FIRST_OPTS.map(([n, l]) => [n, t(l)]), ["custom", t("Custom")]], firstMode, (v) => {
|
||||
fw.append(segs([...G_FIRST_OPTS.map(([n, l]) => [n, t(l)]), ["custom", t("Custom")]], firstMode, (v) => {
|
||||
firstErr = "";
|
||||
firstMode = v;
|
||||
if (v !== "custom") d.firstToken = +v;
|
||||
@@ -7371,10 +7434,13 @@ function routingPage(part) {
|
||||
// every member busy at once: the agent told, or the members asked
|
||||
// again within a budget (#1418)
|
||||
const patHint = el("div", "hint"), patW = el("div");
|
||||
const drawPatience = () => patHint.textContent = d.patience < 0
|
||||
const drawPatience = () => {
|
||||
const own = d.patience || 0, pat = own || groupDefaults().patience;
|
||||
patHint.textContent = (own ? "" : t("As set for every group under the list: {v}.", { v: patienceWord(pat) }) + " ") + (pat < 0
|
||||
? t("When every member has failed, the agent gets the last one's error at once.")
|
||||
: t("When every member has failed with an error that may pass — overloaded, unavailable, rate limited for a moment — and nothing of the reply has reached the agent, each is asked again after a pause, longer each time and never shorter than the vendor asks, for up to {n} more. A streaming agent is kept waiting meanwhile.", { n: patienceWord(d.patience) });
|
||||
patW.append(segs(PATIENCE_OPTS.map(([n, l]) => [n, t(l)]), d.patience || 0, (v) => { d.patience = +v; drawPatience(); }), patHint);
|
||||
: t("When every member has failed with an error that may pass — overloaded, unavailable, rate limited for a moment — and nothing of the reply has reached the agent, each is asked again after a pause, longer each time and never shorter than the vendor asks, for up to {n} more. A streaming agent is kept waiting meanwhile.", { n: patienceWord(pat) }));
|
||||
};
|
||||
patW.append(segs(G_PATIENCE_OPTS.map(([n, l]) => [n, t(l)]), d.patience || 0, (v) => { d.patience = +v; drawPatience(); }), patHint);
|
||||
ed.append(el("label", "", t("Every member busy")), patW);
|
||||
drawPatience();
|
||||
// the window agents are told: the largest member's, the smallest's, or
|
||||
@@ -8136,7 +8202,7 @@ function routingPage(part) {
|
||||
if (own && !d.levels.length) return status(t("Pick a level to offer, or leave them to its models"), "warn");
|
||||
saveBtn.classList.add("busy");
|
||||
// refused, Add can be pressed again (busy, it takes no clicks)
|
||||
groupAction("save", { id: idOf(), from: g?.id, name: d.name.trim() || idOf(), members: namedOf(d), placed: d.members, match: d.match, routing: d.routing, pick: d.pick || "", affinity: d.affinity, sink: !!d.sink && sinkable(d.routing), firstToken: d.firstToken || 0, patience: d.patience || 0, rules: d.rules, effort: d.effort, classifier: d.rules.some((r) => r.intent) || d.effort === "auto" ? d.classifier : "", intentSure: d.intentSure ?? null, context: d.context || 0, levels: own ? d.levels : [], family: g?.family || "", fast: d.fast.filter((x) => d.members.includes(x)), off: d.off.filter((x) => d.members.includes(x)), weights: Object.fromEntries(Object.entries(d.weights).filter(([x, n]) => d.members.includes(x) && n > 1)), effortMaps: Object.fromEntries(Object.entries(d.effortMaps).filter(([x, m]) => d.members.includes(x) && Object.keys(m).length)), accounts: d.accounts.filter((a) => accountPids().includes(a.slice(0, a.indexOf("/")))), unlists: !!d.unlists }, t(g ? "{name} saved" : "{name} added", { name: d.name.trim() || idOf() }))
|
||||
groupAction("save", { id: idOf(), from: g?.id, name: d.name.trim() || idOf(), members: namedOf(d), placed: d.members, match: d.match, routing: d.routing, pick: d.pick || "", affinity: d.affinity, sink: d.sink === "sink" && sinkable(d.routing), noSink: d.sink === "", firstToken: d.firstToken || 0, patience: d.patience || 0, rules: d.rules, effort: d.effort, classifier: d.rules.some((r) => r.intent) || d.effort === "auto" ? d.classifier : "", intentSure: d.intentSure ?? null, context: d.context || 0, levels: own ? d.levels : [], family: g?.family || "", fast: d.fast.filter((x) => d.members.includes(x)), off: d.off.filter((x) => d.members.includes(x)), weights: Object.fromEntries(Object.entries(d.weights).filter(([x, n]) => d.members.includes(x) && n > 1)), effortMaps: Object.fromEntries(Object.entries(d.effortMaps).filter(([x, m]) => d.members.includes(x) && Object.keys(m).length)), accounts: d.accounts.filter((a) => accountPids().includes(a.slice(0, a.indexOf("/")))), unlists: !!d.unlists }, t(g ? "{name} saved" : "{name} added", { name: d.name.trim() || idOf() }))
|
||||
.then(() => saveBtn.classList.remove("busy"));
|
||||
};
|
||||
// what goes wrong is said where it is seen, never a click that does nothing
|
||||
|
||||
@@ -197,6 +197,7 @@ magpie.strings({
|
||||
"Agents' model lists and the gateway's /v1/models show the group, not the models it names or its patterns match: they are used through it. Codex keeps its ChatGPT sign-in's own models. A request naming one is still answered.": "Agent 的模型列表和网关的 /v1/models 只列出本组,不列出它点名的模型和模式匹配到的模型:这些模型通过本组使用。Codex 仍列出它所登录的 ChatGPT 账号自己的模型。直接点名其中一个模型的请求仍会被应答。",
|
||||
"Slow to start": "迟迟不出字",
|
||||
"Every member busy": "成员全都忙",
|
||||
"As set for every group under the list: {v}.": "按列表下方为所有组的设置:{v}。",
|
||||
"When every member has failed with an error that may pass — overloaded, unavailable, rate limited for a moment — and nothing of the reply has reached the agent, each is asked again after a pause, longer each time and never shorter than the vendor asks, for up to {n} more. A streaming agent is kept waiting meanwhile.": "每个成员都因暂时性错误(过载、暂不可用、短暂限流)失败,而回复还一点都没到智能体时,过一会儿依次再问一遍每个成员,间隔一次比一次长,也不短于厂商要求的等待,最多再等 {n}。流式请求的智能体在此期间会一直被保持等待。",
|
||||
"When every member has failed, the agent gets the last one's error at once.": "每个成员都失败时,智能体立刻拿到最后一个的错误。",
|
||||
"{who} answered {status} · {fail}, and every member had failed with an error that may pass, so after {d} the {n} of them are asked again, in turn, before any of the reply reaches {agent}. The group waits up to {p} for one to answer.": "{who} 回了 {status} · {fail},而每个成员都因暂时性错误失败,所以 {d} 后依次再问这 {n} 个,回复还一点都没到 {agent}。这个分组最多等 {p} 让其中一个回答。",
|
||||
@@ -881,6 +882,7 @@ magpie.strings({
|
||||
"Agents' model lists and the gateway's /v1/models show the group, not the models it names or its patterns match: they are used through it. Codex keeps its ChatGPT sign-in's own models. A request naming one is still answered.": "Agent 的模型清單和閘道的 /v1/models 只列出本組,不列出它點名的模型和模式比對到的模型:這些模型透過本組使用。Codex 仍列出它所登入的 ChatGPT 帳號自己的模型。直接點名其中一個模型的請求仍會被回應。",
|
||||
"Slow to start": "遲遲不出字",
|
||||
"Every member busy": "成員全都忙",
|
||||
"As set for every group under the list: {v}.": "依列表下方為所有組的設定:{v}。",
|
||||
"When every member has failed with an error that may pass — overloaded, unavailable, rate limited for a moment — and nothing of the reply has reached the agent, each is asked again after a pause, longer each time and never shorter than the vendor asks, for up to {n} more. A streaming agent is kept waiting meanwhile.": "每個成員都因暫時性錯誤(過載、暫不可用、短暫限流)失敗,而回覆還一點都沒到智慧體時,過一會兒依序再問一遍每個成員,間隔一次比一次長,也不短於廠商要求的等待,最多再等 {n}。串流請求的智慧體在此期間會一直被保持等待。",
|
||||
"When every member has failed, the agent gets the last one's error at once.": "每個成員都失敗時,智慧體立刻拿到最後一個的錯誤。",
|
||||
"{who} answered {status} · {fail}, and every member had failed with an error that may pass, so after {d} the {n} of them are asked again, in turn, before any of the reply reaches {agent}. The group waits up to {p} for one to answer.": "{who} 回了 {status} · {fail},而每個成員都因暫時性錯誤失敗,所以 {d} 後依序再問這 {n} 個,回覆還一點都沒到 {agent}。這個分組最多等 {p} 讓其中一個回答。",
|
||||
@@ -1543,6 +1545,7 @@ magpie.strings({
|
||||
"Agents' model lists and the gateway's /v1/models show the group, not the models it names or its patterns match: they are used through it. Codex keeps its ChatGPT sign-in's own models. A request naming one is still answered.": "エージェントのモデル一覧とゲートウェイの /v1/models にはグループだけが並び、指定したモデルやパターンに合うモデルは出ません。これらはグループを通して使われます。Codex にはサインインしている ChatGPT アカウント自身のモデルが残ります。モデルを名指しするリクエストには引き続き応答します。",
|
||||
"Slow to start": "応答開始が遅いとき",
|
||||
"Every member busy": "全メンバーが混雑",
|
||||
"As set for every group under the list: {v}.": "一覧の下の、すべてのグループ共通の設定どおり:{v}。",
|
||||
"When every member has failed with an error that may pass — overloaded, unavailable, rate limited for a moment — and nothing of the reply has reached the agent, each is asked again after a pause, longer each time and never shorter than the vendor asks, for up to {n} more. A streaming agent is kept waiting meanwhile.": "すべてのメンバーが一時的なエラー(過負荷、利用不可、短時間のレート制限)で失敗し、応答がまだエージェントに何も届いていないときは、少し待ってから各メンバーに順に聞き直します。待ち時間は回ごとに長くなり、ベンダーが求める待ち時間より短くはなりません。さらに最大 {n} まで続けます。ストリーミングのエージェントはその間待たせたままにします。",
|
||||
"When every member has failed, the agent gets the last one's error at once.": "すべてのメンバーが失敗したら、最後のメンバーのエラーをすぐエージェントに返します。",
|
||||
"{who} answered {status} · {fail}, and every member had failed with an error that may pass, so after {d} the {n} of them are asked again, in turn, before any of the reply reaches {agent}. The group waits up to {p} for one to answer.": "{who} は {status} · {fail} を返し、すべてのメンバーが一時的なエラーで失敗したため、{d} 後にその {n} 件に順に聞き直します。応答はまだ {agent} に何も届いていません。グループはいずれかが答えるまで最大 {p} 待ちます。",
|
||||
@@ -2217,6 +2220,7 @@ magpie.strings({
|
||||
"Agents' model lists and the gateway's /v1/models show the group, not the models it names or its patterns match: they are used through it. Codex keeps its ChatGPT sign-in's own models. A request naming one is still answered.": "Die Modelllisten der Agenten und /v1/models des Gateways zeigen die Gruppe, nicht die Modelle, die sie nennt oder deren Muster passen: Sie werden über die Gruppe genutzt. Codex behält die eigenen Modelle seiner ChatGPT-Anmeldung. Eine Anfrage, die eines davon nennt, wird weiter beantwortet.",
|
||||
"Slow to start": "Langsamer Start",
|
||||
"Every member busy": "Alle Mitglieder ausgelastet",
|
||||
"As set for every group under the list: {v}.": "Wie unter der Liste für alle Gruppen eingestellt: {v}.",
|
||||
"When every member has failed with an error that may pass — overloaded, unavailable, rate limited for a moment — and nothing of the reply has reached the agent, each is asked again after a pause, longer each time and never shorter than the vendor asks, for up to {n} more. A streaming agent is kept waiting meanwhile.": "Sind alle Mitglieder mit einem vorübergehenden Fehler gescheitert – überlastet, nicht verfügbar, kurz ratenbegrenzt – und hat den Agenten noch nichts von der Antwort erreicht, wird jedes nach einer Pause erneut gefragt, jedes Mal länger und nie kürzer, als der Anbieter verlangt, bis zu {n} lang. Ein streamender Agent wird so lange hingehalten.",
|
||||
"When every member has failed, the agent gets the last one's error at once.": "Sind alle Mitglieder gescheitert, bekommt der Agent sofort den Fehler des letzten.",
|
||||
"{who} answered {status} · {fail}, and every member had failed with an error that may pass, so after {d} the {n} of them are asked again, in turn, before any of the reply reaches {agent}. The group waits up to {p} for one to answer.": "{who} antwortete {status} · {fail}, und alle Mitglieder waren mit einem vorübergehenden Fehler gescheitert, daher werden die {n} nach {d} der Reihe nach erneut gefragt, bevor etwas von der Antwort {agent} erreicht. Die Gruppe wartet bis zu {p}, dass eines antwortet.",
|
||||
|
||||
@@ -283,8 +283,8 @@
|
||||
.rt-gsec > .row-head:first-child .rt-gcount { margin-left: 10px; white-space: nowrap; }
|
||||
.rt-gsec > .row-head:first-child .rt-gfilter + .rt-gcount { margin-left: 10px; }
|
||||
/* the settings for every group, a card under the list */
|
||||
.rt-gset > :is(.rt-gfound, .rt-gnames) { padding: 12px 14px; }
|
||||
.rt-gset > .rt-gnames { border-top: 1px solid var(--line-2); }
|
||||
.rt-gset > :is(.rt-gfound, .rt-gnames, .rt-gdef) { padding: 12px 14px; }
|
||||
.rt-gset > :is(.rt-gnames, .rt-gdef) { border-top: 1px solid var(--line-2); }
|
||||
/* an email, hidden: stand-in letters of its shape, softly blurred —
|
||||
coming in out of focus when asked for */
|
||||
.pii { filter: blur(2.2px); opacity: .5; user-select: none; }
|
||||
@@ -648,12 +648,12 @@ button.rt-session { cursor: pointer; }
|
||||
.rt-goffbox { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; padding: 12px 14px; }
|
||||
.rt-goffwhy { flex: 1 1 260px; min-width: 0; font-size: 12px; line-height: 1.5; color: var(--fg-2); }
|
||||
.rt-goffon { flex: none; }
|
||||
.rt-gfound, .rt-gnames { display: flex; align-items: center; gap: 12px; padding: 2px 4px 4px; }
|
||||
.rt-gfound .txt, .rt-gnames .txt { flex: 1; min-width: 0; display: grid; gap: 2px; }
|
||||
.rt-gfound b, .rt-gnames b { font-size: 12.5px; font-weight: 600; }
|
||||
.rt-gfound small, .rt-gnames small { font-size: 11.5px; line-height: 1.45; color: var(--muted); }
|
||||
.rt-gfound, .rt-gnames, .rt-gdef { display: flex; align-items: center; gap: 12px; padding: 2px 4px 4px; }
|
||||
.rt-gfound .txt, .rt-gnames .txt, .rt-gdef .txt { flex: 1; min-width: 0; display: grid; gap: 2px; }
|
||||
.rt-gfound b, .rt-gnames b, .rt-gdef b { font-size: 12.5px; font-weight: 600; }
|
||||
.rt-gfound small, .rt-gnames small, .rt-gdef small { font-size: 11.5px; line-height: 1.45; color: var(--muted); }
|
||||
/* the names setting's three choices go under its words when it is narrow */
|
||||
.rt-gnames { flex-wrap: wrap; }
|
||||
.rt-gnames, .rt-gdef { flex-wrap: wrap; }
|
||||
/* the providers kept out of found groups: a text button under the
|
||||
switch's words, its menu the app's */
|
||||
.rt-gfound .rt-skip-pick { justify-self: start; display: inline-flex; align-items: center; gap: 3px; max-width: 100%; height: 22px; margin-left: -7px; font-size: 11.5px; }
|
||||
@@ -661,7 +661,7 @@ button.rt-session { cursor: pointer; }
|
||||
.rt-skip-pick svg { flex: none; opacity: .7; transition: transform .15s var(--ease); }
|
||||
.rt-skip-pick.open svg { transform: rotate(180deg); }
|
||||
.pop.proto-menu.rt-skip-menu { width: 230px; max-width: calc(100vw - 16px); background: var(--card); }
|
||||
.rt-gnames .txt { flex-basis: 220px; }
|
||||
.rt-gnames .txt, .rt-gdef .txt { flex-basis: 220px; }
|
||||
.rt-ghidden { display: flex; align-items: center; padding: 4px 12px 4px 8px; }
|
||||
.rt-ghidden .rt-gremoved { display: inline-flex; align-items: center; gap: 4px; font-size: 11.5px; color: var(--faint); }
|
||||
.rt-ghidden .rt-gremoved:hover, .rt-ghidden .rt-gremoved.open { color: var(--fg-2); }
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// The Routing groups page's Settings card sets what every group follows
|
||||
// when it sets nothing of its own (jiezhengj on Discord); the page reads
|
||||
// it back in /api/groups, a bad value is refused, and the groups and the
|
||||
// rest of the settings are left as they were.
|
||||
func TestGroupDefaultsSaved(t *testing.T) {
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
t.Setenv("USERPROFILE", os.Getenv("HOME"))
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
s := settings.Load()
|
||||
s.ClassifyTimeout = 9
|
||||
if err := settings.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := provider.Save(provider.Provider{ID: "a", Name: "a", Key: "ka", Chat: "http://127.0.0.1:1/v1", Models: []string{"m1"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := provider.SaveGroup(provider.Group{ID: "own", Name: "Own", Members: []string{"a/m1"}, FirstToken: provider.FirstTokenWait}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
groupRoutes(mux)
|
||||
post := func(body string) (int, groupsJSON) {
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/groups/defaults", strings.NewReader(body)))
|
||||
var out groupsJSON
|
||||
if w.Code == 200 {
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return w.Code, out
|
||||
}
|
||||
code, got := post(`{"sink":true,"firstToken":60,"patience":-1}`)
|
||||
if code != 200 || got.Defaults != (groupDefaultsJSON{Sink: true, FirstToken: 60, Patience: -1}) {
|
||||
t.Fatalf("%d %+v", code, got.Defaults)
|
||||
}
|
||||
s = settings.Load()
|
||||
if !s.GroupSink || s.GroupFirstToken != 60 || s.GroupPatience != -1 || s.ClassifyTimeout != 9 {
|
||||
t.Fatalf("settings: %v %d %d %d", s.GroupSink, s.GroupFirstToken, s.GroupPatience, s.ClassifyTimeout)
|
||||
}
|
||||
if g, _, _ := provider.FindGroup("group/own"); g.FirstToken != provider.FirstTokenWait || g.FirstTokenOr() > 0 || !g.Sinks() || g.Waits() != 0 {
|
||||
t.Fatalf("group: %+v", g)
|
||||
}
|
||||
if st := groupsState(); st.Defaults != (groupDefaultsJSON{Sink: true, FirstToken: 60, Patience: -1}) {
|
||||
t.Fatalf("state: %+v", st.Defaults)
|
||||
}
|
||||
if code, _ := post(`{"patience":999}`); code == 200 {
|
||||
t.Fatal("patience 999 saved")
|
||||
}
|
||||
if s := settings.Load(); s.GroupPatience != -1 {
|
||||
t.Fatalf("after a refusal: %d", s.GroupPatience)
|
||||
}
|
||||
// back to magpie's own
|
||||
if code, got := post(`{}`); code != 200 || got.Defaults != (groupDefaultsJSON{}) {
|
||||
t.Fatalf("cleared: %d %+v", code, got.Defaults)
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,15 @@ type groupsJSON struct {
|
||||
// to (Group.Accounts), as a gateway key's list has them (#905): each
|
||||
// provider with more than one, or one a group names already
|
||||
Accounts map[string][]keyModelJSON `json:"accounts"`
|
||||
// Defaults: what every group follows when it sets no value of its own
|
||||
// (settings.GroupSink, GroupFirstToken, GroupPatience)
|
||||
Defaults groupDefaultsJSON `json:"defaults"`
|
||||
}
|
||||
|
||||
type groupDefaultsJSON struct {
|
||||
Sink bool `json:"sink"`
|
||||
FirstToken int `json:"firstToken"`
|
||||
Patience int `json:"patience"`
|
||||
}
|
||||
|
||||
type skippableJSON struct {
|
||||
@@ -294,6 +303,8 @@ func groupsState() groupsJSON {
|
||||
_, offset := time.Now().Zone()
|
||||
out := groupsJSON{Groups: []groupJSON{}, Models: []modelRef{}, Pools: []poolJSON{}, Deciders: []modelRef{}, Drawers: []modelRef{}, Found: provider.AutoGroupsOn(), Templates: provider.Templates(),
|
||||
Clock: clockJSON{Zone: provider.LocalZone(), Offset: offset}}
|
||||
def := settings.Load()
|
||||
out.Defaults = groupDefaultsJSON{Sink: def.GroupSink, FirstToken: def.GroupFirstToken, Patience: def.GroupPatience}
|
||||
for i := range out.Templates {
|
||||
if out.Templates[i].Group.Members == nil {
|
||||
out.Templates[i].Group.Members = []string{} // one that can't be made has none
|
||||
@@ -563,6 +574,10 @@ func groupRoutes(mux *http.ServeMux) {
|
||||
err = provider.SwitchGroup(in.ID, body.On)
|
||||
case "arrange":
|
||||
err = provider.SetGroupOrder(body.Order)
|
||||
case "defaults":
|
||||
// what every group follows when it sets no value of its own
|
||||
// (jiezhengj on Discord: set once, not in each group)
|
||||
err = settings.SetGroupDefaults(in.Sink, in.FirstToken, in.Patience)
|
||||
case "pick":
|
||||
// a Manual group's member every request goes to, and nothing
|
||||
// else of it (#2489: the tray panel switches it)
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// What every routing group does when one is rate limited, slow to start or
|
||||
// every member is busy is set once, in the Settings card under the groups
|
||||
// (jiezhengj on Discord: each group had to be set on its own). Each row
|
||||
// picks its value in the app's segments and posts groups/defaults with all
|
||||
// three at once; a group's editor opens on Default for those it sets none
|
||||
// of, its hint saying the value it follows, and the group's own pick still
|
||||
// wins. In five languages, Chromium and WebKit, at 1100 and 420, with no
|
||||
// native select and nothing past the window's side.
|
||||
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 models = [
|
||||
{ id: "a/m", name: "m", providerName: "A", icon: "generic" },
|
||||
{ id: "b/m", name: "m", providerName: "B", icon: "generic" },
|
||||
];
|
||||
const members = models.map((m) => m.id);
|
||||
|
||||
function serve(lang, posts, st) {
|
||||
const state = { agents: [{ id: "codex", name: "Codex", path: "/test/codex", fields: [] }], profiles: [], settings: { lang, theme: "light" } };
|
||||
const groups = () => ({
|
||||
models, pools: [], deciders: [], found: true, defaults: { ...st.defaults },
|
||||
groups: [{ id: "sol", name: "Sol", members, routing: "order", ready: true, memberInfo: members.map((id) => ({ id, ready: true })), ...st.group }],
|
||||
});
|
||||
return async (r) => {
|
||||
const url = new URL(r.request().url());
|
||||
const json = (data) => r.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json(state);
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/gateway/trace") {
|
||||
if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes
|
||||
return json({ mine: true, now: new Date().toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });
|
||||
}
|
||||
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
|
||||
if (url.pathname === "/api/groups") return json(groups());
|
||||
if (url.pathname.startsWith("/api/groups/")) {
|
||||
const body = JSON.parse(r.request().postData() || "{}");
|
||||
posts.push({ path: url.pathname, body });
|
||||
if (url.pathname === "/api/groups/defaults") st.defaults = { sink: !!body.sink, firstToken: body.firstToken || 0, patience: body.patience || 0 };
|
||||
if (url.pathname === "/api/groups/save") st.group = { sink: !!body.sink, noSink: !!body.noSink, firstToken: body.firstToken || 0, patience: body.patience || 0 };
|
||||
return json(groups());
|
||||
}
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
await r.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) for (const width of [1100, 420]) {
|
||||
test(`${engine} ${lang} ${width}: every group follows one default unless it sets its own`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const page = await (await browser.newContext({ viewport: { width, height: 2000 }, reducedMotion: "reduce" })).newPage();
|
||||
t.after(async () => {
|
||||
if (process.env.ARTIFACT_DIR) {
|
||||
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
|
||||
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-group-defaults.png`), fullPage: true });
|
||||
}
|
||||
await browser.close();
|
||||
});
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [], posts = [], st = { defaults: { sink: false, firstToken: 0, patience: 0 }, group: {} };
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang, posts, st));
|
||||
await page.goto("http://magpie.test/?view=groups");
|
||||
const card = page.locator(".rt-group", { hasText: "Sol" });
|
||||
await card.waitFor();
|
||||
const tr = (k, v) => page.evaluate(([k, v]) => t(k, v), [k, v]);
|
||||
// at 420 the page runs past the window's foot, and WebKit doesn't
|
||||
// scroll the page's own scroller to a click: wheel it into view
|
||||
const reach = async (loc) => {
|
||||
await loc.waitFor();
|
||||
await page.mouse.move(width / 2, 600);
|
||||
for (let i = 0; i < 30; i++) {
|
||||
const b = await loc.boundingBox();
|
||||
if (b && b.y >= 0 && b.y + b.height <= 2000) return loc;
|
||||
await page.mouse.wheel(0, b && b.y < 0 ? -400 : 400);
|
||||
await page.waitForTimeout(50);
|
||||
}
|
||||
return loc;
|
||||
};
|
||||
const on = async (row) => (await row.locator(".opt.on").textContent()).trim();
|
||||
// a pick is saved, and the row drawn again from what came back
|
||||
const pick = async (row, name) => {
|
||||
const was = await row.locator(".segs").elementHandle();
|
||||
await (await reach(row.locator(".opt", { hasText: new RegExp(`^${name}$`) }))).click();
|
||||
await page.waitForFunction((s) => !s.isConnected, was);
|
||||
assert.equal(await on(row), name);
|
||||
return posts.filter((p) => p.path === "/api/groups/defaults").at(-1)?.body;
|
||||
};
|
||||
|
||||
// the Settings card under the list: each row says what it is and
|
||||
// starts at magpie's own
|
||||
const set = page.locator(".rt-gset");
|
||||
const sink = set.locator(".rt-gdef-sink"), first = set.locator(".rt-gdef-first"), pat = set.locator(".rt-gdef-patience");
|
||||
await reach(pat);
|
||||
assert.equal((await sink.locator("b").textContent()).trim(), await tr("Rate limited"));
|
||||
assert.equal((await first.locator("b").textContent()).trim(), await tr("Slow to start"));
|
||||
assert.equal((await pat.locator("b").textContent()).trim(), await tr("Every member busy"));
|
||||
assert.equal(await on(sink), await tr("Keeps its place"));
|
||||
assert.equal(await on(first), await tr("Wait"));
|
||||
assert.equal(await on(pat), await tr("1 min"));
|
||||
assert.equal(await page.locator("select").count(), 0, "no native select");
|
||||
|
||||
// each pick posts all three, the others as they are
|
||||
assert.deepEqual(await pick(sink, await tr("Goes to the back")), { sink: true, firstToken: 0, patience: 0 });
|
||||
assert.deepEqual(await pick(first, await tr("1 min")), { sink: true, firstToken: 60, patience: 0 });
|
||||
assert.deepEqual(await pick(pat, await tr("Off")), { sink: true, firstToken: 60, patience: -1 });
|
||||
assert((await first.locator("small").textContent()).includes(await tr("{n} s", { n: 60 })), "the hint says what the value does");
|
||||
assert((await pat.locator("small").textContent()).includes(await tr("When every member has failed, the agent gets the last one's error at once.")));
|
||||
const fits = () => page.evaluate(() => {
|
||||
const box = document.querySelector(".rt-gset").getBoundingClientRect();
|
||||
return [...document.querySelectorAll(".rt-gdef .segs")].every((s) => {
|
||||
const b = s.getBoundingClientRect();
|
||||
return b.left >= box.left - 0.5 && b.right <= box.right + 0.5;
|
||||
}) && document.scrollingElement.scrollWidth <= document.scrollingElement.clientWidth;
|
||||
});
|
||||
assert.equal(await fits(), true, "the rows fit at " + width);
|
||||
|
||||
// a group that sets none opens on Default, its hint saying what it follows
|
||||
await (await reach(card.locator("button", { hasText: await tr("Edit") }))).click();
|
||||
const ed = page.locator(".rt-gedit");
|
||||
const field = (label) => ed.locator("label", { hasText: new RegExp(`^${label}$`) }).locator("xpath=following-sibling::div[1]");
|
||||
const eSink = field(await tr("Rate limited")), eFirst = field(await tr("Slow to start")), ePat = field(await tr("Every member busy"));
|
||||
await eSink.waitFor();
|
||||
const dflt = await tr("Default");
|
||||
for (const row of [eSink, eFirst, ePat]) assert.equal(await on(row), dflt);
|
||||
const follows = (v) => tr("As set for every group under the list: {v}.", { v });
|
||||
assert((await eSink.locator(".hint").textContent()).startsWith(await follows(await tr("Goes to the back"))));
|
||||
assert((await eFirst.locator(".hint").textContent()).startsWith(await follows(await tr("1 min"))));
|
||||
assert((await ePat.locator(".hint").textContent()).startsWith(await follows(await tr("Off"))));
|
||||
assert((await ePat.locator(".hint").textContent()).includes(await tr("When every member has failed, the agent gets the last one's error at once.")));
|
||||
|
||||
// the group's own picks win, and are sent as its own
|
||||
await (await reach(eSink.locator(".opt", { hasText: new RegExp(`^${await tr("Keeps its place")}$`) }))).click();
|
||||
await (await reach(eFirst.locator(".opt", { hasText: new RegExp(`^${await tr("Wait")}$`) }))).click();
|
||||
await (await reach(ePat.locator(".opt", { hasText: new RegExp(`^${await tr("1 min")}$`) }))).click();
|
||||
assert(!(await ePat.locator(".hint").textContent()).startsWith(await follows(await tr("Off"))), "its own value's hint, not the default's");
|
||||
await (await reach(ed.locator("button.primary", { hasText: await tr("Save") }))).click();
|
||||
await page.waitForFunction(() => !document.querySelector(".rt-gedit"));
|
||||
const saved = posts.filter((p) => p.path === "/api/groups/save").at(-1).body;
|
||||
assert.deepEqual([saved.sink, saved.noSink, saved.firstToken, saved.patience], [false, true, -1, 60]);
|
||||
|
||||
// opened again, it shows its own; Default sends none of them
|
||||
await (await reach(card.locator("button", { hasText: await tr("Edit") }))).click();
|
||||
await eSink.waitFor();
|
||||
assert.equal(await on(eSink), await tr("Keeps its place"));
|
||||
assert.equal(await on(eFirst), await tr("Wait"));
|
||||
assert.equal(await on(ePat), await tr("1 min"));
|
||||
for (const row of [eSink, eFirst, ePat]) await (await reach(row.locator(".opt", { hasText: new RegExp(`^${dflt}$`) }))).click();
|
||||
await (await reach(ed.locator("button.primary", { hasText: await tr("Save") }))).click();
|
||||
await page.waitForFunction(() => !document.querySelector(".rt-gedit"));
|
||||
const back = posts.filter((p) => p.path === "/api/groups/save").at(-1).body;
|
||||
assert.deepEqual([back.sink, back.noSink, back.firstToken, back.patience], [false, false, 0, 0]);
|
||||
assert.equal(await fits(), true, "the rows fit at " + width + " after the editor");
|
||||
|
||||
const missing = await page.evaluate(() => [
|
||||
"As set for every group under the list: {v}.", "Default", "Rate limited", "Slow to start", "Every member busy",
|
||||
"Keeps its place", "Goes to the back", "Wait", "Off", "30 s", "1 min", "2 min", "4 min",
|
||||
].flatMap((k) => ["zh", "zh-TW", "ja", "de"].filter((l) => !I18N[l][k]).map((l) => l + ": " + k)));
|
||||
assert.deepEqual(missing, [], "every string has its zh, zh-TW, ja and de");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A routing group may let a member go that is slow to begin its answer
|
||||
// (Chen on X: every answer waits on a slow vendor). The group editor's
|
||||
// "Slow to start" row picks Wait, 30 s, 1 min or 2 min, or Custom and as
|
||||
// many minutes as are typed (Kismet Alan on Discord), its hint saying what
|
||||
// each does; saved, the group is sent with firstToken in seconds and its
|
||||
// card says "Next after 60 s without a first token". Wait sends 0 and the
|
||||
// card says nothing. In five languages, Chromium and WebKit, at 1100 and 420.
|
||||
// "Slow to start" row picks Default (what the Settings card under the list
|
||||
// sets for every group, sent as 0), Wait (the group's own, sent as -1),
|
||||
// 30 s, 1 min or 2 min, or Custom and as many minutes as are typed (Kismet
|
||||
// Alan on Discord), its hint saying what each does; saved, the group is
|
||||
// sent with firstToken in seconds and its card says "Next after 60 s
|
||||
// without a first token". Wait and Default leave the card saying nothing. In five languages, Chromium and WebKit, at 1100 and 420.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
@@ -27,11 +28,11 @@ const groups = () => ({
|
||||
});
|
||||
|
||||
const words = {
|
||||
en: { edit: "Edit", save: "Save", label: "Slow to start", wait: "Wait", min: "1 min", tag: "Next after 60 s without a first token", waits: "Every member is waited for" },
|
||||
zh: { edit: "编辑", save: "保存", label: "迟迟不出字", wait: "一直等", min: "1 分钟", tag: "60 秒 无首字换下一个", waits: "每个成员都会一直等" },
|
||||
"zh-TW": { edit: "編輯", save: "儲存", label: "遲遲不出字", wait: "一直等", min: "1 分鐘", tag: "60 秒 無首字換下一個", waits: "每個成員都會一直等" },
|
||||
ja: { edit: "編集", save: "保存", label: "応答開始が遅いとき", wait: "待つ", min: "1 分", tag: "最初のトークンが 60 秒 なければ次へ", waits: "どのメンバーも" },
|
||||
de: { edit: "Bearbeiten", save: "Speichern", label: "Langsamer Start", wait: "Warten", min: "1 Min.", tag: "Nächstes nach 60 s ohne erstes Token", waits: "Auf jedes Mitglied wird gewartet" },
|
||||
en: { dflt: "Default", edit: "Edit", save: "Save", label: "Slow to start", wait: "Wait", min: "1 min", tag: "Next after 60 s without a first token", waits: "Every member is waited for" },
|
||||
zh: { dflt: "默认", edit: "编辑", save: "保存", label: "迟迟不出字", wait: "一直等", min: "1 分钟", tag: "60 秒 无首字换下一个", waits: "每个成员都会一直等" },
|
||||
"zh-TW": { dflt: "預設", edit: "編輯", save: "儲存", label: "遲遲不出字", wait: "一直等", min: "1 分鐘", tag: "60 秒 無首字換下一個", waits: "每個成員都會一直等" },
|
||||
ja: { dflt: "デフォルト", edit: "編集", save: "保存", label: "応答開始が遅いとき", wait: "待つ", min: "1 分", tag: "最初のトークンが 60 秒 なければ次へ", waits: "どのメンバーも" },
|
||||
de: { dflt: "Standard", edit: "Bearbeiten", save: "Speichern", label: "Langsamer Start", wait: "Warten", min: "1 Min.", tag: "Nächstes nach 60 s ohne erstes Token", waits: "Auf jedes Mitglied wird gewartet" },
|
||||
};
|
||||
const custom = { en: "Custom", zh: "自定义", "zh-TW": "自定義", ja: "カスタム", de: "Benutzerdefiniert" };
|
||||
|
||||
@@ -112,8 +113,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
const row = ed.locator("label", { hasText: w.label }).locator("xpath=following-sibling::div[1]");
|
||||
await row.waitFor();
|
||||
await reach(row);
|
||||
assert.equal(await row.locator(".opt.on").textContent(), w.wait);
|
||||
assert((await row.locator(".hint").textContent()).startsWith(w.waits));
|
||||
assert.equal(await row.locator(".opt.on").textContent(), w.dflt, "a group that sets none follows the default");
|
||||
assert((await row.locator(".hint").textContent()).includes(w.waits));
|
||||
await row.locator(".opt", { hasText: w.min }).click();
|
||||
const secs = (n) => page.evaluate((n) => t("{n} s", { n }), n);
|
||||
assert((await row.locator(".hint").textContent()).includes(await secs(60)));
|
||||
@@ -125,7 +126,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await reach(row);
|
||||
assert.equal(await row.locator(".opt.on").textContent(), w.min, "the editor opens at what was saved");
|
||||
await row.locator(".opt", { hasText: w.wait }).click();
|
||||
assert.equal((await save()).firstToken, 0);
|
||||
assert.equal((await save()).firstToken, -1, "Wait is the group's own");
|
||||
await page.waitForFunction((tag) => ![...document.querySelectorAll(".rt-group .tag")].some((x) => x.textContent === tag), w.tag);
|
||||
|
||||
// Custom: as many minutes as are typed, from 5 when it was Wait
|
||||
@@ -167,6 +168,12 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
assert.equal(await minutes.isVisible(), false);
|
||||
assert.equal((await save()).firstToken, 60);
|
||||
|
||||
await (await reach(card.locator("button", { hasText: w.edit }))).click();
|
||||
await row.waitFor();
|
||||
await reach(row);
|
||||
await row.locator(".opt", { hasText: w.dflt }).click();
|
||||
assert.equal((await save()).firstToken, 0, "the default is saved as none set");
|
||||
|
||||
const missing = await page.evaluate(() => [
|
||||
"Wait", "30 s", "1 min", "2 min", "Slow to start", "slow to start", "Next after {n} without a first token",
|
||||
"Every member is waited for, however long it takes to begin answering.",
|
||||
|
||||
@@ -96,7 +96,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
return [...s.children].map((c) => c.className).filter((c) => c !== "rt-goff");
|
||||
});
|
||||
assert.deepEqual(order.slice(0, 4), ["row-head", "list rt-groups", "row-head rt-gset-head", "list rt-gset"]);
|
||||
assert.deepEqual(await page.evaluate(() => [...document.querySelector(".rt-gset").children].map((c) => c.className)), ["rt-gfound", "rt-gnames"]);
|
||||
assert.deepEqual(await page.evaluate(() => [...document.querySelector(".rt-gset").children].map((c) => c.className)), ["rt-gfound", "rt-gnames", "rt-gdef rt-gdef-sink", "rt-gdef rt-gdef-first", "rt-gdef rt-gdef-patience"]);
|
||||
const border = await sw.evaluate((e) => { const c = getComputedStyle(e); return c.borderLeftWidth !== c.borderRightWidth || c.borderLeftColor !== c.borderRightColor; });
|
||||
assert.equal(border, false, "no left-border accent");
|
||||
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
// A routing group whose every member is busy at once — overloaded,
|
||||
// unavailable, rate limited for a moment — asks them again within a budget
|
||||
// rather than handing the agent the last one's error (#1418, Aliceonly).
|
||||
// The group editor's "Every member busy" row picks Off, 1 min (the
|
||||
// default, saved as 0), 2 min or 4 min, its hint saying what each does;
|
||||
// saved, the group is sent with patience in seconds, -1 for off. In
|
||||
// The group editor's "Every member busy" row picks Default (what the
|
||||
// Settings card under the list sets for every group, saved as 0), Off,
|
||||
// 1 min (saved as 60, the group's own), 2 min or 4 min, its hint saying
|
||||
// what each does; saved, the group is sent with patience in seconds, -1
|
||||
// for off. In
|
||||
// English and Chinese, Chromium and WebKit; every string has its Chinese,
|
||||
// Traditional Chinese, Japanese and German.
|
||||
const assert = require("node:assert/strict");
|
||||
@@ -27,8 +29,8 @@ const groups = () => ({
|
||||
});
|
||||
|
||||
const words = {
|
||||
en: { edit: "Edit", save: "Save", label: "Every member busy", off: "Off", def: "1 min", four: "4 min", on: "each is asked again after a pause", offHint: "gets the last one's error at once" },
|
||||
zh: { edit: "编辑", save: "保存", label: "成员全都忙", off: "关闭", def: "1 分钟", four: "4 分钟", on: "依次再问一遍每个成员", offHint: "立刻拿到最后一个的错误" },
|
||||
en: { edit: "Edit", save: "Save", label: "Every member busy", dflt: "Default", off: "Off", def: "1 min", four: "4 min", on: "each is asked again after a pause", offHint: "gets the last one's error at once" },
|
||||
zh: { edit: "编辑", save: "保存", label: "成员全都忙", dflt: "默认", off: "关闭", def: "1 分钟", four: "4 分钟", on: "依次再问一遍每个成员", offHint: "立刻拿到最后一个的错误" },
|
||||
};
|
||||
|
||||
function serve(lang, posts) {
|
||||
@@ -96,7 +98,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
return row;
|
||||
};
|
||||
let row = await open();
|
||||
assert.equal(await row.locator(".opt.on").textContent(), w.def, "1 min by default");
|
||||
assert.equal(await row.locator(".opt.on").textContent(), w.dflt, "a group that sets none follows the default");
|
||||
assert((await row.locator(".hint").textContent()).includes(w.on));
|
||||
await row.locator(".opt", { hasText: w.four }).click();
|
||||
assert((await row.locator(".hint").textContent()).includes(lang === "zh" ? "4 分" : "4 min"));
|
||||
@@ -111,6 +113,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
row = await open();
|
||||
assert.equal(await row.locator(".opt.on").textContent(), w.off);
|
||||
await row.locator(".opt", { hasText: w.def }).click();
|
||||
assert.equal((await save()).patience, 60, "1 min is the group's own");
|
||||
row = await open();
|
||||
assert.equal(await row.locator(".opt.on").textContent(), w.def);
|
||||
await row.locator(".opt", { hasText: w.dflt }).click();
|
||||
assert.equal((await save()).patience, 0, "the default is saved as none set");
|
||||
|
||||
const missing = await page.evaluate(() => {
|
||||
|
||||
+49
-11
@@ -149,15 +149,44 @@ const (
|
||||
)
|
||||
|
||||
// Waits is how long a request to the group may be kept for its members to
|
||||
// come back (Patience), 0 for not at all.
|
||||
// come back (Patience), 0 for not at all. A group that sets none follows
|
||||
// the default for every group (settings' GroupPatience, jiezhengj on
|
||||
// Discord), PatienceDefault while that is unset too.
|
||||
func (g Group) Waits() time.Duration {
|
||||
n := g.Patience
|
||||
if n == 0 {
|
||||
n = settings.Load().GroupPatience
|
||||
}
|
||||
switch {
|
||||
case g.Patience < 0:
|
||||
case n < 0:
|
||||
return 0
|
||||
case g.Patience == 0:
|
||||
case n == 0:
|
||||
return PatienceDefault * time.Second
|
||||
}
|
||||
return time.Duration(min(g.Patience, PatienceLongest)) * time.Second
|
||||
return time.Duration(min(n, PatienceLongest)) * time.Second
|
||||
}
|
||||
|
||||
// FirstTokenWait is a group's FirstToken when the user picked Wait for it
|
||||
// itself: every member waited for, whatever the default for every group.
|
||||
// 0 is a group that sets nothing, which follows that default.
|
||||
const FirstTokenWait = -1
|
||||
|
||||
// FirstTokenOr is the seconds the group lets a member take to its first
|
||||
// content: its own FirstToken, else the default for every group
|
||||
// (settings' GroupFirstToken); 0 or less waits as long as it takes.
|
||||
func (g Group) FirstTokenOr() int {
|
||||
if g.FirstToken != 0 {
|
||||
return g.FirstToken
|
||||
}
|
||||
return settings.Load().GroupFirstToken
|
||||
}
|
||||
|
||||
// Sinks is whether one of the group's accounts or keys rate limited with
|
||||
// quota left goes to the back (Sink): the group's own word, Sink or
|
||||
// NoSink, else the default for every group (settings' GroupSink). Whether
|
||||
// its routing can sink at all is the gateway's to say.
|
||||
func (g Group) Sinks() bool {
|
||||
return g.Sink || !g.NoSink && settings.Load().GroupSink
|
||||
}
|
||||
|
||||
// ContextSmallest is a group's Context when agents are told the window of
|
||||
@@ -192,19 +221,25 @@ type Group struct {
|
||||
// together: one rate limited with quota left goes behind every other
|
||||
// member's. Not for "rotate" or Manual.
|
||||
Sink bool `json:"sink,omitempty"`
|
||||
// NoSink is the user's Keeps its place for the group itself: none
|
||||
// sinks, whatever the default for every group says (Sinks). Neither
|
||||
// set, the group follows that default.
|
||||
NoSink bool `json:"noSink,omitempty"`
|
||||
// FirstToken is how many seconds a member's streamed reply may take to
|
||||
// its first content — text, reasoning or a tool call — before the next
|
||||
// member is asked instead, nothing of it having reached the agent; 0
|
||||
// waits as long as it takes. The last one left is always waited for,
|
||||
// and the slow one doesn't rest.
|
||||
// member is asked instead, nothing of it having reached the agent;
|
||||
// FirstTokenWait waits as long as it takes, and 0 follows the default
|
||||
// for every group (FirstTokenOr). The last one left is always waited
|
||||
// for, and the slow one doesn't rest.
|
||||
FirstToken int `json:"firstToken,omitempty"`
|
||||
// Patience is how many seconds more a request may be kept, once every
|
||||
// member has failed and nothing of a reply has been sent, for the
|
||||
// members that failed in a way that passes —
|
||||
// busy, overloaded, rate limited for a moment — to be asked again
|
||||
// after a pause, in turn, until one answers (#1418). 0 is
|
||||
// PatienceDefault; PatienceOff gives the agent the last one's error
|
||||
// once each has been asked.
|
||||
// after a pause, in turn, until one answers (#1418). 0 follows the
|
||||
// default for every group, PatienceDefault while that is unset (Waits);
|
||||
// PatienceOff gives the agent the last one's error once each has been
|
||||
// asked.
|
||||
Patience int `json:"patience,omitempty"`
|
||||
// Off are the members switched off: kept where they are in the
|
||||
// order, with their rules, but sent nothing until switched on again,
|
||||
@@ -1526,7 +1561,10 @@ func SaveGroup(g Group) error {
|
||||
if g.Name == "" {
|
||||
g.Name = g.ID
|
||||
}
|
||||
g.FirstToken = max(g.FirstToken, 0)
|
||||
g.FirstToken = max(g.FirstToken, FirstTokenWait)
|
||||
if g.Sink {
|
||||
g.NoSink = false
|
||||
}
|
||||
if g.Patience < 0 {
|
||||
g.Patience = PatienceOff
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// What a group sets wins; what it leaves unset follows the default for
|
||||
// every group in settings (jiezhengj on Discord), and with that unset too,
|
||||
// magpie's own: wait for a first token, keep one's place, a minute's
|
||||
// patience.
|
||||
func TestGroupDefaultsUnlessItsOwn(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
none := Group{}
|
||||
if none.Waits() != PatienceDefault*time.Second || none.FirstTokenOr() != 0 || none.Sinks() {
|
||||
t.Fatalf("magpie's own: %s %d %v", none.Waits(), none.FirstTokenOr(), none.Sinks())
|
||||
}
|
||||
if err := settings.SetGroupDefaults(true, 45, 200); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if none.Waits() != 200*time.Second || none.FirstTokenOr() != 45 || !none.Sinks() {
|
||||
t.Fatalf("default: %s %d %v", none.Waits(), none.FirstTokenOr(), none.Sinks())
|
||||
}
|
||||
own := Group{Patience: PatienceDefault, FirstToken: FirstTokenWait, NoSink: true}
|
||||
if own.Waits() != PatienceDefault*time.Second || own.FirstTokenOr() > 0 || own.Sinks() {
|
||||
t.Fatalf("own: %s %d %v", own.Waits(), own.FirstTokenOr(), own.Sinks())
|
||||
}
|
||||
if err := settings.SetGroupDefaults(false, 0, PatienceOff); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if none.Waits() != 0 {
|
||||
t.Fatalf("default off: %s", none.Waits())
|
||||
}
|
||||
if g := (Group{Patience: 120, Sink: true, FirstToken: 30}); g.Waits() != 120*time.Second || !g.Sinks() || g.FirstTokenOr() != 30 {
|
||||
t.Fatalf("own over off: %s %v %d", g.Waits(), g.Sinks(), g.FirstTokenOr())
|
||||
}
|
||||
// a value no setting can hold is refused, and the file kept
|
||||
for _, bad := range [][2]int{{-2, 0}, {0, -2}, {0, PatienceLongest + 1}} {
|
||||
if err := settings.SetGroupDefaults(false, bad[0], bad[1]); err == nil {
|
||||
t.Fatalf("%v saved", bad)
|
||||
}
|
||||
}
|
||||
if none.Waits() != 0 {
|
||||
t.Fatalf("after refusals: %s", none.Waits())
|
||||
}
|
||||
|
||||
// Wait, a minute and Keeps its place are kept as the group's own
|
||||
if err := Save(Provider{ID: "a", Name: "a", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"x"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SaveGroup(Group{Name: "Own", Members: []string{"a/x"}, Routing: Ordered, FirstToken: FirstTokenWait, Patience: PatienceDefault, NoSink: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g, _, _ := FindGroup("group/own")
|
||||
if g.FirstToken != FirstTokenWait || g.Patience != PatienceDefault || !g.NoSink {
|
||||
t.Fatalf("saved: %+v", g)
|
||||
}
|
||||
// Sink and NoSink both: Sink
|
||||
if err := SaveGroup(Group{ID: "own", Name: "Own", Members: []string{"a/x"}, Routing: Ordered, Sink: true, NoSink: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if g, _, _ := FindGroup("group/own"); !g.Sink || g.NoSink {
|
||||
t.Fatalf("both: %+v", g)
|
||||
}
|
||||
}
|
||||
@@ -510,6 +510,17 @@ type Settings struct {
|
||||
// haiku needed more than 8): from 1 to ClassifyTimeoutMost, 0 for
|
||||
// ClassifyTimeoutDefault. ClassifyWait reads it.
|
||||
ClassifyTimeout int `json:"classifyTimeout,omitempty"`
|
||||
// GroupSink, GroupFirstToken and GroupPatience are what every routing
|
||||
// group does that says nothing of its own (jiezhengj on Discord: set
|
||||
// once, not in each group), as provider.Group's Sink, FirstToken and
|
||||
// Patience: one rate limited with quota left goes to the back; the
|
||||
// seconds a member may take to its first token, 0 to wait; the seconds
|
||||
// a request is kept while every member is busy, 0 for
|
||||
// provider.PatienceDefault and -1 for off. A group that sets its own
|
||||
// keeps it (provider.Group.Sinks, FirstTokenOr, Waits).
|
||||
GroupSink bool `json:"groupSink,omitempty"`
|
||||
GroupFirstToken int `json:"groupFirstToken,omitempty"`
|
||||
GroupPatience int `json:"groupPatience,omitempty"`
|
||||
// BusyLoad puts a model whose plugin reports it busier than this
|
||||
// percent behind the others it could go to (plugin.ModelLoad,
|
||||
// axelburks on Discord): from 1 to BusyLoadMost-1, past 100 for a
|
||||
@@ -1978,6 +1989,21 @@ func EditCheckinOff(edit func([]string) []string) error {
|
||||
return save(s, false)
|
||||
}
|
||||
|
||||
// SetGroupDefaults sets what every routing group follows when it sets no
|
||||
// value of its own (GroupSink, GroupFirstToken, GroupPatience), from what
|
||||
// the file holds now, so a save elsewhere from an older snapshot isn't
|
||||
// undone. A settings file that can't be read is left as it is, with the
|
||||
// error.
|
||||
func SetGroupDefaults(sink bool, firstToken, patience int) error {
|
||||
defer lockFile()()
|
||||
s, err := loadChecked()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.GroupSink, s.GroupFirstToken, s.GroupPatience = sink, firstToken, patience
|
||||
return save(s, false)
|
||||
}
|
||||
|
||||
// EditUsageAliases changes UsageAliases alone, as edit returns them from
|
||||
// what the file holds now, so a save elsewhere from an older snapshot isn't
|
||||
// undone. A settings file that can't be read is left as it is, with the
|
||||
@@ -2159,6 +2185,14 @@ func saveOwn(s Settings, recording, reads bool) error {
|
||||
if s.ClassifyTimeout < 0 || s.ClassifyTimeout > ClassifyTimeoutMost {
|
||||
return fmt.Errorf("a routing group's classifier is given from 1 to %d seconds, or 0 for %d, not %d", ClassifyTimeoutMost, ClassifyTimeoutDefault, s.ClassifyTimeout)
|
||||
}
|
||||
if s.GroupFirstToken < 0 {
|
||||
return fmt.Errorf("a routing group's member is given a number of seconds to its first token, or 0 to wait, not %d", s.GroupFirstToken)
|
||||
}
|
||||
// provider.PatienceOff and provider.PatienceLongest, which settings
|
||||
// can't import
|
||||
if s.GroupPatience < -1 || s.GroupPatience > 240 {
|
||||
return fmt.Errorf("a routing group whose every member is busy waits from 1 to 240 seconds, 0 for 60 or -1 for not at all, not %d", s.GroupPatience)
|
||||
}
|
||||
if s.SearchCount < 0 || s.SearchCount > SearchCountMost {
|
||||
return fmt.Errorf("a search is answered with from 1 to %d results, or 0 for %d, not %d", SearchCountMost, SearchCountDefault, s.SearchCount)
|
||||
}
|
||||
|
||||
@@ -47,6 +47,8 @@ var Keys = []string{
|
||||
// models: replies, vision, images, search
|
||||
"replyModel", "noLoopGuard", "claudeLeanPrompt", "claudePrintMode", "refusalRetries", "retryAfterCap",
|
||||
"vision", "visionEffort", "imageGen", "imageTimeout", "classifyTimeout",
|
||||
// what every routing group does that says nothing of its own
|
||||
"groupSink", "groupFirstToken", "groupPatience",
|
||||
"searcher", "searcherThen", "searcherEffort", "searchFirst",
|
||||
// updates
|
||||
"noUpdatePill", "noAutoUpdate", "updateEvery", "noAutoDownload", "autoRestart", "updateChannel",
|
||||
@@ -211,6 +213,17 @@ func Merge(body []byte, cur settings.Settings, web bool) (settings.Settings, err
|
||||
if _, sent := fields["classifyTimeout"]; !sent {
|
||||
in.ClassifyTimeout = cur.ClassifyTimeout
|
||||
}
|
||||
// nor what every routing group does that says nothing of its own,
|
||||
// which the Routing groups page sets (jiezhengj on Discord)
|
||||
if _, sent := fields["groupSink"]; !sent {
|
||||
in.GroupSink = cur.GroupSink
|
||||
}
|
||||
if _, sent := fields["groupFirstToken"]; !sent {
|
||||
in.GroupFirstToken = cur.GroupFirstToken
|
||||
}
|
||||
if _, sent := fields["groupPatience"]; !sent {
|
||||
in.GroupPatience = cur.GroupPatience
|
||||
}
|
||||
// nor whether animations are stilled (#3813)
|
||||
if _, sent := fields["reduceMotion"]; !sent {
|
||||
in.ReduceMotion = cur.ReduceMotion
|
||||
|
||||
Reference in New Issue
Block a user