diff --git a/internal/agent/applied.go b/internal/agent/applied.go index 78f0ded9f..38e62db42 100644 --- a/internal/agent/applied.go +++ b/internal/agent/applied.go @@ -303,7 +303,7 @@ func (a *Agent) Pick(key, v string) error { vals := a.Values() vals[key] = v if v == magpieID || magpieValue(a, *f, v, vals) { - if err := a.Connect(); err != nil { + if _, err := a.connect(); err != nil { return err } } @@ -320,9 +320,44 @@ func (a *Agent) Pick(key, v string) error { // every one of magpie's models. An agent that can keep the model it is on // (Join) keeps it. An agent already connected is left as it is. func (a *Agent) Connect() error { + _, err := a.ConnectHow() + return err +} + +// Connection is how Connect chose the model an agent starts on, for the +// Agents page to say it (#726: Codex showed its last pick, Claude Code a +// Sonnet through magpie and Antigravity some model, with nothing saying +// why). How is one of: +// +// - "kept": it was connected already, left as it was +// - "again": the models it was on when it was switched off, put back +// - "joined": the model it is on stays its own (Codex signed in with +// ChatGPT), magpie's models join its list +// - "magpie": an app whose one setting is magpie as its provider +// - "same": the model it is on now, through magpie +// - "alike": the model its alias (opus) stands for, through magpie +// - "default": on its own default with no model set: the first of its +// own models in its list (the newest, for Claude Code), through magpie +// - "first": magpie has none of the model it is on: the first on the +// account it is signed in to, else a subscription's, else the first +// +// Field and Value are the field set and what it was set to, where Connect +// picked one model ("" for kept, again and joined). +type Connection struct { + How string `json:"how"` + Field string `json:"field,omitempty"` + Value string `json:"value,omitempty"` +} + +// ConnectHow is Connect, saying how the model was chosen. +func (a *Agent) ConnectHow() (Connection, error) { if len(a.Fields) == 0 || a.Wired() { - return nil + return Connection{How: "kept"}, nil } + return a.connect() +} + +func (a *Agent) connect() (Connection, error) { // what it is on now, for Disconnect to put back what it can't // otherwise (Goose's own model) now := a.Values() @@ -330,13 +365,13 @@ func (a *Agent) Connect() error { stash(map[string]string{a.ID + ".connect.was": string(b)}) // switched off and on again: the models it was on, as they were if ok, err := a.reconnect(now); ok || err != nil { - return err + return Connection{How: "again"}, err } // the model it is on stays, where the agent can have magpie's models // beside it (the owner: Codex keeps its own last pick) if a.Join != nil { if ok, err := a.Join(); ok || err != nil { - return err + return Connection{How: "joined"}, err } } // the field magpie is picked in: the one listing magpie's models (for @@ -363,12 +398,13 @@ func (a *Agent) Connect() error { } } if f == nil { - return fmt.Errorf("%s can't be connected to magpie", a.Name) + return Connection{}, fmt.Errorf("%s can't be connected to magpie", a.Name) } cur := connectWas(vals[f.Key], opts) if cur == "" && f.Key != a.Fields[0].Key { cur = connectWas(a.Values()[a.Fields[0].Key], nil) } + onDefault := cur == "" if cur == "" { // on its default: the first of its own models for _, o := range opts { @@ -386,7 +422,7 @@ func (a *Agent) Connect() error { sameRank, alikeRank := -1, -1 for _, o := range opts { if o.Value == magpieID { - return a.Apply(f.Key, magpieID) + return Connection{How: "magpie", Field: f.Key, Value: magpieID}, a.Apply(f.Key, magpieID) } if o.Ref == "" || o.Group == RoutingGroups { continue @@ -415,20 +451,24 @@ func (a *Agent) Connect() error { sub = o.Value } } + how := "first" switch { case same != "": - pick = same + pick, how = same, "same" + if onDefault { + how = "default" + } case alike != "": - pick = alike + pick, how = alike, "alike" case own != "": pick = own case sub != "": pick = sub } if pick == "" { - return fmt.Errorf("magpie has no models %s can use: add a subscription or a provider first", a.Name) + return Connection{}, fmt.Errorf("magpie has no models %s can use: add a subscription or a provider first", a.Name) } - return a.Apply(f.Key, pick) + return Connection{How: how, Field: f.Key, Value: pick}, a.Apply(f.Key, pick) } // connectWas is the model an agent is on before it is connected, as a diff --git a/internal/agent/connect_pick_test.go b/internal/agent/connect_pick_test.go index c3bf44b00..96be4cb73 100644 --- a/internal/agent/connect_pick_test.go +++ b/internal/agent/connect_pick_test.go @@ -313,3 +313,48 @@ func TestPickConnectsFirst(t *testing.T) { } } } + +// The switch says how it chose the model it connected an agent on (#726: +// Codex kept its last pick, Claude Code went to a Sonnet through magpie, +// with nothing to say why): Claude Code on its opus alias goes to the +// Opus magpie serves, said "alike"; switched off and on, it is back on what +// it was on, "again"; one already connected is "kept"; on a model magpie +// doesn't serve, "first". +func TestConnectSaysHow(t *testing.T) { + home, _ := codexHome(t, "", "") + if err := provider.Save(provider.Provider{ID: "aaa", Name: "AAA", Chat: "https://a.example/v1", Key: "k", Models: []string{"first", "claude-opus-5-5", "claude-sonnet-5-5"}}); err != nil { + t.Fatal(err) + } + path := filepath.Join(home, ".claude", "settings.json") + writeFile(t, path, `{"model": "opus"}`) + c := claude(home) + how, err := c.ConnectHow() + if err != nil { + t.Fatal(err) + } + if how != (Connection{How: "alike", Field: "model", Value: "aaa/claude-opus-5-5"}) { + t.Fatalf("connected %+v:\n%s", how, readFile(path)) + } + if how, _ := c.ConnectHow(); how.How != "kept" { + t.Fatalf("again while connected: %+v", how) + } + if err := c.Apply("model", "aaa/claude-sonnet-5-5"); err != nil { + t.Fatal(err) + } + if err := c.Disconnect(); err != nil { + t.Fatal(err) + } + if how, err := c.ConnectHow(); err != nil || how.How != "again" { + t.Fatalf("switched on again: %+v %v", how, err) + } + if m, _ := edit.GetJSON(path, "model"); m != "aaa/claude-sonnet-5-5" { + t.Fatalf("back on %q", m) + } + if err := c.Disconnect(); err != nil { + t.Fatal(err) + } + writeFile(t, path, `{"model": "claude-haiku-9"}`) + if how, err := c.ConnectHow(); err != nil || how.How != "first" || how.Value == "" { + t.Fatalf("on a model magpie lacks: %+v %v", how, err) + } +} diff --git a/internal/gui/api.go b/internal/gui/api.go index 18d8d89f2..38cf31542 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -207,6 +207,9 @@ type stateJSON struct { Profiles []profileJSON `json:"profiles"` Catalog string `json:"catalog"` Notice string `json:"notice,omitempty"` // advice after a change, e.g. "restart Codex" + // Connected is how the 「接入」 switch chose the model the agent starts + // on, in the answer to agents/connect (agent.Connection) + Connected *agent.Connection `json:"connected,omitempty"` // CLIBehind is the terminal's magpie command, told to the user when // it's a copied file rather than the installer's link: a copy can't // follow updates (#531's lesson). "" when it's the link or absent, or @@ -695,13 +698,16 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { fail(rw, err) return } + var how *agent.Connection switch r.PathValue("action") { case "reapply": err = a.Reapply() case "keep": a.Keep() case "connect": - err = a.Connect() + var c agent.Connection + c, err = a.ConnectHow() + how = &c case "disconnect": err = a.Disconnect() default: @@ -716,6 +722,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { if a.Notice != nil { s.Notice = a.Notice() } + s.Connected = how writeJSON(rw, s) }) mux.HandleFunc("POST /api/profile/{action}", func(rw http.ResponseWriter, r *http.Request) { diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 00b4a4285..3ed76b1e5 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -1429,7 +1429,7 @@ body.window .foot { padding-left: 18px; } .pop li .ic { width: 16px; height: 16px; } .pop li .option-words { display: flex; align-items: center; min-width: 0; flex: 1 1 auto; gap: 9px; } .pop li .v { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; font-variant-numeric: tabular-nums; } -.pop li .badge.free, .pop li .badge.ctx, .pop li .badge.rate { flex: none; margin-left: -4px; padding: 0 4px; font-size: 9px; line-height: 14px; align-self: center; } +.pop li .badge.free, .pop li .badge.ctx, .pop li .badge.rate, .pop li .badge.path { flex: none; margin-left: -4px; padding: 0 4px; font-size: 9px; line-height: 14px; align-self: center; } .pop li .n { flex: 1 1 0; min-width: 0; font-size: 11.5px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; } .pop li .favorite { display: none; align-items: center; justify-content: center; color: var(--faint); width: 24px; height: 24px; border-radius: 6px; flex: none; } .pop li:hover .favorite, .pop li .favorite.on { display: inline-flex; } @@ -1665,6 +1665,10 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .badge.off { background: var(--pill); color: var(--muted); } .badge.free { background: var(--green-soft); color: var(--green); } /* a model's context, when it is a large one: grey, as it is a fact, not a warning */ +/* which way a model goes (#726): through magpie, or straight to its vendor */ +.badge.path { letter-spacing: .02em; text-transform: none; white-space: nowrap; } +.badge.path.via { background: var(--accent-soft); color: var(--accent); } +.badge.path.direct { background: var(--pill); color: var(--muted); box-shadow: inset 0 0 0 1px var(--line); } .badge.ctx { background: var(--pill); color: var(--muted); box-shadow: inset 0 0 0 1px var(--line); letter-spacing: .02em; } .badge.wsl { background: var(--pill); color: var(--muted); box-shadow: inset 0 0 0 1px var(--line); letter-spacing: .02em; text-transform: none; } /* a model's credit rate (0.5×): grey, a fact to pick by; a discount's price before it struck through */ diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 8f8d42dc5..3b6b6cce9 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -779,6 +779,26 @@ function connectSaid(a) { 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 }); } +// connectedSaid: what the switch connected an agent on, and why (#726: +// switched on, Codex kept its last pick, Claude Code started on a Sonnet +// through magpie and Antigravity on some model, with nothing to say why). +// c is agent.Connection: how the model was chosen. +const CONNECTED_HOW = { + again: "{agent} is connected to magpie · back on {model}, what it was on when it was switched off", + same: "{agent} is connected to magpie · on {model} through magpie, the model it was on", + alike: "{agent} is connected to magpie · on {model} through magpie, the model it was on", + default: "{agent} is connected to magpie · on {model} through magpie: it had no model set, so the first of its own", + first: "{agent} is connected to magpie · on {model} through magpie: magpie doesn't serve the model it was on", +}; +function connectedSaid(a, c) { + const plain = t("{agent} is connected to magpie", { agent: a.name }); + if (c?.how === "joined") return t("{agent} is connected to magpie · it stays on its own last pick; magpie's models join its {cmd}", { agent: a.name, cmd: PICKS_IN[a.id] || "/model" }); + const now = state.agents.find((x) => x.id === a.id); + const f = now && startField(now); + const model = f?.value ? optionFor(f, f.value)?.label || f.value : ""; + return CONNECTED_HOW[c?.how] && model ? t(CONNECTED_HOW[c.how], { agent: a.name, model }) : plain; +} + function connectSwitch(a) { const s = el("button", "lib-switch ag-conn" + (a.wired ? " on" : "")); s.type = "button"; @@ -796,8 +816,9 @@ function connectSwitch(a) { try { state = await api("agents/connect/" + a.id, {}); renderAgents(); - const msg = t("{agent} is connected to magpie", { agent: a.name }); + const msg = connectedSaid(a, state.connected); if (state.notice) status(`${msg}. ${t(state.notice)}`, "warn", 9000); + else if (msg !== t("{agent} is connected to magpie", { agent: a.name })) status(msg, "ok", 7000); else status(msg, "ok"); } catch (err) { s.disabled = false; @@ -3450,6 +3471,28 @@ function contextTag(n, name) { return tag; } +// pathTag: an agent's model picker says by each model whether the agent +// asks it through magpie or of its own vendor directly (Claude Code on its +// own sign-in), and its Default, while it is connected, that it takes the +// agent off magpie. Only where the list has both ways: elsewhere every +// model listed is magpie's, and its note says so. +function pathTag(o) { + if (!pick?.agent || o.custom || o.run) return null; + const mixed = pick.field.options?.some((x) => x.direct); + let tag = null; + if (o.ref && mixed) { + tag = el("span", "badge path via", t("via magpie")); + tag.title = t("{agent} asks magpie for it", { agent: pick.agent.name }); + } else if (o.direct) { + tag = el("span", "badge path direct", t("direct, not via magpie")); + tag.title = t("straight to {vendor}, not through magpie", { vendor: o.direct }); + } else if (o.reset && o.value === "" && leavesMagpie(pick.agent, pick.field, "", o)) { + tag = el("span", "badge path direct", t("off magpie")); + tag.title = t("{agent} as installed: magpie's endpoint and models come out", { agent: pick.agent.name }); + } + return tag; +} + function renderList() { const list = $("#list"); list.replaceChildren(); @@ -3474,6 +3517,12 @@ function renderList() { const ctx = contextTag(o.context, o.label); if (ctx) words.append(ctx); let note = o.note && o.note !== (o.label || o.value) ? (own ? t(o.note) : o.note) : ""; + // which way the model goes, as a tag the note's ellipsis can't cut + // off: "· via magpie" ended a long note (an account's e-mail), and + // Claude Code's own models said nothing, so an Opus asked of Anthropic + // directly and a Sonnet through magpie looked alike (#726) + const path = pathTag(o); + if (path) { words.append(path); note = note.replace(/(^| · )via magpie$/, ""); } if (q && o.group && !note) note = o.group; if (note) words.append(el("span", "n", note)); li.append(words); @@ -3577,11 +3626,68 @@ async function commit(value) { return; } if (value === field.value) return; + // a pick that takes a connected agent off magpie (its Default, or a + // model of its own asked of its vendor directly) is asked first, as the + // switch's off is: it moved Claude Code under Not set up at a click + // (#726) + if (leavesMagpie(agent, field, value, opt)) { askLeave(agent, field, value, opt); return; } + return setPick(agent, field, value, opt); +} + +// leavesMagpie: picking value in field takes the connected agent off +// magpie: its Default in the field it is connected through (Set("") takes +// out what magpie wired in), or a model of its own it asks its vendor for +// directly (Claude Code's own, which unroutes it). From one of its own +// models already, the pick doesn't move it off magpie. +function leavesMagpie(a, field, value, opt) { + if (!a?.wired || !connectable(a) || field !== (startField(a) || connectField(a))) return false; + if (optionFor(field, field.value)?.direct) return false; + return value === "" || !!opt?.direct; +} + +// askLeave: what such a pick does, and the way back, before it is made. +// Default isn't Disconnect: it leaves the agent as installed, where +// Disconnect puts back what it had before magpie, so both are offered. +function askLeave(a, field, value, opt) { + const model = opt?.label || value; + const ed = el("div", "editor disconnect-ask leave-ask"); + const head = el("div", "ehead"); + head.append(icon(a.icon), el("b", "", t("Take {agent} off magpie?", { agent: a.name }))); + ed.append(head); + ed.append(el("p", "lib-confirm", value === "" + ? t("Default is {agent} as installed: magpie's endpoint and models come out, and {agent} starts on its own default model. What it had before magpie isn't put back; Disconnect and restore does that.", { agent: a.name }) + : t("{model} is {agent}'s own model: {agent} asks {vendor} for it itself, with its own sign-in, not through magpie. Picking it takes {agent} off magpie, and it starts on {model}.", { agent: a.name, model, vendor: opt.direct }))); + const others = state.agents.some((x) => x.id !== a.id && onMagpie(x) && !isHidden(x)); + ed.append(el("p", "lib-confirm", others + ? t("「接入」 goes off, and {agent} is listed under Not set up with the agents not connected. Switch it on again to go back through magpie.", { agent: a.name }) + : t("「接入」 goes off. Switch it on again to go back through magpie."))); + const bar = el("div", "bar"); + const go = el("button", "text primary", value === "" ? t("Use default") : t("Use {model}", { model })); + go.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); setPick(a, field, value, opt); }; + const cancel = el("button", "text", t("Cancel")); + cancel.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); }; + bar.append(STARTS_WITH.has(a.id) ? el("span", "ag-bar-note", t("Running {agent} copies take it once reopened", { agent: a.name })) : el("span"), el("span", "grow"), cancel); + if (value === "") { + const restore = el("button", "text", t("Disconnect and restore")); + restore.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); askDisconnect(a); }; + bar.append(restore); + } + bar.append(go); + ed.append(bar); + confirmAsk = ed; + openModal(ed); + $("#modal").classList.add("lib"); + cancel.focus({ preventScroll: true }); +} + +// setPick writes a value picked for an agent's field +async function setPick(agent, field, value, opt) { // The pick shows at once: the row is drawn with it before magpie has // written the config and answered with the whole state, which can take // seconds (every agent's lists are read again for it). The answer then // draws what the config really says; a refused pick puts the old one back. const was = field.value; + const leaving = leavesMagpie(agent, field, value, opt); const seq = commit.seq = (commit.seq || 0) + 1; field.value = value; const picked = performance.now(); @@ -3604,6 +3710,7 @@ async function commit(value) { flash(); const shown = opt?.label || value; if (state.notice) status(`${agent.name} → ${shown}. ${t(state.notice)}`, "warn", 9000); + else if (leaving && value === "") status(t("{agent} no longer goes through magpie · on its own default", { agent: agent.name }), "ok", 6000); else if (opt?.direct) status(`${agent.name} ${t(field.label)} → ${shown} · ${t("straight to {vendor}, not through magpie", { vendor: opt.direct })}`, "ok", 6000); else status(`${agent.name} ${t(field.label)} → ${shown}`, "ok"); if (providers) loadProviders(); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 263841381..246a7b5b5 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -213,6 +213,24 @@ const I18N = { "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} is connected to magpie · back on {model}, what it was on when it was switched off": "{agent} 已接入 magpie · 回到上次断开前用的 {model}", + "{agent} is connected to magpie · on {model} through magpie, the model it was on": "{agent} 已接入 magpie · 经 magpie 继续用它原来的模型 {model}", + "{agent} is connected to magpie · on {model} through magpie: it had no model set, so the first of its own": "{agent} 已接入 magpie · 它原来没有设模型,所以经 magpie 用它自己模型列表里的第一个:{model}", + "{agent} is connected to magpie · on {model} through magpie: magpie doesn't serve the model it was on": "{agent} 已接入 magpie · magpie 没有它原来用的模型,所以经 magpie 用 {model}", + "{agent} is connected to magpie · it stays on its own last pick; magpie's models join its {cmd}": "{agent} 已接入 magpie · 模型仍是它自己上次的选择,magpie 的模型加进了它的 {cmd}", + "via magpie": "经 magpie", + "{agent} asks magpie for it": "{agent} 经 magpie 请求这个模型", + "direct, not via magpie": "直连,不经 magpie", + "off magpie": "不经 magpie", + "{agent} as installed: magpie's endpoint and models come out": "{agent} 安装时的样子:移除 magpie 的地址和模型", + "Take {agent} off magpie?": "让 {agent} 不再经过 magpie?", + "Default is {agent} as installed: magpie's endpoint and models come out, and {agent} starts on its own default model. What it had before magpie isn't put back; Disconnect and restore does that.": "「默认」是 {agent} 刚安装时的样子:移除 magpie 的地址和模型,{agent} 用它自己的默认模型启动。不会还原接入 magpie 之前的设置;要还原请用「断开并还原」。", + "{model} is {agent}'s own model: {agent} asks {vendor} for it itself, with its own sign-in, not through magpie. Picking it takes {agent} off magpie, and it starts on {model}.": "{model} 是 {agent} 自己的模型:{agent} 用自己的登录直接向 {vendor} 请求,不经过 magpie。选它会让 {agent} 断开 magpie,并以 {model} 启动。", + "「接入」 goes off, and {agent} is listed under Not set up with the agents not connected. Switch it on again to go back through magpie.": "「接入」会关闭,{agent} 会和其他未接入的 agent 一起列在「未设置」里。再打开「接入」即可重新经过 magpie。", + "「接入」 goes off. Switch it on again to go back through magpie.": "「接入」会关闭。再打开「接入」即可重新经过 magpie。", + "Use default": "使用默认", + "Use {model}": "使用 {model}", + "{agent} no longer goes through magpie · on its own default": "{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-leave-magpie.test.cjs b/internal/gui/tests/agent-leave-magpie.test.cjs new file mode 100644 index 000000000..3a21b7627 --- /dev/null +++ b/internal/gui/tests/agent-leave-magpie.test.cjs @@ -0,0 +1,187 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// #726 (EZN7L2C3): with Claude Code connected, picking Opus 5.5 in its +// model list moved it under Not set up and turned 「接入」 off, picking +// Sonnet 5.5 then turned it back on, and neither row said why: the Opus +// was Claude Code's own model, asked of Anthropic directly (picking it +// unroutes Claude Code), the Sonnet magpie's, its "· via magpie" cut off +// the end of a long note. Now each model says which way it goes, and a +// pick that takes a connected agent off magpie (one of its own models, or +// Default) is asked first, as the switch's off is; Default's ask offers +// Disconnect and restore beside it, the two not being the same. Switched +// on, the switch says what model it started the agent on and why. No click +// moves the page; in English and Chinese, the API 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: "claude-opus-5-5", note: "Claude Opus 5.5", group: "Claude Code", direct: "Anthropic", icon: "claude-color" }, + { value: "claude-sonnet-5-5", note: "Claude Sonnet 5.5", group: "Claude Code", direct: "Anthropic", icon: "claude-color" }, + { value: "claude/claude-sonnet-5-5[1m]", label: "Claude Sonnet 5.5", ref: "claude/claude-sonnet-5-5", group: "Claude", icon: "claude-color", + note: "someone.with.a.long.address@example.com · via magpie" }, + { value: "claude/claude-opus-5-5[1m]", label: "Claude Opus 5.5", ref: "claude/claude-opus-5-5", group: "Claude", icon: "claude-color", + note: "someone.with.a.long.address@example.com · via magpie" }, +]; +const fresh = () => ({ + agents: [ + { id: "claude", name: "Claude Code", icon: "generic", path: "/fixture/claude", wired: true, fields: [{ key: "model", label: "model", value: "claude/claude-sonnet-5-5[1m]", options }] }, + { id: "codex", name: "Codex", icon: "generic", path: "/fixture/codex", wired: true, fields: [{ key: "model", label: "model", value: "", options: [{ value: "relay/m1", label: "m1", ref: "relay/m1", note: "Relay · via magpie" }] }] }, + ], + profiles: [], +}); + +function server(lang, posts) { + let cur = fresh(); + const reply = (route, extra = {}) => route.fulfill({ json: { ...cur, ...extra, 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); + if (url.pathname === "/api/set") { + const body = JSON.parse(req.postData()); + posts.push(body); + cur = JSON.parse(JSON.stringify(cur)); + const a = cur.agents.find((x) => x.id === body.agent); + a.fields[0].value = body.value; + a.wired = body.value.includes("/"); + return reply(route); + } + if (url.pathname === "/api/agents/connect/claude") { + posts.push({ connect: "claude" }); + cur = JSON.parse(JSON.stringify(cur)); + const a = cur.agents.find((x) => x.id === "claude"); + a.wired = true; + a.fields[0].value = "claude/claude-sonnet-5-5[1m]"; + return reply(route, { connected: { how: "default", field: "model", value: "claude/claude-sonnet-5-5[1m]" } }); + } + if (url.pathname.startsWith("/api/agents/preview/")) return json({ changes: [] }); + 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: { via: "via magpie", direct: "direct, not via magpie", off: "off magpie", ask: "Take Claude Code off magpie?", use: "Use claude-opus-5-5", restore: "Disconnect and restore", cancel: "Cancel", connected: "it had no model set, so the first of its own" }, + zh: { via: "经 magpie", direct: "直连,不经 magpie", off: "不经 magpie", ask: "让 Claude Code 不再经过 magpie?", use: "使用 claude-opus-5-5", restore: "断开并还原", cancel: "取消", connected: "它原来没有设模型" }, +}; +const row = '.row.agent[data-id="claude"]'; + +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}: a pick that takes Claude Code off magpie says so and is asked first`, 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: 560 }, 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} .ag-conn`).waitFor(); + const missing = await page.evaluate(() => [ + "via magpie", "{agent} asks magpie for it", "direct, not via magpie", "off magpie", + "{agent} as installed: magpie's endpoint and models come out", "Take {agent} off magpie?", + "Default is {agent} as installed: magpie's endpoint and models come out, and {agent} starts on its own default model. What it had before magpie isn't put back; Disconnect and restore does that.", + "{model} is {agent}'s own model: {agent} asks {vendor} for it itself, with its own sign-in, not through magpie. Picking it takes {agent} off magpie, and it starts on {model}.", + "「接入」 goes off, and {agent} is listed under Not set up with the agents not connected. Switch it on again to go back through magpie.", + "「接入」 goes off. Switch it on again to go back through magpie.", + "Use default", "Use {model}", "{agent} no longer goes through magpie · on its own default", + "{agent} is connected to magpie · back on {model}, what it was on when it was switched off", + "{agent} is connected to magpie · on {model} through magpie, the model it was on", + "{agent} is connected to magpie · on {model} through magpie: it had no model set, so the first of its own", + "{agent} is connected to magpie · on {model} through magpie: magpie doesn't serve the model it was on", + "{agent} is connected to magpie · it stays on its own last pick; magpie's models join its {cmd}", + ].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 start = page.locator(`${row} > .field.ag-start`); + const item = (text) => page.locator("#pop #list li", { hasText: text }).first(); + const open = async () => { await start.click(); await page.locator("#pop:not([hidden]) #list li").first().waitFor(); }; + + // each model says which way it goes, the tag whole however long the note + await open(); + const tag = (li) => li.locator(".badge.path").textContent(); + assert.equal(await tag(item("claude-opus-5-5")), w.direct); + const via = item("someone.with"); + assert.equal(await tag(via), w.via); + assert.ok(await via.locator(".badge.path").evaluate((b) => b.scrollWidth <= b.clientWidth + 1 && b.getBoundingClientRect().right <= b.closest("li").getBoundingClientRect().right), "the tag isn't cut off"); + assert.ok(!(await via.locator(".n").textContent()).includes("via magpie"), "said once, as the tag"); + assert.equal(await tag(page.locator("#pop #list li.reset", { hasText: lang === "en" ? "Default" : "默认" }).first()), w.off); + + // Claude Code's own Opus is asked first; Cancel leaves it connected + await item("claude-opus-5-5").click(); + const ask = page.locator("#modal .leave-ask"); + await ask.waitFor(); + assert.equal((await ask.locator(".ehead b").textContent()).trim(), w.ask); + assert.deepEqual(posts, [], "nothing written before it is confirmed"); + await ask.locator("button", { hasText: w.cancel }).click(); + await ask.waitFor({ state: "detached" }); + assert.deepEqual(posts, []); + assert.equal(await page.locator(`${row} .ag-conn`).getAttribute("aria-checked"), "true"); + + // Default is asked too, with Disconnect and restore beside it + await open(); + await page.locator("#pop #list li.reset", { hasText: lang === "en" ? "Default" : "默认" }).first().click(); + await ask.waitFor(); + assert.equal(await ask.locator("button", { hasText: w.restore }).count(), 1); + await ask.locator("button", { hasText: w.cancel }).click(); + await ask.waitFor({ state: "detached" }); + assert.deepEqual(posts, []); + + // confirmed, it is written: off magpie, 「接入」 off + await open(); + await item("claude-opus-5-5").click(); + await ask.waitFor(); + await ask.locator("button", { hasText: w.use }).click(); + await page.waitForFunction(() => document.querySelector("#modal").hidden); + await page.waitForFunction((r) => document.querySelector(r + " .ag-conn")?.getAttribute("aria-checked") === "false", row); + assert.deepEqual(posts, [{ agent: "claude", field: "model", value: "claude-opus-5-5" }]); + + // a model of magpie's picked while not connected connects it, no ask + // (the owner's one click), and is said to go through magpie; off + // magpie, the row is folded under Not set up with Codex still on it + assert.equal(await page.locator(".agent-more").getAttribute("aria-expanded"), "false"); + await page.locator(".agent-more").click(); + await open(); + assert.equal(await tag(item("someone.with")), w.via); + await item("someone.with").click(); + await page.waitForFunction((r) => document.querySelector(r + " .ag-conn")?.getAttribute("aria-checked") === "true", row); + assert.equal(await page.locator("#modal:not([hidden]) .leave-ask").count(), 0); + assert.equal(posts.length, 2); + + // a pick within magpie's models isn't asked + await open(); + await page.locator("#pop #list li", { hasText: "someone.with" }).filter({ hasText: "Opus" }).click(); + await page.waitForFunction(() => document.querySelector('.row.agent[data-id="claude"] > .field.ag-start')?.textContent.includes("Opus")); + assert.equal(await page.locator("#modal:not([hidden]) .leave-ask").count(), 0); + assert.deepEqual(posts.at(-1), { agent: "claude", field: "model", value: "claude/claude-opus-5-5[1m]" }); + + // the switch says what it started the agent on, and why + const s = page.locator(`${row} .ag-conn`); + await page.evaluate(() => { const a = state.agents.find((x) => x.id === "claude"); a.wired = false; renderAgents(); }); + await s.click(); + await page.waitForFunction((r) => document.querySelector(r + " .ag-conn")?.getAttribute("aria-checked") === "true", row); + assert.ok((await page.locator("#status").textContent()).includes(w.connected), await page.locator("#status").textContent()); + assert.ok((await page.locator("#status").textContent()).includes("Claude Sonnet 5.5")); + + assert.deepEqual(await tops(), top, "no click moved the page"); + assert.deepEqual(dialogs, [], "no native dialog"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/gui/tests/claude-picker-fold.test.cjs b/internal/gui/tests/claude-picker-fold.test.cjs index 9d81ae6f5..c8f003a74 100644 --- a/internal/gui/tests/claude-picker-fold.test.cjs +++ b/internal/gui/tests/claude-picker-fold.test.cjs @@ -149,7 +149,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.locator("#pop:not([hidden]) #list li").first().waitFor(); list = await rows(page); // after Default and, connected, the way back - assert.deepEqual(list[2], { v: "Claude Opus 5.5", n: "me@example.com · via magpie", cur: true, fold: false }, JSON.stringify(list)); + assert.deepEqual(list[2], { v: "Claude Opus 5.5", n: "me@example.com", cur: true, fold: false }, JSON.stringify(list)); + // "via magpie" is said once, as its tag, beside Claude Code's own marked direct (#726) + assert.equal(await page.locator("#list li.cur .badge.path.via").textContent(), lang === "en" ? "via magpie" : "经 magpie"); + assert.equal(await page.locator("#list li:not(.cur)", { hasText: "claude-opus-5-5" }).first().locator(".badge.path.direct").count(), 1); assert.equal(list.filter((r) => r.fold).map((r) => r.v).join(), w.one); await page.context().close(); }); @@ -181,7 +184,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.locator("#q").fill("Claude Opus 5.5"); const list = await rows(page); assert(!list.some((r) => r.fold), JSON.stringify(list)); - assert(list.some((r) => r.v === "Claude Opus 5.5" && r.n === "me@example.com · via magpie"), JSON.stringify(list)); + assert(list.some((r) => r.v === "Claude Opus 5.5" && r.n === "me@example.com"), JSON.stringify(list)); await page.locator("#q").fill("claude/claude-opus-5-5[1m]"); await page.keyboard.press("Enter"); await page.waitForFunction(() => document.querySelector("#pop").hidden);