diff --git a/internal/cli/groups_cli.go b/internal/cli/groups_cli.go index d6e15e2d1..d103098a8 100644 --- a/internal/cli/groups_cli.go +++ b/internal/cli/groups_cli.go @@ -23,7 +23,9 @@ const groupUsage = `usage: magpie group add models=[,m2…] [routing=…] [stays=…] make a group; agents pick it as group/, the id made from the name; a name in use replaces that group - magpie group set k=v… change one: name, models (the whole list, in order, patterns too), + magpie group set k=v… change one: name, note (your own word on it, shown under its name: + note='for the work key'; empty clears it), + models (the whole list, in order, patterns too), models+=[,m2…] (append), models-=[,m2…] (drop), routing, stays, context (how long a request agents are told it takes: 272k; smallest is its smallest model's; empty is its largest model's), levels (the reasoning levels agents are offered: @@ -522,6 +524,8 @@ func applyGroupPairs(g *provider.Group, pairs []string, resolve func(string) (st } case "family", "tag": g.Family = strings.TrimSpace(v) + case "note", "description", "desc", "remark": + g.Note = provider.CleanNote(v) case "listed": // no: the models in it leave the lists agents see (#1783) switch strings.ToLower(strings.TrimSpace(v)) { @@ -601,7 +605,7 @@ func applyGroupPairs(g *provider.Group, pairs []string, resolve func(string) (st g.Pick, err = pickMember(g.Members, v) g.Routing = provider.Manual default: - return fmt.Errorf("unknown field %q (fields: name, models, models+, models-, routing, pick, stays, context, levels, family, effort, classifier, intent-sure, fast, weight, listed; magpie group help)", k) + return fmt.Errorf("unknown field %q (fields: name, note, models, models+, models-, routing, pick, stays, context, levels, family, effort, classifier, intent-sure, fast, weight, listed; magpie group help)", k) } if err != nil { return err @@ -1113,11 +1117,11 @@ func groups() error { names[e.ID] = e // a group in a group is served when it is } } - type row struct{ name, id, how, members, uses string } + type row struct{ name, id, how, members, uses, note string } var rows []row w := [3]int{} for _, g := range shown { - r := row{name: bold.Render(g.Name), id: muted.Render(g.Ref())} + r := row{name: bold.Render(g.Name), id: muted.Render(g.Ref()), note: g.Note} if g.Auto { r.name += " " + faint.Render("found") } @@ -1173,6 +1177,9 @@ func groups() error { } for _, r := range rows { fmt.Printf(" %s %s %s %s%s\n", pad(r.name, w[0]), pad(r.id, w[1]), pad(r.how, w[2]), r.members, r.uses) + if r.note != "" { + fmt.Printf(" %s\n", muted.Render(r.note)) // the user's own word on it, under its row + } } var ids []string for _, g := range hidden { @@ -1201,6 +1208,9 @@ func showGroup(g provider.Group) error { head += amber.Render(" removed") + muted.Render(" · magpie group restore "+g.ID) } fmt.Println(" ", head) + if g.Note != "" { + kv("note", g.Note) + } if g.Routing == provider.Manual { kv("routing", "manual"+muted.Render(" every request to "+g.Picked()+"; magpie group pick "+g.ID+" picks another")) } else { diff --git a/internal/cli/groups_note_cli_test.go b/internal/cli/groups_note_cli_test.go new file mode 100644 index 000000000..c4c3d7166 --- /dev/null +++ b/internal/cli/groups_note_cli_test.go @@ -0,0 +1,43 @@ +package cli + +import ( + "strings" + "testing" +) + +// A routing group's note (ConatusMoon2222 on X) is set from the terminal +// with note=, given at add or set, shown by magpie group and under its +// row in magpie groups, and cleared with note= empty, when nothing shows. +func TestGroupNoteCLI(t *testing.T) { + groupsHome(t) + if _, err := addGroup("Work", []string{"models=a/m", "note=for the office key"}); err != nil { + t.Fatal(err) + } + if gs := storedGroups(t); len(gs) != 1 || gs[0]["note"] != "for the office key" { + t.Fatalf("stored: %v", gs) + } + if err := groupCmd([]string{"group", "set", "work", "note= weekdays\n only "}); err != nil { + t.Fatal(err) + } + if gs := storedGroups(t); gs[0]["note"] != "weekdays only" { + t.Fatalf("set: %v", gs) + } + out, err := stdoutOf(t, func() error { return groupCmd([]string{"group", "work"}) }) + if err != nil || !strings.Contains(out, "note") || !strings.Contains(out, "weekdays only") { + t.Fatalf("show: %v\n%s", err, out) + } + out, err = stdoutOf(t, groups) + if err != nil || !strings.Contains(out, "weekdays only") { + t.Fatalf("list: %v\n%s", err, out) + } + if err := groupCmd([]string{"group", "set", "work", "note="}); err != nil { + t.Fatal(err) + } + if gs := storedGroups(t); gs[0]["note"] != nil { + t.Fatalf("cleared: %v", gs) + } + out, _ = stdoutOf(t, func() error { return groupCmd([]string{"group", "work"}) }) + if strings.Contains(out, "note") { + t.Fatalf("a group without a note shows one:\n%s", out) + } +} diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index cabb6648c..7109c8676 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -6191,7 +6191,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 || [])], keys: [...(g.keys || [])], 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 || [])], where: (r.where || []).map((c) => ({ ...c })), time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } }; + gEdit = { id: g.id, draft: { name: g.name, note: g.note || "", 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 || [])], keys: [...(g.keys || [])], 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 || [])], where: (r.where || []).map((c) => ({ ...c })), time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } }; renderGroups(); return true; }; @@ -6883,10 +6883,18 @@ function routingPage(part) { const nm = el("div", "nm"); nm.append(el("b", "", g.name), el("code", "mdl", g.ref || "group/" + g.id)); if (g.auto) nm.append(el("small", "auto", t("found by magpie"))); + main.append(nm); + // the user's own word on it (ConatusMoon2222 on X), one quiet line, + // only when there is one; the whole of it on hover + if (g.note) { + const note = el("div", "rt-gnote", g.note); + note.title = g.note; + main.append(note); + } const manual = g.routing === "manual"; const sep = g.routing === "order" ? " → " : " · "; const mem = manual ? pickRow(g) : el("div", "mem", shownMembers(g).map((id) => memberLabel(g, id) + (g.off?.includes(id) ? ` (${t("off")})` : "")).join(sep)); - main.append(nm, mem); + main.append(mem); if (!g.decides) main.append(...groupQuota(g)); for (const p of g.patterns || []) { const line = el("div", "mem pat" + (p.models ? "" : " none")); @@ -6990,7 +6998,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), 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 }, + await groupAction("save", { id: g.id, name: g.name, note: g.note || "", 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 }); @@ -7123,7 +7131,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, 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 }, + groupAction("save", { id: g.id, name: g.name, note: g.note || "", 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); @@ -7144,7 +7152,7 @@ function routingPage(part) { h.append(el("b", "", g ? g.name : t("New group"))); if (g?.auto) h.append(el("span", "note", t("found by magpie — saving a change makes it yours"))); ed.append(h); - const keys = (i) => { i.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Escape") { cancelGroup(); } else if (e.key === "Enter" && i === name) saveBtn.onclick(); }; return i; }; + const keys = (i) => { i.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Escape") { cancelGroup(); } else if (e.key === "Enter" && (i === name || i === noteIn)) saveBtn.onclick(); }; return i; }; const name = keys(input(d.name, t("e.g. Opus anywhere"))); const idHint = el("div", "hint"); // an existing group's id can change (an auto- one found by magpie too); @@ -7198,6 +7206,12 @@ function routingPage(part) { nw.append(name); if (!g) nw.append(idHint); ed.append(el("label", "", t("Name")), nw); + // the user's own word on the group, shown under its name in the list + const noteIn = keys(input(d.note || "", t("e.g. for the work key"))); + noteIn.classList.add("rt-gnote-in"); + noteIn.maxLength = 200; // provider.NoteLongest + noteIn.oninput = () => { d.note = noteIn.value; }; + ed.append(el("label", "", t("Note")), noteIn); const sw = el("div", "gsuffix"); sw.append(sfxSaid); sayLabel(); @@ -8697,7 +8711,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 === "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("/")))), keys: d.keys, 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(), note: (d.note || "").trim(), 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("/")))), keys: d.keys, 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 diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.js index d3d356f44..357f51069 100644 --- a/internal/gui/assets/plugins/routing/i18n.js +++ b/internal/gui/assets/plugins/routing/i18n.js @@ -188,6 +188,7 @@ magpie.strings({ "Save or Cancel your changes first": "有未保存的修改,请先保存或取消", "found by magpie — saving a change makes it yours": "由 magpie 自动发现,保存修改后归你管理", "e.g. Opus anywhere": "例如:Opus 多家备份", + "e.g. for the work key": "例如:给工作 Key 用", "Agents pick it as {id}": "Agent 里选 {id}", "an agent set to {id} needs setting again": "已选 {id} 的 agent 需重新选择", "The first answers for what the model can do. In order, they are tried top first.": "排第一的模型决定本组对外的能力;按顺序模式下从上往下尝试。", @@ -921,6 +922,7 @@ magpie.strings({ "Save or Cancel your changes first": "有未儲存的修改,請先儲存或取消", "found by magpie — saving a change makes it yours": "由 magpie 自動發現,儲存修改後歸你管理", "e.g. Opus anywhere": "例如:Opus 多家備份", + "e.g. for the work key": "例如:給工作 Key 用", "Agents pick it as {id}": "Agent 裡選 {id}", "an agent set to {id} needs setting again": "已選 {id} 的 agent 需重新選擇", "The first answers for what the model can do. In order, they are tried top first.": "排第一的模型決定本組對外的能力;按順序模式下從上往下嘗試。", @@ -1632,6 +1634,7 @@ magpie.strings({ "Save or Cancel your changes first": "未保存の変更があります。先に保存かキャンセルをしてください", "found by magpie — saving a change makes it yours": "magpie が自動作成 — 変更を保存すると自分のグループになります", "e.g. Opus anywhere": "例:Opus をどこでも", + "e.g. for the work key": "例:仕事用のキー向け", "Agents pick it as {id}": "エージェントでは {id} として選びます", "an agent set to {id} needs setting again": "{id} を選んでいるエージェントは設定し直しが必要です", "The first answers for what the model can do. In order, they are tried top first.": "先頭のモデルがモデルの能力を決めます。順番モードでは上から順に試されます。", @@ -2355,6 +2358,7 @@ magpie.strings({ "Save or Cancel your changes first": "Klicken Sie zuerst auf „Speichern“ oder „Abbrechen“", "found by magpie — saving a change makes it yours": "von magpie gefunden – nach dem Speichern einer Änderung gehört sie Ihnen", "e.g. Opus anywhere": "z. B. Opus überall", + "e.g. for the work key": "z. B. für den Arbeitsschlüssel", "Agents pick it as {id}": "Agenten wählen sie als {id}", "an agent set to {id} needs setting again": "ein auf {id} eingestellter Agent muss neu eingestellt werden", "The first answers for what the model can do. In order, they are tried top first.": "Das erste bestimmt, was das Modell kann. Der Reihe nach werden sie von oben versucht.", diff --git a/internal/gui/assets/plugins/routing/routing.css b/internal/gui/assets/plugins/routing/routing.css index efe50ca14..7bd614018 100644 --- a/internal/gui/assets/plugins/routing/routing.css +++ b/internal/gui/assets/plugins/routing/routing.css @@ -624,6 +624,7 @@ button.rt-session { cursor: pointer; } opens the editor (groupRow). Its controls stay controls. */ .rt-groups:not(.sorting) > .rt-group :is(.nm b, .nm code.mdl, .mem), .rt-gedit .fallback:not(.rt-rules) > .fbl:not(.sorting) > .fbrow > .n, .rt-gaccts > .fbrow > .n { user-select: text; -webkit-user-select: text; } +.rt-group .rt-gnote { margin-top: 1px; font-size: 12px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .rt-group .mem { margin-top: 2px; font-size: 11.5px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } /* a pattern the group finds models by, and how many it matches now */ .rt-group .mem.pat code, .rt-pats code { font: var(--code-style, normal) 500 11px/1.5 var(--code-font, var(--code)); font-stretch: var(--code-stretch, 100%); color: var(--fg-2); } diff --git a/internal/gui/tests/group-defaults.test.cjs b/internal/gui/tests/group-defaults.test.cjs index a07832c89..5598bb1ca 100644 --- a/internal/gui/tests/group-defaults.test.cjs +++ b/internal/gui/tests/group-defaults.test.cjs @@ -88,7 +88,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", 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; + // in sight is above the view's foot bar, which sits over the page + const foot = await page.evaluate(() => document.querySelector(".view-foot")?.getBoundingClientRect().top ?? 2000); + if (b && b.y >= 0 && b.y + b.height <= Math.min(foot, 2000)) return loc; await page.mouse.wheel(0, b && b.y < 0 ? -400 : 400); await page.waitForTimeout(50); } diff --git a/internal/gui/tests/group-note.test.cjs b/internal/gui/tests/group-note.test.cjs new file mode 100644 index 000000000..d5f31f6c2 --- /dev/null +++ b/internal/gui/tests/group-note.test.cjs @@ -0,0 +1,182 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A routing group carries a note of the user's (ConatusMoon2222 on X: "请问 +// 路由组可以添加备注吗?"). The Routing list shows it under the group's name, +// one muted line cut short with an ellipsis, the whole of it on hover, and +// only when there is one: a group without a note shows no line and no empty +// space for one. The editor has a Note field under Name; Save sends what is +// typed there, and clearing it sends none. A pick on a manual group's card +// and a routing picked from the row keep the note as it was. At a phone's +// width the note stays on one line, with no sideways scroll. In English, +// Chinese, Traditional Chinese, Japanese and German. +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(process.env.MAGPIE_ROUTING_ASSETS || path.join(__dirname, "../assets")); +const models = [ + { id: "a/sol", name: "sol", providerName: "A", icon: "generic" }, + { id: "b/flash", name: "flash", providerName: "B", icon: "generic" }, +]; +const members = ["a/sol", "b/flash"]; +const long = "For the office key only: Sol first, Flash when Sol is rate limited, and never on weekends because the plan resets on Monday morning"; +const group = (id, name, extra) => ({ id, name, members, routing: "order", ready: true, memberInfo: members.map((m) => ({ id: m, ready: true })), ...extra }); + +const words = { + en: { label: "Note", hint: "e.g. for the work key" }, + zh: { label: "备注", hint: "例如:给工作 Key 用" }, + "zh-TW": { label: "備註", hint: "例如:給工作 Key 用" }, + ja: { label: "メモ", hint: "例:仕事用のキー向け" }, + de: { label: "Notiz", hint: "z. B. für den Arbeitsschlüssel" }, +}; + +function serve(lang, posts) { + const state = { agents: [{ id: "codex", name: "Codex", path: "/test/codex", fields: [] }], profiles: [], settings: { lang, theme: "light" } }; + const g = { + noted: group("noted", "Noted", { note: long }), + plain: group("plain", "Plain", {}), + hand: group("hand", "Hand", { routing: "manual", pick: "a/sol", picked: "a/sol", note: "pick by hand" }), + }; + const groups = () => ({ models, pools: [], groups: Object.values(g) }); + 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/save" && g[body.id]) { + // as provider.SaveGroup: an empty note is no note + g[body.id] = { ...g[body.id], ...body, picked: body.routing === "manual" ? body.pick : undefined }; + if (!body.note) delete g[body.id].note; + } + 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 }); + }; +} + +async function open(t, engine, lang, width = 1100) { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 1400 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = [], posts = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, posts)); + await page.goto("http://magpie.test/?view=groups"); + await page.locator('.rt-group[data-id="noted"]').waitFor(); + return { page, errors, posts }; +} + +// the note's line: one line, cut short, the name's line above it +const noteLine = (page, id) => page.locator(`.rt-group[data-id="${id}"] .rt-gnote`).evaluate((n) => { + const cs = getComputedStyle(n), nm = n.parentElement.querySelector(".nm").getBoundingClientRect(), r = n.getBoundingClientRect(); + return { text: n.textContent, title: n.title, cut: n.scrollWidth > n.clientWidth, ellipsis: cs.textOverflow, oneLine: r.height <= parseFloat(cs.lineHeight || cs.fontSize) * 1.6 + 1, + below: r.top >= nm.bottom - 1, inside: r.right <= n.closest(".rt-group").getBoundingClientRect().right + 0.5, color: cs.color }; +}); + +const waitPost = async (page, posts, n) => { + for (let i = 0; i < 150 && posts.length === n; i++) await page.waitForTimeout(20); // the post is the state waited for + assert.ok(posts.length > n, "a save was posted"); + return posts.at(-1).body; +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + const w = words[lang]; + test(`${engine} ${lang}: a routing group's note shows on its row and is edited in its editor`, async (t) => { + const { page, errors, posts } = await open(t, engine, lang); + + // the row: one muted line under the name, cut short, whole on hover + const ln = await noteLine(page, "noted"); + assert.equal(ln.text, long); + assert.equal(ln.title, long, "the whole note on hover"); + assert.ok(ln.cut && ln.ellipsis === "ellipsis", "a long note is cut short with an ellipsis"); + assert.ok(ln.oneLine && ln.below && ln.inside, JSON.stringify(ln)); + const nameColor = await page.locator('.rt-group[data-id="noted"] .nm b').evaluate((b) => getComputedStyle(b).color); + assert.notEqual(ln.color, nameColor, "the note is quieter than the name"); + assert.equal(await page.locator('.rt-group[data-id="plain"] .rt-gnote').count(), 0, "no note, no line"); + + // the editor: a Note field under Name with the note in it + await page.locator('.rt-group[data-id="noted"]').click(); + const ed = page.locator(".rt-gedit"); + await ed.waitFor(); + const labels = await ed.locator(":scope > label").allTextContents(); + assert.equal(labels[1], w.label, `the field after Name: ${labels}`); + const field = ed.locator("input.rt-gnote-in"); + assert.equal(await field.inputValue(), long); + assert.equal(await field.getAttribute("placeholder"), w.hint); + await field.fill(" Office key, weekdays "); + let n = posts.length; + await field.press("Enter"); // Enter in it saves, as in Name + let body = await waitPost(page, posts, n); + assert.equal(body.note, "Office key, weekdays"); + await page.waitForFunction(() => !document.querySelector(".rt-gedit")); + await page.waitForFunction(() => document.querySelector('.rt-group[data-id="noted"] .rt-gnote')?.textContent === "Office key, weekdays"); + + // cleared, it sends none and the row has no line + await page.locator('.rt-group[data-id="noted"]').click(); + await ed.waitFor(); + await ed.locator("input.rt-gnote-in").fill(""); + n = posts.length; + await ed.locator("button.primary").click(); + body = await waitPost(page, posts, n); + assert.equal(body.note, ""); + await page.waitForFunction(() => !document.querySelector('.rt-group[data-id="noted"] .rt-gnote')); + + // a group without one: its field is empty and Save sends none + await page.locator('.rt-group[data-id="plain"]').click(); + await ed.waitFor(); + assert.equal(await ed.locator("input.rt-gnote-in").inputValue(), ""); + n = posts.length; + await ed.locator("button.primary").click(); + assert.equal((await waitPost(page, posts, n)).note, ""); + await page.waitForFunction(() => !document.querySelector(".rt-gedit")); + + // a pick on a manual group's card keeps its note + n = posts.length; + await page.locator('.rt-group[data-id="hand"] .rt-pick[data-member="b/flash"]').click(); + body = await waitPost(page, posts, n); + assert.deepEqual({ pick: body.pick, note: body.note }, { pick: "b/flash", note: "pick by hand" }); + + // a routing picked from the row keeps it too + n = posts.length; + await page.locator('.rt-group[data-id="hand"] button.rt-groute').click(); + const menu = page.locator(".proto-menu"); + await menu.waitFor(); + await menu.locator('.pm-item[aria-checked="false"]').first().click(); + body = await waitPost(page, posts, n); + assert.notEqual(body.routing, "manual"); + assert.equal(body.note, "pick by hand", "a routing pick keeps the note"); + assert.deepEqual(errors, []); + }); + } + + test(`${engine}: at a phone's width a group's note stays one line`, async (t) => { + const { page, errors } = await open(t, engine, "en", 390); + const ln = await noteLine(page, "noted"); + assert.ok(ln.cut && ln.oneLine && ln.inside, JSON.stringify(ln)); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "no sideways scroll"); + 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}-note-390.png`) }); + } + assert.deepEqual(errors, []); + }); +} diff --git a/internal/gui/tests/group-unlists.test.cjs b/internal/gui/tests/group-unlists.test.cjs index 300eedfe3..8ad9855b1 100644 --- a/internal/gui/tests/group-unlists.test.cjs +++ b/internal/gui/tests/group-unlists.test.cjs @@ -14,7 +14,19 @@ const { chromium, webkit } = require("playwright"); const openAdvanced = async (page) => { const d = page.locator(".rt-gedit .rt-gadv"); await d.waitFor({ state: "attached" }); - if (!(await d.evaluate((e) => e.open))) await d.locator(":scope > summary").click(); + if (await d.evaluate((e) => e.open)) return; + // WebKit doesn't scroll the page's own scroller to a click: wheel the + // summary above the view's foot bar, which sits over the page + const s = d.locator(":scope > summary"); + const vw = page.viewportSize(); + await page.mouse.move(vw.width / 2, vw.height / 2); + for (let i = 0; i < 20; i++) { + const b = await s.boundingBox(), foot = await page.evaluate(() => document.querySelector(".view-foot")?.getBoundingClientRect().top ?? innerHeight); + if (b && b.y >= 0 && b.y + b.height <= foot) break; + await page.mouse.wheel(0, b && b.y < 0 ? -300 : 300); + await page.waitForTimeout(100); + } + await s.click(); }; const assets = path.resolve(__dirname, "../assets"); diff --git a/internal/provider/group.go b/internal/provider/group.go index 514319762..612acd42e 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -195,8 +195,13 @@ const ContextSmallest = -1 // Group is a routing group. type Group struct { - ID string `json:"id"` - Name string `json:"name"` + ID string `json:"id"` + Name string `json:"name"` + // Note is the user's own word on the group (ConatusMoon2222 on X: + // which key it is for, why it is ordered so): one line, shown under + // its name on the Routing page and by magpie group, never sent to an + // agent or a vendor. Empty shows nothing (CleanNote). + Note string `json:"note,omitempty"` Members []string `json:"members"` // "provider/model[:effort]" or "group/", in order (see MemberEffort) // Former are the ids it had before a rename (RenameGroup), newest // last: a request still asking group/ is routed to it, until a @@ -1666,6 +1671,19 @@ func (e Entry) Quiet() bool { return e.Reasonless || !e.Reasoning && len(e.Efforts) == 0 && !levelsUnknown(e) } +// NoteLongest is how many characters a group's note keeps. +const NoteLongest = 200 + +// CleanNote is a group's note as stored: one line, its spaces and line +// breaks run together, at most NoteLongest characters. +func CleanNote(s string) string { + s = strings.Join(strings.Fields(s), " ") + if r := []rune(s); len(r) > NoteLongest { + s = strings.TrimSpace(string(r[:NoteLongest])) + } + return s +} + // SaveGroup adds or replaces a group of the user's. Changing one magpie // found makes it the user's. func SaveGroup(g Group) error { @@ -1682,6 +1700,7 @@ func SaveGroup(g Group) error { if g.Name == "" { g.Name = g.ID } + g.Note = CleanNote(g.Note) g.FirstToken = max(g.FirstToken, FirstTokenWait) if g.Sink { g.NoSink = false diff --git a/internal/provider/group_note_test.go b/internal/provider/group_note_test.go new file mode 100644 index 000000000..89a8922ea --- /dev/null +++ b/internal/provider/group_note_test.go @@ -0,0 +1,112 @@ +package provider + +import ( + "strings" + "testing" +) + +// A routing group keeps a note of the user's (ConatusMoon2222 on X): saved +// as one line, its spaces run together, cut at NoteLongest characters, and +// cleared by saving it empty. It goes with the group where the group goes: +// a copy, a group shared to another magpie, a backup's StoredGroups and +// sync's Mirror. A save that changes something else keeps it. +func TestGroupNote(t *testing.T) { + fastHome(t) + note := func(id string) string { + t.Helper() + g, _, ok := FindGroup(GroupPrefix + id) + if !ok { + t.Fatalf("no group %s", id) + } + return g.Note + } + g := Group{ID: "work", Name: "Work", Note: " for the office key\n\tweekdays only ", Members: []string{"rl/claude-opus-5-5", "an/claude-sonnet-5"}} + if err := SaveGroup(g); err != nil { + t.Fatal(err) + } + if got := note("work"); got != "for the office key weekdays only" { + t.Fatalf("note %q", got) + } + + // another change keeps it + saved, _, _ := FindGroup(GroupPrefix + "work") + saved.Routing = Rotate + if err := SaveGroup(saved); err != nil { + t.Fatal(err) + } + if got := note("work"); got != "for the office key weekdays only" { + t.Fatalf("after a routing change %q", got) + } + + // a long one is cut, in characters, not bytes + saved.Note = strings.Repeat("备", NoteLongest+50) + if err := SaveGroup(saved); err != nil { + t.Fatal(err) + } + if got := note("work"); got != strings.Repeat("备", NoteLongest) { + t.Fatalf("long note kept %d characters", len([]rune(got))) + } + saved.Note = "for the office key" + if err := SaveGroup(saved); err != nil { + t.Fatal(err) + } + + // a copy has it + cp, err := CopyGroup("work", "") + if err != nil { + t.Fatal(err) + } + if got := note(cp.ID); got != "for the office key" { + t.Fatalf("copy's note %q", got) + } + + // shared to another magpie + text, err := ShareGroup("work") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(text, `"note":"for the office key"`) { + t.Fatalf("shared text without the note: %s", text) + } + + // a backup and a sync carry it + stored, err := StoredGroups() + if err != nil { + t.Fatal(err) + } + ps, err := Stored() + if err != nil { + t.Fatal(err) + } + if err := Mirror(ps, nil); err != nil { + t.Fatal(err) + } + if _, _, ok := FindGroup(GroupPrefix + "work"); ok { + t.Fatal("Mirror with no groups kept work") + } + if err := Mirror(ps, stored); err != nil { + t.Fatal(err) + } + if got := note("work"); got != "for the office key" { + t.Fatalf("after Mirror %q", got) + } + if err := DeleteGroup("work"); err != nil { + t.Fatal(err) + } + if err := RestoreGroups(stored); err != nil { + t.Fatal(err) + } + if got := note("work"); got != "for the office key" { + t.Fatalf("after RestoreGroups %q", got) + } + + // cleared + saved, _, _ = FindGroup(GroupPrefix + "work") + saved.Note = " " + if err := SaveGroup(saved); err != nil { + t.Fatal(err) + } + if got := note("work"); got != "" { + t.Fatalf("cleared note %q", got) + } +} diff --git a/internal/tui/routing.go b/internal/tui/routing.go index b12d7f73b..c2bf5a4c4 100644 --- a/internal/tui/routing.go +++ b/internal/tui/routing.go @@ -495,6 +495,15 @@ func (m model) updateGroup(msg tea.KeyMsg) (tea.Model, tea.Cmd) { return saveGroup(g.ID, func(g *provider.Group) error { g.Family = v; return nil }, g.Name+" family "+dash(v)) }}) m.back = modeGroup + case "N": + in := newInput("your own word on it, e.g. office key only") + in.SetValue(g.Note) + m.openAsk(ask{crumbs: []string{"routing", g.Name, "note"}, input: in, empty: true, + hint: "shown under its name; empty clears it", + onEnter: func(v string) tea.Cmd { + return saveGroup(g.ID, func(g *provider.Group) error { g.Note = v; return nil }, g.Name+" note "+dash(provider.CleanNote(v))) + }}) + m.back = modeGroup case "x": in := newInput("tokens, e.g. 200k · empty for its models' own") if g.Context > 0 { @@ -683,7 +692,11 @@ func (m model) viewGroup() string { if g.Auto { head = append(head, "found by magpie: a change makes it yours") } - b.WriteString(pad + " " + sMuted.Render(strings.Join(head, " · ")) + "\n\n") + b.WriteString(pad + " " + sMuted.Render(strings.Join(head, " · ")) + "\n") + if g.Note != "" { + b.WriteString(pad + " " + sText.Render(trunc(g.Note, max(m.w-8, 10))) + "\n") + } + b.WriteString("\n") b.WriteString(pad + " " + sFaint.Render("models · the first that can take a request gets it") + "\n") hits := provider.PatternHits(g) memFrom, memTo, ruleFrom, ruleTo := groupWindow(len(g.Members), len(g.Rules), m.gsel, m.groupRows(g, len(hits))) @@ -758,6 +771,9 @@ func (m model) groupRows(g provider.Group, hits int) int { if len(g.Rules) == 0 { fixed++ } + if g.Note != "" { + fixed++ // its line under the head + } if slices.ContainsFunc(g.Rules, func(r provider.Rule) bool { return r.Intent != "" }) { fixed += 2 } diff --git a/internal/tui/tui.go b/internal/tui/tui.go index 1434f4d4c..87c1bb261 100644 --- a/internal/tui/tui.go +++ b/internal/tui/tui.go @@ -824,7 +824,7 @@ func (m model) View() string { body = m.viewGroup() // two lines: there is more to do to a group than one holds footer = hints("↑↓", "model / rule", "J K", "move", "a", "add model", "n", "new rule", "↵", "edit rule", "d", "take out", "esc", "back") + "\n" + - pad + hints("E", "effort", "F", "fast", "c", "classifier", "o", "routing", "s", "stays", "x", "context", "l", "levels", "f", "family", "R", "rename") + pad + hints("E", "effort", "F", "fast", "c", "classifier", "o", "routing", "s", "stays", "x", "context", "l", "levels", "f", "family", "N", "note", "R", "rename") case modeName: body = m.viewName() footer = hints("↵", "save", "esc", "cancel")