diff --git a/internal/gui/agent_models.go b/internal/gui/agent_models.go index 8058461b9..969458ea7 100644 --- a/internal/gui/agent_models.go +++ b/internal/gui/agent_models.go @@ -61,6 +61,10 @@ type agentModelJSON struct { // Own: one of Codex's own, a ChatGPT account's, which Codex lists // ahead of magpie's until the user puts them in an order (#855) Own bool `json:"own,omitempty"` + // Kept: the agent's visibility (magpie visible) keeps it out of its + // lists, so it is off; ticked, the list sends it as widen, and its + // provider or group is listed (whysugarsweet on X) + Kept bool `json:"kept,omitempty"` } // takesCatalog reports whether an agent picks among magpie's catalog: some @@ -198,13 +202,19 @@ func usedBy(a *agent.Agent, vals map[string]string, e provider.Entry) bool { func agentModelList(a *agent.Agent) []agentModelJSON { id := a.ListsFor() - listed, _ := provider.ListedFor(id) + listed, kept := provider.ListedFor(id) off := provider.ModelOff(id) vals := a.Values() out := []agentModelJSON{} - for _, e := range listed { + // the ones its visibility keeps after the rest, off, so a provider + // added after the agent was narrowed is still in its list to tick + n := len(listed) + for i, e := range append(listed, kept...) { m := agentModelJSON{ID: e.ID, Name: e.Name, Group: e.Provider.Name, Icon: e.Provider.Icon, Context: e.Context, Hidden: off(e.ID), InUse: usedBy(a, vals, e), Own: id == "codex" && provider.CodexOwn(e)} + if i >= n { + m.Hidden, m.Kept = true, true + } if m.Name == "" { m.Name = e.Model } @@ -284,6 +294,9 @@ func agentModelsAPI(mux *http.ServeMux) { Only *bool // OwnHidden, sent as ownHidden OwnHidden *bool + // Widen: models its visibility keeps that were ticked, whose + // providers or groups it is shown from now on + Widen []string } if err := json.NewDecoder(r.Body).Decode(&in); err != nil { fail(rw, err) @@ -323,8 +336,18 @@ func agentModelsAPI(mux *http.ServeMux) { answer() return } + if err := provider.Widen(id, in.Widen); err != nil { + fail(rw, err) + return + } used := map[string]bool{} - listed := agentModelList(a) + // what the visibility still keeps is neither picked nor taken out: + // it isn't listed + keptID := map[string]bool{} + listed := slices.DeleteFunc(agentModelList(a), func(m agentModelJSON) bool { + keptID[m.ID] = m.Kept + return m.Kept + }) for _, m := range listed { used[m.ID] = m.InUse } @@ -369,7 +392,7 @@ func agentModelsAPI(mux *http.ServeMux) { } else { hidden = in.Hidden } - hidden = slices.DeleteFunc(slices.Clone(hidden), func(s string) bool { return used[s] }) + hidden = slices.DeleteFunc(slices.Clone(hidden), func(s string) bool { return used[s] || keptID[s] }) if err := provider.SetHiddenModels(id, hidden); err != nil { fail(rw, err) return diff --git a/internal/gui/agent_models_kept_test.go b/internal/gui/agent_models_kept_test.go new file mode 100644 index 000000000..6f1295b25 --- /dev/null +++ b/internal/gui/agent_models_kept_test.go @@ -0,0 +1,152 @@ +package gui + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// whysugarsweet on X: Claude Desktop narrowed to some providers (magpie +// visible, from the terminal) never listed OpenCode Go added after, while +// Pi listed it, and the Agents page's list had no way to it. The models +// the visibility keeps are in the list, off; ticking one shows the agent +// its provider, and with nothing kept after, the agent is narrowed no more. +func TestAgentModelsKeptByVisibility(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + for _, p := range []provider.Provider{ + {ID: "deepseek-x", Name: "DeepSeek X", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"d1"}}, + {ID: "opencode-go", Name: "OpenCode Go", Preset: "opencode-go", Key: "k", Anthropic: provider.OpenCodeGoAnthropic, Chat: provider.OpenCodeGoChat, Models: []string{"kimi-k2.6", "glm-5.1"}}, + {ID: "zen-x", Name: "Zen X", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"z1"}}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + s := settings.Load() + s.Visible = map[string][]string{"claude-desktop": {"deepseek-x"}} + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + agentModelsAPI(mux) + call := func(method, body string) (out struct { + Models []agentModelJSON + Count *modelCountJSON + }) { + t.Helper() + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest(method, "/api/agent-models/claude-desktop", strings.NewReader(body))) + if w.Code != 200 { + t.Fatalf("%s %d %s", method, w.Code, w.Body) + } + json.Unmarshal(w.Body.Bytes(), &out) + return out + } + find := func(ms []agentModelJSON, id string) agentModelJSON { + t.Helper() + for _, m := range ms { + if m.ID == id { + return m + } + } + t.Fatalf("no %s in %+v", id, ms) + return agentModelJSON{} + } + got := call("GET", "") + if m := find(got.Models, "deepseek-x/d1"); m.Kept || m.Hidden { + t.Fatalf("listed one: %+v", m) + } + for _, id := range []string{"opencode-go/kimi-k2.6", "opencode-go/glm-5.1", "zen-x/z1"} { + if m := find(got.Models, id); !m.Kept || !m.Hidden || m.Group == "" { + t.Fatalf("kept one not in the list, off: %+v", m) + } + } + + // a list sending the kept ones among what it hides takes none of them + // out one by one, and narrows the agent no differently + got = call("POST", `{"hidden":["opencode-go/kimi-k2.6","opencode-go/glm-5.1","zen-x/z1"]}`) + if h := settings.Load().HiddenModels["claude-desktop"]; len(h) != 0 { + t.Fatalf("kept ones saved as taken out: %v", h) + } + if got.Count == nil || got.Count.Shown != 1 || got.Count.Listed != 1 { + t.Fatalf("count: %+v", got.Count) + } + + // Kimi ticked: OpenCode Go is shown, GLM listed and off + got = call("POST", `{"hidden":["opencode-go/glm-5.1","zen-x/z1"],"widen":["opencode-go/kimi-k2.6"]}`) + if v := settings.Load().Visible["claude-desktop"]; !slices.Equal(v, []string{"deepseek-x", "opencode-go"}) { + t.Fatalf("visible: %v", v) + } + if m := find(got.Models, "opencode-go/kimi-k2.6"); m.Kept || m.Hidden { + t.Fatalf("ticked: %+v", m) + } + if m := find(got.Models, "opencode-go/glm-5.1"); m.Kept || !m.Hidden { + t.Fatalf("its provider's other: %+v", m) + } + if m := find(got.Models, "zen-x/z1"); !m.Kept { + t.Fatalf("another provider widened too: %+v", m) + } + if got.Count == nil || got.Count.Shown != 2 || got.Count.Listed != 3 { + t.Fatalf("count: %+v", got.Count) + } + shown, _ := provider.CatalogFor("claude-desktop") + if !slices.ContainsFunc(shown, func(e provider.Entry) bool { return e.ID == "opencode-go/kimi-k2.6" }) { + t.Fatalf("Desktop's catalog lacks it: %v", shown) + } + + // the last kept one ticked: nothing is kept, so it is narrowed no more + call("POST", `{"hidden":["opencode-go/glm-5.1"],"widen":["zen-x/z1"]}`) + if v, ok := settings.Load().Visible["claude-desktop"]; ok { + t.Fatalf("still narrowed: %v", v) + } + if h := settings.Load().HiddenModels["claude-desktop"]; !slices.Equal(h, []string{"opencode-go/glm-5.1"}) { + t.Fatalf("taken out: %v", h) + } +} + +// Shown only its picks, a kept one ticked is a pick of the agent's. +func TestAgentModelsKeptPicked(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + for _, p := range []provider.Provider{ + {ID: "relay", Name: "Relay", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"a1"}}, + {ID: "late", Name: "Late", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"b1", "b2"}}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + s := settings.Load() + s.Visible = map[string][]string{"pi": {"relay"}} + s.PickedModels = map[string][]string{"pi": {"relay/a1"}} + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + agentModelsAPI(mux) + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/agent-models/pi", strings.NewReader(`{"shown":["relay/a1","late/b2"],"widen":["late/b2"]}`))) + if w.Code != 200 { + t.Fatalf("%d %s", w.Code, w.Body) + } + if p := settings.Load().PickedModels["pi"]; !slices.Equal(p, []string{"late/b2", "relay/a1"}) { + t.Fatalf("picks: %v", p) + } + if _, ok := settings.Load().Visible["pi"]; ok { + t.Fatal("still narrowed with nothing kept") + } +} diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 11b97353e..ffcba252d 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -3510,6 +3510,13 @@ async function openAgentModels(a, anchor, ev) { const me = agentModels = { a, anchor, box, saving: Promise.resolve(), changed: false }; const save = () => { me.changed = true; + // one its visibility kept, ticked, has the agent shown its provider + // (or its group): the provider's others are listed from then on, off + // until ticked (whysugarsweet on X) + const widen = models.filter((m) => m.kept && !m.hidden).map((m) => m.id); + for (const w of models.filter((m) => m.kept && !m.hidden)) { + for (const m of models) if (m.kept && (m === w || w.group !== ROUTING_GROUPS && m.group === w.group)) m.kept = false; + } const hidden = models.filter((m) => m.hidden).map((m) => m.id); me.hidden = new Set(hidden); // by whose they are, as the state counts them, for a connected row's chips @@ -3521,7 +3528,9 @@ async function openAgentModels(a, anchor, ev) { g.n++; } const names = models.filter((m) => !m.hidden).slice(0, 3).map((m) => m.name); - const count = { shown: models.length - hidden.length, listed: models.length, by, names }; + const listed = models.filter((m) => !m.kept).length; + // a kept one is off and not listed: it counts in neither + const count = { shown: models.length - hidden.length, listed, by, names }; me.count = a.models = count; // the line under the name counts them, a menu's button names them; an // opened row is drawn again @@ -3535,7 +3544,13 @@ async function openAgentModels(a, anchor, ev) { // shown only its picks, the ones ticked are what is sent: a model that // came since the list was opened isn't among them, so it stays off const body = only ? { shown: models.filter((m) => !m.hidden).map((m) => m.id) } : { hidden }; + if (widen.length) body.widen = widen; me.saving = me.saving.then(() => api("agent-models/" + encodeURIComponent(a.id), body)) + .then((r) => { + if (!widen.length || !r?.models) return; + const still = new Map(r.models.map((m) => [m.id, !!m.kept])); + for (const m of models) if (still.has(m.id)) m.kept = still.get(m.id); + }) .catch(statusErr); }; onlySw.onclick = (e) => { diff --git a/internal/gui/tests/desktop-model-kept.test.cjs b/internal/gui/tests/desktop-model-kept.test.cjs new file mode 100644 index 000000000..a951dab4d --- /dev/null +++ b/internal/gui/tests/desktop-model-kept.test.cjs @@ -0,0 +1,148 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// whysugarsweet on X: Claude Desktop narrowed to some providers (magpie +// visible, from the terminal) never listed OpenCode Go, added after, while +// Pi listed it, and Desktop's model list had no way to it. The models its +// visibility keeps come in the list, off, under their provider; ticking one +// is posted as widen, so the agent is shown that provider, whose other +// models are then listed, off, and ticked as any other (no widen again). +// The row counts only what is listed. Window (with the rail) and the tray +// panel (no rail), Chromium and WebKit, every language. No backend. +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"); +// a real Desktop row has its tiers' fields too +const tiers = ["opus", "sonnet", "haiku", "fable"]; +const options = [{ value: "deepseek/deepseek-v4", label: "DeepSeek V4", ref: "deepseek/deepseek-v4" }]; + +function fixture(lang) { + const list = [ + { id: "deepseek/deepseek-v4", name: "DeepSeek V4", group: "DeepSeek", icon: "deepseek" }, + { id: "grok/grok-4.6", name: "grok-4.6", group: "Grok", icon: "generic" }, + { id: "opencode-go/kimi-k2.6", name: "Kimi K2.6", group: "OpenCode Go", icon: "opencode", hidden: true, kept: true }, + { id: "opencode-go/glm-5.1", name: "GLM-5.1", group: "OpenCode Go", icon: "opencode", hidden: true, kept: true }, + ]; + const posts = []; + const count = () => { + const on = list.filter((m) => !m.hidden); + return { shown: on.length, listed: list.filter((m) => !m.kept).length, by: [], names: on.slice(0, 3).map((m) => m.name) }; + }; + const state = () => ({ + agents: [{ + id: "claude-desktop", name: "Claude Desktop", path: "/test/claude_desktop_config.json", icon: "claude-color", wired: true, + fields: [ + { key: "provider", label: "provider", value: "magpie", options: [{ value: "magpie", label: "magpie", icon: "magpie" }] }, + ...tiers.map((tier) => ({ key: tier, label: tier, value: "", options })), + ], + models: count(), + }], + profiles: [], settings: { lang, theme: "light" }, + }); + async function serve(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};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state()); + if (url.pathname === "/api/agent-models/claude-desktop") { + if (req.method() === "POST") { + const body = req.postDataJSON(); + posts.push(body); + // as the server does: a widened one's provider is listed + const groups = new Set(list.filter((m) => body.widen?.includes(m.id)).map((m) => m.group)); + for (const m of list) { + if (groups.has(m.group)) m.kept = false; + m.hidden = m.kept || body.hidden.includes(m.id); + } + return json({ models: list, count: count() }); + } + return json({ models: list }); + } + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/agents/cli") return json({ agents: {}, pending: false }); + if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true } }); + 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)]; + const body = await fs.readFile(file).catch(() => null); + if (!body) return route.fulfill({ status: 404, body: "" }); + await route.fulfill({ body, contentType }); + } + return { serve, posts }; +} + +const cd = '.row.agent[data-id="claude-desktop"]'; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const where of ["window", "panel"]) { + test(`${engine} ${lang} ${where}: a provider Claude Desktop's visibility keeps is in its list, and ticked is shown it`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await browser.newPage({ viewport: where === "panel" ? { width: 420, height: 640 } : { width: 1100, height: 700 } }); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const fx = fixture(lang); + await page.route("**/*", fx.serve); + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${where}-desktop-kept.png`) }); + } + await browser.close(); + }); + await page.goto("http://magpie.test/" + (where === "panel" ? "?mode=panel" : "")); + await page.locator(cd).waitFor(); + let menu; + if (where === "window") menu = page.locator(`${cd} > .ag-menu`); + else { + await page.locator(`${cd} .ag-sum`).click(); + menu = page.locator(`${cd} .ag-open .ag-menu`); + await page.waitForFunction((sel) => document.querySelector(sel)?.getBoundingClientRect().height > 0, `${cd} .ag-open .ag-menu`); + } + assert.equal(await menu.locator(".v").textContent(), await page.evaluate(() => t("All {n} models", { n: 2 })), "a kept one counted as listed"); + const y = await page.evaluate(() => scrollY); + await menu.click(); + const box = page.locator(".am-pop:not(.leaving)"); + await box.waitFor(); + const rows = () => box.locator(".am-mr").evaluateAll((es) => es.map((e) => [e.querySelector(".n").textContent, e.getAttribute("aria-checked")])); + assert.deepEqual(await rows(), [["DeepSeek V4", "true"], ["grok-4.6", "true"], ["Kimi K2.6", "false"], ["GLM-5.1", "false"]]); + if (where === "window") { + assert.deepEqual(await box.locator(".am-rail .am-ri .c").allInnerTexts(), ["2/4", "1/1", "1/1", "0/2"]); + } else assert.equal(await box.locator(".am-rail .am-ri").count(), 0, "a rail at 420px"); + const box1 = await box.boundingBox(); + assert.ok(box1.x >= 0 && box1.x + box1.width <= (where === "panel" ? 420 : 1100), JSON.stringify(box1)); + + // wait on the posts, never on a duration + const posted = async (n) => { + for (const end = Date.now() + 5000; Date.now() < end; await new Promise((r) => setTimeout(r, 25))) if (fx.posts.length === n) return; + assert.fail(n + " posts"); + }; + // Kimi ticked: sent as widen, GLM as taken out + await box.locator(".am-mr", { hasText: "Kimi K2.6" }).click(); + await posted(1); + assert.deepEqual(fx.posts[0].widen, ["opencode-go/kimi-k2.6"]); + assert.deepEqual(fx.posts[0].hidden, ["opencode-go/glm-5.1"]); + const some = await page.evaluate(() => t("Showing {shown} / {listed} models", { shown: 3, listed: 4 })); + await page.waitForFunction((s) => document.querySelector(".ag-menu .v")?.textContent === s, some); + // GLM ticked after: listed now, so no widen + await box.locator(".am-mr", { hasText: "GLM-5.1" }).click(); + await posted(2); + assert.equal(fx.posts[1].widen, undefined, JSON.stringify(fx.posts[1])); + assert.deepEqual(fx.posts[1].hidden, []); + const all = await page.evaluate(() => t("All {n} models", { n: 4 })); + await page.waitForFunction((s) => document.querySelector(".ag-menu .v")?.textContent === s, all); + assert.deepEqual(await rows(), [["DeepSeek V4", "true"], ["grok-4.6", "true"], ["Kimi K2.6", "true"], ["GLM-5.1", "true"]]); + + assert.equal(await page.evaluate(() => scrollY), y, "a click scrolled the page"); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/provider/visible.go b/internal/provider/visible.go index c00032ac3..1c55977a6 100644 --- a/internal/provider/visible.go +++ b/internal/provider/visible.go @@ -264,6 +264,55 @@ func sortedIDs(ids []string) []string { return keep } +// Widen lets agent's visibility give it these entries, of those it keeps +// now (whysugarsweet on X: Claude Desktop narrowed to five providers, set +// from the terminal, never listed OpenCode Go added later, and the Agents +// page's list had no way to it): each one's provider, or its group, is +// added to the names the agent is narrowed to, so the provider's other +// models are listed too, for its list to show or not. When nothing is +// kept after, the agent is narrowed no more. An id not kept is passed by. +func Widen(agent string, ids []string) error { + agent = strings.ToLower(strings.TrimSpace(agent)) + if agent == "" { + return errors.New("no agent") + } + names, narrowed := VisibleTo(agent) + if !narrowed || len(ids) == 0 { + return nil + } + _, kept := ListedFor(agent) + added := false + for _, e := range kept { + if !slices.Contains(ids, e.ID) { + continue + } + n := e.Provider.ID + if e.Group != "" { + n = e.Group + } + if !slices.ContainsFunc(names, func(v string) bool { return strings.EqualFold(v, n) }) { + names, added = append(names, n), true + } + } + if !added { + return nil + } + s := settings.Load() + if slices.ContainsFunc(kept, func(e Entry) bool { return !Shows(names, e) }) { + if s.Visible == nil { + s.Visible = map[string][]string{} + } + s.Visible[agent] = names + } else { + delete(s.Visible, agent) + } + if err := settings.Save(s); err != nil { + return err + } + catalog.Touched() + return nil +} + // SetHiddenModels takes these entries out of agent's lists, and puts back // every other; none shows it every model its visibility gives it. The // agents that keep the models in files of their own are told.