groups: free: takes the models a catalog marks free (#5903)
A routing group's pattern may now start with free: (provider.FreePrefix): free:workbuddy/* is, of the models workbuddy/* matches, those whose catalog entry says free (Entry.Free, the vendor's or plugin's own flag as the catalog was last read). The rest after free: is a glob, a re: pattern or an id, matched as on its own, so free:re:workbuddy/hy.* works too. It is expanded where every pattern is (matchesIn, PatternHits) each time the groups are read, from the catalog magpie already keeps: no request to a vendor, and a model the next list marks free joins without a save. Only the flag decides. A $0 price (PricedFree), a rate of 0, an account named Free or "free" in an id never counts; the test holds a deepseek-v4-free id with no flag, a rate-0 model and an or/y priced at $0 out. Existing patterns read as before: openrouter/*:free still means ids ending in :free (that is why the rule is a prefix, not a :free suffix), and a provider's AutoInclude takes no free: (isIDPattern). GUI: the Routing editor's pattern box counts and lists a free: rule live as it does any pattern (patternTest in plugins/routing/client.js, from groups.models' free), refuses "free:" alone, and one hint line says the flag is the last catalog's, not a promise of no charge, in en, zh, zh-TW, ja and de. CLI help, docs/subsystems/providers-accounts.md and the site's routing-groups page (en, zh, ja) say the same. routing-levels.test.cjs: the Advanced hint line made the editor taller, so the second group's Levels row opened under the editor's sticky foot and the click landed on the foot (webkit en). The test already wheels to that row for its first group; it now does for the second too. Run: - TestGroupFreeRule, TestFreeRuleSyntax and the existing pattern tests pass. Broken by hand: with groupmatch.go and autolist.go from origin/main both are red (no members for free:workbuddy/*, IsPattern); with takes() ignoring the flag, TestGroupFreeRule is red (all six WorkBuddy models matched). - group-free-rule.test.cjs (new): chromium and webkit, en and zh, green; red with origin/main's client.js. - go vet ./... (darwin, mica), GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: clean. gofmt -l: nothing. - Full suite go test -tags nogui -timeout 45m ./... on Linux (WSL magpie-desktop) at 1e180c630 (this change onac4a4cf84): 102 ok, no FAIL. Not run whole on macOS: mote had another session's GUI suite and mica's disk was full (2 GB free; a run there failed on "no space left on device"). - At the pushed head 6801ae683 on Linux: internal/provider, cli, plugin, agent, gui packages; group-free-rule, group-patterns, routing-levels, gui-zh-tw, gui-ja, gui-de: all ok, 21 tests pass. - GUI: the 182 files that reach the Routing page or i18n, on Linux at d55680755's tree: 2805 pass, 112 fail in 21 files. The same 21 run on origin/maincb4ad12bd: 102 fail in 18 of them. The three red only here (input-look, search-keys, routing-levels) were rerun at concurrency 2: input-look and search-keys green, routing-levels red from this change and fixed above (green 2 of 2). Reds on main, filed: group-editor-selected #5049, i18n-keys #6877, codex-memories-settings #6372, inner-scroll-contain #4689, grip-inset #6293, and the rest in #4120's class; form-align newly filed as #6894. Not tried: a real WorkBuddy account's catalog (the flags come from the plugin's list, as the test's fixture has them); the GUI files on macOS.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -95,6 +95,8 @@ const groupUsage = `usage:
|
||||
* is any run of characters, / too, over the provider/model id in any case (openrouter/*:free,
|
||||
*-free, opencode-zen/*), or re:<regexp> matching the whole id, in any case too (re:openrouter/.*:(free|beta));
|
||||
(?-i) in the regexp makes case matter (re:(?-i)openrouter/.*:FREE).
|
||||
free: before a pattern keeps only the models it matches that their last catalog marks free
|
||||
(free:workbuddy/*): the vendor's free flag as last read, not a promise of no charge.
|
||||
Quote it for the shell. The group keeps the pattern, not its models: one the vendor adds joins,
|
||||
one it drops leaves. The models you name come first, in your order, then those the patterns
|
||||
match, in the order magpie models lists them; one both named and matched keeps its named place.
|
||||
|
||||
@@ -6620,13 +6620,24 @@ function routingPage(part) {
|
||||
// id, both in any case (provider.compilePattern). The group keeps them,
|
||||
// and the models they match now follow those it names, in the catalog's
|
||||
// order (Group.Matched)
|
||||
const isPattern = (s) => s.startsWith("re:") || s.includes("*");
|
||||
// A free: rule (provider.FreePrefix, #5903) keeps, of the models the
|
||||
// rest of it matches, those the last catalog marks free (m.free): never
|
||||
// a $0 price (m.zero), a rate or an id that says free
|
||||
const isPattern = (s) => s.startsWith("re:") || s.startsWith("free:") || s.includes("*");
|
||||
function patternRe(p) {
|
||||
try {
|
||||
if (p.startsWith("re:")) return goRe(p.slice(3));
|
||||
return new RegExp("^" + p.split("*").map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*") + "$", "i");
|
||||
} catch { return null; }
|
||||
}
|
||||
// patternTest is the models a pattern takes, as provider.compileRule
|
||||
// reads it; null when it is one magpie can't read
|
||||
function patternTest(p) {
|
||||
const free = p.startsWith("free:"), scope = free ? p.slice(5).trim() : p;
|
||||
if (free && (!scope || scope.startsWith("free:"))) return null;
|
||||
const r = patternRe(scope);
|
||||
return r && ((m) => (!free || m.free === true) && r.test(m.id));
|
||||
}
|
||||
// goRe is a re: pattern's regexp as Go reads it, in any case: Go's
|
||||
// leading flag group, "(?-i)" to make case matter, is JS's flags (U,
|
||||
// ungreedy, changes no whole-id match). null when it has none or JS
|
||||
@@ -6646,11 +6657,11 @@ function routingPage(part) {
|
||||
// the models served now the patterns match, but those the group names
|
||||
// (at any reasoning): as provider.matchesIn finds them
|
||||
function matchedBy(patterns, named) {
|
||||
const res = patterns.map(patternRe).filter(Boolean);
|
||||
const res = patterns.map(patternTest).filter(Boolean);
|
||||
const own = new Set(named.map((id) => splitMember(id)[0]));
|
||||
return (groups?.models || []).filter((m) => !own.has(m.id) && res.some((r) => r.test(m.id))).map((m) => m.id);
|
||||
return (groups?.models || []).filter((m) => !own.has(m.id) && res.some((r) => r(m))).map((m) => m.id);
|
||||
}
|
||||
const patternCount = (p) => { const r = patternRe(p); return r ? (groups?.models || []).filter((m) => r.test(m.id)).length : 0; };
|
||||
const patternCount = (p) => { const r = patternTest(p); return r ? (groups?.models || []).filter(r).length : 0; };
|
||||
const patternWords = (n) => n ? t(n === 1 ? "1 model" : "{n} models", { n }) : t("matches nothing now");
|
||||
// what a group keeps of its members: those it names, not those its
|
||||
// patterns matched when it was read — they are found again each time
|
||||
@@ -8283,7 +8294,7 @@ function routingPage(part) {
|
||||
const p = pin.value.trim();
|
||||
if (!p) return "";
|
||||
if (!isPattern(p)) return status(t("A pattern has a * in it, or starts with re:"), "warn"), null;
|
||||
if (!patternRe(p)) return status(t("{pattern} is not a regular expression magpie can read", { pattern: p }), "warn"), null;
|
||||
if (!patternTest(p)) return status(t("{pattern} is not a regular expression magpie can read", { pattern: p }), "warn"), null;
|
||||
if (!d.match.includes(p)) d.match.push(p);
|
||||
pin.value = "";
|
||||
rematch(); drawPats(); draw(); drawRules();
|
||||
@@ -8296,7 +8307,8 @@ function routingPage(part) {
|
||||
pbox.append(plist, padd);
|
||||
drawPats();
|
||||
const pw = el("div");
|
||||
pw.append(pbox, el("div", "hint", t("Every model a pattern matches is in the group, now and as providers list new ones, after the models above: * is any run of characters in provider/model, re: starts a regular expression.")));
|
||||
pw.append(pbox, el("div", "hint", t("Every model a pattern matches is in the group, now and as providers list new ones, after the models above: * is any run of characters in provider/model, re: starts a regular expression.")),
|
||||
el("div", "hint", t("free: before a pattern keeps the models the last catalog marked free, as in free:workbuddy/*. It is the catalog's flag, not a promise of no charge.")));
|
||||
// what few change — patterns, the lists, routing, the waits, the
|
||||
// window, how long a conversation stays, reasoning — folded under
|
||||
// Advanced below the rules, as a provider's editor folds its own (the
|
||||
|
||||
@@ -156,6 +156,7 @@ magpie.strings({
|
||||
"A pattern has a * in it, or starts with re:": "模式需要包含 *,或以 re: 开头",
|
||||
"{pattern} is not a regular expression magpie can read": "{pattern} 不是 magpie 能识别的正则表达式",
|
||||
"Every model a pattern matches is in the group, now and as providers list new ones, after the models above: * is any run of characters in provider/model, re: starts a regular expression.": "模式匹配的模型均入组(含供应商日后新增的),排在上方模型之后:* 匹配 provider/model 中任意字符,re: 开头表示正则表达式。",
|
||||
"free: before a pattern keeps the models the last catalog marked free, as in free:workbuddy/*. It is the catalog's flag, not a promise of no charge.": "模式前加 free: 只保留最近一次目录标为免费的模型,如 free:workbuddy/*。这是目录的标记,不保证不扣费。",
|
||||
"{api} only · after the others": "仅 {api} · 排在其他之后",
|
||||
"{who} is in reserve: {n} of its provider's accounts or keys take requests at once, the first in the list, so it's tried only once they have all failed.": "{who} 是备用的:其提供商同时只用列表中前 {n} 个账号或 Key,所以只有它们都失败后才会试它。",
|
||||
"{who} answered this conversation last, but it is in reserve while those before it in the list can take requests, so the conversation moves back to them.": "{who} 上次回答了这个对话,但列表中排在它前面的账号能接请求时它只作备用,所以对话回到它们那里。",
|
||||
@@ -929,6 +930,7 @@ magpie.strings({
|
||||
"A pattern has a * in it, or starts with re:": "模式需要包含 *,或以 re: 開頭",
|
||||
"{pattern} is not a regular expression magpie can read": "{pattern} 不是 magpie 能識別的正規表示式",
|
||||
"Every model a pattern matches is in the group, now and as providers list new ones, after the models above: * is any run of characters in provider/model, re: starts a regular expression.": "模式匹配的模型均入組(含供應商日後新增的),排在上方模型之後:* 匹配 provider/model 中任意字元,re: 開頭表示正規表示式。",
|
||||
"free: before a pattern keeps the models the last catalog marked free, as in free:workbuddy/*. It is the catalog's flag, not a promise of no charge.": "模式前加 free: 只保留最近一次目錄標為免費的模型,如 free:workbuddy/*。這是目錄的標記,不保證不扣費。",
|
||||
"{api} only · after the others": "僅 {api} · 排在其他之後",
|
||||
"{who} is in reserve: {n} of its provider's accounts or keys take requests at once, the first in the list, so it's tried only once they have all failed.": "{who} 是備用的:其供應商同時只用清單中前 {n} 個帳號或 Key,所以只有它們都失敗後才會試它。",
|
||||
"{who} answered this conversation last, but it is in reserve while those before it in the list can take requests, so the conversation moves back to them.": "{who} 上次回答了這個對話,但清單中排在它前面的帳號能接請求時它只作備用,所以對話回到它們那裡。",
|
||||
@@ -1680,6 +1682,7 @@ magpie.strings({
|
||||
"A pattern has a * in it, or starts with re:": "パターンには * を含めるか、re: で始めてください",
|
||||
"{pattern} is not a regular expression magpie can read": "{pattern} は magpie が読める正規表現ではありません",
|
||||
"Every model a pattern matches is in the group, now and as providers list new ones, after the models above: * is any run of characters in provider/model, re: starts a regular expression.": "パターンに一致するモデルは、プロバイダが今後追加するものも含めてすべて、上のモデルの後にグループに入ります。* は provider/model の任意の文字列、re: で始めると正規表現です。",
|
||||
"free: before a pattern keeps the models the last catalog marked free, as in free:workbuddy/*. It is the catalog's flag, not a promise of no charge.": "パターンの前に free: を付けると、直近のカタログで無料とされたモデルだけを含めます(例: free:workbuddy/*)。カタログの表示であり、課金されない保証ではありません。",
|
||||
"{api} only · after the others": "{api} のみ · 他の後",
|
||||
"{who} is in reserve: {n} of its provider's accounts or keys take requests at once, the first in the list, so it's tried only once they have all failed.": "{who} は予備です。このプロバイダーは一覧の先頭から {n} 個のアカウントやキーだけを同時に使うので、それらがすべて失敗したときだけ試されます。",
|
||||
"{who} answered this conversation last, but it is in reserve while those before it in the list can take requests, so the conversation moves back to them.": "{who} がこの会話に前回答えましたが、一覧でその前にあるアカウントがリクエストを受けられる間は予備なので、会話はそちらに戻ります。",
|
||||
@@ -2443,6 +2446,7 @@ magpie.strings({
|
||||
"A pattern has a * in it, or starts with re:": "Ein Muster enthält ein * oder beginnt mit re:",
|
||||
"{pattern} is not a regular expression magpie can read": "{pattern} ist kein regulärer Ausdruck, den magpie lesen kann",
|
||||
"Every model a pattern matches is in the group, now and as providers list new ones, after the models above: * is any run of characters in provider/model, re: starts a regular expression.": "Jedes Modell, auf das ein Muster passt, ist in der Gruppe, jetzt und sobald Anbieter neue auflisten, nach den Modellen oben: * steht für beliebige Zeichen in provider/model, re: leitet einen regulären Ausdruck ein.",
|
||||
"free: before a pattern keeps the models the last catalog marked free, as in free:workbuddy/*. It is the catalog's flag, not a promise of no charge.": "free: vor einem Muster behält nur die Modelle, die der letzte Katalog als kostenlos markiert hat, etwa free:workbuddy/*. Das ist die Markierung des Katalogs, keine Zusage, dass nichts berechnet wird.",
|
||||
"{api} only · after the others": "nur {api} · nach den anderen",
|
||||
"{who} is in reserve: {n} of its provider's accounts or keys take requests at once, the first in the list, so it's tried only once they have all failed.": "{who} ist in Reserve: Von seinem Anbieter nehmen nur die ersten {n} Konten oder Schlüssel der Liste gleichzeitig Anfragen an, also wird es erst versucht, wenn sie alle fehlgeschlagen sind.",
|
||||
"{who} answered this conversation last, but it is in reserve while those before it in the list can take requests, so the conversation moves back to them.": "{who} hat diese Unterhaltung zuletzt beantwortet, ist aber in Reserve, solange die Konten davor in der Liste Anfragen annehmen können, also geht die Unterhaltung zu ihnen zurück.",
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A group's free: rule (#5903, provider.FreePrefix): in the editor's
|
||||
// pattern box free:wb/* takes, of WorkBuddy's models, only those the
|
||||
// catalog marks free (free: true), never one priced at $0 (zero), at a
|
||||
// rate or with free in its id, nor another provider's free one. It shows
|
||||
// its live count as any pattern does, and one line says the flag is the
|
||||
// last catalog's, not a promise of no charge. Saved, the rule is sent as
|
||||
// typed. In English and Chinese; every language has the line.
|
||||
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: "wb/hy4free", name: "hy4free", providerName: "WorkBuddy", icon: "generic", free: true },
|
||||
{ id: "wb/glm-5.1", name: "glm-5.1", providerName: "WorkBuddy", icon: "generic" },
|
||||
{ id: "wb/hy3", name: "hy3", providerName: "WorkBuddy", icon: "generic", free: true },
|
||||
{ id: "wb/deepseek-v4-free", name: "deepseek-v4-free", providerName: "WorkBuddy", icon: "generic" },
|
||||
{ id: "wb/hy-zero", name: "hy-zero", providerName: "WorkBuddy", icon: "generic", zero: true },
|
||||
{ id: "wb/hy4flash-exp4", name: "hy4flash-exp4", providerName: "WorkBuddy", icon: "generic", free: true },
|
||||
{ id: "cl/mimo", name: "mimo", providerName: "Cline", icon: "generic", free: true },
|
||||
{ id: "an/claude-opus-5-5", name: "claude-opus-5-5", providerName: "Anthropic", icon: "generic" },
|
||||
];
|
||||
const members = ["an/claude-opus-5-5"];
|
||||
const groups = () => ({
|
||||
models, pools: [],
|
||||
groups: [{ id: "pool", name: "Pool", members, match: [], matched: [], fast: [], off: [], routing: "order", ready: true, patterns: [],
|
||||
memberInfo: members.map((id) => ({ id, ready: true })) }],
|
||||
});
|
||||
const LINE = "free: before a pattern keeps the models the last catalog marked free, as in free:workbuddy/*. It is the catalog's flag, not a promise of no charge.";
|
||||
|
||||
const words = {
|
||||
en: { edit: "Edit", save: "Save", add: "Add pattern", advanced: "Advanced", three: "3 models", line: LINE },
|
||||
zh: { edit: "编辑", save: "保存", add: "添加模式", advanced: "高级", three: "3 个模型", line: "模式前加 free: 只保留最近一次目录标为免费的模型,如 free:workbuddy/*。这是目录的标记,不保证不扣费。" },
|
||||
};
|
||||
|
||||
function serve(lang, posts) {
|
||||
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(() => {}); // 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/")) {
|
||||
posts.push({ path: url.pathname, body: JSON.parse(r.request().postData() || "{}") });
|
||||
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"]) {
|
||||
const w = words[lang];
|
||||
test(`${engine} ${lang}: a free: rule takes the models the catalog marks free`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const page = await (await browser.newContext({ viewport: { width: 1100, height: 2000 }, reducedMotion: "reduce" })).newPage();
|
||||
t.after(() => browser.close());
|
||||
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");
|
||||
const card = page.locator(".rt-group", { hasText: "Pool" });
|
||||
await card.waitFor();
|
||||
await card.locator("button", { hasText: w.edit }).click();
|
||||
const ed = page.locator(".rt-gedit");
|
||||
const names = () => ed.locator(".fallback:not(.rt-pats) .fbrow .n > span:first-child").allTextContents();
|
||||
await ed.locator(".fallback:not(.rt-pats) .fbrow").first().waitFor();
|
||||
assert.deepEqual(await names(), ["claude-opus-5-5"]);
|
||||
|
||||
const adv = ed.locator("details.rt-gadv");
|
||||
if (!(await adv.evaluate((d) => d.open))) await adv.locator("summary").click();
|
||||
assert.equal(await adv.locator(".hint", { hasText: w.line }).count(), 1, "the line says what free: is");
|
||||
const pbox = ed.locator(".rt-pats");
|
||||
await pbox.locator("input").fill("free:wb/*");
|
||||
await pbox.locator("button", { hasText: w.add }).click();
|
||||
assert.deepEqual(await names(), ["claude-opus-5-5", "hy4free", "hy3", "hy4flash-exp4"], "only those marked free, of WorkBuddy's, in the catalog's order");
|
||||
const rule = pbox.locator(".fbrow").first();
|
||||
assert.equal(await rule.locator("code").textContent(), "free:wb/*");
|
||||
assert.equal(await rule.locator("small").textContent(), w.three, "its live count");
|
||||
|
||||
// the plain pattern beside it is as it was: every one of WorkBuddy's
|
||||
await pbox.locator("input").fill("wb/*-free");
|
||||
await pbox.locator("button", { hasText: w.add }).click();
|
||||
assert.deepEqual(await names(), ["claude-opus-5-5", "hy4free", "hy3", "deepseek-v4-free", "hy4flash-exp4"]);
|
||||
await pbox.locator(".fbrow").nth(1).locator("button").click();
|
||||
assert.deepEqual(await names(), ["claude-opus-5-5", "hy4free", "hy3", "hy4flash-exp4"]);
|
||||
// free: with nothing after it is refused, the box keeping it
|
||||
await pbox.locator("input").fill("free:");
|
||||
await pbox.locator("button", { hasText: w.add }).click();
|
||||
assert.equal(await pbox.locator(".fbrow").count(), 1);
|
||||
assert.equal(await pbox.locator("input").inputValue(), "free:");
|
||||
await pbox.locator("input").fill("");
|
||||
|
||||
const b = ed.locator("button.primary", { hasText: w.save });
|
||||
await b.scrollIntoViewIfNeeded();
|
||||
await b.click();
|
||||
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 model named is sent");
|
||||
assert.deepEqual(sent.body.match, ["free:wb/*"], "the rule as typed");
|
||||
|
||||
const missing = await page.evaluate((k) => ["zh", "zh-TW", "ja", "de"].filter((l) => !I18N[l][k]), LINE);
|
||||
assert.deepEqual(missing, [], "every language has the line");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -101,11 +101,14 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
// window's foot as the editor grew, wheeled to as the reader would:
|
||||
// WebKit's own scroll left a sliver of it over the footer and clicked
|
||||
// the footer)
|
||||
await page.mouse.move(550, 600);
|
||||
for (let i = 0; i < 10 && (await row().boundingBox()).y > 1400 - 260; i++) {
|
||||
await page.mouse.wheel(0, 300);
|
||||
await page.waitForTimeout(150);
|
||||
}
|
||||
const wheelToRow = async () => {
|
||||
await page.mouse.move(550, 600);
|
||||
for (let i = 0; i < 10 && (await row().boundingBox()).y > 1400 - 260; i++) {
|
||||
await page.mouse.wheel(0, 300);
|
||||
await page.waitForTimeout(150);
|
||||
}
|
||||
};
|
||||
await wheelToRow();
|
||||
await row().locator(".segs .opt", { hasText: w.named }).click();
|
||||
assert.equal(await row().locator(".hint").textContent(), w.namedHint);
|
||||
assert.deepEqual(await chips().allTextContents(), ["none", "minimal", "low", "medium", "high", "xhigh", "max"]);
|
||||
@@ -131,6 +134,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await row().waitFor();
|
||||
assert.equal(await row().locator(".segs .opt.on").textContent(), w.named);
|
||||
assert.deepEqual(await lit(), ["medium", "xhigh"]);
|
||||
await wheelToRow(); // as above: the row can open under the foot
|
||||
await chips().filter({ hasText: /^medium$/ }).click();
|
||||
await chips().filter({ hasText: /^xhigh$/ }).click();
|
||||
await save();
|
||||
|
||||
@@ -153,7 +153,7 @@ func CleanAutoInclude(in []string) ([]string, error) {
|
||||
if p == "" || slices.Contains(out, p) {
|
||||
continue
|
||||
}
|
||||
if !IsPattern(p) {
|
||||
if !isIDPattern(p) {
|
||||
return nil, fmt.Errorf("%q is a model's id, not a rule: a rule has a * in it, or starts with %s (magpie provider models <id> +%s picks that one)", p, RegexpPrefix, p)
|
||||
}
|
||||
if _, err := compilePattern(p); err != nil {
|
||||
|
||||
@@ -31,11 +31,29 @@ import (
|
||||
// "(?-i)" in it makes case matter from there on: "re:(?-i)openrouter/.*:FREE".
|
||||
const RegexpPrefix = "re:"
|
||||
|
||||
// FreePrefix starts a group's member rule that takes, of the models the
|
||||
// rest of it matches, only those their catalog marks free (Entry.Free,
|
||||
// catalog.Model's: the vendor's or its plugin's own word, as the catalog
|
||||
// was last read): "free:workbuddy/*" is WorkBuddy's free models, today's
|
||||
// and those its next list marks so (#5903). The flag alone decides: a
|
||||
// model listed at $0, at a rate of 0, on an account named Free or with
|
||||
// "free" in its id is not taken for one, and the rule is no promise that
|
||||
// a request costs nothing — the flag is the catalog's, not the bill's.
|
||||
// The rest is a glob, a "re:" pattern or an id, matched as on its own.
|
||||
const FreePrefix = "free:"
|
||||
|
||||
// IsPattern reports whether a member as typed is a pattern rather than a
|
||||
// model's id: a regular expression ("re:…") or a glob with "*" in it. No
|
||||
// vendor's model id has a "*" in it, so a glob can't be taken for one.
|
||||
// model's id: a regular expression ("re:…"), a free rule ("free:…") or a
|
||||
// glob with "*" in it. No vendor's model id has a "*" in it or starts
|
||||
// with either prefix, so none can be taken for one.
|
||||
func IsPattern(s string) bool {
|
||||
s = strings.TrimSpace(s)
|
||||
return strings.HasPrefix(s, FreePrefix) || isIDPattern(s)
|
||||
}
|
||||
|
||||
// isIDPattern is IsPattern for a rule over ids alone, as a provider's
|
||||
// AutoInclude takes them: a regular expression or a glob.
|
||||
func isIDPattern(s string) bool {
|
||||
return strings.HasPrefix(s, RegexpPrefix) || strings.Contains(s, "*")
|
||||
}
|
||||
|
||||
@@ -85,19 +103,54 @@ func compilePattern(p string) (matcher, error) {
|
||||
return regexp.MustCompile("(?i)^" + strings.Join(parts, ".*") + "$"), nil
|
||||
}
|
||||
|
||||
// rule is a group's pattern compiled: the ids it matches, and with free
|
||||
// set only the models among them their catalog marks free (FreePrefix).
|
||||
type rule struct {
|
||||
ids matcher
|
||||
free bool
|
||||
}
|
||||
|
||||
// takes reports whether the rule puts e in its group.
|
||||
func (r rule) takes(e Entry) bool {
|
||||
return (!r.free || e.Free) && r.ids.MatchString(e.ID)
|
||||
}
|
||||
|
||||
// compileRule is a group's pattern as the rule it means: a "free:" one's
|
||||
// scope is compiled as a pattern of its own, and each model it matches
|
||||
// must be marked free besides.
|
||||
func compileRule(p string) (rule, error) {
|
||||
scope, free := strings.CutPrefix(p, FreePrefix)
|
||||
if !free {
|
||||
x, err := compilePattern(p)
|
||||
return rule{ids: x}, err
|
||||
}
|
||||
scope = strings.TrimSpace(scope)
|
||||
switch {
|
||||
case scope == "":
|
||||
return rule{}, fmt.Errorf("%q names no models after %s: free:workbuddy/* is WorkBuddy's models its catalog marks free", p, FreePrefix)
|
||||
case strings.HasPrefix(scope, FreePrefix):
|
||||
return rule{}, fmt.Errorf("%q says %s twice", p, FreePrefix)
|
||||
}
|
||||
x, err := compilePattern(scope)
|
||||
return rule{ids: x, free: true}, err
|
||||
}
|
||||
|
||||
// CleanPatterns are a group's patterns as they are kept: trimmed, each
|
||||
// once, every one one magpie can read.
|
||||
func CleanPatterns(in []string) ([]string, error) {
|
||||
var out []string
|
||||
for _, p := range in {
|
||||
p = strings.TrimPrefix(strings.TrimSpace(p), "magpie/")
|
||||
if scope, ok := strings.CutPrefix(p, FreePrefix); ok {
|
||||
p = FreePrefix + strings.TrimPrefix(strings.TrimSpace(scope), "magpie/")
|
||||
}
|
||||
if p == "" || slices.Contains(out, p) {
|
||||
continue
|
||||
}
|
||||
if !IsPattern(p) {
|
||||
return nil, fmt.Errorf("%q is a model's id, not a pattern: a pattern has a * in it, or starts with %s", p, RegexpPrefix)
|
||||
return nil, fmt.Errorf("%q is a model's id, not a pattern: a pattern has a * in it, or starts with %s or %s", p, RegexpPrefix, FreePrefix)
|
||||
}
|
||||
if _, err := compilePattern(p); err != nil {
|
||||
if _, err := compileRule(p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, p)
|
||||
@@ -106,9 +159,11 @@ func CleanPatterns(in []string) ([]string, error) {
|
||||
}
|
||||
|
||||
// PatternMatches reports whether a pattern matches a "provider/model" id.
|
||||
// A free rule's scope is matched (FreePrefix): the flag is the model's,
|
||||
// not its id's, and a caller asks this of a model the rule took.
|
||||
func PatternMatches(pattern, id string) bool {
|
||||
x, err := compilePattern(pattern)
|
||||
return err == nil && x.MatchString(id)
|
||||
r, err := compileRule(pattern)
|
||||
return err == nil && r.ids.MatchString(id)
|
||||
}
|
||||
|
||||
// matchesIn are the models g's patterns match among entries — the models
|
||||
@@ -119,10 +174,10 @@ func matchesIn(entries []Entry, g Group) []string {
|
||||
if len(g.Match) == 0 {
|
||||
return nil
|
||||
}
|
||||
var res []matcher
|
||||
var res []rule
|
||||
for _, p := range g.Match {
|
||||
if x, err := compilePattern(p); err == nil {
|
||||
res = append(res, x)
|
||||
if r, err := compileRule(p); err == nil {
|
||||
res = append(res, r)
|
||||
}
|
||||
}
|
||||
named := map[string]bool{}
|
||||
@@ -135,7 +190,7 @@ func matchesIn(entries []Entry, g Group) []string {
|
||||
if named[e.ID] || slices.Contains(out, e.ID) {
|
||||
continue
|
||||
}
|
||||
if slices.ContainsFunc(res, func(x matcher) bool { return x.MatchString(e.ID) }) {
|
||||
if slices.ContainsFunc(res, func(r rule) bool { return r.takes(e) }) {
|
||||
out = append(out, e.ID)
|
||||
}
|
||||
}
|
||||
@@ -276,9 +331,9 @@ func PatternHits(g Group) []PatternHit {
|
||||
out := make([]PatternHit, 0, len(g.Match))
|
||||
for _, p := range g.Match {
|
||||
h := PatternHit{Pattern: p}
|
||||
if x, err := compilePattern(p); err == nil {
|
||||
if r, err := compileRule(p); err == nil {
|
||||
for _, e := range entries {
|
||||
if x.MatchString(e.ID) {
|
||||
if r.takes(e) {
|
||||
h.Models++
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,9 +3,14 @@ package provider
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
func patternHome(t *testing.T) {
|
||||
@@ -323,3 +328,128 @@ func TestRegexpPatternLookahead(t *testing.T) {
|
||||
t.Errorf("auto-include lookahead refused: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// freePlugins are WorkBuddy's and Cline's plugins signed in, their models
|
||||
// as each lists them (#5903): WorkBuddy's hy4free, hy3 and hy4flash-exp4
|
||||
// marked free (its "credits": "x0.00"), glm-5.1 at a rate, one with "free"
|
||||
// in its id that isn't marked so, and one at a rate of 0 not marked free.
|
||||
func freePlugins(t *testing.T, wb []plugin.Model) {
|
||||
t.Helper()
|
||||
claudeHome(t)
|
||||
t.Setenv("MAGPIE_BUN", "")
|
||||
write := func(name string, v any) {
|
||||
t.Helper()
|
||||
b, _ := json.Marshal(v)
|
||||
os.MkdirAll(settings.Dir(), 0o700)
|
||||
if err := os.WriteFile(filepath.Join(settings.Dir(), name), b, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
wbSpec, clSpec := "@magpie-community/opencode-workbuddy-auth", "@magpie-community/opencode-cline-auth"
|
||||
write("plugins.json", map[string]any{"plugins": []map[string]any{{"spec": wbSpec}, {"spec": clSpec}}})
|
||||
write("plugin-auth.json", map[string]map[string]any{"workbuddy": {"type": "api", "key": "wb-1234"}, "cline": {"type": "api", "key": "sk-cline-1234"}})
|
||||
t.Cleanup(func() { plugin.UseCached(nil) })
|
||||
listWorkBuddy(wb)
|
||||
}
|
||||
|
||||
// listWorkBuddy is the plugins' catalog as read again, WorkBuddy listing wb.
|
||||
func listWorkBuddy(wb []plugin.Model) {
|
||||
wbSpec, clSpec := "@magpie-community/opencode-workbuddy-auth", "@magpie-community/opencode-cline-auth"
|
||||
plugin.UseCached([]plugin.Provider{
|
||||
{ID: "workbuddy", Spec: wbSpec, Name: "WorkBuddy", Methods: []plugin.Method{{Type: "api", Label: "API key"}}, Accounts: []plugin.Account{{Key: "workbuddy", Type: "api"}}, Models: wb},
|
||||
{ID: "cline", Spec: clSpec, Name: "Cline", Methods: []plugin.Method{{Type: "api", Label: "API key"}}, Accounts: []plugin.Account{{Key: "cline", Type: "api"}},
|
||||
Models: []plugin.Model{{ID: "cline-free/mimo-v2.6-flash", Name: "MiMo V2.6 Flash (free)", Free: true}}},
|
||||
})
|
||||
}
|
||||
|
||||
// A group's free: rule (#5903) takes, of the models its scope matches,
|
||||
// only those their catalog marks free: within the provider it names, as
|
||||
// the catalog was last read. A model at $0, at a rate of 0 or with free in
|
||||
// its id is not taken, nor one of another provider; the catalog marking
|
||||
// another free, or one free no longer, changes the group with no save, and
|
||||
// the patterns that were there before match as they did.
|
||||
func TestGroupFreeRule(t *testing.T) {
|
||||
wb := []plugin.Model{
|
||||
{ID: "hy4free", Name: "Hy4 Free", Free: true},
|
||||
{ID: "glm-5.1", Name: "GLM 5.1", Rate: 1},
|
||||
{ID: "hy3", Name: "Hy3", Free: true},
|
||||
{ID: "deepseek-v4-free", Name: "DeepSeek V4 Free"},
|
||||
{ID: "hy-rate0", Name: "Hy Rate 0", Rate: 0},
|
||||
{ID: "hy4flash-exp4", Name: "Hy4 Flash Exp4", Free: true},
|
||||
}
|
||||
freePlugins(t, wb)
|
||||
if err := Save(Provider{ID: "or", Name: "OR", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"x:free", "y"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// a model the user priced at $0 is not one its catalog marks free
|
||||
if err := SetModelPrice("or/y", &catalog.Price{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p, _ := Find("or"); p == nil || !p.PricedFree(settings.Load(), "y") {
|
||||
t.Fatal("or/y is not priced free: the fixture tests nothing")
|
||||
}
|
||||
for _, g := range []Group{
|
||||
{Name: "WB Free", Members: []string{"free:workbuddy/*"}},
|
||||
{Name: "All Free", Match: []string{"free:*"}},
|
||||
{Name: "WB", Match: []string{"workbuddy/*"}},
|
||||
{Name: "OR Free", Match: []string{"or/*:free"}},
|
||||
} {
|
||||
if err := SaveGroup(g); err != nil {
|
||||
t.Fatalf("%s: %v", g.Name, err)
|
||||
}
|
||||
}
|
||||
wbFree := []string{"workbuddy/hy4free", "workbuddy/hy3", "workbuddy/hy4flash-exp4"}
|
||||
g, _, _ := FindGroup("group/wb-free")
|
||||
if !slices.Equal(g.Match, []string{"free:workbuddy/*"}) || !slices.Equal(g.Members, wbFree) {
|
||||
t.Fatalf("free:workbuddy/*: match %v members %v (served %v)", g.Match, g.Members, IDs())
|
||||
}
|
||||
if got := routedIDs(t, "group/wb-free"); !slices.Equal(got, wbFree) {
|
||||
t.Fatalf("routed: %v", got)
|
||||
}
|
||||
if hits := PatternHits(g); len(hits) != 1 || hits[0].Models != 3 {
|
||||
t.Fatalf("hits: %+v", hits)
|
||||
}
|
||||
if got := routedIDs(t, "group/all-free"); !slices.Equal(got, append(slices.Clone(wbFree), "cline/cline-free/mimo-v2.6-flash")) {
|
||||
t.Fatalf("free:*: %v", got)
|
||||
}
|
||||
// the rules there before are as they were
|
||||
if got := routedIDs(t, "group/wb"); len(got) != len(wb) {
|
||||
t.Fatalf("workbuddy/*: %v", got)
|
||||
}
|
||||
if got := routedIDs(t, "group/or-free"); !slices.Equal(got, []string{"or/x:free"}) {
|
||||
t.Fatalf("or/*:free: %v", got)
|
||||
}
|
||||
// the next catalog: hy3 free no longer, hy5 new and free, hy4free gone
|
||||
listWorkBuddy([]plugin.Model{
|
||||
{ID: "hy3", Name: "Hy3", Rate: 0.5},
|
||||
{ID: "hy4flash-exp4", Name: "Hy4 Flash Exp4", Free: true},
|
||||
{ID: "hy5", Name: "Hy5", Free: true},
|
||||
})
|
||||
if got := routedIDs(t, "group/wb-free"); !slices.Equal(got, []string{"workbuddy/hy4flash-exp4", "workbuddy/hy5"}) {
|
||||
t.Fatalf("after the catalog changed: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A free: rule is said as a pattern and kept as typed, magpie/ and spaces
|
||||
// trimmed; one naming nothing, or free: twice, is refused. A provider's
|
||||
// AutoInclude, over ids alone, reads free: as it did before.
|
||||
func TestFreeRuleSyntax(t *testing.T) {
|
||||
if !IsPattern("free:workbuddy/hy3") || !IsPattern("free:re:workbuddy/hy.*") {
|
||||
t.Error("IsPattern")
|
||||
}
|
||||
got, err := CleanPatterns([]string{" free: magpie/workbuddy/* ", "free:re:workbuddy/hy.*", "free:workbuddy/*"})
|
||||
if err != nil || !slices.Equal(got, []string{"free:workbuddy/*", "free:re:workbuddy/hy.*"}) {
|
||||
t.Fatalf("clean: %v %v", got, err)
|
||||
}
|
||||
for _, p := range []string{"free:", "free: ", "free:free:x/*", "free:re:x/(a"} {
|
||||
if _, err := CleanPatterns([]string{p}); err == nil {
|
||||
t.Errorf("%q taken", p)
|
||||
}
|
||||
}
|
||||
if !PatternMatches("free:workbuddy/*", "workbuddy/hy3") || PatternMatches("free:workbuddy/*", "cline/hy3") {
|
||||
t.Error("PatternMatches over a free rule's scope")
|
||||
}
|
||||
if _, err := CleanAutoInclude([]string{"free:x"}); err == nil {
|
||||
t.Error("an auto-include rule over ids took free:x")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,7 +193,7 @@
|
||||
<p>ルーティンググループは異なるプロバイダーのモデルをまとめます。たとえば Claude サブスクリプションの Opus と Copilot の Opus、あるいは複数の無料モデルです。エージェントはモデルとして <code>group/<id></code> を選び、magpie はグループのルーティングとルールに従って各リクエストを送ります。グループは <span class="ui">ルーティング</span> ページの <span class="ui">ルーティンググループ</span> にあり、<span class="ui">新しいグループ</span> で作ります。</p>
|
||||
<ol class="steps">
|
||||
<li><b>magpie が自分でグループを見つける</b>二つ以上のプロバイダーが提供するモデルは自動でグループ(auto-<モデル>)になり、設定は不要です。不要なら <span class="ui">グループを自動で作成</span> をオフにします。</li>
|
||||
<li><b>入れられるもの</b>provider/model で書いた任意のモデル、別のグループ(8 段まで)、パターン。<code>openrouter/*:free</code> なら後から増える無料モデルも入ります。</li>
|
||||
<li><b>入れられるもの</b>provider/model で書いた任意のモデル、別のグループ(8 段まで)、パターン。<code>openrouter/*:free</code> なら後から増える無料モデルも入ります。パターンの前に <code>free:</code> を付けると、直近のカタログで無料とされたモデルだけになります(例: <code>free:workbuddy/*</code>)。カタログの表示であり、課金されない保証ではありません。</li>
|
||||
<li><b>グループのルーティング</b>上のものに加えて、<span class="ui">重み付け</span>(モデルごとの重み)と <span class="ui">手動</span>(選んだモデルだけ、切り替えなし)があります。</li>
|
||||
<li><b>ルール</b>ターンの長さ、画像の有無、求められた推論の強さ、エージェントで、ターンを最初にどのモデルへ送るかを決めます。</li>
|
||||
</ol>
|
||||
|
||||
@@ -193,7 +193,7 @@
|
||||
<p>A routing group puts models from different providers together: Opus from a Claude subscription and from Copilot, say, or several free models. An agent picks <code>group/<id></code> as its model, and magpie sends each request as the group's routing and rules say. Groups are under <span class="ui">Routing groups</span> on the <span class="ui">Routing</span> page; <span class="ui">New group</span> makes one.</p>
|
||||
<ol class="steps">
|
||||
<li><b>magpie finds groups by itself</b>A model two or more of your providers serve becomes a group of them (auto-<model>), with nothing to set. Switch off <span class="ui">Find groups on their own</span> if you don't want them.</li>
|
||||
<li><b>What goes in</b>Any model as provider/model, another group (up to 8 deep), or a pattern: <code>openrouter/*:free</code> takes in free models the vendor adds later too.</li>
|
||||
<li><b>What goes in</b>Any model as provider/model, another group (up to 8 deep), or a pattern: <code>openrouter/*:free</code> takes in free models the vendor adds later too. <code>free:</code> before a pattern keeps only the models the last catalog marks free, as in <code>free:workbuddy/*</code>: the vendor's flag, not a promise of no charge.</li>
|
||||
<li><b>A group's routing</b>Besides the ones above, a group can go <span class="ui">By weight</span> (each model's weight) or <span class="ui">Manual</span> (only the model you pick, with no failover).</li>
|
||||
<li><b>Rules</b>Which model a turn goes to first, by its length, an image, the reasoning asked for or the agent.</li>
|
||||
</ol>
|
||||
|
||||
@@ -193,7 +193,7 @@
|
||||
<p>路由组把不同供应商的模型放在一起,比如官方 Claude 订阅里的 Opus 和 Copilot 里的 Opus,或者几个免费模型。Agent 选 <code>group/<id></code> 作为模型,magpie 按组的路由方式和规则决定每个请求交给谁。组在 <span class="ui">路由</span> 页的 <span class="ui">路由组</span> 里,用 <span class="ui">新建组</span> 创建。</p>
|
||||
<ol class="steps">
|
||||
<li><b>magpie 自己会找组</b>两个及以上供应商都提供的模型,自动成为一个组(auto-<模型>),不用设置。不想要可以关掉 <span class="ui">自动创建路由组</span>。</li>
|
||||
<li><b>组里放什么</b>任意模型,用 provider/model 写;也可以放另一个组(最多 8 层),或者用通配符:<code>openrouter/*:free</code> 会把以后新出的免费模型也加进来。</li>
|
||||
<li><b>组里放什么</b>任意模型,用 provider/model 写;也可以放另一个组(最多 8 层),或者用通配符:<code>openrouter/*:free</code> 会把以后新出的免费模型也加进来。模式前加 <code>free:</code> 只保留最近一次目录标为免费的模型,如 <code>free:workbuddy/*</code>;这是厂商目录的标记,不保证不扣费。</li>
|
||||
<li><b>组的路由方式</b>除了上面几种,组还有 <span class="ui">按权重</span>(按每个模型的权重)和 <span class="ui">手动</span>(只用你选的那个,不切换)。</li>
|
||||
<li><b>规则</b>可以按一轮的长度、是否带图、要求的推理强度或 Agent,决定一轮先交给哪个模型。</li>
|
||||
</ol>
|
||||
|
||||
Reference in New Issue
Block a user