routing: a group's member its provider counts free says free on its card and in its editor (jiabubu)

jiabubu on Discord: v0.1.2274's Free for me and a group's Free first,
but a routing group never showed which of its members are free.

groupsState's memberInfo now carries free (provider.FreeModel: the
provider is Free for me, or its vendor serves the model free). The
Routing page says a muted "free" for such a member, whatever the
group's routing, so it shows before Free first is picked (and Cheapest
first reads the same word): on the group's card line, beside the
provider in the group editor (a small like "by pattern", with a hover
saying what Free first and Cheapest first do with it), and in a manual
group's pick row and menu. A paid member says nothing. Routing plugin
files only; the core's scripts are unchanged. No new colours.

Run at 67dedea38 (rebased on origin/main a4916aec1), on mote:
- group-member-free.test.cjs: 20/20 (Chromium, WebKit; 1100, 420px;
  en, zh, zh-TW, ja, de); i18n-keys 4/4
- go test ./internal/gui -run TestGroupMemberSaysFree|
  TestGroupModelsCarryWhatTheyTake|TestCoreScriptBudget: ok
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gui: ok; gofmt clean
- earlier at fb23a3279 (pre-rebase): go test ./internal/gui all but
  TestMainWindowCorners/macOS_26_SDK (#3949, macOS 27 on mote);
  the whole GUI suite (make test-ui) still running at push, reds named
  so far are filed: balance-fix (#4683), agent-panel-name-width (#4600),
  codex-auto-reset (#4790, #2360); none in a Routing or group file.

Broken by hand: freeIn always false and the editor tag off: the card
and editor assertions go red; the editor tag alone: "the free member
has no free tag"; memberJSON.Free always false: TestGroupMemberSaysFree
red.

Not tried: a real ModelScope provider in the real app; the whole GUI
suite to its end at the pushed head.
This commit is contained in:
yetone
2026-11-02 14:13:52 +08:00
parent e7fbbaab9f
commit ce2e81da11
6 changed files with 164 additions and 4 deletions
File diff suppressed because one or more lines are too long
+13 -3
View File
@@ -5370,10 +5370,15 @@ function routingPage(part) {
const memberNote = (id) => { const o = !subOf(id) && !modelOf(id) && offOf(id); return subOf(id) ? t("routing group") : [modelOf(id)?.providerName || o && `${o.name} · ${t("switched off")}`, fixedOf(id) && fixedWords(fixedOf(id))].filter(Boolean).join(" · "); };
// a member the group sends in its vendor's fast mode (Group.Fast)
const fastIn = (g, id) => !!g?.fast?.includes(id) && !subOf(id);
// a member Free first and Cheapest first count as costing nothing: its
// provider is Free for me, or its vendor serves it free (memberJSON.Free),
// said whatever the group's routing, so it shows before Free first is
// picked (jiabubu on Discord)
const freeIn = (g, id) => !!g?.memberInfo?.find((x) => x.id === id)?.free;
function memberLabel(g, id) {
const i = g.memberInfo?.find((x) => x.id === id), m = modelOf(id), s = subOf(id), f = fixedOf(id);
if (s) return `${t("routing group")} · ${s.name}`;
const at = (f ? ` · ${fixedWords(f)}` : "") + (fastIn(g, id) ? ` · ${t("fast")}` : "");
const at = (f ? ` · ${fixedWords(f)}` : "") + (fastIn(g, id) ? ` · ${t("fast")}` : "") + (freeIn(g, id) ? ` · ${t("free")}` : "");
if (m) return `${m.providerName} · ${modelName(m)}${at}`;
if (i?.providerOff) return `${i.name} · ${i.model}${at} (${t("switched off")})`;
return i?.name ? `${i.name} · ${i.model}${at}` : id;
@@ -6169,7 +6174,7 @@ function routingPage(part) {
b.setAttribute("aria-checked", String(on));
b.dataset.member = id;
b.append(el("span", "dot"), memberIcon(id), el("span", "n", memberName(id)));
const note = [memberNote(id), fastIn(g, id) && t("fast")].filter(Boolean).join(" · ");
const note = [memberNote(id), fastIn(g, id) && t("fast"), freeIn(g, id) && t("free")].filter(Boolean).join(" · ");
if (note) b.append(el("small", "", note));
b.title = on ? t("Every request goes to {name}", { name: memberLabel(g, id) })
: info?.providerOff ? offWords(info)
@@ -6375,6 +6380,11 @@ function routingPage(part) {
n.append(nm);
if (m || s) n.append(el("small", "", subOf(id) ? memberNote(id) : m.providerName));
else if (info?.providerOff) n.append(el("small", "", `${info.name} · ${t("switched off")}`));
if (info?.free && !s) {
const fr = el("small", "rt-free", t("free"));
fr.title = t("Free first uses it before paid ones, and Cheapest first counts it as costing nothing");
n.append(fr);
}
const matched = d.matched.includes(id);
if (matched) n.append(el("small", "", t("by pattern")));
// switched off, it keeps its place and its rules but is sent
@@ -7948,7 +7958,7 @@ function routingPage(part) {
if (b.classList.contains("open")) return closeProtoMenu();
openProtoMenu(b, g.members.map((id) => {
const info = g.memberInfo?.find((x) => x.id === id);
const note = [memberNote(id), fastIn(g, id) && t("fast"), info && !info.ready && t("no provider serves it now")].filter(Boolean).join(" · ");
const note = [memberNote(id), fastIn(g, id) && t("fast"), freeIn(g, id) && t("free"), info && !info.ready && t("no provider serves it now")].filter(Boolean).join(" · ");
return { v: id, name: memberName(id), literalName: true, note, title: memberLabel(g, id) };
}), picked, async (id) => {
closeProtoMenu();
@@ -2,6 +2,7 @@
// kernel adds them to i18n.js's (magpie.strings).
magpie.strings({
zh: {
"Free first uses it before paid ones, and Cheapest first counts it as costing nothing": "免费优先会先用它再用付费的,最便宜优先把它算作不花钱",
"{name}, {n} accounts: {windows}": "{name}({n} 个账号):{windows}",
"What is left of this provider's accounts the group can use, together: amounts of one unit added up, a share the mean of the accounts on one plan. Each account is on the Usage page.": "本组可用的这家供应商账号合起来还剩多少:同一单位的额度相加,百分比取同一套餐账号的平均值。各账号详情在用量页。",
"Each session's context window": "各会话的上下文窗口",
@@ -653,6 +654,7 @@ magpie.strings({
"This group may spend every account of {provider}": "这个组可以消耗 {provider} 的每个账号",
},
"zh-TW": {
"Free first uses it before paid ones, and Cheapest first counts it as costing nothing": "免費優先會先用它再用付費的,最便宜優先把它算作不花錢",
"{name}, {n} accounts: {windows}": "{name}({n} 個帳號):{windows}",
"What is left of this provider's accounts the group can use, together: amounts of one unit added up, a share the mean of the accounts on one plan. Each account is on the Usage page.": "本組可用的這家供應商帳號合起來還剩多少:同一單位的額度相加,百分比取同一方案帳號的平均值。各帳號詳情在用量頁。",
"Each session's context window": "各會話的上下文視窗",
@@ -1304,6 +1306,7 @@ magpie.strings({
"This group may spend every account of {provider}": "這個組可以消耗 {provider} 的每個帳號",
},
ja: {
"Free first uses it before paid ones, and Cheapest first counts it as costing nothing": "無料優先は有料より先にこれを使い、最安優先はこれを費用ゼロとして数えます",
"{name}, {n} accounts: {windows}": "{name}({n} アカウント):{windows}",
"What is left of this provider's accounts the group can use, together: amounts of one unit added up, a share the mean of the accounts on one plan. Each account is on the Usage page.": "このグループが使えるこのプロバイダーのアカウントの残りの合計:同じ単位の量は足し合わせ、割合は同じプランのアカウントの平均。各アカウントは使用量ページにあります。",
"Each session's context window": "セッションごとのコンテキストウィンドウ",
@@ -1955,6 +1958,7 @@ magpie.strings({
"This group may spend every account of {provider}": "このグループは {provider} のすべてのアカウントを使えます",
},
de: {
"Free first uses it before paid ones, and Cheapest first counts it as costing nothing": "„Kostenlos zuerst“ nutzt es vor bezahlten, „Günstigste zuerst“ zählt es als kostenlos",
"{name}, {n} accounts: {windows}": "{name}, {n} Konten: {windows}",
"What is left of this provider's accounts the group can use, together: amounts of one unit added up, a share the mean of the accounts on one plan. Each account is on the Usage page.": "Was von den Konten dieses Anbieters, die die Gruppe nutzen kann, zusammen übrig ist: Mengen derselben Einheit addiert, ein Anteil als Mittelwert der Konten mit demselben Tarif. Die einzelnen Konten stehen auf der Seite Nutzung.",
"Each session's context window": "Kontextfenster jeder Sitzung",
+38
View File
@@ -281,3 +281,41 @@ func TestGroupModelImagesOnTheWire(t *testing.T) {
}
}
}
// A group's member says it is free when Free first would count it so
// (provider.FreeModel): every model of a provider the user marked Free for
// me, and none of one they didn't (jiabubu on Discord)
func TestGroupMemberSaysFree(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())
for _, p := range []provider.Provider{
{ID: "scope", Name: "Scope", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"qwen"}, CountFree: true},
{ID: "paid", Name: "Paid", Key: "k", Chat: "http://127.0.0.1:2/v1", Models: []string{"qwen"}},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
if err := provider.SaveGroup(provider.Group{ID: "g", Name: "G", Members: []string{"scope/qwen", "paid/qwen"}}); err != nil {
t.Fatal(err)
}
for _, g := range groupsState().Groups {
if g.ID != "g" {
continue
}
free := map[string]bool{}
for _, m := range g.Info {
if !m.Ready {
t.Fatalf("%s is not served", m.ID)
}
free[m.ID] = m.Free
}
if !free["scope/qwen"] || free["paid/qwen"] {
t.Fatalf("free: %v, want scope/qwen only", free)
}
return
}
t.Fatal("group g is not in the state")
}
+5
View File
@@ -135,6 +135,10 @@ type memberJSON struct {
// own `images` decides then). Named apart from the Gateway page's
// `imageSet`, which means the user answered for the model themselves
ImagesUnknown bool `json:"imagesUnknown,omitempty"`
// Free: Free first and Cheapest first count it as costing nothing
// (provider.FreeModel): its provider is the user's Free for me, or its
// vendor serves it free. The Routing page tags it (jiabubu on Discord)
Free bool `json:"free,omitempty"`
}
type modelRef struct {
@@ -370,6 +374,7 @@ func groupsState() groupsJSON {
m.CanFast = provider.CanFast(p, model)
m.OwnFast = m.CanFast && provider.OwnFast(p, model)
m.Fast = m.CanFast && g.IsFast(id)
m.Free = p.FreeModel(model)
for _, e := range served {
if e.Group == "" && e.Provider.ID == p.ID && e.Model == model {
m.Context, m.Images, m.ImagesUnknown = e.Context, seesImages(e), imagesUnknown(e)
@@ -0,0 +1,103 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// jiabubu on Discord: a routing group says which of its members cost
// nothing (a provider marked Free for me, memberJSON.Free), whatever the
// group's routing, so it shows before Free first is picked: on the
// group's card, and in its editor beside the member's provider, with a
// hover in the window's language. A paid member says nothing of it. Every
// language, Chromium and WebKit, wide and narrow.
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: "scope/qwen", name: "qwen", provider: "scope", providerName: "Scope", icon: "generic" },
{ id: "paid/qwen", name: "qwen", provider: "paid", providerName: "Paid", icon: "generic" },
];
const words = {
en: { edit: "Edit", free: "free" },
zh: { edit: "编辑", free: "免费" },
"zh-TW": { edit: "編輯", free: "免費" },
ja: { edit: "編集", free: "無料" },
de: { edit: "Bearbeiten", free: "kostenlos" },
};
const hover = "Free first uses it before paid ones, and Cheapest first counts it as costing nothing";
function serve(lang) {
// the gateway's word (memberJSON.Free): Scope is Free for me, Paid not
const groups = () => ({
models, deciders: [], pools: [],
groups: [
{ id: "g", name: "G", members: ["scope/qwen", "paid/qwen"], off: [], routing: "smart", ready: true,
memberInfo: [{ id: "scope/qwen", ready: true, provider: "scope", name: "Scope", model: "qwen", free: true }, { id: "paid/qwen", ready: true, provider: "paid", name: "Paid", model: "qwen" }] },
],
});
const state = { agents: [{ id: "codex", name: "Codex", path: "/test/codex", fields: [] }], profiles: [], settings: { lang, theme: "light" } };
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(() => {});
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/")) 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 width of [1100, 420]) {
for (const lang of Object.keys(words)) {
const w = words[lang];
test(`${engine} ${width} ${lang}: a free member says so on its group's card and in the editor, a paid one doesn't`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await (await browser.newContext({ viewport: { width, height: 1200 }, reducedMotion: "reduce" })).newPage();
t.after(() => browser.close());
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang));
await page.goto("http://magpie.test/?view=routing");
const card = page.locator('.rt-group[data-id="g"]');
await card.waitFor();
const mem = (await card.locator(".mem").first().textContent()).trim();
const parts = mem.split(" · ");
assert.deepEqual(parts, ["Scope", "qwen", w.free, "Paid", "qwen"], `the card's members read ${mem}`);
await card.locator("button", { hasText: w.edit }).click();
const rows = page.locator(".rt-gedit .fbl").first().locator(".fbrow");
await rows.nth(1).waitFor();
const scope = rows.filter({ hasText: "Scope" }), paid = rows.filter({ hasText: "Paid" });
const tag = scope.locator(".n small.rt-free");
assert.equal(await tag.count(), 1, "the free member has no free tag");
assert.equal((await tag.textContent()).trim(), w.free);
const title = await tag.getAttribute("title");
if (lang === "en") assert.equal(title, hover);
else assert.ok(title && title !== hover, `the tag's hover is in English in ${lang}: ${title}`);
await tag.scrollIntoViewIfNeeded();
assert.ok(await tag.isVisible(), "the free tag is out of sight");
const box = await tag.boundingBox();
assert.ok(box.width > 4, `the free tag is squeezed to ${box.width}px`);
assert.equal(await paid.locator(".rt-free").count(), 0, "the paid member says it is free");
assert.ok(!(await paid.locator(".n").textContent()).includes(w.free), "the paid member's name says free");
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), "the page scrolls sideways");
assert.deepEqual(errors, []);
});
}
}
}