agent, gui: ZCode's row picks which of magpie's models its picker lists, as Pencil's, T3 Code's, WorkBuddy's and Copilot in JetBrains' do now (#1508, NovaTrailX)
settings.hiddenModels had no "zcode", and ZCode's ~/.zcode/v2/config.json and provider_config.json listed every model. The files magpie writes for ZCode already leave out what is hidden for it (magpieModels(id) reads provider.CatalogFor), but its row had no list to hide one in: ZCode's only field puts magpie in its own picker, with no option among the catalog, and the Agents page gives a models line and menu only to an agent that has one (takesCatalog) or ListsModels (Cursor Private Inference). Audit of every agent row: each agent with a field among the catalog (viaMagpie) already had the list. Those whose only field puts magpie's models in their own picker had none: zcode, pencil, t3code, workbuddy, workbuddy-ai and copilot-jetbrains. They now set ListsModels; Claude Desktop's tier pickers list the catalog once connected, and cursor-local had it already. - agent: ListsModels on those six, its doc says when it applies. - gui/api.go: the row's JSON says menu (ListsModels), so app.js gives it the models button as it does Claude Desktop's and Cursor's, rather than a hard-coded set of ids. Tests: - TestEveryPickerOfMagpiesModelsCanBeNarrowed: any built-in agent that puts magpie in a picker with no option among the catalog and no ListsModels fails, so a new agent can't miss it. - TestZCodeListsOnlyThePicked: from a config the user edited by hand (own providers, theme, rules, a manual rule for one of magpie's models, ui lang), hiding one model takes it out of both files at the next sync and showing it puts it back; the user's entries stay at every step. - TestZCodeModelList: through the GUI handlers: connect, the row has menu and 2/2, hide one, settings.hiddenModels.zcode is set, the row reads 1/2, and after SyncCatalog both files list only the other. - tests/zcode-models.test.cjs: ZCode's row in en, zh, zh-TW, ja, de, in the window (1100px) and the tray panel (420px), Chromium and WebKit: the line, the menu button, unticking one posts it and the count drops, ticking it back; no scroll, no <select>, no overflow. 20/20. Without ZCode's ListsModels, the first and third fail (tried); without a.menu in app.js, all 20 GUI cases fail (tried). All in a sandbox HOME; the live ~/.zcode was never touched. Run: go test -tags nogui ./internal/agent ./internal/gui; gofmt -l; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/agent ./internal/gui; node --test on zcode-models, agent-model*, agent-models-*, agent-notice-lang, click-scroll, cursor-local-*, gui-de/ja/zh-tw and i18n-keys, both engines: all pass (three load timeouts under a machine load of ~140 passed rerun alone). go test -tags nogui -timeout 40m ./... on the rebased tree: every package ok but internal/gateway, whose TestQueuedStreamKeptAliveForTheMinute hit its 1.5s read deadline at a machine load of ~130; it passes -count=3 run alone, and this change touches nothing it runs.
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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 <select>,
|
||||
// and no click scrolls the page. No backend: 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");
|
||||
|
||||
function fixture(lang) {
|
||||
const list = [
|
||||
{ id: "deepseek/pro", name: "DeepSeek Pro", group: "DeepSeek", icon: "deepseek" },
|
||||
{ id: "deepseek/flash", name: "DeepSeek Flash", group: "DeepSeek", icon: "deepseek" },
|
||||
{ id: "kimi/k3", name: "Kimi K3", group: "Kimi", icon: "generic" },
|
||||
];
|
||||
const posts = [];
|
||||
const count = () => {
|
||||
const on = list.filter((m) => !m.hidden);
|
||||
const by = [];
|
||||
for (const m of on) {
|
||||
let g = by.find((x) => x.name === m.group);
|
||||
if (!g) by.push(g = { name: m.group, icon: m.icon, n: 0 });
|
||||
g.n++;
|
||||
}
|
||||
return { shown: on.length, listed: list.length, by, names: on.slice(0, 3).map((m) => m.name) };
|
||||
};
|
||||
const state = () => ({
|
||||
agents: [{
|
||||
id: "zcode", name: "ZCode", path: "~/.zcode/v2/config.json", icon: "zcode", wired: true, menu: true,
|
||||
fields: [{ key: "provider", label: "provider", value: "magpie", options: [{ value: "magpie", label: "magpie", icon: "magpie", note: "every magpie model in ZCode's picker" }] }],
|
||||
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/zcode") {
|
||||
if (req.method() === "POST") {
|
||||
const { hidden } = req.postDataJSON();
|
||||
posts.push(hidden);
|
||||
for (const m of list) m.hidden = 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);
|
||||
await route.fulfill(body ? { body, contentType } : { status: 404, body: "" });
|
||||
}
|
||||
return { serve, posts };
|
||||
}
|
||||
|
||||
const cd = '.row.agent[data-id="zcode"]';
|
||||
|
||||
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}: ZCode's row picks the models its picker lists`, 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);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const fx = fixture(lang);
|
||||
await page.route("**/*", fx.serve);
|
||||
t.after(() => browser.close());
|
||||
await page.goto("http://magpie.test/" + (where === "panel" ? "?mode=panel" : ""));
|
||||
await page.locator(cd).waitFor();
|
||||
const said = (n) => page.evaluate((n) => t("Connected · {n} models in {agent}'s model menu", { n, agent: "ZCode" }), n);
|
||||
|
||||
let menu;
|
||||
if (where === "window") {
|
||||
assert.equal(await page.locator(`${cd} .ag-st-t`).textContent(), await said(3));
|
||||
menu = page.locator(`${cd} > .ag-menu`);
|
||||
} else {
|
||||
assert.equal(await page.locator(`${cd} .ag-sum .vt`).textContent(), "DeepSeek Pro, DeepSeek Flash +1");
|
||||
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 page.locator(`${cd} .ag-conn-said`).textContent(), await said(3));
|
||||
}
|
||||
assert.equal(await menu.count(), 1, "no models button");
|
||||
assert.equal(await menu.locator(".v").textContent(), "DeepSeek Pro, DeepSeek Flash +1");
|
||||
|
||||
const y = await page.evaluate(() => scrollY);
|
||||
await menu.click();
|
||||
const box = page.locator(".am-pop:not(.leaving)");
|
||||
await box.waitFor();
|
||||
assert.equal(await box.locator(".am-t").textContent(), await page.evaluate(() => t("{agent}'s model list", { agent: "ZCode" })));
|
||||
const rows = await box.locator(".am-mr").evaluateAll((es) => es.map((e) => [e.querySelector(".n").textContent, e.getAttribute("aria-checked")]));
|
||||
assert.deepEqual(rows, [["DeepSeek Pro", "true"], ["DeepSeek Flash", "true"], ["Kimi K3", "true"]]);
|
||||
|
||||
// DeepSeek Flash out: posted at once, the list stays open, the row says so
|
||||
await box.locator(".am-mr", { hasText: "DeepSeek Flash" }).click();
|
||||
await page.waitForFunction(() => document.querySelector(".ag-menu .v")?.textContent === "DeepSeek Pro, Kimi K3");
|
||||
await page.waitForTimeout(150);
|
||||
assert.deepEqual(fx.posts, [["deepseek/flash"]]);
|
||||
assert.equal(await box.count(), 1, "the list closed after one pick");
|
||||
assert.equal(await page.locator(where === "window" ? `${cd} .ag-st-t` : `${cd} .ag-conn-said`).textContent(), await said(2));
|
||||
// and back in
|
||||
await box.locator(".am-mr", { hasText: "DeepSeek Flash" }).click();
|
||||
await page.waitForFunction(() => document.querySelector(".ag-menu .v")?.textContent === "DeepSeek Pro, DeepSeek Flash +1");
|
||||
await page.waitForTimeout(150);
|
||||
assert.deepEqual(fx.posts.at(-1), []);
|
||||
|
||||
assert.equal(await page.evaluate(() => scrollY), y, "a click scrolled the page");
|
||||
assert.equal(await page.locator("select").count(), 0, "a native select");
|
||||
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), "the row runs past the window");
|
||||
if (lang !== "en") assert.ok(!(await page.locator(cd).textContent()).includes("models in"), "English in the row");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user