diff --git a/internal/agent/agent.go b/internal/agent/agent.go index 18f075752..b5a0e74a1 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -112,10 +112,12 @@ type Agent struct { // UA is what the agent's User-Agent begins with, lower-case: how the // gateway tells its requests from others' UA []string - // ListsModels: the agent's own model menu is the gateway's /v1/models - // as asked with its key, so the models picked on the Agents page for it - // (settings.HiddenModels) are its menu, though no field of its picks - // among the catalog (Cursor Private Inference) + // ListsModels: the agent's own model menu is magpie's models as picked + // on the Agents page for it (settings.HiddenModels, PickedModels), + // though no field of its picks among the catalog: the gateway's + // /v1/models as asked with its key (Cursor Private Inference), or the + // list magpie writes into its files, magpieModels(id), where its only + // field puts magpie in its picker (ZCode, Pencil: #1508) ListsModels bool // Sync, for an agent that reads magpie's models from a file of its own // rather than asking the gateway, rewrites that list as the catalog is diff --git a/internal/agent/copilotjetbrains.go b/internal/agent/copilotjetbrains.go index 471fd936b..40d722c6e 100644 --- a/internal/agent/copilotjetbrains.go +++ b/internal/agent/copilotjetbrains.go @@ -156,6 +156,8 @@ func copilotJetBrainsAt(path string, installed func() bool) *Agent { return edit.GetJSON(path, k) }, "deploymentUrl", vscodeURL(), copilotJBKey, gateway.TokenFor(copilotJBID)) }, + // its picker lists the models picked for it (#1508) + ListsModels: true, Fields: []Field{{ Key: "provider", Label: "provider", Get: func() string { diff --git a/internal/agent/lists_models_test.go b/internal/agent/lists_models_test.go new file mode 100644 index 000000000..acc32b06f --- /dev/null +++ b/internal/agent/lists_models_test.go @@ -0,0 +1,165 @@ +package agent + +import ( + "encoding/json" + "os" + "path/filepath" + "slices" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// listsSandbox is a HOME of its own with one provider of two models. +func listsSandbox(t *testing.T) (home, cfg string) { + t.Helper() + home = t.TempDir() + cfg = filepath.Join(home, ".config") + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", cfg) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro", "flash"}}); err != nil { + t.Fatal(err) + } + return home, cfg +} + +// An agent whose switch puts magpie's models in a picker of its own, with +// no field of its picking among them, lists only the ones picked for it on +// the Agents page, as every other agent does: ZCode was given every model, +// with no way to hide one (#1508, NovaTrailX). ListsModels is what gives +// its row that list. +func TestEveryPickerOfMagpiesModelsCanBeNarrowed(t *testing.T) { + home, cfg := listsSandbox(t) + var bare, menus []string + for _, a := range builtins(home, cfg) { + vals := a.Values() + refs, magpie := false, false + for _, f := range a.Fields { + if f.Options == nil { + continue + } + for _, o := range f.Options(vals) { + refs = refs || o.Ref != "" + magpie = magpie || o.Value == magpieID + } + } + switch { + // Claude Desktop's tier pickers list the catalog once it is + // connected (desktopTierFields), and the sandbox has no Desktop + case refs, a.ID == "claude-desktop": + case a.ListsModels: + menus = append(menus, a.ID) + case magpie: + bare = append(bare, a.ID) + } + } + if len(bare) > 0 { + t.Errorf("magpie's models are put in these agents' pickers with no way to pick which: %v", bare) + } + for _, id := range []string{"zcode", "pencil", "t3code", "workbuddy", "workbuddy-ai", copilotJBID, CursorLocalID} { + if !slices.Contains(menus, id) { + t.Errorf("%s's row has no model list to pick in (ListsModels): %v", id, menus) + } + } +} + +// The models taken out of ZCode's list on the Agents page are out of both +// files it reads, config.json and provider_config.json, and come back when +// they are put back; what the user set by hand stays: their own providers, +// rules and keys, and their manual rule for a model of magpie's (#1508). +func TestZCodeListsOnlyThePicked(t *testing.T) { + home, _ := listsSandbox(t) + dir := filepath.Join(home, ".zcode", "v2") + path, rules := filepath.Join(dir, "config.json"), filepath.Join(dir, "provider_config.json") + os.MkdirAll(dir, 0o755) + os.WriteFile(path, []byte(`{"provider":{"builtin:bigmodel":{"name":"Bigmodel","kind":"anthropic","enabled":true},"mine":{"name":"Mine","kind":"openai","models":{"m1":{"name":"M1"}}}},"theme":"dark"}`), 0o644) + os.WriteFile(rules, []byte(`{"schemaVersion":1,"config":{"providerConfigRules":{"providerRules":[{"providerId":"mine","enabled":true,"config":{"personalModelIds":["m1"]}}]},"modelConfigRules":{"providerModelRules":[{"providerId":"mine","modelId":"m1","config":{"properties":{"contextWindow":1000}}}],"manualProviderModelRules":[{"providerId":"magpie","modelId":"deepseek/pro","config":{"enabled":true,"properties":{"contextWindow":4242}}}]}},"ui":{"lang":"zh"}}`), 0o600) + a := zcode(home) + if err := a.Field("provider").Set("magpie"); err != nil { + t.Fatal(err) + } + type configDoc struct { + Theme string `json:"theme"` + Provider map[string]map[string]any `json:"provider"` + } + readConfig := func() configDoc { + var c configDoc + b, _ := os.ReadFile(path) + if err := json.Unmarshal(b, &c); err != nil { + t.Fatalf("%v\n%s", err, b) + } + if c.Theme != "dark" || c.Provider["builtin:bigmodel"] == nil || c.Provider["mine"]["models"].(map[string]any)["m1"] == nil { + t.Fatalf("the user's own config went: %s", b) + } + return c + } + type rulesDoc struct { + UI map[string]any `json:"ui"` + Config struct { + ProviderConfigRules struct { + ProviderRules []map[string]any `json:"providerRules"` + } `json:"providerConfigRules"` + ModelConfigRules struct { + ProviderModelRules []map[string]any `json:"providerModelRules"` + ManualProviderModelRules []map[string]any `json:"manualProviderModelRules"` + } `json:"modelConfigRules"` + } `json:"config"` + } + readRules := func() rulesDoc { + var d rulesDoc + b, _ := os.ReadFile(rules) + if err := json.Unmarshal(b, &d); err != nil { + t.Fatalf("%v\n%s", err, b) + } + pr, mr := d.Config.ProviderConfigRules.ProviderRules, d.Config.ModelConfigRules + if d.UI["lang"] != "zh" || len(pr) != 2 || pr[0]["providerId"] != "mine" || + !slices.ContainsFunc(mr.ProviderModelRules, func(r map[string]any) bool { return r["providerId"] == "mine" && r["modelId"] == "m1" }) || + len(mr.ManualProviderModelRules) != 1 || mr.ManualProviderModelRules[0]["modelId"] != "deepseek/pro" { + t.Fatalf("the user's own rules went: %s", b) + } + return d + } + listed := func() (config, personal, ruled []string) { + for id := range readConfig().Provider["magpie"]["models"].(map[string]any) { + config = append(config, id) + } + d := readRules() + for _, id := range d.Config.ProviderConfigRules.ProviderRules[1]["config"].(map[string]any)["personalModelIds"].([]any) { + personal = append(personal, id.(string)) + } + for _, r := range d.Config.ModelConfigRules.ProviderModelRules { + if r["providerId"] == magpieID { + ruled = append(ruled, r["modelId"].(string)) + } + } + slices.Sort(config) + slices.Sort(personal) + return config, personal, ruled + } + both := []string{"deepseek/flash", "deepseek/pro"} + if c, p, _ := listed(); !slices.Equal(c, both) || !slices.Equal(p, both) { + t.Fatalf("connected: config.json %v, provider_config.json %v", c, p) + } + // taken out on the Agents page: gone from both, at the next sync + if err := provider.SetHiddenModels("zcode", []string{"deepseek/flash"}); err != nil { + t.Fatal(err) + } + if err := a.Sync(); err != nil { + t.Fatal(err) + } + if c, p, r := listed(); !slices.Equal(c, []string{"deepseek/pro"}) || !slices.Equal(p, []string{"deepseek/pro"}) || len(r) != 0 { + t.Fatalf("hidden: config.json %v, provider_config.json %v, rules %v", c, p, r) + } + // and back + if err := provider.SetHiddenModels("zcode", nil); err != nil { + t.Fatal(err) + } + if err := a.Sync(); err != nil { + t.Fatal(err) + } + if c, p, r := listed(); !slices.Equal(c, both) || !slices.Equal(p, both) || !slices.Equal(r, []string{"deepseek/flash"}) { + t.Fatalf("shown again: config.json %v, provider_config.json %v, rules %v", c, p, r) + } +} diff --git a/internal/agent/pencil.go b/internal/agent/pencil.go index 62e12f708..e743232c7 100644 --- a/internal/agent/pencil.go +++ b/internal/agent/pencil.go @@ -52,6 +52,8 @@ func pencil(home string) *Agent { Sync: func() error { return syncJSON(path, key, theirsKept(path, key, func() any { return pencilProviderJSON(gateway.URL()) }, "models")) }, + // its picker lists the models picked for it (#1508) + ListsModels: true, Fields: []Field{{ Key: "provider", Label: "provider", Get: func() string { diff --git a/internal/agent/t3code.go b/internal/agent/t3code.go index 0c956d5ac..fa01beb62 100644 --- a/internal/agent/t3code.go +++ b/internal/agent/t3code.go @@ -68,6 +68,8 @@ func t3code(home string) *Agent { Sync: func() error { return syncJSON(path, t3Instance, func() any { return t3InstanceJSON(path, gateway.URL()) }) }, + // its custom models are the models picked for it (#1508) + ListsModels: true, Fields: []Field{{ Key: "provider", Label: "provider", Get: func() string { diff --git a/internal/agent/workbuddy.go b/internal/agent/workbuddy.go index 05093fcc2..ac7e3128e 100644 --- a/internal/agent/workbuddy.go +++ b/internal/agent/workbuddy.go @@ -68,6 +68,8 @@ func workbuddyBuild(id, name, dir string, aliases []string) *Agent { } return write(true) }, + // its picker lists the models picked for it (#1508) + ListsModels: true, Fields: []Field{{ Key: "provider", Label: "provider", Get: func() string { diff --git a/internal/agent/zcode.go b/internal/agent/zcode.go index 04e8bf5e7..6e24eb704 100644 --- a/internal/agent/zcode.go +++ b/internal/agent/zcode.go @@ -65,6 +65,8 @@ func zcode(home string) *Agent { ID: "zcode", Name: "ZCode", Icon: "zcode", Aliases: []string{"z-code"}, UA: []string{"zcode"}, Dir: dir, Path: path, + // its picker lists the models picked for it, in both files (#1508) + ListsModels: true, Notice: func() string { if Running(`ZCode\.app/`, `(^|/)ZCode( |$)`) { return noticeZcode.String() diff --git a/internal/gui/agent_models_zcode_test.go b/internal/gui/agent_models_zcode_test.go new file mode 100644 index 000000000..41d610bf5 --- /dev/null +++ b/internal/gui/agent_models_zcode_test.go @@ -0,0 +1,105 @@ +package gui + +import ( + "encoding/json" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/yetone/magpie/internal/agent" + "github.com/yetone/magpie/internal/provider" +) + +// ZCode's row picks which of magpie's models its picker lists, as every +// other agent's does (#1508, NovaTrailX: settings.hiddenModels had no +// zcode, and both its files got every model). Through the page's own +// handlers: its row has the line and the menu, the list takes one out, the +// row counts one fewer, and the files magpie writes for it leave it out. +func TestZCodeModelList(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")) + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m1", "m2"}}); err != nil { + t.Fatal(err) + } + dir := filepath.Join(home, ".zcode", "v2") + os.MkdirAll(dir, 0o755) + os.WriteFile(filepath.Join(dir, "config.json"), []byte(`{"provider":{"mine":{"name":"Mine","kind":"openai"}}}`), 0o644) + h := Handler(nil, nil) + call := func(path, body string, out any) { + t.Helper() + method := "POST" + if body == "" { + method = "GET" + } + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(method, path, strings.NewReader(body))) + if rec.Code != 200 { + t.Fatalf("%s %d %s", path, rec.Code, rec.Body) + } + json.Unmarshal(rec.Body.Bytes(), out) + } + row := func() agentJSON { + var s stateJSON + call("/api/state", "", &s) + for _, a := range s.Agents { + if a.ID == "zcode" { + return a + } + } + t.Fatalf("no zcode in %+v", s.Agents) + return agentJSON{} + } + var s stateJSON + call("/api/agents/connect/zcode", "{}", &s) + r := row() + if !r.Wired || !r.Menu || r.Models == nil || r.Models.Shown != 2 || r.Models.Listed != 2 { + t.Fatalf("connected, its row: wired %v, menu %v, models %+v", r.Wired, r.Menu, r.Models) + } + var list struct { + Models []agentModelJSON + Count *modelCountJSON + } + call("/api/agent-models/zcode", "", &list) + if len(list.Models) != 2 { + t.Fatalf("its list: %+v", list.Models) + } + call("/api/agent-models/zcode", `{"hidden":["relay/m2"]}`, &list) + if list.Count == nil || list.Count.Shown != 1 { + t.Fatalf("one taken out: %+v", list.Count) + } + if got := provider.HiddenModels("zcode"); !got["relay/m2"] || len(got) != 1 { + t.Fatalf("settings.hiddenModels.zcode: %v", got) + } + if r := row(); r.Models == nil || r.Models.Shown != 1 || r.Models.Listed != 2 { + t.Fatalf("its row after: %+v", r.Models) + } + // what a change to the catalog runs (catalog.Changed) + agent.SyncCatalog() + var c struct { + Provider map[string]struct { + Models map[string]any `json:"models"` + } `json:"provider"` + } + b, _ := os.ReadFile(filepath.Join(dir, "config.json")) + json.Unmarshal(b, &c) + if _, ok := c.Provider["mine"]; !ok { + t.Fatalf("the user's own provider went: %s", b) + } + var ids []string + for id := range c.Provider["magpie"].Models { + ids = append(ids, id) + } + if !slices.Equal(ids, []string{"relay/m1"}) { + t.Fatalf("config.json lists %v", ids) + } + b, _ = os.ReadFile(filepath.Join(dir, "provider_config.json")) + if !strings.Contains(string(b), `"personalModelIds":["relay/m1"]`) { + t.Fatalf("provider_config.json: %s", b) + } +} diff --git a/internal/gui/api.go b/internal/gui/api.go index b31fbb156..7065f2eb6 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -193,6 +193,9 @@ type agentJSON struct { // Models: how many of the catalog its lists show, for an agent that // picks among it (agent_models.go) Models *modelCountJSON `json:"models,omitempty"` + // Menu: its own model menu is the models picked here, no one model to + // start on (agent.ListsModels): ZCode's, Cursor Private Inference's + Menu bool `json:"menu,omitempty"` // Source: what an agent not connected runs on now (agent.Source), and // Stale: copies of a connected one still running on the list they // started with (agent.Stale), for the line under its name @@ -1780,6 +1783,7 @@ func state() stateJSON { vals := a.Values() aj := agentJSON{ID: a.ID, Name: a.Name, Icon: a.Icon, Path: tilde(a.Path), Fields: agentFields(a, vals)} aj.Models = agentModelCount(a, aj.Fields) + aj.Menu = a.ListsModels aj.Drift = a.Drift() aj.Wired = a.Wired() if aj.Wired { diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 1656ba79f..4f9e77a2a 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -939,7 +939,11 @@ const NO_PICKER = new Set(["gemini", "hermes", "morph", "agy", "muse"]); // start on, but which of magpie's it offers (Claude Desktop and Cursor // Private Inference read /v1/models, and the user switches among them in it) const MENU_FROM_LIST = new Set(["claude-desktop", "cursor-local"]); -const menuFromList = (a) => MENU_FROM_LIST.has(a.id) && a.wired && !!a.models; +// or the server says so (agent.ListsModels): ZCode, Pencil, T3 Code, +// WorkBuddy's and Copilot in JetBrains put magpie's models in their own +// picker (#1508) +const listsMenu = (a) => MENU_FROM_LIST.has(a.id) || !!a.menu; +const menuFromList = (a) => listsMenu(a) && a.wired && !!a.models; // menuSaid: the models such an agent lists, by name while they are few function menuSaid(c) { @@ -1130,7 +1134,7 @@ function expandLink(a) { const b = el("button", "ag-link" + (open ? " open" : "")); b.type = "button"; b.setAttribute("aria-expanded", String(open)); - b.append(el("span", "", open ? t("Collapse") : a.id === "claude" ? t("Tiers") : a.models && !MENU_FROM_LIST.has(a.id) ? t("Models {n}", { n: a.models.shown }) : t("Details"))); + b.append(el("span", "", open ? t("Collapse") : a.id === "claude" ? t("Tiers") : a.models && !listsMenu(a) ? t("Models {n}", { n: a.models.shown }) : t("Details"))); if (!open) { const c = el("span", "chev"); c.append(svg(CHEV_R, 10, 1.6)); @@ -1215,7 +1219,7 @@ function connectRow(a, row, who, { fields, extras, fieldBtn, sw, kind }) { if (back) row.append(back); // the model it starts on, one click away beside the switch (the owner: // both ways at once): picked here, it is connected first if it wasn't - const start = kind === "ok" && !MENU_FROM_LIST.has(a.id) ? startField(a) : null; + const start = kind === "ok" && !listsMenu(a) ? startField(a) : null; if (start) fields.querySelector(`:scope > [data-key="${CSS.escape(start.key)}"]`)?.remove(); if (kind === "ok") { if (a.wired) row.append(expandLink(a)); diff --git a/internal/gui/tests/zcode-models.test.cjs b/internal/gui/tests/zcode-models.test.cjs new file mode 100644 index 000000000..9b40cfdff --- /dev/null +++ b/internal/gui/tests/zcode-models.test.cjs @@ -0,0 +1,133 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// ZCode's row picks which of magpie's models its picker lists, as every +// other agent's does (#1508, NovaTrailX: settings.hiddenModels had no +// zcode, and ZCode got every model). Its one field puts magpie in ZCode's +// own picker, so, as Cursor Private Inference's, its row has the models +// button the server says it has (menu), which opens the list; unticking +// one is posted at once and the row says so. In the window and the tray +// panel, in every language, in Chromium and WebKit. No native