routing: a group's pattern members can be put in order by hand (usrname1833)
In a routing group, members a pattern added followed the catalog's
order. The editor gave them no grip or Up/Down, and the gateway tried
them in that order. Now every row gets the same grip, Alt+arrow and
Up/Down that named members have. Matched rows still have no Remove,
since the pattern decides those.
The order is stored as Group.Placed, keyed by provider/model as Members
spells them. It is nil while the order equals the default (named, then
matched in catalog order), so existing groups.json files don't change.
Read (withMatches -> placedIn): members follow Placed. A model matched
since goes after them, and one no longer matched drops out. The gateway
tries members in the order the group is read, so it follows the editor.
Saved (SaveGroup -> placedOver): Members orders the named members, and
Placed (sent, or the stored one when a save doesn't send it) places the
matched ones. A save that doesn't know Placed (card routing, the CLI's
models+=, TUI, import) keeps the matched where they were, and a model it
names newly goes after the last named one. A provider rename, fold,
group rename and RenameMember carry Placed along.
Run:
- go test -timeout 45m -count=1 ./... on mote: 80 packages ok.
internal/gui fails 10 AppKit window tests at 30s (TestDockJoinLeadsCommandTab,
TestPanelCloseHidesIt, TestMainWindowCorners, ...). On a fresh origin/main
cf9ea977c the five I reran fail the same way. That is mote's #4125 (open).
- TestGroupPatternMembersKeepTheirPlace is red on the old code
(read [zen/y or/a:free or/c:free]).
- Broken by hand, each red at its own step: no stored-Placed fallback
("after a named-only save"), a newly named model put last instead of
after the last named one ("after an add"). On the earlier draft, no
rename mapping ("after a rename").
- GUI: group-member-drag and group-patterns in chromium and webkit on
Linux (wsl-run), 8/8 at this head. group-member-drag was red on the old
client.js. The whole GUI suite ran at the draft before the save
payload's `placed` field. It was still running when this was pushed,
and its reds will be filed once it ends.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet of provider and
gateway on mote.
Not tried: a real account or the real app's window; WebKit on macOS
(mote's browser launches hang, #4125), so WebKit only on Linux. The TUI
has no way to reorder matched members; it keeps the stored order.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -5951,19 +5951,18 @@ function routingPage(part) {
|
||||
const sortBtn = el("button", "text rt-wsort", t("Sort by weight"));
|
||||
sortBtn.type = "button";
|
||||
sortBtn.title = t("Heaviest first. When a model fails, the next one in this order takes over");
|
||||
const byWeight = () => d.members.slice(0, named()).map((id, i) => [id, i]).sort(([a, i], [b, j]) => Math.max(d.weights[b] || 0, 1) - Math.max(d.weights[a] || 0, 1) || i - j).map(([id]) => id);
|
||||
sortBtn.onclick = () => { d.members.splice(0, named(), ...byWeight()); draw(); };
|
||||
// moveMember puts the member at `from` at `to` among those named — a
|
||||
// pattern's follow them, in the catalog's order — and keeps the
|
||||
// keyboard on its handle when it was there
|
||||
const named = () => d.members.filter((x) => !d.matched.includes(x)).length;
|
||||
const byWeight = () => d.members.map((id, i) => [id, i]).sort(([a, i], [b, j]) => Math.max(d.weights[b] || 0, 1) - Math.max(d.weights[a] || 0, 1) || i - j).map(([id]) => id);
|
||||
sortBtn.onclick = () => { d.members = byWeight(); draw(); };
|
||||
// moveMember puts the member at `from` at `to`, a pattern's as well as
|
||||
// one named (usrname1833 on Discord: provider.Group.Placed), and keeps
|
||||
// the keyboard on its handle when it was there
|
||||
const moveMember = (from, to, keep) => {
|
||||
if (to < 0 || to >= named() || to === from) return;
|
||||
if (to < 0 || to >= d.members.length || to === from) return;
|
||||
d.members.splice(to, 0, d.members.splice(from, 1)[0]);
|
||||
draw();
|
||||
if (keep) list.querySelector(`.rt-mhandle[data-at="${to}"]`)?.focus({ preventScroll: true });
|
||||
};
|
||||
// memberHandle is a named member's place in the order, which is also
|
||||
// memberHandle is a member's place in the order, which is also
|
||||
// its handle (PAMI on Discord: only Up, one step a click): drag it to
|
||||
// move the model, or Alt+↑/↓ from the keyboard; Up and Down stay
|
||||
// beside it. The grip that says so shows only on hover, as on the
|
||||
@@ -6053,7 +6052,7 @@ function routingPage(part) {
|
||||
sw.append(el("i"));
|
||||
sw.onclick = () => { d.off = off ? d.off.filter((x) => x !== id) : [...d.off, id]; draw(); };
|
||||
if (off) row.classList.add("muted");
|
||||
row.append(sw, matched ? el("span", "i", String(i + 1)) : memberHandle(id, i, row), memberIcon(id), n, el("span", "grow"));
|
||||
row.append(sw, memberHandle(id, i, row), memberIcon(id), n, el("span", "grow"));
|
||||
// what the model is, in the same chips the Gateway page's list says it
|
||||
// in (modelInfo): its reasoning levels, whether it sees images and the
|
||||
// window it holds. A group mixing members that see images with ones
|
||||
@@ -6150,6 +6149,8 @@ function routingPage(part) {
|
||||
if (d.routing === "weight") row.append(memberWeight(id, off));
|
||||
if (s) row.title = s.members.map((x) => memberLabel(s, x)).join(s.routing === "order" ? " → " : " · ");
|
||||
if (!m && !s) { row.classList.add("off"); row.title = info?.providerOff ? offWords(info) : t("No provider serves {id} now; it is skipped", { id }); }
|
||||
if (i) { const up = el("button", "text", t("Up")); up.onclick = () => moveMember(i, i - 1); row.append(up); }
|
||||
if (i < d.members.length - 1) { const down = el("button", "text", t("Down")); down.onclick = () => moveMember(i, i + 1); row.append(down); }
|
||||
if (matched) {
|
||||
// a pattern's: it follows the catalog, so it is switched off
|
||||
// rather than taken out — the pattern would find it again
|
||||
@@ -6157,8 +6158,6 @@ function routingPage(part) {
|
||||
list.append(row);
|
||||
return;
|
||||
}
|
||||
if (i) { const up = el("button", "text", t("Up")); up.onclick = () => moveMember(i, i - 1); row.append(up); }
|
||||
if (i < named() - 1) { const down = el("button", "text", t("Down")); down.onclick = () => moveMember(i, i + 1); row.append(down); }
|
||||
const rm = el("button", "text", t("Remove"));
|
||||
rm.onclick = () => { d.members.splice(i, 1); rematch(); draw(); drawRules(); };
|
||||
row.append(rm);
|
||||
@@ -6194,7 +6193,7 @@ function routingPage(part) {
|
||||
openPicker({ id: "", name: "", fields: [] }, { key: "member", label: "model", value: "", options, multi: true, picked: (id) => !!holding(id), onPick: (id) => {
|
||||
if (!id) return;
|
||||
const m = holding(id);
|
||||
if (!m) d.members.splice(named(), 0, id); // after those named, before a pattern's
|
||||
if (!m) d.members.splice(d.members.findLastIndex((x) => !d.matched.includes(x)) + 1, 0, id); // after the last named
|
||||
else if (d.matched.includes(m)) return status(t("In the group by a pattern: switch it off to send it nothing"), "warn");
|
||||
else { d.members.splice(d.members.indexOf(m), 1); rematch(); }
|
||||
draw(); drawRules();
|
||||
@@ -6209,11 +6208,14 @@ function routingPage(part) {
|
||||
ed.append(el("label", "", t("Models")), mw);
|
||||
|
||||
// patterns: models found by their ids, now and as providers list new
|
||||
// ones (#766); what they match follows the models named above
|
||||
// ones (#766): after the models named, in the catalog's order, until
|
||||
// the user puts them in another; then each keeps its place, one gone
|
||||
// drops out and one new goes last
|
||||
function rematch() {
|
||||
const named = d.members.filter((x) => !d.matched.includes(x));
|
||||
const named = d.members.filter((x) => !d.matched.includes(x)), was = [...named, ...d.matched];
|
||||
const placed = d.members.some((x, i) => x !== was[i]);
|
||||
d.matched = matchedBy(d.match, named);
|
||||
d.members = [...named, ...d.matched];
|
||||
d.members = placed ? [...d.members.filter((x) => named.includes(x) || d.matched.includes(x)), ...d.matched.filter((x) => !d.members.includes(x))] : [...named, ...d.matched];
|
||||
// a rule keeps the models still here; it goes with its last
|
||||
d.rules = d.rules.filter((r) => { setUses(r, rUses(r).filter((x) => d.members.includes(x))); return !!r.use; });
|
||||
d.fast = d.fast.filter((x) => d.members.includes(x));
|
||||
@@ -7075,7 +7077,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), 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 : "", 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)), 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 && 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 : "", 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)), 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
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
// one step a click). In the editor a named member's number is its handle,
|
||||
// with a grip beside it drawn only while the row is under the pointer;
|
||||
// dragging it moves the model, Alt+↑/↓ moves it from the keyboard, which
|
||||
// stays on it, and Up and Down stay beside it. A pattern's members follow
|
||||
// the named ones and have no handle. Saved, the members go in the new
|
||||
// order. No click or drag moves the page. In English and Chinese, Chromium
|
||||
// and WebKit.
|
||||
// stays on it, and Up and Down stay beside it. A pattern's members are
|
||||
// moved the same way (usrname1833 on Discord), among the named ones too.
|
||||
// Saved, the order of them all goes as placed. No click
|
||||
// or drag moves the page. In English and Chinese, Chromium and WebKit.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
@@ -80,21 +80,21 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
const row = (name) => ed.locator(".fbrow", { has: page.locator(".n > span:first-child", { hasText: new RegExp(`^${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`) }) });
|
||||
const handle = (name) => row(name).locator(".rt-mhandle");
|
||||
|
||||
// every named member has a handle with its number; the pattern's none
|
||||
assert.deepEqual(await ed.locator(".fbrow .rt-mhandle").allTextContents(), ["1", "2", "3"]);
|
||||
assert.equal(await handle("free:free").count(), 0, "a pattern's member has a handle");
|
||||
// every member has a handle with its number, a pattern's too
|
||||
assert.deepEqual(await ed.locator(".fbrow .rt-mhandle").allTextContents(), ["1", "2", "3", "4"]);
|
||||
assert.equal(await handle("two").getAttribute("aria-label"), w.move);
|
||||
// Up on all but the first named, Down on all but the last named
|
||||
// Up on all but the first, Down on all but the last
|
||||
const btns = async (name) => row(name).locator("button.text").allTextContents();
|
||||
assert(!(await btns("one")).includes(w.up) && (await btns("one")).includes(w.down));
|
||||
assert((await btns("three")).includes(w.up) && !(await btns("three")).includes(w.down));
|
||||
assert((await btns("three")).includes(w.up) && (await btns("three")).includes(w.down));
|
||||
assert((await btns("free:free")).includes(w.up) && !(await btns("free:free")).includes(w.down));
|
||||
|
||||
// the grip shows on the row under the pointer only
|
||||
await page.mouse.move(1, 1);
|
||||
const grip = (name) => handle(name).evaluate((h) => getComputedStyle(h, "::before").opacity);
|
||||
assert.equal(await grip("two"), "0");
|
||||
await row("two").locator(".n").hover();
|
||||
await page.waitForFunction(() => [...document.querySelectorAll(".rt-mhandle")].map((h) => getComputedStyle(h, "::before").opacity).join() === "0,1,0");
|
||||
await page.waitForFunction(() => [...document.querySelectorAll(".rt-mhandle")].map((h) => getComputedStyle(h, "::before").opacity).join() === "0,1,0,0");
|
||||
|
||||
await ed.evaluate((x) => x.scrollIntoView({ block: "center" })); // by the test, as the reader would
|
||||
await page.waitForTimeout(200);
|
||||
@@ -115,14 +115,21 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await page.keyboard.press("Alt+ArrowDown");
|
||||
assert.deepEqual(await order(), ["three", "two", "one", "free:free"]);
|
||||
assert.equal(await page.evaluate(() => document.activeElement?.closest(".fbrow")?.querySelector(".n > span")?.textContent), "one", "the keyboard left the moved model");
|
||||
// it never goes past the pattern's
|
||||
// past a pattern's too
|
||||
await page.keyboard.press("Alt+ArrowDown");
|
||||
assert.deepEqual(await order(), ["three", "two", "one", "free:free"]);
|
||||
assert.deepEqual(await order(), ["three", "two", "free:free", "one"]);
|
||||
// Down and Up still move it a step
|
||||
await row("three").locator("button.text", { hasText: w.down }).click();
|
||||
assert.deepEqual(await order(), ["two", "three", "one", "free:free"]);
|
||||
assert.deepEqual(await order(), ["two", "three", "free:free", "one"]);
|
||||
await row("one").locator("button.text", { hasText: w.up }).click();
|
||||
assert.deepEqual(await order(), ["two", "one", "three", "free:free"]);
|
||||
assert.deepEqual(await order(), ["two", "three", "one", "free:free"]);
|
||||
// a pattern's dragged to the top
|
||||
const hf = await handle("free:free").boundingBox(), first = await row("two").boundingBox();
|
||||
await page.mouse.move(hf.x + hf.width / 2, hf.y + hf.height / 2);
|
||||
await page.mouse.down();
|
||||
for (let i = 1; i <= 8; i++) await page.mouse.move(hf.x + hf.width / 2, hf.y + hf.height / 2 - ((hf.y - first.y + 6) * i) / 8);
|
||||
await page.mouse.up();
|
||||
assert.deepEqual(await order(), ["free:free", "two", "three", "one"], "a pattern's was dragged");
|
||||
assert.equal(await at(), before, "a click or drag moved the page");
|
||||
|
||||
const b = ed.locator("button.primary", { hasText: w.save });
|
||||
@@ -135,7 +142,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await page.mouse.click(bb.x + bb.width / 2, bb.y + bb.height / 2);
|
||||
await page.waitForFunction(() => !document.querySelector(".rt-gedit"));
|
||||
const sent = posts.find((p) => p.path === "/api/groups/save");
|
||||
assert.deepEqual(sent.body.members.slice(0, 3), ["a/two", "a/one", "b/three"]);
|
||||
assert.deepEqual(sent.body.members, ["a/two", "b/three", "a/one"]);
|
||||
assert.deepEqual(sent.body.placed, ["c/free:free", "a/two", "b/three", "a/one"], "the order, a pattern's among them");
|
||||
|
||||
const missing = await page.evaluate(() => ["Down", "Move {name}", "Drag to reorder · Alt+↑/↓ to move"].filter((k) => !I18N.zh[k] || !I18N.ja[k] || !I18N.de[k]));
|
||||
assert.deepEqual(missing, [], "every string has its Chinese, Japanese and German");
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
// In the editor the matched models follow those named, marked "by pattern",
|
||||
// with an off switch and no Remove; a pattern is added and removed in its
|
||||
// own box, its models coming and going with it. Saved, the group sends the
|
||||
// models it names and its patterns, never what they matched. In English and
|
||||
// Chinese.
|
||||
// models it names and its patterns, never what they matched, and the
|
||||
// order of them all (placed). In English and Chinese.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
@@ -125,6 +125,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await page.waitForFunction(() => !document.querySelector(".rt-gedit"));
|
||||
const sent = posts.find((p) => p.path === "/api/groups/save");
|
||||
assert.deepEqual(sent.body.members, ["an/claude-opus-5-5"], "only the models named are sent");
|
||||
assert.deepEqual(sent.body.placed, ["an/claude-opus-5-5", "zen/d-free"], "and the order of them all");
|
||||
assert.deepEqual(sent.body.match, ["nope/*", "*-free"]);
|
||||
assert.deepEqual(sent.body.off, ["zen/d-free"], "a matched model may be off");
|
||||
|
||||
|
||||
@@ -342,6 +342,7 @@ func foldWhere(candidates func([]Provider) [][]int) (int, error) {
|
||||
g.Rules[k].MapUses(ref)
|
||||
}
|
||||
g.Fast = compact(mapEach(g.Fast, ref))
|
||||
g.Placed = compact(mapEach(g.Placed, ref))
|
||||
g.Off = compact(mapEach(g.Off, ref))
|
||||
g.Weights = renamedWeights(g.Weights, ref)
|
||||
g.Classifier = ref(g.Classifier)
|
||||
|
||||
@@ -177,7 +177,15 @@ type Group struct {
|
||||
Match []string `json:"match,omitempty"`
|
||||
// Matched are the members the patterns match now, as Members has them
|
||||
// after its own. Derived each time the group is read, never stored.
|
||||
Matched []string `json:"matched,omitempty"`
|
||||
Matched []string `json:"matched,omitempty"`
|
||||
// Placed is the order the user put the members in, those the
|
||||
// patterns match among those it names (usrname1833 on Discord), as
|
||||
// Members spells them. Read, the members follow it: a model matched
|
||||
// since comes after them in the catalog's order, and one no longer
|
||||
// matched drops out (placedIn). Empty when it is the order the group
|
||||
// has unasked, its own members first, then the matched. Saved, it
|
||||
// places the matched; the named go in Members' order (placedOver).
|
||||
Placed []string `json:"placed,omitempty"`
|
||||
Routing string `json:"routing,omitempty"` // as Provider.Routing, over all the members' keys and accounts; or Manual
|
||||
Affinity string `json:"affinity,omitempty"` // as Provider.Affinity
|
||||
// Sink is Provider.Sink over the group's members' accounts and keys
|
||||
@@ -399,7 +407,7 @@ func cloneGroups(gs []Group) []Group {
|
||||
}
|
||||
out := make([]Group, len(gs))
|
||||
for i, g := range gs {
|
||||
g.Members, g.Match, g.Matched = slices.Clone(g.Members), slices.Clone(g.Match), slices.Clone(g.Matched)
|
||||
g.Members, g.Match, g.Matched, g.Placed = slices.Clone(g.Members), slices.Clone(g.Match), slices.Clone(g.Matched), slices.Clone(g.Placed)
|
||||
g.Off, g.Levels, g.Fast = slices.Clone(g.Off), slices.Clone(g.Levels), slices.Clone(g.Fast)
|
||||
g.Weights = maps.Clone(g.Weights)
|
||||
if g.Rules != nil {
|
||||
@@ -514,6 +522,7 @@ func (g Group) own() Group {
|
||||
g.Members = slices.Clone(g.Members)
|
||||
g.Match = slices.Clone(g.Match)
|
||||
g.Matched = slices.Clone(g.Matched)
|
||||
g.Placed = slices.Clone(g.Placed)
|
||||
g.Off = slices.Clone(g.Off)
|
||||
g.Levels = slices.Clone(g.Levels)
|
||||
g.Fast = slices.Clone(g.Fast)
|
||||
@@ -1366,6 +1375,23 @@ func SaveGroup(g Group) error {
|
||||
}
|
||||
own := cleanList(g.Members[:named])
|
||||
g.Members = append(slices.Clone(own), slices.DeleteFunc(cleanList(g.Members[named:]), func(m string) bool { return slices.Contains(own, m) })...)
|
||||
// the order the user put them in, a pattern's members among them: as
|
||||
// the caller sends it (the Routing page's editor), or as it was. The
|
||||
// models named go in the order the caller names them, so one added
|
||||
// to a group as read (models+=, the TUI) goes after those named
|
||||
before := g.Placed
|
||||
if len(before) == 0 {
|
||||
if i := slices.IndexFunc(f.Groups, func(x Group) bool { return x.ID == g.ID }); i >= 0 {
|
||||
before = f.Groups[i].Placed
|
||||
}
|
||||
}
|
||||
key := func(m string) string {
|
||||
id, _ := memberFastIn(entries, strings.TrimSpace(m))
|
||||
return cleanMember(entries, id)
|
||||
}
|
||||
if g.Placed = placedOver(g.Members, mapEach(before, key), mapEach(members, key)); g.Placed != nil {
|
||||
own = slices.DeleteFunc(slices.Clone(g.Placed), func(m string) bool { return !slices.Contains(own, m) })
|
||||
}
|
||||
var off []string
|
||||
for _, m := range cleanList(g.Off) {
|
||||
if m = cleanMember(entries, m); slices.Contains(g.Members, m) && !slices.Contains(off, m) {
|
||||
@@ -1780,6 +1806,11 @@ func RenameGroup(from, to string) error {
|
||||
f.Groups[i].Members[j] = now
|
||||
}
|
||||
}
|
||||
for j, m := range f.Groups[i].Placed {
|
||||
if m == old {
|
||||
f.Groups[i].Placed[j] = now
|
||||
}
|
||||
}
|
||||
for j := range f.Groups[i].Rules {
|
||||
f.Groups[i].Rules[j].MapUses(func(u string) string {
|
||||
if u == old {
|
||||
|
||||
@@ -250,6 +250,11 @@ func (g *Group) RenameMember(from, to string) {
|
||||
g.Fast[i] = to
|
||||
}
|
||||
}
|
||||
for i, p := range g.Placed {
|
||||
if p == from {
|
||||
g.Placed[i] = to
|
||||
}
|
||||
}
|
||||
for i, o := range g.Off {
|
||||
if o == from {
|
||||
g.Off[i] = to
|
||||
|
||||
@@ -12,8 +12,9 @@ package provider
|
||||
// again. Every reader — the gateway's routing, /v1/models, rules, the
|
||||
// Routing view, the TUI and the CLI — gets the group from there, so all of
|
||||
// them see the same members: those the user named, in their order, then
|
||||
// those the patterns match, in the catalog's order. A model named and
|
||||
// matched both keeps the place it was named at.
|
||||
// those the patterns match, in the catalog's order, or in the order the
|
||||
// user put them in (Group.Placed). A model named and matched both keeps
|
||||
// the place it was named at.
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -115,16 +116,92 @@ func matchesIn(entries []Entry, g Group) []string {
|
||||
}
|
||||
|
||||
// withMatches is a stored group as it is read: the members its patterns
|
||||
// match now after those it names (Matched says which they are).
|
||||
// match now after those it names (Matched says which they are), or in
|
||||
// the order the user put them in (Placed).
|
||||
func withMatches(entries []Entry, g Group) Group {
|
||||
if len(g.Match) == 0 {
|
||||
return g
|
||||
}
|
||||
g.Matched = matchesIn(entries, g)
|
||||
g.Members = append(slices.Clone(g.Members), g.Matched...)
|
||||
g.Members = placedIn(append(slices.Clone(g.Members), g.Matched...), g.Placed)
|
||||
return g
|
||||
}
|
||||
|
||||
// placedIn are members in the order placed has them: those it names
|
||||
// first, as it has them, then the rest in their own order — a model a
|
||||
// pattern matches since it was placed, at the end. One placed that isn't
|
||||
// a member now is left out.
|
||||
func placedIn(members, placed []string) []string {
|
||||
if len(placed) == 0 {
|
||||
return members
|
||||
}
|
||||
in := make(map[string]bool, len(members))
|
||||
for _, m := range members {
|
||||
in[m] = true
|
||||
}
|
||||
out := make([]string, 0, len(members))
|
||||
for _, p := range placed {
|
||||
if in[p] {
|
||||
out = append(out, p)
|
||||
delete(in, p)
|
||||
}
|
||||
}
|
||||
for _, m := range members {
|
||||
if in[m] {
|
||||
out = append(out, m)
|
||||
delete(in, m)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// placedOver is the Placed a group is saved with: its members (named
|
||||
// first, then the matched) in the order placed before (the caller's, or
|
||||
// the one stored), with those the caller names (given) put in the places
|
||||
// those have, in the caller's order. So the named are reordered as the
|
||||
// caller says and the pattern's stay where they were placed; a model
|
||||
// named since goes after the last one named, one matched since last.
|
||||
// nil when that is the members' own order.
|
||||
func placedOver(members, before, given []string) []string {
|
||||
if len(before) == 0 {
|
||||
return nil
|
||||
}
|
||||
sent := map[string]bool{}
|
||||
var order []string
|
||||
for _, m := range given {
|
||||
if !sent[m] && slices.Contains(members, m) {
|
||||
sent[m] = true
|
||||
order = append(order, m)
|
||||
}
|
||||
}
|
||||
var seq []string
|
||||
for _, m := range before {
|
||||
if slices.Contains(members, m) && !slices.Contains(seq, m) {
|
||||
seq = append(seq, m)
|
||||
}
|
||||
}
|
||||
for _, m := range order {
|
||||
if !slices.Contains(seq, m) {
|
||||
at := len(seq)
|
||||
for at > 0 && !sent[seq[at-1]] {
|
||||
at--
|
||||
}
|
||||
seq = slices.Insert(seq, at, m)
|
||||
}
|
||||
}
|
||||
seq = placedIn(members, seq)
|
||||
for i, j := 0, 0; i < len(seq); i++ {
|
||||
if sent[seq[i]] {
|
||||
seq[i] = order[j]
|
||||
j++
|
||||
}
|
||||
}
|
||||
if slices.Equal(seq, members) {
|
||||
return nil
|
||||
}
|
||||
return seq
|
||||
}
|
||||
|
||||
// ownMembers are the members a group names itself and its patterns, from a
|
||||
// group as it was read: the members its patterns matched (Matched) are
|
||||
// left out, so that saving a group never writes today's matches into it,
|
||||
|
||||
@@ -93,6 +93,93 @@ func TestGroupPatterns(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The members a pattern matches are put in order by hand as a named one
|
||||
// is (usrname1833 on Discord): the group is read, and routed, in the order
|
||||
// the user put them in, a model matched since joins at the end in the
|
||||
// catalog's order, one no longer matched drops out, and the order is kept
|
||||
// through a save that sends the named members only, and a provider's
|
||||
// rename.
|
||||
func TestGroupPatternMembersKeepTheirPlace(t *testing.T) {
|
||||
patternHome(t)
|
||||
or := func(models ...string) {
|
||||
t.Helper()
|
||||
if err := Save(Provider{ID: "or", Name: "OR", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: models}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
or("a:free", "b", "c:free")
|
||||
if err := Save(Provider{ID: "zen", Name: "Zen", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"y"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SaveGroup(Group{Name: "Free", Members: []string{"zen/y", "or/*:free"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := routedIDs(t, "group/free"); !slices.Equal(got, []string{"zen/y", "or/a:free", "or/c:free"}) {
|
||||
t.Fatalf("unplaced: %v", got)
|
||||
}
|
||||
// dragged in the Routing page's editor, which sends the order:
|
||||
// a matched one first, the named one between
|
||||
g, _, _ := FindGroup("group/free")
|
||||
g.Placed = []string{"or/c:free", "zen/y", "or/a:free"}
|
||||
if err := SaveGroup(g); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{"or/c:free", "zen/y", "or/a:free"}
|
||||
if g, _, _ := FindGroup("group/free"); !slices.Equal(g.Members, want) || !slices.Equal(g.Matched, []string{"or/a:free", "or/c:free"}) {
|
||||
t.Fatalf("read: %v matched %v", g.Members, g.Matched)
|
||||
}
|
||||
if got := routedIDs(t, "group/free"); !slices.Equal(got, want) {
|
||||
t.Fatalf("routed: %v", got)
|
||||
}
|
||||
if s, _ := StoredGroups(); !slices.Equal(s[0].Members, []string{"zen/y"}) {
|
||||
t.Fatalf("stored members: %v", s[0].Members)
|
||||
}
|
||||
// a save of the named ones only (the card's routing menu) keeps it
|
||||
if err := SaveGroup(Group{ID: "free", Name: "Free", Members: []string{"zen/y"}, Match: []string{"or/*:free"}, Routing: Ordered}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := routedIDs(t, "group/free"); !slices.Equal(got, want) {
|
||||
t.Fatalf("after a named-only save: %v", got)
|
||||
}
|
||||
// the vendor drops one and adds another: gone, and joined at the end
|
||||
or("b", "c:free", "d:free")
|
||||
if got := routedIDs(t, "group/free"); !slices.Equal(got, []string{"or/c:free", "zen/y", "or/d:free"}) {
|
||||
t.Fatalf("after the catalog changed: %v", got)
|
||||
}
|
||||
// the provider renamed: its models keep their places
|
||||
if err := Rename("or", "op"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SaveGroup(Group{ID: "free", Name: "Free", Members: []string{"zen/y"}, Match: []string{"op/*:free"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := routedIDs(t, "group/free"); !slices.Equal(got, []string{"op/c:free", "zen/y", "op/d:free"}) {
|
||||
t.Fatalf("after a rename: %v", got)
|
||||
}
|
||||
// a model added to the group as read (models+=, the TUI) goes after
|
||||
// those named, the pattern's staying where they were
|
||||
if err := Save(Provider{ID: "zen", Name: "Zen", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"y", "z"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g, _, _ = FindGroup("group/free")
|
||||
g.Members = append(g.Members, "zen/z")
|
||||
if err := SaveGroup(g); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := routedIDs(t, "group/free"); !slices.Equal(got, []string{"op/c:free", "zen/y", "zen/z", "op/d:free"}) {
|
||||
t.Fatalf("after an add: %v", got)
|
||||
}
|
||||
// put back in the order it has unasked, nothing is kept
|
||||
g, _, _ = FindGroup("group/free")
|
||||
g.Placed = []string{"zen/y", "zen/z", "op/c:free", "op/d:free"}
|
||||
if err := SaveGroup(g); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b, _ := os.ReadFile(Path()); strings.Contains(string(b), `"placed"`) {
|
||||
t.Fatalf("placed kept: %s", b)
|
||||
}
|
||||
}
|
||||
|
||||
// A matched member may be switched off, picked, or ruled, like a named one;
|
||||
// and named at an effort of its own it is not matched again.
|
||||
func TestGroupPatternMembersOffAndRules(t *testing.T) {
|
||||
|
||||
@@ -108,6 +108,9 @@ func Rename(from, to string) error {
|
||||
for k, m := range g.Fast {
|
||||
g.Fast[k] = renamedRef(m, from, to)
|
||||
}
|
||||
for k, m := range g.Placed {
|
||||
g.Placed[k] = renamedRef(m, from, to)
|
||||
}
|
||||
for k, m := range g.Off {
|
||||
g.Off[k] = renamedRef(m, from, to)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user