diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 9f2a36a99..15cb0070c 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -11202,6 +11202,8 @@ function renderModels(p) { // an agent's own list can leave a pick out (Kylin_Cloud on X) const by = !draft.unlisted && (on || served.has(m.id)) ? hiders(m.id) : []; if (by.length) c.title = (c.title || m.id) + "\n" + t("Left out of {agents}'s model list, on the Agents page", { agents: by.join(", ") }); + const kb = !draft.unlisted && (on || served.has(m.id)) ? p.keptBy?.[m.id] || [] : []; + if (kb.length) c.title = (c.title || m.id) + "\n" + t("Kept out of agents' lists by {groups}, a routing group listed alone", { groups: kb.join(", ") }); tested(c, m.id); menu(c, m.id); // a click picks the model, a served one too: with none picked it @@ -11253,10 +11255,13 @@ function renderModels(p) { hid.replaceChildren(); const ids = draft.unlisted || decideOnly(p) ? [] : servedIds(p); const lines = (p.agents || []).map((a) => [a.name, ids.filter((id) => a.hides?.includes(id))]).filter(([, l]) => l.length); - hid.hidden = !lines.length; - for (const [agent, l] of lines.slice(0, 4)) { - hid.append(el("div", "", t("{agent}'s model list leaves out {models}: shown again from there, on the Agents page.", { agent, models: l.slice(0, 6).join(", ") + (l.length > 6 ? " …" : "") }))); - } + // a group listed alone keeps its models out of every agent's list, + // this switch off or on (hayden4608 on Discord) + const kept = [...new Set(ids.flatMap((id) => p.keptBy?.[id] || []))].map((g) => [g, ids.filter((id) => p.keptBy?.[id]?.includes(g))]); + hid.hidden = !lines.length && !kept.length; + const few = (l) => l.slice(0, 6).join(", ") + (l.length > 6 ? " …" : ""); + for (const [agent, l] of lines.slice(0, 4)) hid.append(el("div", "", t("{agent}'s model list leaves out {models}: shown again from there, on the Agents page.", { agent, models: few(l) }))); + for (const [group, l] of kept.slice(0, 4)) hid.append(el("div", "", t("The routing group {group} is listed alone, so agents don't see {models}: change its Model lists on the Routing page.", { group, models: few(l) }))); }; // those of its models in no routing group, while it is kept for groups: // nothing can use them, which is said here rather than left for the diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index f417313ca..0cc5fc847 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3726,6 +3726,8 @@ const I18N = { "Its models leave the list agents pick from; the routing groups they are in still use them": "它的模型不出现在 Agent 的可选列表里;所在的路由分组仍会使用它们", "Picked: the routing groups it is in use it. Agents don't see it.": "已选:它所在的路由分组会用到。Agent 看不到它。", "Left out of {agents}'s model list, on the Agents page": "已在 Agent 页从 {agents} 的模型列表中隐藏", + "Kept out of agents' lists by {groups}, a routing group listed alone": "被路由组 {groups} 挡在 Agent 的模型列表外:它的模型列表设为「只列出本组」", + "The routing group {group} is listed alone, so agents don't see {models}: change its Model lists on the Routing page.": "路由组 {group} 的模型列表设为「只列出本组」,Agent 因此看不到 {models}:在路由页把它的「模型列表」改成「也列出成员模型」。", "{agent}'s model list leaves out {models}: shown again from there, on the Agents page.": "{agent} 的模型列表隐藏了 {models}:要再显示,请到 Agent 页的该列表里打开。", "Agents don't see them: only the routing groups they are in use them.": "Agent 看不到这些模型,只有它们所在的路由分组会用到。", "Agents see the models picked.": "Agent 看到的是已勾选的模型。", @@ -7963,6 +7965,8 @@ const I18N = { "Its models leave the list agents pick from; the routing groups they are in still use them": "它的模型不出現在 Agent 的可選列表裡;所在的路由分組仍會使用它們", "Picked: the routing groups it is in use it. Agents don't see it.": "已選:它所在的路由分組會用到。Agent 看不到它。", "Left out of {agents}'s model list, on the Agents page": "已在 Agent 頁從 {agents} 的模型列表中隱藏", + "Kept out of agents' lists by {groups}, a routing group listed alone": "被路由組 {groups} 擋在 Agent 的模型清單外:它的模型清單設為「只列出本組」", + "The routing group {group} is listed alone, so agents don't see {models}: change its Model lists on the Routing page.": "路由組 {group} 的模型清單設為「只列出本組」,Agent 因此看不到 {models}:在路由頁把它的「模型清單」改成「也列出成員模型」。", "{agent}'s model list leaves out {models}: shown again from there, on the Agents page.": "{agent} 的模型列表隱藏了 {models}:要再顯示,請到 Agent 頁的該列表裡開啟。", "Agents don't see them: only the routing groups they are in use them.": "Agent 看不到這些模型,只有它們所在的路由分組會用到。", "Agents see the models picked.": "Agent 看到的是已勾選的模型。", @@ -12216,6 +12220,8 @@ const I18N = { "Its models leave the list agents pick from; the routing groups they are in still use them": "そのモデルはエージェントが選ぶリストから外れます。所属するルーティンググループでは引き続き使われます", "Picked: the routing groups it is in use it. Agents don't see it.": "選択済み:所属するルーティンググループが使います。エージェントには見えません。", "Left out of {agents}'s model list, on the Agents page": "エージェントページで {agents} のモデル一覧から外されています", + "Kept out of agents' lists by {groups}, a routing group listed alone": "ルーティンググループ {groups} のモデル一覧が「グループだけ」のため、エージェントの一覧から外れています", + "The routing group {group} is listed alone, so agents don't see {models}: change its Model lists on the Routing page.": "ルーティンググループ {group} のモデル一覧が「グループだけ」のため、エージェントには {models} が見えません。ルーティングページでその「モデル一覧」を「メンバーのモデルも」にしてください。", "{agent}'s model list leaves out {models}: shown again from there, on the Agents page.": "{agent} のモデル一覧は {models} を外しています。エージェントページのその一覧から再表示できます。", "Agents don't see them: only the routing groups they are in use them.": "エージェントには見えません。所属するルーティンググループだけが使います。", "Agents see the models picked.": "エージェントには選択したモデルが表示されます。", @@ -16484,6 +16490,8 @@ const I18N = { "Its models leave the list agents pick from; the routing groups they are in still use them": "Seine Modelle verschwinden aus der Auswahlliste der Agenten; die Weiterleitungsgruppen, in denen sie sind, nutzen sie weiterhin", "Picked: the routing groups it is in use it. Agents don't see it.": "Ausgewählt: Die Weiterleitungsgruppen, in denen es ist, nutzen es. Agenten sehen es nicht.", "Left out of {agents}'s model list, on the Agents page": "Auf der Seite Agenten aus der Modellliste von {agents} genommen", + "Kept out of agents' lists by {groups}, a routing group listed alone": "Von {groups} aus den Listen der Agenten gehalten: ihre Modellliste steht auf „Nur die Gruppe“", + "The routing group {group} is listed alone, so agents don't see {models}: change its Model lists on the Routing page.": "Die Routing-Gruppe {group} listet nur sich selbst, daher sehen Agenten {models} nicht: Stelle ihre Modelllisten auf der Seite Weiterleitung auf „Auch seine Modelle“.", "{agent}'s model list leaves out {models}: shown again from there, on the Agents page.": "Die Modellliste von {agent} lässt {models} aus: Dort, auf der Seite Agenten, wieder einblenden.", "Agents don't see them: only the routing groups they are in use them.": "Agenten sehen sie nicht: Nur die Weiterleitungsgruppen, in denen sie sind, nutzen sie.", "Agents see the models picked.": "Agenten sehen die gewählten Modelle.", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index df2327290..a86fe48d9 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -284,7 +284,11 @@ type providerJSON struct { // Groups are the routing groups ("group/") each of its models is // in, by model id: what an unlisted one is still used through, and the // editor names those in none - Groups map[string][]string `json:"groups,omitempty"` + Groups map[string][]string `json:"groups,omitempty"` + // KeptBy are the routing groups listing alone (Group.Unlists) that + // keep each of its models out of agents' lists, by model id: its own + // "Only through routing groups" switched off doesn't bring those back + KeptBy map[string][]string `json:"keptBy,omitempty"` Off bool `json:"off"` // switched off: kept, but agents get none of its models Contexts map[string]int `json:"contexts,omitempty"` // the windows the user set, "*" for all its models Outputs map[string]int `json:"outputs,omitempty"` // the reply limits the user set (provider.OutputsOf) @@ -757,6 +761,14 @@ func providerInfoWith(p provider.Provider, agents []agentUse, desktop map[string out.Groups[m] = gs } } + for id, gs := range provider.GroupKept() { + if m, ok := strings.CutPrefix(id, p.ID+"/"); ok { + if out.KeptBy == nil { + out.KeptBy = map[string][]string{} + } + out.KeptBy[m] = gs + } + } if a := p.Account; a != nil { out.Account = &accountJSON{Account: *a, Agent: a.Agent} out.Account.Name, out.Account.Icon = accountLabel(p) diff --git a/internal/gui/tests/unlisted-group-kept.test.cjs b/internal/gui/tests/unlisted-group-kept.test.cjs new file mode 100644 index 000000000..63402072b --- /dev/null +++ b/internal/gui/tests/unlisted-group-kept.test.cjs @@ -0,0 +1,103 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// hayden4608 on Discord: with a provider's "Only through routing groups" +// switched off, its models were still missing from the Agents page, while +// the editor said agents see them. A routing group whose Model lists is +// "The group alone" keeps its members out of every agent's list, this +// switch off or on, so the editor names that group under the models and on +// each chip, and says where to change it. +// Chromium and WebKit, wide and narrow, in every language. +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 relay = { + id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "", + models: ["alpha", "beta", "gamma"].map((id) => ({ id, name: id, on: true })), chosen: ["alpha", "beta", "gamma"], + groups: {}, unlisted: false, fallback: [], headers: {}, + agents: [{ id: "codex", name: "Codex", icon: "generic" }], keptBy: { beta: ["Alone"], gamma: ["Alone", "Solo"] }, + key: { set: true, masked: "sk-…one" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", +}; + +const LINE = "The routing group {group} is listed alone, so agents don't see {models}: change its Model lists on the Routing page."; +const CHIP = "Kept out of agents' lists by {groups}, a routing group listed alone"; +const fill = (s, v) => s.replace(/\{(\w+)\}/g, (_, k) => v[k]); + +function serve(lang, p) { + return async (r) => { + const req = r.request(), url = new URL(req.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" || url.pathname === "/api/set") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/agents/cli") return json({ agents: {}, pending: false }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) return new Promise(() => {}); + return json({ mine: true, now: new Date().toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/groups" || url.pathname.startsWith("/api/groups/")) return json({ groups: [], pools: [], deciders: [], models: [] }); + if (url.pathname === "/api/providers") return json({ providers: [p], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999", groups: [] } }); + 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", "zh-TW", "ja", "de"]) { + for (const width of [1000, 420]) { + test(`${engine} ${lang} ${width}px: the editor names the group listed alone that keeps a model from agents`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" })); + t.after(() => browser.close()); + const errors = []; + const open = async (p) => { + const page = await (await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, p)); + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: "Relay" }).click(); + await page.locator(".editor .mchip").first().waitFor(); + return page; + }; + let page = await open(relay); + const w = await page.evaluate(([keys, lang]) => Object.fromEntries(keys.map((k) => [k, lang === "en" ? k : I18N[lang][k]])), [[LINE, CHIP, "Only through routing groups"], lang]); + assert.deepEqual(Object.entries(w).filter(([, v]) => !v).map(([k]) => k), [], "every string has its words"); + + const hid = page.locator(".editor .agent-hides"); + assert.ok(await hid.isVisible(), "said under the models"); + assert.deepEqual(await hid.locator("div").allTextContents(), [ + fill(w[LINE], { group: "Alone", models: "beta, gamma" }), + fill(w[LINE], { group: "Solo", models: "gamma" }), + ]); + const chip = (id) => page.locator(".editor .mchip", { hasText: new RegExp(`^${id}`) }); + assert.ok((await chip("gamma").getAttribute("title")).includes(fill(w[CHIP], { groups: "Alone, Solo" })), "the chip says it too"); + assert.ok(!(await chip("alpha").getAttribute("title") || "").includes(fill(w[CHIP], { groups: "Alone" })), "only on the ones kept out"); + const box = await hid.boundingBox(); + assert.ok(box.x >= 0 && box.x + box.width <= width, `fits the width: ${JSON.stringify(box)}`); + assert.equal(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), true, "no sideways scroll"); + assert.equal(parseFloat(await hid.evaluate((e) => getComputedStyle(e).borderLeftWidth)), 0, "no left-border accent"); + + // kept for routing groups: no agent lists them anyway + const tick = page.locator(".editor label", { hasText: w["Only through routing groups"] }).locator("input"); + await tick.check(); + assert.ok(await hid.isHidden(), "not said while no agent lists them"); + assert.ok(!(await chip("beta").getAttribute("title")).includes(fill(w[CHIP], { groups: "Alone" }))); + await tick.uncheck(); + assert.ok(await hid.isVisible(), "said again when unticked"); + + // no group keeps them out: nothing said + page = await open({ ...relay, keptBy: undefined }); + assert.ok(await page.locator(".editor .agent-hides").isHidden()); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/gui/unlisted_group_kept_test.go b/internal/gui/unlisted_group_kept_test.go new file mode 100644 index 000000000..71090acd6 --- /dev/null +++ b/internal/gui/unlisted_group_kept_test.go @@ -0,0 +1,48 @@ +package gui + +import ( + "os" + "slices" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// A provider's "Only through routing groups" switched off brings its +// models back to agents' lists, unless a routing group listed alone +// (Group.Unlists: the group listed alone) keeps them out: then they stayed out +// of every agent's list with the provider's editor saying agents see them +// (hayden4608 on Discord). The editor is told which groups keep which of +// its models out, to say so. +func TestUnlistedGroupKeptSaid(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()) + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m2", "m3"}}); err != nil { + t.Fatal(err) + } + if err := provider.SaveGroup(provider.Group{ID: "alone", Name: "Alone", Members: []string{"relay/m2"}, Unlists: true}); err != nil { + t.Fatal(err) + } + if err := provider.SaveGroup(provider.Group{ID: "also", Name: "Also", Members: []string{"relay/m3"}}); err != nil { + t.Fatal(err) + } + var listed []string + for _, e := range provider.Catalog() { + if e.Group == "" { + listed = append(listed, e.ID) + } + } + if !slices.Equal(listed, []string{"relay/m3"}) { + t.Fatalf("agents are offered %v, want relay/m3 alone", listed) + } + p, err := provider.Find("relay") + if err != nil { + t.Fatal(err) + } + j := providerInfo(*p, nil) + if !slices.Equal(j.KeptBy["m2"], []string{"Alone"}) || len(j.KeptBy) != 1 { + t.Fatalf("keptBy %v, want m2 kept by Alone alone", j.KeptBy) + } +} diff --git a/internal/provider/models.go b/internal/provider/models.go index ea7d78e30..d77af0d1f 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -2727,7 +2727,7 @@ func catalogKeeping(keep func(Entry) bool) []Entry { out := slices.Clone(groupEntries(entries)) // held: the caller's to change kept := unlistedByGroups(entries) for _, e := range entries { - if !e.Provider.Unlisted && !kept[e.ID] || keep != nil && keep(e) { + if !e.Provider.Unlisted && len(kept[e.ID]) == 0 || keep != nil && keep(e) { out = append(out, e) } } @@ -2735,13 +2735,14 @@ func catalogKeeping(keep func(Entry) bool) []Entry { } // unlistedByGroups are the models, by "provider/model", that a group -// keeps out of the lists (Group.Unlists): those it names, a member fixed -// at an effort counting as its model, and those its patterns match. -func unlistedByGroups(entries []Entry) map[string]bool { +// keeps out of the lists (Group.Unlists), with the names of the groups +// that do: those it names, a member fixed at an effort counting as its +// model, and those its patterns match. +func unlistedByGroups(entries []Entry) map[string][]string { if !slices.ContainsFunc(heldOf("file", load).Groups, func(g Group) bool { return g.Unlists }) { return nil } - out := map[string]bool{} + out := map[string][]string{} for _, g := range groupsIn(entries) { if !g.Unlists || g.Hidden || g.Disabled { continue @@ -2751,14 +2752,34 @@ func unlistedByGroups(entries []Entry) map[string]bool { continue } model, _ := memberEffortIn(entries, id) - if p, m, ok := resolveIn(entries, model); ok { - out[p.ID+"/"+m] = true + if p, m, ok := resolveIn(entries, model); ok && !slices.Contains(out[p.ID+"/"+m], cmp.Or(g.Name, g.ID)) { + out[p.ID+"/"+m] = append(out[p.ID+"/"+m], cmp.Or(g.Name, g.ID)) } } } return out } +// GroupKept is the models, by "provider/model", that a group listing +// alone (Group.Unlists) keeps out of agents' lists, with those groups' +// names: a provider's editor names them, as a model its own switch put +// back for agents is still left out by them. A signed-in subscription's +// models, which agents keep (SubscriptionKept), aren't among them. +func GroupKept() map[string][]string { + entries := providerEntries() + kept := unlistedByGroups(entries) + if len(kept) == 0 { + return nil + } + out := map[string][]string{} + for _, e := range entries { + if gs := kept[e.ID]; len(gs) > 0 && !SubscriptionKept(e) { + out[e.ID] = slices.Clone(gs) + } + } + return out +} + // Served is the catalog with the unlisted providers' models as well: every // model a routing group can be made of, or a request can name. Like // providerEntries it is shared, only for reading: a request asks it for @@ -2779,7 +2800,7 @@ func Unlisted() []Entry { entries := providerEntries() kept := unlistedByGroups(entries) for _, e := range entries { - if e.Provider.Unlisted || kept[e.ID] && !SubscriptionKept(e) { + if e.Provider.Unlisted || len(kept[e.ID]) > 0 && !SubscriptionKept(e) { out = append(out, e) } }