Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
providers: an image model can be unticked in its provider's editor, and leaves the lists (321sssrt on X)
yetoneded4935745c8
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex 0d7b26303..945c81cc4 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -1009,6 +1009,32 @@ Covered by `TestAutoVisionPassesOverOneOut`,`TestAutoVisionTierAmongThoseWithAllowance`, `TestSpentModelAcrossAccounts`,`TestVisionDoesNotAskSpentDescriber` and `TestSearcherPassesOverOneOut`.+## Hidden image models++A provider's editor lists its image models (`gateway.Drawers`, the+`drawIds` of `/api/providers`) apart from its chat models, each ticked.+Unticking one saves its id in `provider.HiddenDrawers` (providers.json,+and an account's picks entry through `withPicks`). It is a deny list+beside `Models`, not an entry in it: an image id in `Models` would be+offered to agents to chat with, and the allow list would make hiding one+picking every chat model by hand. A Save that leaves `hiddenDrawers` out+keeps the old list; `[]` ticks them all again.++`gateway.OfferedDrawers` is `Drawers` less the hidden ones. It is what+lists image models to pick from or picks among: `AutoDrawer`,+`drawerObjects` (another magpie's `X-Magpie-Drawers` list) and Aside's+image options. Settings › Images (`settingsState`) leaves them out too,+except the one picked there. A hidden model still draws: `resolveDrawing`+and `drawingModel` read `Drawers`, so a request that names one, or a+Settings › Images pick made before it was hidden, draws as before. That+pick stays listed as picked, and `imageGenHidden` puts a line under the+row that it is unticked and leaves the list once another is picked.+Refusing a model outright is Disabled models, below. Video models aren't+listed in the editor, so there is nothing to hide there.++Covered by `TestHiddenDrawerLeavesListsButStillDraws`,+`TestImageModelsHidden` and `internal/gui/tests/image-models-hide.test.cjs`.+## Disabled modelsSettings › Models › Disabled models, `magpie model disable|enable|disabled`diff --git a/internal/agent/aside_native.go b/internal/agent/aside_native.goindex 834d2af17..925d41e43 100644--- a/internal/agent/aside_native.go+++ b/internal/agent/aside_native.go@@ -12,6 +12,7 @@ import ("sync""testing"+ "github.com/yetone/magpie/internal/catalog""github.com/yetone/magpie/internal/edit""github.com/yetone/magpie/internal/filememo""github.com/yetone/magpie/internal/gateway"@@ -412,13 +413,17 @@ func (c *asideConnection) state() NativeState {return s}-func asideImageOptions() []Option {+// asideImageOptions are the image models Aside is offered: those unticked+// in their provider's editor left out (provider.HiddenDrawers).+func asideImageOptions() []Option { return asideImages(gateway.OfferedDrawers) }++func asideImages(drawers func(provider.Provider) []catalog.Model) []Option {var out []Optionfor _, p := range provider.All() {if !p.On() {continue}- for _, m := range gateway.Drawers(p) {+ for _, m := range drawers(p) {ref := p.ID + "/" + m.IDout = append(out, Option{Value: "magpie/" + ref, Ref: ref, Label: m.Name, Group: p.Name, Icon: p.Icon, Note: "image generation · via magpie"})}@@ -432,7 +437,8 @@ func asideImageOffered(value string) bool {if ref, ok := strings.CutPrefix(value, "magpie/"); ok {value = "magpie/" + gateway.ListedDrawer(ref)}- for _, o := range asideImageOptions() {+ // one unticked in its editor still draws: Aside set to it keeps it+ for _, o := range asideImages(gateway.Drawers) {if o.Value == value {return true}diff --git a/internal/gateway/draw.go b/internal/gateway/draw.goindex 52a2a949c..0a6cd8546 100644--- a/internal/gateway/draw.go+++ b/internal/gateway/draw.go@@ -313,6 +313,32 @@ func Drawers(p provider.Provider) []catalog.Model {return slices.DeleteFunc(out, func(m catalog.Model) bool { return p.ModelKind(m.ID) == provider.KindVideo })}+// OfferedDrawers are Drawers less those the user unticked in p's editor+// (provider.HiddenDrawers, 321sssrt on X): the image models a list offers+// to pick from and Automatic picks among. A request that names a hidden+// one still draws with it (resolveDrawing reads Drawers), as does a+// Settings › Images pick of one made before it was hidden.+func OfferedDrawers(p provider.Provider) []catalog.Model {+ ms := Drawers(p)+ if len(p.HiddenDrawers) == 0 {+ return ms+ }+ return slices.DeleteFunc(slices.Clone(ms), func(m catalog.Model) bool { return p.DrawerHidden(m.ID) })+}++// DrawerHidden is whether ref (provider/model), a model Settings › Images+// names, is one the user unticked in its provider's editor: it still draws,+// and the Settings row says it is hidden. A ChatGPT account's other GPT+// Image names stand for its one (ListedDrawer).+func DrawerHidden(ref string) bool {+ pid, id, ok := strings.Cut(ListedDrawer(ref), "/")+ if !ok {+ return false+ }+ p, err := provider.Find(pid)+ return err == nil && p.DrawerHidden(id)+}+// kindModel is p's model id, one the user said makes images or videos// (provider.SetModelKind), as its list names it.func kindModel(p provider.Provider, id string) catalog.Model {@@ -338,7 +364,8 @@ func AutoDrawer() string {// with its model picked or namedcontinue}- for _, m := range Drawers(p) {+ // one unticked in its editor isn't Automatic's choice+ for _, m := range OfferedDrawers(p) {if drawsCodex(p) && m.ID != codexDrawer {// Codex CLI draws with gpt-image-2 only; a plan may be// refused the others (chatgpt.com: 403, #545)diff --git a/internal/gateway/draw_hidden_test.go b/internal/gateway/draw_hidden_test.gonew file mode 100644index 000000000..1f9f0fd81--- /dev/null+++ b/internal/gateway/draw_hidden_test.go@@ -0,0 +1,90 @@+package gateway++import (+ "net/http"+ "net/http/httptest"+ "slices"+ "testing"++ "github.com/yetone/magpie/internal/catalog"+ "github.com/yetone/magpie/internal/provider"+ "github.com/yetone/magpie/internal/settings"+)++// 321sssrt on X: an image model unticked in its provider's editor+// (HiddenDrawers) leaves what lists image models to pick from, and+// Automatic, but still draws when named or picked in Settings › Images.+func TestHiddenDrawerLeavesListsButStillDraws(t *testing.T) {+ fresh(t)+ drawingRelay(t, "hd", "gpt-image-hidden", "gpt-image-shown")+ found, err := provider.Find("hd")+ if err != nil {+ t.Fatal(err)+ }+ p := *found+ p.HiddenDrawers = []string{"gpt-image-hidden"}+ if err := provider.Save(p); err != nil {+ t.Fatal(err)+ }+ found, _ = provider.Find("hd")+ p = *found+ ids := func(ms []catalog.Model) (out []string) {+ for _, m := range ms {+ out = append(out, m.ID)+ }+ return+ }+ if got := ids(OfferedDrawers(p)); !slices.Equal(got, []string{"gpt-image-shown"}) {+ t.Fatalf("offered %v", got)+ }+ if got := ids(Drawers(p)); !slices.Contains(got, "gpt-image-hidden") {+ t.Fatalf("drawers lost the hidden one: %v", got)+ }+ if !DrawerHidden("hd/gpt-image-hidden") || DrawerHidden("hd/gpt-image-shown") || DrawerHidden("nope/gpt-image-hidden") {+ t.Fatal("DrawerHidden")+ }++ var listed []string+ for _, o := range drawerObjects(httptest.NewRequest(http.MethodGet, "/v1/models", nil)) {+ listed = append(listed, o["id"].(string))+ }+ if slices.Contains(listed, "hd/gpt-image-hidden") || !slices.Contains(listed, "hd/gpt-image-shown") {+ t.Fatalf("drawer objects %v", listed)+ }++ // Automatic never lands on the hidden one, whichever order it reads+ for range 3 {+ if a := AutoDrawer(); a == "hd/gpt-image-hidden" {+ t.Fatalf("automatic picked the hidden model")+ }+ }+ p.HiddenDrawers = []string{"gpt-image-hidden", "gpt-image-shown"}+ if err := provider.Save(p); err != nil {+ t.Fatal(err)+ }+ if a := AutoDrawer(); a != "" {+ t.Fatalf("automatic with every model hidden: %q", a)+ }++ // named, or picked in Settings, it still draws+ if _, id, ok := resolveDrawing("hd/gpt-image-hidden"); !ok || id != "gpt-image-hidden" {+ t.Fatalf("resolve named hidden: %q %v", id, ok)+ }+ if _, id, ok := resolveDrawing("gpt-image-hidden"); !ok || id != "gpt-image-hidden" {+ t.Fatalf("resolve bare hidden: %q %v", id, ok)+ }+ st := settings.Load()+ st.ImageGen = "hd/gpt-image-hidden"+ if err := settings.Save(st); err != nil {+ t.Fatal(err)+ }+ if Drawer() != "hd/gpt-image-hidden" || DrawerMissing() != "" {+ t.Fatalf("a hidden pick isn't what draws: %q missing %q", Drawer(), DrawerMissing())+ }+ s := New()+ drawingMainTurn(t, s, "hd/text", "session", "turn", "", "magpie-codex")+ code, answer, raw := drawingToolCall(t, s, "/v1/images/generations", "", "", "turn", "magpie-codex")+ if code != 200 || answer.Model != "hd/gpt-image-hidden" {+ t.Fatalf("settings pick hidden: %d %s", code, raw)+ }+}diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.goindex 3831890d8..68f50afe9 100644--- a/internal/gateway/gateway.go+++ b/internal/gateway/gateway.go@@ -1135,7 +1135,8 @@ func drawerObjects(r *http.Request) []map[string]any {if !p.On() || p.DecideOnly() {continue}- for _, m := range Drawers(p) {+ // less those unticked in its editor, as Settings › Images lists them+ for _, m := range OfferedDrawers(p) {if held && (!modelAllowed(who, p, m.ID) || !accountServes(who, p, m.ID)) {continue}diff --git a/internal/gui/api.go b/internal/gui/api.goindex 02f931115..08519ef72 100644--- a/internal/gui/api.go+++ b/internal/gui/api.go@@ -447,6 +447,10 @@ type settingsJSON struct {// magpie listed it, is its one GPT Image (gateway.ListedDrawer, #1865)ImageGenShown string `json:"imageGenShown,omitempty"`ImageGenModels []modelRef `json:"imageGenModels"`+ // the ImageGen the user picked is one unticked in its provider's+ // editor since (provider.HiddenDrawers): it still draws, and is+ // listed, as picked, with the row saying it is hidden+ ImageGenHidden bool `json:"imageGenHidden,omitempty"`// the web search APIs a model's search goes to when no provider can// search (#419), their keys masked; the ones that can be added; and// the provider that searches first, if one does@@ -721,7 +725,12 @@ func settingsState() settingsJSON {if !p.On() || p.DecideOnly() {continue}+ // those unticked in its editor left out, but the one picked here+ // (321sssrt on X): a hidden pick still draws, and shows as pickedfor _, m := range gateway.Drawers(p) {+ if p.DrawerHidden(m.ID) && gateway.ListedDrawer(s.ImageGen) != p.ID+"/"+m.ID {+ continue+ }name := m.Nameif name == "" {name = m.ID@@ -732,6 +741,7 @@ func settingsState() settingsJSON {if v := gateway.ListedDrawer(s.ImageGen); v != s.ImageGen {s.ImageGenShown = v}+ s.ImageGenHidden = gateway.DrawerHidden(s.ImageGen)// the Codex subagents row's warning: magpie's multi-agent V1 doesn't reach// Codex where its own multi_agent_v2 is on in the config magpie routes, and// magpie writes nothing there — the setting is the user's to turn offdiff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.jsindex 8463f8e7b..33e2ef61d 100644--- a/internal/gui/assets/app.js+++ b/internal/gui/assets/app.js@@ -9019,7 +9019,7 @@ function baseAPIOf(p) {// draftOf is a saved provider as its editor's form holds it.function draftOf(p) {- return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), icon: p.icon || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, searches: !!p.searches, unredacted: !!p.unredacted, insecureTLS: !!p.insecureTLS, limitRestOff: !!p.limitRestOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p) };+ return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), icon: p.icon || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], searches: !!p.searches, unredacted: !!p.unredacted, insecureTLS: !!p.insecureTLS, limitRestOff: !!p.limitRestOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p) };}// duplicateProvider opens the Add form on a copy of p (#268): its URLs,@@ -9366,7 +9366,7 @@ function drawEditor(p, presetID) {if (priceTypedError(ed)) return;const picked = accountModelsDraft(p);if (picked === false) return pickError();- const body = { id: p.id, models: chosenIds(), noModels: noneChosen(), unlisted: draft.unlisted, fallback: draft.fallback, contexts: cx.map, outputs: ox.map, compacts: cpx.map, proxy, accountProxies: own.map, maxConcurrency, ...queue, priceRate, modelPrefs: modelPrefsOfDraft(), pinUpstream: !!draft.pinUpstream, ...(p.carriesCompaction ? { nativeCompaction: !!draft.nativeCompaction } : {}), ...routingOfDraft(p) };+ const body = { id: p.id, models: chosenIds(), noModels: noneChosen(), unlisted: draft.unlisted, hiddenDrawers: draft.hiddenDrawers, fallback: draft.fallback, contexts: cx.map, outputs: ox.map, compacts: cpx.map, proxy, accountProxies: own.map, maxConcurrency, ...queue, priceRate, modelPrefs: modelPrefsOfDraft(), pinUpstream: !!draft.pinUpstream, ...(p.carriesCompaction ? { nativeCompaction: !!draft.nativeCompaction } : {}), ...routingOfDraft(p) };saving(saveBtn, t("Saving…"));saveAccountModelsDraft(picked).then(() => savePluginOptions(subOf(a.agent))).then(() => providerAction("save", body, t("{name} saved", { name: p.name })), (e) => { doneSaving(saveBtn); editorError(e.message || String(e)); }); };bar.append(cancel, saveBtn);@@ -9971,7 +9971,7 @@ function drawEditor(p, presetID) {body.baseAPI = draft.api === "openai" ? "chat" : draft.api;}if (custom) { body.icon = draft.icon || "generic"; body.balanceURL = (draft.balanceURL || "").trim(); body.balancePath = (draft.balancePath || "").trim(); body.balanceMethod = draft.balanceMethod || ""; body.modelsURL = (draft.modelsURL || "").trim(); }- if (p) { body.fallback = draft.fallback; body.unlisted = draft.unlisted; body.noModels = noneChosen(); body.modelPrefs = modelPrefsOfDraft(); Object.assign(body, routingOfDraft(p)); }+ if (p) { body.fallback = draft.fallback; body.unlisted = draft.unlisted; body.hiddenDrawers = draft.hiddenDrawers; body.noModels = noneChosen(); body.modelPrefs = modelPrefsOfDraft(); Object.assign(body, routingOfDraft(p)); }body.searches = !!draft.searches && searchable();body.pinUpstream = !!draft.pinUpstream;if (twoKeyHeaders()) body.authHeader = draft.authHeader || "";@@ -11779,12 +11779,25 @@ function renderModels(p) {}// renderDrawers: the provider's image models. Agents don't chat with them,-// so they aren't among its Models; they are listed to say they are there,-// and one is picked in Settings → Images.+// so they aren't among its Models; one is picked in Settings → Images,+// which lists the ticked ones. A click unticks one there, staged in the+// draft until Save as a model's tick is (321sssrt on X: OpenAI's dozen).function renderDrawers(p) {- const chips = el("div", "mchips");- for (const id of p.drawIds) chips.append(el("span", "mchip ro", id));- return field(t("Image models"), chips, t("Agents don't chat with these, so they aren't among its models: the one that draws is picked in Settings → Images."));+ const chips = el("div", "mchips drawers");+ draft.hiddenDrawers ||= [...(p.hiddenDrawers || [])];+ for (const id of p.drawIds) {+ const c = el("button", "mchip pick");+ c.type = "button";+ c.append(el("span", "", id));+ const show = () => { const on = !draft.hiddenDrawers.includes(id); c.classList.toggle("on", on); c.setAttribute("aria-pressed", on); };+ c.onclick = () => {+ draft.hiddenDrawers = draft.hiddenDrawers.includes(id) ? draft.hiddenDrawers.filter((x) => x !== id) : [...draft.hiddenDrawers, id];+ show();+ };+ show();+ chips.append(c);+ }+ return field(t("Image models"), chips, t("Settings → Images lists the ticked ones. Agents don't chat with these, so they aren't among its models."));}// renderRouting: how the gateway spreads requests over the keys or@@ -21355,6 +21368,8 @@ function renderImageGen(s, keep, box) {// so where it draws, picked or automatic (#1865)const draws = v === "off" || gone ? "" : v ? shown : s.imageGenAuto;if (models.find((x) => x.id === draws)?.vendorPicks) who.append(el("div", "sub image-gen-vendor", t("ChatGPT's image backend picks the model itself, whichever is named, so one GPT Image is listed")));+ // a pick unticked in its provider's editor since still draws, and says so+ if (s.imageGenHidden && !gone && v !== "off") who.append(el("div", "sub image-gen-hidden", t("{model}, picked here, is unticked in its provider's Image models: it still draws, but leaves this list once another is picked. Tick it there to keep it listed.", { model: named(shown) })));if (gone) who.append(el("div", "sub err image-gen-missing", s.imageGenAuto? t("{model}, picked here, isn't set up any more: its provider was removed or turned off, or no longer has it. {auto}, the automatic choice, draws in its place. Pick another model here.", { model: v, auto: named(s.imageGenAuto) }): t("{model}, picked here, isn't set up any more: its provider was removed or turned off, or no longer has it. No other model draws, so a request that names no model is turned away. Pick another model here.", { model: v })));diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.jsindex 3bde367f1..54c361e9f 100644--- a/internal/gui/assets/i18n.js+++ b/internal/gui/assets/i18n.js@@ -1445,7 +1445,8 @@ const I18N = {"{n} image model": "{n} 个图像模型","{n} image models": "{n} 个图像模型","Image models": "图像模型",- "Agents don't chat with these, so they aren't among its models: the one that draws is picked in Settings → Images.": "Agent 不与它们对话,故不在模型列表中;生图模型在 设置 → 图像 中选择。",+ "Settings → Images lists the ticked ones. Agents don't chat with these, so they aren't among its models.": "设置 → 图像 只列出已勾选的。Agent 不与它们对话,故不在模型列表中。",+ "{model}, picked here, is unticked in its provider's Image models: it still draws, but leaves this list once another is picked. Tick it there to keep it listed.": "{model} 是此处选中的,但在其供应商的“图像模型”中未勾选:它仍用于生图,改选其他模型后便不再列在这里。在那里勾选它即可留在列表中。","no models exposed": "未暴露模型","signed in as {user}": "已登录 {user}","{name} · {model} — click to change": "{name} · {model} — 点击更改",@@ -5528,7 +5529,8 @@ const I18N = {"{n} image model": "{n} 個影像模型","{n} image models": "{n} 個影像模型","Image models": "影像模型",- "Agents don't chat with these, so they aren't among its models: the one that draws is picked in Settings → Images.": "Agent 不與它們對話,故不在模型列表中;生圖模型在 設定 → 影像 中選擇。",+ "Settings → Images lists the ticked ones. Agents don't chat with these, so they aren't among its models.": "設定 → 影像 只列出已勾選的。Agent 不與它們對話,故不在模型列表中。",+ "{model}, picked here, is unticked in its provider's Image models: it still draws, but leaves this list once another is picked. Tick it there to keep it listed.": "{model} 是此處選取的,但在其供應商的「影像模型」中未勾選:它仍用於生圖,改選其他模型後便不再列在這裡。在那裡勾選它即可留在列表中。","no models exposed": "未暴露模型","signed in as {user}": "已登入 {user}","{name} · {model} — click to change": "{name} · {model} — 點選更改",@@ -9586,7 +9588,8 @@ const I18N = {"{n} image model": "{n} 件の画像モデル","{n} image models": "{n} 件の画像モデル","Image models": "画像モデル",- "Agents don't chat with these, so they aren't among its models: the one that draws is picked in Settings → Images.": "エージェントはこれらと会話しないため、モデル一覧には含まれません。描画に使うモデルは 設定 → 画像 で選びます。",+ "Settings → Images lists the ticked ones. Agents don't chat with these, so they aren't among its models.": "設定 → 画像 にはチェックしたものだけが表示されます。エージェントはこれらと会話しないため、モデル一覧には含まれません。",+ "{model}, picked here, is unticked in its provider's Image models: it still draws, but leaves this list once another is picked. Tick it there to keep it listed.": "ここで選んだ {model} は、プロバイダの「画像モデル」でチェックが外されています。描画には引き続き使われますが、別のモデルを選ぶとこの一覧から消えます。一覧に残すには、そちらでチェックしてください。","no models exposed": "公開されているモデルなし","signed in as {user}": "{user} としてサインイン中","{name} · {model} — click to change": "{name} · {model} — クリックして変更",@@ -13674,7 +13677,8 @@ const I18N = {"{n} image model": "{n} Bildmodell","{n} image models": "{n} Bildmodelle","Image models": "Bildmodelle",- "Agents don't chat with these, so they aren't among its models: the one that draws is picked in Settings → Images.": "Agenten chatten nicht mit diesen Modellen, daher stehen sie nicht bei seinen Modellen: Das Bildmodell wählen Sie unter Einstellungen → Bilder.",+ "Settings → Images lists the ticked ones. Agents don't chat with these, so they aren't among its models.": "Einstellungen → Bilder listet die angehakten. Agenten chatten nicht mit diesen Modellen, daher stehen sie nicht bei seinen Modellen.",+ "{model}, picked here, is unticked in its provider's Image models: it still draws, but leaves this list once another is picked. Tick it there to keep it listed.": "{model}, hier gewählt, ist bei den Bildmodellen seines Anbieters abgehakt: Es zeichnet weiter, verschwindet aber aus dieser Liste, sobald ein anderes gewählt ist. Haken Sie es dort an, damit es gelistet bleibt.","no models exposed": "keine Modelle freigegeben","signed in as {user}": "angemeldet als {user}","{name} · {model} — click to change": "{name} · {model} — zum Ändern klicken",diff --git a/internal/gui/image_hidden_test.go b/internal/gui/image_hidden_test.gonew file mode 100644index 000000000..e2291d5a0--- /dev/null+++ b/internal/gui/image_hidden_test.go@@ -0,0 +1,95 @@+package gui++import (+ "net/http"+ "net/http/httptest"+ "os"+ "slices"+ "strings"+ "testing"++ "github.com/yetone/magpie/internal/catalog"+ "github.com/yetone/magpie/internal/provider"+ "github.com/yetone/magpie/internal/settings"+)++// 321sssrt on X: image models unticked in a provider's editor are saved+// as HiddenDrawers, kept by a Save that leaves them out and cleared by [];+// Settings › Images leaves them out, except the one picked there, which+// stays listed as picked with the row saying it is hidden.+func TestImageModelsHidden(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())+ mux := http.NewServeMux()+ providerRoutes(mux, nil)+ post := func(body string) {+ t.Helper()+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/provider/save", strings.NewReader(body)))+ if w.Code != 200 {+ t.Fatalf("%d %s", w.Code, w.Body.String())+ }+ }+ const base = `"id":"pics","name":"Pics","key":"sk-p","chat":"https://pics.example/v1","icon":"generic"`+ post(`{` + base + `,"new":true}`)+ if err := catalog.SaveLive("pics", "https://pics.example/v1", []catalog.Model{{ID: "text"}, {ID: "img-a", Draws: true}, {ID: "img-b", Draws: true}}); err != nil {+ t.Fatal(err)+ }+ hidden := func() []string {+ t.Helper()+ p, err := provider.Find("pics")+ if err != nil {+ t.Fatal(err)+ }+ info := providerInfo(*p, nil)+ if !slices.Equal(info.HiddenDrawers, p.HiddenDrawers) {+ t.Fatalf("the editor is shown %v, saved %v", info.HiddenDrawers, p.HiddenDrawers)+ }+ return p.HiddenDrawers+ }+ listed := func() (ids []string) {+ for _, m := range settingsState().ImageGenModels {+ if m.Provider == "pics" {+ ids = append(ids, m.ID)+ }+ }+ return+ }++ post(`{` + base + `,"from":"pics","models":[],"headers":{},"hiddenDrawers":["img-a"]}`)+ if got := hidden(); !slices.Equal(got, []string{"img-a"}) {+ t.Fatalf("saved %v", got)+ }+ if got := listed(); !slices.Equal(got, []string{"pics/img-b"}) {+ t.Fatalf("Settings › Images lists %v", got)+ }+ if settingsState().ImageGenHidden {+ t.Fatal("hidden note with nothing hidden picked")+ }++ st := settings.Load()+ st.ImageGen = "pics/img-a"+ if err := settings.Save(st); err != nil {+ t.Fatal(err)+ }+ if got := listed(); !slices.Equal(got, []string{"pics/img-a", "pics/img-b"}) {+ t.Fatalf("a hidden pick isn't listed as picked: %v", got)+ }+ if !settingsState().ImageGenHidden {+ t.Fatal("a hidden pick isn't said to be hidden")+ }++ post(`{` + base + `,"from":"pics","models":[],"headers":{}}`)+ if got := hidden(); !slices.Equal(got, []string{"img-a"}) {+ t.Fatalf("a Save that left them out changed them: %v", got)+ }+ post(`{` + base + `,"from":"pics","models":[],"headers":{},"hiddenDrawers":[]}`)+ if got := hidden(); len(got) != 0 {+ t.Fatalf("[] kept %v", got)+ }+ if settingsState().ImageGenHidden {+ t.Fatal("ticked again, still said to be hidden")+ }+}diff --git a/internal/gui/providers.go b/internal/gui/providers.goindex 4238d6319..d629659d0 100644--- a/internal/gui/providers.go+++ b/internal/gui/providers.go@@ -247,8 +247,10 @@ type providerJSON struct {Exposed int `json:"exposed"` // how many reach the agentsDraws int `json:"draws,omitempty"` // how many of its models draw images (gateway.Drawers)DrawIDs []string `json:"drawIds,omitempty"` // those models' ids, listed apart in its editor- Unlisted bool `json:"unlisted"` // its models serve only through routing groups- NoModels bool `json:"noModels"` // Select none: none of its models served (#1818)+ // those of them unticked in its editor (provider.HiddenDrawers)+ HiddenDrawers []string `json:"hiddenDrawers,omitempty"`+ Unlisted bool `json:"unlisted"` // its models serve only through routing groups+ NoModels bool `json:"noModels"` // Select none: none of its models served (#1818)// Groups are the routing groups ("group/<id>") each of its models is// in, by model id: what an unlisted one is still used through, and the// editor names those in none@@ -827,6 +829,11 @@ func providerInfoWith(p provider.Provider, agents []agentUse, desktop map[stringout.DrawIDs = append(out.DrawIDs, m.ID)}out.Draws = len(out.DrawIDs)+ for _, id := range out.DrawIDs {+ if p.DrawerHidden(id) {+ out.HiddenDrawers = append(out.HiddenDrawers, id)+ }+ }if t, ok := p.Listed(); ok {out.Fetched = &t}@@ -1408,6 +1415,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {// back to Smart (fflake33 on Discord)pr.Routing, pr.Affinity, pr.Sink = in.Routing, in.Affinity, in.Sinkpr.Unlisted = in.Unlisted+ pr.HiddenDrawers = in.HiddenDrawerspr.AccountProxies = in.AccountProxiesif in.Name != "" {pr.Name = in.Name@@ -1603,6 +1611,11 @@ func providerRoutes(mux *http.ServeMux, w Windows) {in.AccountConcurrency = old.AccountConcurrencyin.AccountNames = old.AccountNames // with accountname}+ // the image models unticked in its editor likewise: []+ // shows them all (321sssrt on X)+ if in.HiddenDrawers == nil && old != nil {+ in.HiddenDrawers = old.HiddenDrawers+ }// a Zhipu key's team likewise: {} clears itif in.ZhipuTeam == nil && old != nil {in.ZhipuTeam = old.ZhipuTeamdiff --git a/internal/gui/tests/image-models-hide.test.cjs b/internal/gui/tests/image-models-hide.test.cjsnew file mode 100644index 000000000..00899186e--- /dev/null+++ b/internal/gui/tests/image-models-hide.test.cjs@@ -0,0 +1,158 @@+// Run with Node's test runner and Playwright on the module path; see README.md.+// 321sssrt on X: "openai有几十个图片模型,我没办法像是llm一样屏蔽他们". A+// provider's editor listed its image models as plain chips nothing could+// change. Now each is ticked, a click unticks it (and ticks it back), and+// Save writes the unticked ones as hiddenDrawers, which Settings › Images+// then leaves out. A pick in Settings › Images that was unticked since+// still draws, and its row says so and how to keep it listed. Every+// language, wide and at a phone's width; the API is faked here.+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 fetched = new Date(Date.now() - 3600e3).toISOString();+const drawIds = ["gpt-image-2", "gpt-image-1.5", "dall-e-3"];++function providerFor(hidden) {+ return {+ id: "openai", name: "OpenAI", icon: "openai", host: "", chat: "https://api.openai.com/v1", responses: "", anthropic: "", catalog: "",+ models: [{ id: "gpt-6", name: "GPT-6", on: true }], chosen: [], fetched, agents: [], fallback: [], headers: {},+ key: { set: true, masked: "sk-…one", optional: false }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", ready: true,+ draws: drawIds.length, drawIds, hiddenDrawers: hidden,+ };+}++function settingsPayload(lang, over) {+ return {+ theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd", textSize: 100,+ dock: false, dockWindow: false, proxy: "", redact: false, redactPersonal: false, redactWords: [],+ codexWarmup: "", claudeWarmup: "", codexWarmAt: "", claudeWarmAt: "", workbuddyCheckin: false, noStats: false,+ trayUsage: "", trayUsageEvery: 3, vision: "", imageGen: "",+ version: "0.1.400", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425",+ proxyNow: "none", proxySource: "none", login: false,+ visionModels: [], imageGenModels: [+ { id: "openai/gpt-image-2", name: "gpt-image-2", provider: "openai", providerName: "OpenAI", icon: "openai" },+ { id: "openai/dall-e-3", name: "dall-e-3", provider: "openai", providerName: "OpenAI", icon: "openai" },+ ],+ imageGenAuto: "openai/gpt-image-2", workbuddyCheckins: [], lanURLs: [],+ fx: { rate: 7.2, at: new Date().toISOString(), stale: false },+ ...over,+ };+}++function serve(lang, saves, cur) {+ let hidden = ["dall-e-3"];+ const providers = () => ({ providers: [providerFor(hidden)], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [] });+ return async (route) => {+ const req = route.request(), url = new URL(req.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,textSize:100};` });+ if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });+ if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light", textSize: 100 } });+ if (url.pathname === "/api/settings") return json(cur);+ if (url.pathname === "/api/plugins") return json({ plugins: [] });+ if (url.pathname === "/api/providers") return json(providers());+ if (url.pathname === "/api/provider/save") {+ const body = req.postDataJSON();+ saves.push(body.hiddenDrawers);+ if (body.hiddenDrawers) hidden = body.hiddenDrawers;+ return json(providers());+ }+ if (url.pathname === "/api/usage/quotas") return json([]);+ if (url.pathname === "/api/groups") return json({ groups: [], pools: [], models: [] });+ if (url.pathname === "/api/gateway/trace") return json({ routes: [] });+ if (url.pathname === "/api/window/fit") return route.fulfill({ status: 204 });+ 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)];+ const body = await fs.readFile(file).catch(() => null);+ await (body ? route.fulfill({ body, contentType }) : route.fulfill({ status: 404, body: "" }));+ };+}++const words = {+ en: { save: "Save", field: "Image models", hint: /Settings → Images lists the ticked ones/, note: [/dall-e-3 · OpenAI, picked here, is unticked/, /it still draws/] },+ zh: { save: "保存", field: "图像模型", hint: /设置 → 图像 只列出已勾选的/, note: [/dall-e-3 · OpenAI 是此处选中的/, /它仍用于生图/] },+ "zh-TW": { save: "儲存", field: "影像模型", hint: /設定 → 影像 只列出已勾選的/, note: [/dall-e-3 · OpenAI 是此處選取的/, /它仍用於生圖/] },+ ja: { save: "保存", field: "画像モデル", hint: /設定 → 画像 にはチェックしたものだけ/, note: [/ここで選んだ dall-e-3 · OpenAI は/, /描画には引き続き使われます/] },+ de: { save: "Speichern", field: "Bildmodelle", hint: /Einstellungen → Bilder listet die angehakten/, note: [/dall-e-3 · OpenAI, hier gewählt, ist/, /Es zeichnet weiter/] },+};++for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {+ test(engine + ": a provider's image models can be unticked, and a hidden pick says so", async (t) => {+ assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));+ t.after(() => browser.close());+ const open = async (lang, width, view, saves, cur) => {+ const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();+ page.setDefaultTimeout(5000);+ page.errors = [];+ page.on("pageerror", (e) => page.errors.push(e.message));+ await page.route("**/*", serve(lang, saves, cur));+ await page.goto("http://magpie.test/?view=" + view);+ return page;+ };+ const noSideScroll = (page) => page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);+ for (const lang of Object.keys(words)) {+ const w = words[lang];+ for (const width of [1000, 360]) {+ await t.test(`${lang} at ${width}px: the editor unticks and ticks back an image model`, async () => {+ const saves = [];+ const page = await open(lang, width, "providers", saves, settingsPayload(lang, {}));+ const editor = page.locator("#modal:not([hidden]) .editor");+ const openEditor = async () => {+ await page.locator(".row.provider", { hasText: "OpenAI" }).first().click();+ await editor.locator(".mchips.drawers .mchip").first().waitFor();+ };+ const chips = editor.locator(".mchips.drawers .mchip");+ const ticked = () => editor.locator(".mchips.drawers .mchip.on").evaluateAll((cs) => cs.map((c) => c.textContent));+ const chip = (id) => editor.locator(".mchips.drawers .mchip", { has: page.locator(`span:text-is("${id}")`) });+ await openEditor();+ await editor.getByText(w.field, { exact: true }).first().waitFor();+ await editor.getByText(w.hint).waitFor();+ assert.equal(await chips.count(), 3);+ assert.deepEqual(await ticked(), ["gpt-image-2", "gpt-image-1.5"], "the saved hidden one opens unticked");+ assert.equal(await chip("dall-e-3").getAttribute("aria-pressed"), "false");+ await chip("gpt-image-1.5").click();+ assert.deepEqual(await ticked(), ["gpt-image-2"]);+ await chip("dall-e-3").click();+ assert.deepEqual(await ticked(), ["gpt-image-2", "dall-e-3"]);+ assert.equal(await noSideScroll(page), 0);+ await editor.getByRole("button", { name: w.save, exact: true }).click();+ await editor.waitFor({ state: "detached" });+ assert.deepEqual(saves.at(-1), ["gpt-image-1.5"]);+ await openEditor();+ assert.deepEqual(await ticked(), ["gpt-image-2", "dall-e-3"], "reopened as saved");+ assert.equal(await page.locator("select").count(), 0);+ assert.deepEqual(page.errors, []);+ await page.context().close();+ });+ await t.test(`${lang} at ${width}px: Settings › Images says a hidden pick still draws`, async () => {+ const page = await open(lang, width, "settings&tab=models", [], settingsPayload(lang, { imageGen: "openai/dall-e-3", imageGenHidden: true }));+ await page.locator("#imageGenRow").waitFor();+ const note = page.locator("#imageGenRow .image-gen-hidden");+ assert.equal(await note.isVisible(), true);+ for (const re of w.note) assert.match(await note.textContent(), re);+ const fit = await page.evaluate(() => {+ const l = document.querySelector("#imageGenRow .image-gen-hidden"), row = l.closest(".row").getBoundingClientRect(), r = l.getBoundingClientRect();+ return r.left >= row.left - 1 && r.right <= row.right + 1;+ });+ assert.equal(fit, true, "the note runs out of its row");+ assert.equal(await noSideScroll(page), 0);+ assert.deepEqual(page.errors, []);+ await page.context().close();+ });+ }+ await t.test(`${lang}: a pick that isn't hidden has no note`, async () => {+ const page = await open(lang, 1000, "settings&tab=models", [], settingsPayload(lang, { imageGen: "openai/gpt-image-2" }));+ await page.locator("#imageGenRow").waitFor();+ assert.equal(await page.locator("#imageGenRow .image-gen-hidden").count(), 0);+ assert.deepEqual(page.errors, []);+ await page.context().close();+ });+ }+ });+}diff --git a/internal/provider/account_test.go b/internal/provider/account_test.goindex 89c513409..f5b605f6b 100644--- a/internal/provider/account_test.go+++ b/internal/provider/account_test.go@@ -11,6 +11,7 @@ import ("net/http/httptest""os""path/filepath"+ "slices""strings""sync""testing"@@ -235,6 +236,16 @@ func TestAccountsAreProviders(t *testing.T) {}codex.Unlisted = falseSave(codex)+ // and so do the image models unticked in its editor (321sssrt on X)+ codex.HiddenDrawers = []string{"gpt-image-2"}+ if err := Save(codex); err != nil {+ t.Fatal(err)+ }+ if codex, _ = find(All(), "codex"); !slices.Equal(codex.HiddenDrawers, []string{"gpt-image-2"}) || !codex.DrawerHidden("gpt-image-2") {+ t.Fatalf("hidden image models lost on an account: %v", codex.HiddenDrawers)+ }+ codex.HiddenDrawers = nil+ Save(codex)// signed out: gone, and a stale picks entry is not a providerSave(Provider{ID: "copilot", Models: []string{"gpt-5.5"}})diff --git a/internal/provider/modelkind.go b/internal/provider/modelkind.goindex 4ef8a3610..e37515acb 100644--- a/internal/provider/modelkind.go+++ b/internal/provider/modelkind.go@@ -125,3 +125,10 @@ func setModelKind(ref, kind string) (bool, error) {}return true, nil}++// DrawerHidden is whether the user unticked p's image model in its editor+// (HiddenDrawers): it is left out of the lists an image model is picked+// from and of Automatic's choice, and still draws when named.+func (p Provider) DrawerHidden(model string) bool {+ return slices.Contains(p.HiddenDrawers, model)+}diff --git a/internal/provider/provider.go b/internal/provider/provider.goindex 73942693c..09816be10 100644--- a/internal/provider/provider.go+++ b/internal/provider/provider.go@@ -437,6 +437,17 @@ type Provider struct {// it serves only through the routing groups it is in, and by its// "provider/model" ids.Unlisted bool `json:"unlisted,omitempty"`+ // HiddenDrawers are the provider's image models the user unticked in+ // its editor (321sssrt on X: an OpenAI key lists a dozen): left out of+ // every list one is picked from (Settings › Images, another magpie's+ // list, Aside's) and of Automatic's choice, as an unticked chat model+ // is left out of the agents' lists. A deny list beside Models, not in+ // it: Models is what agents chat with, empty meaning the vendor's list,+ // so an image model put there would be offered to chat with, and+ // hiding one would mean picking every chat model. A request that names+ // one still draws with it, and so does the one Settings › Images+ // names: a hidden pick is shown as picked, and said to be hidden.+ HiddenDrawers []string `json:"hiddenDrawers,omitempty"`// Off switches the provider off without removing it: its keys and// settings stay, but agents aren't given its models, no request,// routing group or fallback goes to it, and its balance isn't asked,@@ -761,6 +772,8 @@ func withPicks(a, pk Provider) Provider {// the extra body fields written for it, which a ChatGPT account's// requests take (WithExtraBody, magpie-releases#18)a.ExtraBody = pk.ExtraBody+ // and the image models unticked in its editor (HiddenDrawers)+ a.HiddenDrawers = pk.HiddenDrawersreturn a}@@ -888,7 +901,7 @@ func Save(p Provider) error {if p.ID == "kiro" {key = p.Key}- p = Provider{ID: p.ID, Key: key, Models: p.Models, NoModels: p.NoModels, PickedFrom: p.PickedFrom, Delisted: p.Delisted, Unlisted: p.Unlisted, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, CapStop: p.CapStop, CapCareful: p.CapCareful, AccountNames: p.AccountNames, MaxConcurrency: p.MaxConcurrency, AccountConcurrency: p.AccountConcurrency, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, PriceRate: p.PriceRate, QuotaRest: p.QuotaRest, QuotaResetAt: p.QuotaResetAt, RestCap: p.RestCap, PinUpstream: p.PinUpstream, NativeCompaction: p.NativeCompaction, PromptAsWritten: p.PromptAsWritten, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID), Tucked: tuckedAccount(p.ID)}+ p = Provider{ID: p.ID, Key: key, Models: p.Models, NoModels: p.NoModels, PickedFrom: p.PickedFrom, Delisted: p.Delisted, Unlisted: p.Unlisted, HiddenDrawers: p.HiddenDrawers, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, CapStop: p.CapStop, CapCareful: p.CapCareful, AccountNames: p.AccountNames, MaxConcurrency: p.MaxConcurrency, AccountConcurrency: p.AccountConcurrency, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, PriceRate: p.PriceRate, QuotaRest: p.QuotaRest, QuotaResetAt: p.QuotaResetAt, RestCap: p.RestCap, PinUpstream: p.PinUpstream, NativeCompaction: p.NativeCompaction, PromptAsWritten: p.PromptAsWritten, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID), Tucked: tuckedAccount(p.ID)}} else {p.AccountProxies = keyProxies(p) // a provider of keys proxies each key apartif subscriptionID(p.ID) && !stored(p.ID) {@@ -1097,6 +1110,9 @@ func AddCopy(p Provider, from string) (string, error) {p.Fallback = slices.Clone(src.Fallback)}p.Unlisted = p.Unlisted || src.Unlisted+ if p.HiddenDrawers == nil {+ p.HiddenDrawers = slices.Clone(src.HiddenDrawers)+ }p.Searches = p.Searches || src.Searchesp.Unredacted = p.Unredacted || src.Unredactedp.NativeCompaction = p.NativeCompaction || src.NativeCompaction