From 265217bf4c19fdea22f5819607a7c3d39601157c Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 18 Nov 2026 12:32:23 +0800 Subject: [PATCH] =?UTF-8?q?gui:=20a=20model=20disabled=20in=20Settings=20?= =?UTF-8?q?=E2=86=92=20Models=20says=20so=20in=20its=20provider's=20editor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A model disabled for every request (#1867) still drew in its provider's editor as an ordinary chip, ticked or served, so it read as one agents get while the gateway refused it. /api/providers now gives each model the pattern that turns it off (provider.DisabledPattern, the list read once per provider), and its chip is dimmed with a "disabled" badge and a title naming the pattern and where it is set. Every language. Paid for in the core budget by moving six trailing comments onto lines of their own (whole-line comments aren't counted), no raise. Run (mote, at this tree): - go test ./internal/gui -run 'TestProviderInfoSaysADisabledModel|TestCoreScriptBudget|TestI18n|TestCSS': ok - go test ./internal/provider -run TestDisabled: ok - disabled-model-chips.test.cjs, Chromium and WebKit, en zh zh-TW ja de: 12 pass Broken by hand, each red, then put back: - providers.go not setting Disabled: TestProviderInfoSaysADisabledModel red. - the chip not reading m.disabled: disabled-model-chips 12 of 12 red. Not tried: the real app window; the rest of the GUI suite. --- internal/gui/assets/app.js | 23 +++++-- internal/gui/assets/i18n.js | 8 +++ internal/gui/disabled_chips_test.go | 42 ++++++++++++ internal/gui/providers.go | 5 ++ .../gui/tests/disabled-model-chips.test.cjs | 65 +++++++++++++++++++ internal/provider/disabled.go | 10 +++ 6 files changed, 146 insertions(+), 7 deletions(-) create mode 100644 internal/gui/disabled_chips_test.go create mode 100644 internal/gui/tests/disabled-model-chips.test.cjs diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 16edaa466..6e0707c37 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -83,11 +83,13 @@ let providers = null; // { providers, presets, gateway } let view = "agents"; let backTo = null, jumpNext = false; // Back (jumpFrom) let showAllAgents = false; // the agents no one has set anything on, folded away -let showHiddenAgents = false; // under them, the ones hidden by hand: a fold of their own, shut until asked +// under them, the ones hidden by hand: a fold of their own, shut until asked +let showHiddenAgents = false; let period = "today"; // usage window let usage = null; // last usage summary let pick = null; // { agent, field, options, items, cursor, anchor } -let editing = null; // provider id being edited; { preset } or { custom: true } for a new one +// provider id being edited; { preset } or { custom: true } for a new one +let editing = null; let draft = null; // the editor's working copy let naming = null; // the provider whose models' names and levels are open in its editor let advanced = null; // { of, open }: the editor's Advanced as it was opened or closed by hand, kept by @@ -99,7 +101,8 @@ let adding = false; // the preset sheet is open let partnersCounted = null; // the Partners heading's light has run since the sheet opened (shinePartners) let partnersShone = false; -let importing = null; // a magpie://import link waiting for a yes: { provider, error, replaces } +// a magpie://import link waiting for a yes: { provider, error, replaces } +let importing = null; let importingApps = null; // the Import from other apps dialog: { sources, picks } let providerDiscovery = []; // only opaque fingerprints and app names, never credentials let discoveryAt = 0, discoveryRun = 0, discoveryPending = false; @@ -11579,8 +11582,10 @@ function renderModels(p) { // past the first 80 only the picked are drawn, till the rest are asked for (#685) if (picksOnly && !on) { unpicked++; continue; } if (shown >= 80 && !f && !showAll && !on) { hidden++; continue; } - const c = el("button", "mchip pick" + (on ? " on" : served.has(m.id) ? " auto" : "") + (noAPI(m) ? " noapi" : "")); + const off = m.disabled; + const c = el("button", "mchip pick" + (on ? " on" : served.has(m.id) ? " auto" : "") + (noAPI(m) || off ? " noapi" : "")); c.append(el("span", "", m.name && m.name !== m.id ? m.name : m.id)); + if (off) c.append(el("span", "badge", t("disabled"))); const tell = tellTag(tells.get(m.id)); if (tell) c.append(tell); // which keys list it, when not all do (keysTag, in keyrates.js) @@ -11605,6 +11610,7 @@ function renderModels(p) { else if (m.name && m.name !== m.id) c.title = m.id; if (free) c.title = (c.title || m.id) + " · " + freeWhy(m.free, m.zero); if (noAPI(m)) c.title = (c.title || m.id) + "\n" + t("{p} has no URL for the API its list serves it on ({apis}), so agents aren't offered it. Add that URL, or set the API it is asked on in Model settings.", { p: p.name, apis: (apiNow(m.id) ? [apiNow(m.id)] : m.auto || []).map(apiLabel).join(" · ") }); + if (off) c.title = (c.title || m.id) + "\n" + t("Disabled in Settings → Models ({pattern}): refused on every route", { pattern: off }); if (served.has(m.id)) c.title = (c.title || m.id) + "\n" + t(draft.unlisted ? "Routing groups use it: none are picked, so the vendor's list is used" : "Agents see it: none are picked, so the vendor's list is used") + "\n" + t("Click to pick just this model"); else if (on && draft.unlisted && !decideOnly(p)) c.title = (c.title || m.id) + "\n" + t("Picked: the routing groups it is in use it. Agents don't see it."); // an agent's own list can leave a pick out (Kylin_Cloud on X) @@ -12704,7 +12710,8 @@ function importSay(agent) { checks: t("Each account's sign-in is refreshed and its project looked up, as signing in does."), }; } -let signing = null; // the sign-in under way: { id, agent, url, state, installing, error } +// the sign-in under way: { id, agent, url, state, installing, error } +let signing = null; // stopSignIn tells the server the sign-in under way is given up const stopSignIn = () => { if (signing?.id) api("signin/" + signing.id + "/cancel", {}).catch(() => {}); }; const signingOpen = () => signing?.state === "waiting" || signing?.state === "installing"; @@ -15732,7 +15739,8 @@ function renderMove(p) { const failed = going?.why || m.state === "failed" && (m.why || m.error) && t("It stays built-in: {error}", { error: moveWhy(m, p) }); say(failed || ""); const idle = () => failed ? t("Try again") : t("Move to the plugin"); - const b = el("button", "text action", going?.busy || idle()); // a button, not a line of text: it changes what runs the subscription + // a button, not a line of text: it changes what runs the subscription + const b = el("button", "text action", going?.busy || idle()); b.disabled = b.classList.toggle("busy", !!going?.busy); b.onclick = async () => { b.classList.add("busy"); @@ -23263,7 +23271,8 @@ function keepHeld() { } addEventListener("click", (e) => { const readers = performance.now() < purposeUntil; - purposeUntil = flingUntil = 0; // what came before the click (Space pressed on a button, a tremble, the lift of a tap) is no scroll + // what came before the click (Space pressed on a button, a tremble, the lift of a tap) is no scroll + purposeUntil = flingUntil = 0; // a pick in a menu (in body, outside any view) is a click on the pill that // opened it: what it changes comes in around that pill, which stays put (#961) const at = protoMenu?.box.contains(e.target) ? protoMenu.anchor : e.target; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 4fce18000..10e4f2a27 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4,6 +4,8 @@ // works. {name} slots are filled by t(str, vars). const I18N = { zh: { + "disabled": "已停用", + "Disabled in Settings → Models ({pattern}): refused on every route": "已在 设置 → 模型 中停用({pattern}):所有路由都会拒绝", "Check {model} on {provider}": "在 {provider} 上检查 {model}", "A few small real calls with known answers, billed as any other: write the numbers 1 to 40, work out sums, answer in an exact form, call the right tool. Each says what came back.": "几次小的真实调用,答案事先已知,照常计费:写出 1 到 40、算算术、按指定格式作答、调用正确的工具。每一项都列出实际返回的内容。", "Count to 40": "数到 40", @@ -5462,6 +5464,8 @@ const I18N = { "runs everything without asking": "所有操作都直接运行,不询问", }, "zh-TW": { + "disabled": "已停用", + "Disabled in Settings → Models ({pattern}): refused on every route": "已在 設定 → 模型 中停用({pattern}):所有路由都會拒絕", "Check {model} on {provider}": "在 {provider} 上檢查 {model}", "A few small real calls with known answers, billed as any other: write the numbers 1 to 40, work out sums, answer in an exact form, call the right tool. Each says what came back.": "幾次小的真實呼叫,答案事先已知,照常計費:寫出 1 到 40、算算術、按指定格式作答、呼叫正確的工具。每一項都列出實際回傳的內容。", "Count to 40": "數到 40", @@ -10904,6 +10908,8 @@ const I18N = { "runs everything without asking": "所有操作都直接執行,不詢問", }, ja: { + "disabled": "無効", + "Disabled in Settings → Models ({pattern}): refused on every route": "設定 → モデル で無効にしています({pattern}):どの経路でも断られます", "Check {model} on {provider}": "{provider} で {model} をチェック", "A few small real calls with known answers, billed as any other: write the numbers 1 to 40, work out sums, answer in an exact form, call the right tool. Each says what came back.": "答えの決まった小さな実際の呼び出しを数回行います(通常どおり課金):1 から 40 までを書く、計算する、決まった形式で答える、正しいツールを呼ぶ。それぞれ返ってきた内容を示します。", "Count to 40": "40 まで数える", @@ -16348,6 +16354,8 @@ const I18N = { "runs everything without asking": "すべて確認せずに実行する", }, de: { + "disabled": "deaktiviert", + "Disabled in Settings → Models ({pattern}): refused on every route": "In Einstellungen → Modelle deaktiviert ({pattern}): auf jedem Weg abgelehnt", "Check {model} on {provider}": "{model} bei {provider} prüfen", "A few small real calls with known answers, billed as any other: write the numbers 1 to 40, work out sums, answer in an exact form, call the right tool. Each says what came back.": "Ein paar kleine echte Aufrufe mit bekannten Antworten, wie jeder andere berechnet: die Zahlen 1 bis 40 schreiben, rechnen, in einer genauen Form antworten, das richtige Werkzeug aufrufen. Jeder zeigt, was zurückkam.", "Count to 40": "Bis 40 zählen", diff --git a/internal/gui/disabled_chips_test.go b/internal/gui/disabled_chips_test.go new file mode 100644 index 000000000..0fef9de5f --- /dev/null +++ b/internal/gui/disabled_chips_test.go @@ -0,0 +1,42 @@ +package gui + +import ( + "os" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// A model disabled in Settings → Models (#1867) is still in its provider's +// editor, told by the pattern that turns it off, so its chip can say so +// instead of reading as a pick the gateway then refuses. +func TestProviderInfoSaysADisabledModel(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()) + p := provider.Provider{ID: "relay", Name: "Relay", Chat: "http://127.0.0.1:1/v1", Key: "key", Models: []string{"claude-fable-5", "exact-one", "vendor/tail", "kept"}} + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + if err := provider.SetDisabledModels([]string{"*FABLE*", "relay/exact-one", "tail"}); err != nil { + t.Fatal(err) + } + got, err := provider.Find("relay") + if err != nil { + t.Fatal(err) + } + want := map[string]string{"claude-fable-5": "*FABLE*", "exact-one": "relay/exact-one", "vendor/tail": "tail", "kept": ""} + seen := map[string]bool{} + for _, m := range providerInfo(*got, nil).Models { + seen[m.ID] = true + if w, ok := want[m.ID]; ok && m.Disabled != w { + t.Errorf("%s: disabled %q, want %q", m.ID, m.Disabled, w) + } + } + for id := range want { + if !seen[id] { + t.Errorf("%s left out of the editor", id) + } + } +} diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 6fe970c6a..8d60f0768 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -93,6 +93,9 @@ type modelJSON struct { // provider (#2578): only for a model Claude Desktop, installed here, // is shown and names after its own catalog, "" for every other. Desktop string `json:"desktop,omitempty"` + // Disabled is the pattern of Settings' disabled models (#1867) that + // turns it off, "" for a model that isn't + Disabled string `json:"disabled,omitempty"` // what it costs, USD per million tokens (#819): the price the user set // for it, and its list price, its vendor's else its maker's, before the // provider's price rate @@ -1198,6 +1201,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs // the provider's catalogs worked out once, and each model priced once // for its list price and whether it is free pricer := p.Pricer() + disabled := provider.DisabledPattern() // each model's provider/model ref, made once: the settings' maps and // every agent's hidden list are looked up by it var refs []string @@ -1285,6 +1289,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs j.ListedOutput = 0 } j.Desktop = desktop[ref] + j.Disabled = disabled(p.ID, m.ID) if mp, ok := held.ModelPrices[ref]; ok { if pr, bad := mp.Price(); bad == "" { j.Price = &pr diff --git a/internal/gui/tests/disabled-model-chips.test.cjs b/internal/gui/tests/disabled-model-chips.test.cjs new file mode 100644 index 000000000..c1a3e39d1 --- /dev/null +++ b/internal/gui/tests/disabled-model-chips.test.cjs @@ -0,0 +1,65 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A model disabled in Settings → Models (#1867) says so in its provider's +// editor: its chip is dimmed with a "disabled" badge and its title names the +// pattern, where it read as an ordinary pick the gateway then refused. The +// API names the pattern (TestProviderInfoSaysADisabledModel). Both engines, +// every language; the API is faked. +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_ASSETS || path.join(__dirname, "../assets")); +const L = { en: "disabled", zh: "已停用", "zh-TW": "已停用", ja: "無効", de: "deaktiviert" }; + +function server(lang) { + const settings = { lang, theme: "light", disabledModels: ["*FABLE*", "relay/exact-one", "tail"] }; + const relay = { id: "relay", name: "Relay", icon: "generic", host: "relay.test", chat: "https://relay.test/v1", responses: "", anthropic: "", + models: [["claude-fable-5", "*FABLE*"], ["exact-one", "relay/exact-one"], ["vendor/tail", "tail"], ["kept-model", ""]].map(([id, disabled]) => ({ id, name: id, on: true, ...(disabled && { disabled }) })), + agents: [], fallback: [], headers: {}, key: { set: true, masked: "sk-…1234" }, keyList: [], ready: true }; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings }); + if (url.pathname === "/api/settings") return json(settings); + if (url.pathname === "/api/providers") return json({ providers: [relay], presets: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/groups") return json({ groups: [], pools: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + 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)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a disabled model says so in its provider's editor", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const lang of Object.keys(L)) await t.test(lang, async () => { + const page = await browser.newPage({ viewport: { width: 1100, height: 800 }, reducedMotion: "reduce" }); + t.after(() => page.close()); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang)); + await page.goto("http://magpie.test/?view=providers"); + await page.locator('#providers .row.provider[data-id="relay"]').click(); + await page.locator("#modal .mchips .mchip").first().waitFor(); + const chips = await page.locator("#modal .mchips .mchip.pick").evaluateAll((cs) => cs.map((c) => ({ + id: c.firstChild.textContent, badge: [...c.querySelectorAll(".badge")].map((b) => b.textContent), title: c.title, dim: c.classList.contains("noapi") }))); + const by = Object.fromEntries(chips.map((c) => [c.id, c])); + for (const [id, pat] of [["claude-fable-5", "*FABLE*"], ["exact-one", "relay/exact-one"], ["vendor/tail", "tail"]]) { + assert.deepEqual(by[id].badge, [L[lang]], `${id} badge`); + assert.ok(by[id].dim, `${id} dimmed`); + assert.ok(by[id].title.includes("(" + pat + ")") || by[id].title.includes("(" + pat + ")"), `${id} title names ${pat}: ${by[id].title}`); + } + assert.deepEqual(by["kept-model"].badge, [], "kept-model has no badge"); + assert.equal(by["kept-model"].dim, false); + assert.deepEqual(errors, []); + }); + }); +} diff --git a/internal/provider/disabled.go b/internal/provider/disabled.go index 724d14f98..f6f7611f7 100644 --- a/internal/provider/disabled.go +++ b/internal/provider/disabled.go @@ -168,6 +168,16 @@ func disabledNow() func(pid, model string) bool { } } +// DisabledPattern is ModelDisabled's pattern with the list read once, for +// a loop over many models: "" for a model that isn't disabled. +func DisabledPattern() func(pid, model string) string { + list, _ := disabledList() + return func(pid, model string) string { + pat, _ := matchDisabled(list, namesOf(pid, model)...) + return pat + } +} + // IDDisabled reports whether a model id as asked ("/" or a // bare id) is one the user disabled, and the pattern that did. func IDDisabled(id string) (string, bool) {