From 90d884ee608c48c8ea0836eb21f67941b8948c69 Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 3 Oct 2026 03:19:30 +0800 Subject: [PATCH] =?UTF-8?q?agents:=20a=20switch=20connects=20an=20agent=20?= =?UTF-8?q?to=20magpie,=20and=20its=20models=20are=20picked=20in=20the=20a?= =?UTF-8?q?gent=20(prototype,=20the=20owner:=20=E5=9C=A8=20agent=20?= =?UTF-8?q?=E9=A1=B5=E9=9D=A2=E4=B8=8D=E5=BA=94=E8=AF=A5=E6=98=AF=E4=B8=BA?= =?UTF-8?q?=20agent=20=E9=80=89=E6=8B=A9=E6=9F=90=E4=B8=AA=E6=A8=A1?= =?UTF-8?q?=E5=9E=8B=EF=BC=8C=E8=80=8C=E6=98=AF=E5=BA=94=E8=AF=A5=E6=9C=89?= =?UTF-8?q?=E4=B8=AA=E3=80=8C=E6=8E=A5=E5=85=A5=E3=80=8D=E7=9A=84=E5=BC=80?= =?UTF-8?q?=E5=85=B3)=20=E2=80=94=20agent.Connect=20sets=20the=20agent's?= =?UTF-8?q?=20main=20field=20to=20one=20of=20magpie's=20models=20(the=20on?= =?UTF-8?q?e=20serving=20the=20model=20it=20is=20on=20now,=20else=20the=20?= =?UTF-8?q?first)=20or=20to=20magpie=20itself=20for=20an=20app=20whose=20o?= =?UTF-8?q?ne=20setting=20is=20magpie=20as=20its=20provider;=20that=20writ?= =?UTF-8?q?es=20the=20provider=20and=20the=20whole=20catalog,=20so=20the?= =?UTF-8?q?=20agent's=20own=20list=20has=20every=20model.=20POST=20/api/ag?= =?UTF-8?q?ents/connect/{id}.=20Each=20row=20with=20magpie=20models=20to?= =?UTF-8?q?=20offer=20gets=20a=20switch=20and=20a=20line=20under=20its=20n?= =?UTF-8?q?ame=20(=E5=B7=B2=E6=8E=A5=E5=85=A5=20=C2=B7=20=E5=9C=A8=20Codex?= =?UTF-8?q?=20=E9=87=8C=E7=94=A8=20/model=20=E9=80=89=20magpie=20=E7=9A=84?= =?UTF-8?q?=E6=A8=A1=E5=9E=8B=20/=20=E6=9C=AA=E6=8E=A5=E5=85=A5=20=C2=B7?= =?UTF-8?q?=20Codex=20=E7=94=A8=E5=AE=83=E8=87=AA=E5=B7=B1=E7=9A=84?= =?UTF-8?q?=E8=AE=BE=E7=BD=AE);=20off=20goes=20through=20the=20existing=20?= =?UTF-8?q?Disconnect=20dialog.=20Claude=20Code's=20/model=20lists=20only?= =?UTF-8?q?=20its=20tiers,=20so=20while=20routed=20magpie=20also=20writes?= =?UTF-8?q?=20modelPicker=20(2.1.287)=20with=20every=20magpie=20model,=20t?= =?UTF-8?q?aken=20out=20on=20disconnect;=20one=20the=20user=20wrote=20is?= =?UTF-8?q?=20left=20alone.=20Checked=20in=20a=20sandbox=20HOME=20against?= =?UTF-8?q?=20a=20fake=20upstream:=20Codex=200.160=20/model=20lists=20and?= =?UTF-8?q?=20uses=20magpie's=20models,=20OpenCode=20models,=20Pi=20--list?= =?UTF-8?q?-models,=20Crush's=20providers,=20Claude=20Code=20/model=20afte?= =?UTF-8?q?r=20connect;=20disconnect=20puts=20Codex=20back=20on=20gpt-5.4/?= =?UTF-8?q?high.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/agent/applied.go | 44 ++++++++ internal/agent/claude.go | 42 +++++++ internal/gui/agent_connect_test.go | 127 ++++++++++++++++++++++ internal/gui/api.go | 2 + internal/gui/assets/app.css | 12 ++ internal/gui/assets/app.js | 63 ++++++++++- internal/gui/assets/i18n.js | 7 ++ internal/gui/tests/agent-connect.test.cjs | 117 ++++++++++++++++++++ 8 files changed, 413 insertions(+), 1 deletion(-) create mode 100644 internal/gui/agent_connect_test.go create mode 100644 internal/gui/tests/agent-connect.test.cjs diff --git a/internal/agent/applied.go b/internal/agent/applied.go index 0ecedf783..fda0d5619 100644 --- a/internal/agent/applied.go +++ b/internal/agent/applied.go @@ -284,6 +284,50 @@ func (a *Agent) Wired() bool { return false } +// Connect puts magpie into the agent's config, the Agents page's switch +// (the owner: an agent is connected to magpie, and its models are picked in +// the agent): the agent's main field goes to one of magpie's models — the +// one serving the model it is on now, else the first — or to magpie itself +// for an app whose one setting is magpie as its provider. Setting it writes +// the provider and the whole catalog in, so the agent's own model list has +// every one of magpie's models. An agent already connected is left as it is. +func (a *Agent) Connect() error { + if len(a.Fields) == 0 || a.Wired() { + return nil + } + f := a.Fields[0] + if f.Options == nil { + return fmt.Errorf("%s can't be connected to magpie", a.Name) + } + vals := a.Values() + cur, _, _ := a.split(vals[f.Key]) + if i := strings.LastIndex(cur, "/"); i >= 0 { + cur = cur[i+1:] + } + pick, same := "", "" + for _, o := range f.Options(vals) { + switch { + case o.Value == magpieID: + return a.Apply(f.Key, magpieID) + case o.Ref == "" || o.Group == RoutingGroups: + case pick == "": + pick = o.Value + fallthrough + case same == "" && cur != "" && strings.HasSuffix(o.Ref, "/"+cur): + if strings.HasSuffix(o.Ref, "/"+cur) { + same = o.Value + } + } + } + if same != "" { + pick = same + } + if pick == "" { + return fmt.Errorf("magpie has no models %s can use: add a subscription or a provider first", a.Name) + } + return a.Apply(f.Key, pick) +} + // Disconnect takes magpie out of the agent's config and puts back what the // user had, the Agents page's "Disconnect from magpie" (Fate on Discord: // picking the agent's default did it, but nothing said so). Unwire first, diff --git a/internal/agent/claude.go b/internal/agent/claude.go index 0625a086a..01199fdfb 100644 --- a/internal/agent/claude.go +++ b/internal/agent/claude.go @@ -315,6 +315,36 @@ func claudeIn(at place) *Agent { } return nil } + // Claude Code's /model lists what modelPicker says (2.1.287): while it + // runs on magpie, that is every one of magpie's models, so the user + // picks among them in Claude Code itself. One the user wrote is theirs. + pickerKey := at.key("claude.model_picker") + pickerOurs := func() bool { return stashLoad()[pickerKey] != "" } + dropPicker := func() error { + defer forget(pickerKey) + if _, has := edit.GetJSON(path, "modelPicker"); has && pickerOurs() { + return edit.DelJSON(path, "modelPicker") + } + return nil + } + writePicker := func() error { + if _, has := edit.GetJSON(path, "modelPicker"); has && !pickerOurs() { + return nil + } + mark1M := claude1M() + rows := []any{} + for _, o := range viaMagpie("claude", "") { + if o.Group == RoutingGroups { + continue + } + rows = append(rows, map[string]any{"model": mark1M(o.Value), "label": cmp.Or(o.Label, o.Value), "description": o.Note}) + } + if len(rows) == 0 { + return dropPicker() + } + stash(map[string]string{pickerKey: "1"}) + return edit.SetJSON(path, edit.KV{Path: "modelPicker", Value: map[string]any{"options": rows}}) + } // writeCaps says what magpie's models can do, the ones in models first; // Claude Desktop's ids too while it runs on magpie, its Code tab being // Claude Code on this settings.json @@ -381,6 +411,9 @@ func claudeIn(at place) *Agent { if err := dropCaps(); err != nil { return "", err } + if err := dropPicker(); err != nil { + return "", err + } if !routed() { return "", nil } @@ -421,6 +454,9 @@ func claudeIn(at place) *Agent { if err := dropCaps(); err != nil { return err } + if err := dropPicker(); err != nil { + return err + } return edit.DelJSON(path, keys...) } if isMagpie(v) { @@ -521,6 +557,9 @@ func claudeIn(at place) *Agent { m, _ := tierAt(tiers[t]) models = append(models, m) } + if err := writePicker(); err != nil { + return err + } return writeCaps(models...) } @@ -817,6 +856,9 @@ func claudeIn(at place) *Agent { for _, t := range claudeTiers { models = append(models, env(tierEnv(t))) } + if err := writePicker(); err != nil { + return err + } return writeCaps(models...) }, Check: func() string { diff --git a/internal/gui/agent_connect_test.go b/internal/gui/agent_connect_test.go new file mode 100644 index 000000000..9d069e3df --- /dev/null +++ b/internal/gui/agent_connect_test.go @@ -0,0 +1,127 @@ +package gui + +import ( + "encoding/json" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// The Agents page's switch: connecting Codex puts it on magpie with the +// whole catalog in its own model list — the model it was on, served by +// magpie, when magpie has it — and switching it off puts back what it had. +func TestAgentConnectAPI(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")) + t.Setenv("CODEX_HOME", filepath.Join(home, ".codex")) + os.MkdirAll(filepath.Join(home, ".codex"), 0o755) + cfg := filepath.Join(home, ".codex", "config.toml") + os.WriteFile(cfg, []byte("model = \"m2\"\n"), 0o600) + 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) + } + h := Handler(nil, nil) + call := func(path, body string) stateJSON { + 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) + } + var s stateJSON + json.Unmarshal(rec.Body.Bytes(), &s) + return s + } + codex := func(s stateJSON) agentJSON { + for _, a := range s.Agents { + if a.ID == "codex" { + return a + } + } + t.Fatalf("no codex in %+v", s.Agents) + return agentJSON{} + } + a := codex(call("/api/agents/connect/codex", "{}")) + if !a.Wired || a.Fields[0].Value != "relay/m2" { + t.Fatalf("after connect: wired %v, model %q", a.Wired, a.Fields[0].Value) + } + cat, err := os.ReadFile(filepath.Join(home, ".codex", "magpie-models.json")) + if err != nil || !strings.Contains(string(cat), "relay/m1") || !strings.Contains(string(cat), "relay/m2") { + t.Fatalf("Codex's model list: %s %v", cat, err) + } + // connecting again changes nothing: the user's pick in the agent stays + call("/api/set", `{"agent":"codex","field":"model","value":"relay/m1"}`) + if a := codex(call("/api/agents/connect/codex", "{}")); a.Fields[0].Value != "relay/m1" { + t.Fatalf("connect again moved the model to %q", a.Fields[0].Value) + } + a = codex(call("/api/agents/disconnect/codex", "{}")) + if a.Wired || a.Fields[0].Value != "m2" { + t.Fatalf("after disconnect: wired %v, model %q", a.Wired, a.Fields[0].Value) + } +} + +// Claude Code's /model lists modelPicker's rows: connected, they are +// magpie's models; switched off, they go, and a modelPicker the user wrote +// is never touched. +func TestAgentConnectClaudePicker(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")) + os.MkdirAll(filepath.Join(home, ".claude"), 0o755) + cfg := filepath.Join(home, ".claude", "settings.json") + 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) + } + h := Handler(nil, nil) + post := func(path string) { + t.Helper() + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader("{}"))) + if rec.Code != 200 { + t.Fatalf("%s %d %s", path, rec.Code, rec.Body) + } + } + picker := func() []string { + var s struct { + ModelPicker *struct{ Options []struct{ Model string } } `json:"modelPicker"` + } + b, _ := os.ReadFile(cfg) + json.Unmarshal(b, &s) + if s.ModelPicker == nil { + return nil + } + var out []string + for _, o := range s.ModelPicker.Options { + out = append(out, o.Model) + } + return out + } + post("/api/agents/connect/claude") + if got := strings.Join(picker(), " "); got != "relay/m1 relay/m2" { + t.Fatalf("connected, /model lists %q", got) + } + post("/api/agents/disconnect/claude") + if got := picker(); got != nil { + t.Fatalf("switched off, /model still lists %q", got) + } + own := `{"modelPicker":{"options":[{"model":"mine"}]}}` + os.WriteFile(cfg, []byte(own), 0o600) + post("/api/agents/connect/claude") + post("/api/agents/disconnect/claude") + if got := strings.Join(picker(), " "); got != "mine" { + t.Fatalf("the user's own modelPicker became %q", got) + } +} diff --git a/internal/gui/api.go b/internal/gui/api.go index 45eec43b5..9819d5644 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -656,6 +656,8 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { err = a.Reapply() case "keep": a.Keep() + case "connect": + err = a.Connect() case "disconnect": err = a.Disconnect() default: diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index b8be96164..933711f3f 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -496,6 +496,7 @@ body.window .field.solo { grid-column: auto; } body.window .row.agent > .who { grid-column: 2; grid-row: 1; width: 100%; } body.window .row.agent > .fields { grid-column: 2; grid-row: 2; width: 100%; min-width: 0; margin-left: 0; } body.window #agents.extras .row.agent > .fields { grid-template-columns: minmax(0, 1fr) 124px var(--extras-w); } + body.window .row.agent > .ag-conn { grid-column: 2; grid-row: 1; justify-self: end; margin-left: 0; } } .field:hover, .field.open { background: var(--pill-hover); } .field.open { box-shadow: inset 0 0 0 1px var(--accent); } @@ -2635,3 +2636,14 @@ body.window .row.agent .who.with-models { flex-wrap: wrap; row-gap: 0; } .am-reset:hover:not(:disabled) { color: var(--accent); } .am-reset:disabled { color: var(--faint); cursor: default; } .am-dot { color: var(--faint); } + +/* ---- an agent's switch onto magpie ---------------------------------------- */ +body.window .row.agent > .ag-conn { margin-left: 12px; align-self: center; cursor: pointer; } +.ag-conn-line { flex: 0 0 100%; min-width: 0; font-size: 11.5px; line-height: 18px; color: var(--faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.ag-conn-line.on { color: var(--muted); } +.ag-conn-line.on::before { content: ""; display: inline-block; width: 6px; height: 6px; margin-right: 6px; border-radius: 50%; background: var(--green); vertical-align: 1px; } +.row.agent.unplugged > .fields { opacity: .55; transition: opacity .15s; } +.row.agent.unplugged:hover > .fields { opacity: 1; } +.ag-conn-row { display: flex; align-items: center; gap: 8px; min-height: 28px; } +.ag-conn-row .ag-conn-said { flex: 1; min-width: 0; font-size: 11.5px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.ag-conn-row .lib-switch { cursor: pointer; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index e4187b765..c45ac79c8 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -410,9 +410,22 @@ function renderAgents() { who.append(line); who.classList.add("with-models"); } + // connected to magpie or not, said under the name, with where the agent + // picks among magpie's models itself + const sw = connectable(a) ? connectSwitch(a) : null; + if (sw && mode !== "panel") { + who.append(el("div", "ag-conn-line" + (a.wired ? " on" : ""), connectSaid(a))); + who.classList.add("with-models"); + row.classList.toggle("unplugged", !a.wired); + } + if (sw && openBox) { + const line = el("div", "ag-conn-row"); + line.append(el("span", "k", t("magpie")), el("span", "ag-conn-said", connectSaid(a)), sw); + openBox.querySelector(".ag-body").prepend(line); + } row.append(agentHandle(a, row, inFold), who); if (sum) row.append(sum, ...(openBox ? [openBox] : [])); - else row.append(fields); + else row.append(fields, ...(sw ? [sw] : [])); return row; }; // the extras column is there for every row once any agent has one, so the @@ -722,6 +735,54 @@ const REAPPLY = "M13.5 8a5.5 5.5 0 1 1-1.6-3.9M13.5 2.5v3.25h-3.25"; const UNPLUG = "M6 2v3M10 2v3M4.5 5h7v2.5a3.5 3.5 0 0 1-7 0zM8 11v3M2 2l12 12"; const DISCONNECT_TIP = "Take out everything magpie wrote into {agent}'s config and put back what it had before"; +// An agent is connected to magpie with a switch (the owner: the Agents page +// connects an agent, and its models are picked in the agent): on, magpie is +// its provider and its own model list has magpie's models (agent.Connect); +// off, magpie takes out what it wrote (askDisconnect). An agent with none of +// magpie's models to offer (Cursor, Copilot) has no switch. +function connectable(a) { + const f = a.fields[0]; + return !a.import && !!f && f.options.some((o) => o.ref || o.value === "magpie"); +} + +// PICKS_IN is where an agent picks a model itself, for the words under it. +const PICKS_IN = { codex: "/model", claude: "/model", opencode: "/models", pi: "/model", droid: "/model", kimi: "/model", grok: "/model", "minimax-code": "/model", dsh: "/model", crush: "ctrl+p", omp: "/model", qwen: "/model", mimocode: "/model" }; + +function connectSaid(a) { + if (!a.wired) return t("Not connected · {agent} uses its own settings", { agent: a.name }); + const at = PICKS_IN[a.id]; + return at ? t("Connected · pick magpie's models with {cmd} in {agent}", { cmd: at, agent: a.name }) : t("Connected · magpie's models are in {agent}'s model list", { agent: a.name }); +} + +function connectSwitch(a) { + const s = el("button", "lib-switch ag-conn" + (a.wired ? " on" : "")); + s.type = "button"; + s.setAttribute("role", "switch"); + s.setAttribute("aria-checked", a.wired ? "true" : "false"); + s.setAttribute("aria-label", t("Connect {agent} to magpie", { agent: a.name })); + s.title = a.wired ? t("Connected · switch off to put back what {agent} had before magpie", { agent: a.name }) : t("Switch on and {agent}'s model list gets magpie's models", { agent: a.name }); + s.append(el("i")); + s.onclick = async (e) => { + e.stopPropagation(); + if (a.wired) { askDisconnect(a); return; } + if (s.disabled) return; + s.disabled = true; + s.classList.add("on"); + try { + state = await api("agents/connect/" + a.id, {}); + renderAgents(); + const msg = t("{agent} is connected to magpie", { agent: a.name }); + if (state.notice) status(`${msg}. ${t(state.notice)}`, "warn", 9000); + else status(msg, "ok"); + } catch (err) { + s.disabled = false; + s.classList.remove("on"); + status(t(err.message), "err"); + } + }; + return s; +} + // askDisconnect takes magpie out of an agent's config once asked: every // field magpie set, and its endpoint and key, give way to what the agent // had before magpie (agent.Disconnect). Picking Default isn't that: it is diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 0e877bbf9..7a5486daf 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -137,6 +137,13 @@ const I18N = { "Disconnect {agent} from magpie?": "断开 {agent} 与 magpie 的连接?", "magpie takes out everything it wrote into {agent}'s config — its endpoint, key, models and effort — and puts back the settings {agent} had before. magpie's providers and accounts stay as they are.": "magpie 会移除它写入 {agent} 配置的所有内容(接口地址、密钥、模型和推理强度),并还原 {agent} 之前的设置。magpie 里的供应商和账号保持不变。", "Disconnect": "断开", + "Not connected · {agent} uses its own settings": "未接入 · {agent} 用它自己的设置", + "Connected · pick magpie's models with {cmd} in {agent}": "已接入 · 在 {agent} 里用 {cmd} 选 magpie 的模型", + "Connected · magpie's models are in {agent}'s model list": "已接入 · magpie 的模型在 {agent} 的模型列表里", + "Connect {agent} to magpie": "将 {agent} 接入 magpie", + "Connected · switch off to put back what {agent} had before magpie": "已接入 · 关掉即还原 {agent} 接入 magpie 之前的设置", + "Switch on and {agent}'s model list gets magpie's models": "打开后,{agent} 的模型列表里就有 magpie 的模型", + "{agent} is connected to magpie": "{agent} 已接入 magpie", "{agent} no longer goes through magpie; its own settings are back": "{agent} 已不再经过 magpie,原来的设置已还原", "Update to {v}": "更新到 {v}", "Updates with {cmd}": "通过 {cmd} 更新", diff --git a/internal/gui/tests/agent-connect.test.cjs b/internal/gui/tests/agent-connect.test.cjs new file mode 100644 index 000000000..92ed0d732 --- /dev/null +++ b/internal/gui/tests/agent-connect.test.cjs @@ -0,0 +1,117 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The owner: an agent is connected to magpie with a switch, and its models +// are picked in the agent itself. An agent magpie has models for gets a +// switch, off while magpie isn't in its config, saying so under its name; +// switching it on posts agents/connect and the row says where in the agent +// magpie's models are picked (Codex's /model). Switching it off asks first +// in the app's own dialog and posts agents/disconnect. An agent with none of +// magpie's models (Cursor) has no switch. No click moves the page. In +// English and Chinese; no backend, 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 options = [{ value: "gpt-5.4", label: "GPT-5.4" }, { value: "relay/m1", label: "m1", ref: "relay/m1", note: "Relay · via magpie" }]; +const fresh = () => ({ + agents: [ + { id: "codex", name: "Codex", icon: "generic", path: "/fixture/codex", fields: [{ key: "model", label: "model", value: "gpt-5.4", options }] }, + { id: "cursor", name: "Cursor", icon: "generic", path: "/fixture/cursor", fields: [{ key: "model", label: "model", value: "auto", options: [{ value: "auto", label: "Auto" }] }] }, + ], + profiles: [], +}); + +function server(lang, posts) { + let cur = fresh(); + const reply = (route) => route.fulfill({ json: { ...cur, settings: { lang, theme: "light" } } }); + 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};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return reply(route); + const act = url.pathname.match(/^\/api\/agents\/(connect|disconnect)\/(\w+)$/); + if (act) { + posts.push(url.pathname); + cur = JSON.parse(JSON.stringify(cur)); + const a = cur.agents.find((x) => x.id === act[2]); + if (act[1] === "connect") { a.wired = true; a.fields[0].value = "relay/m1"; } + else { delete a.wired; a.fields[0].value = "gpt-5.4"; } + return reply(route); + } + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/agents/cli") return json({ agents: {}, pending: false }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }); + 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 route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const words = { + en: { off: "Not connected · Codex uses its own settings", on: "Connected · pick magpie's models with /model in Codex", go: "Disconnect", done: /Codex is connected to magpie/ }, + zh: { off: "未接入 · Codex 用它自己的设置", on: "已接入 · 在 Codex 里用 /model 选 magpie 的模型", go: "断开", done: /Codex 已接入 magpie/ }, +}; +const row = (id) => `.row.agent[data-id="${id}"]`; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + const w = words[lang]; + test(`${engine} ${lang}: an agent's switch connects it to magpie and back`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width: 980, height: 520 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + const errors = [], posts = [], dialogs = []; + page.on("pageerror", (e) => errors.push(e.message)); + page.on("dialog", (d) => { dialogs.push(d.message()); d.dismiss(); }); + await page.route("**/*", server(lang, posts)); + await page.goto("http://magpie.test/?view=agents"); + await page.locator(`${row("codex")} .ag-conn`).waitFor(); + const missing = await page.evaluate(() => [ + "Not connected · {agent} uses its own settings", + "Connected · pick magpie's models with {cmd} in {agent}", + "Connected · magpie's models are in {agent}'s model list", + "Connect {agent} to magpie", + "Connected · switch off to put back what {agent} had before magpie", + "Switch on and {agent}'s model list gets magpie's models", + "{agent} is connected to magpie", + ].filter((k) => !I18N.zh[k])); + assert.deepEqual(missing, [], "every string has its Chinese"); + const tops = () => page.evaluate(() => [document.scrollingElement.scrollTop, document.querySelector("#view-agents")?.scrollTop]); + const top = await tops(); + const sw = () => page.locator(`${row("codex")} .ag-conn`); + const said = () => page.locator(`${row("codex")} .ag-conn-line`).textContent(); + + assert.equal(await page.locator(`${row("cursor")} .ag-conn`).count(), 0, "nothing of magpie's to connect it to"); + assert.equal(await sw().getAttribute("role"), "switch"); + assert.equal(await sw().getAttribute("aria-checked"), "false"); + assert.equal(await said(), w.off); + + await sw().click(); + await page.waitForFunction((r) => document.querySelector(r + " .ag-conn")?.getAttribute("aria-checked") === "true", row("codex")); + assert.deepEqual(posts, ["/api/agents/connect/codex"]); + assert.equal(await said(), w.on); + assert.match(await page.locator("#status").textContent(), w.done); + + // off asks first, in the app's own dialog + await sw().click(); + const ask = page.locator(".editor.disconnect-ask"); + await ask.waitFor(); + assert.deepEqual(posts, ["/api/agents/connect/codex"], "switching off asks before it posts"); + await ask.locator(".bar button", { hasText: w.go }).click(); + await ask.waitFor({ state: "detached" }); + await page.waitForFunction((r) => document.querySelector(r + " .ag-conn")?.getAttribute("aria-checked") === "false", row("codex")); + assert.deepEqual(posts, ["/api/agents/connect/codex", "/api/agents/disconnect/codex"]); + assert.equal(await said(), w.off); + assert.deepEqual(await tops(), top, "no click moved the page"); + assert.deepEqual(dialogs, [], "no native dialog"); + assert.deepEqual(errors, []); + }); + } +}