From f55747ce82e2abf441dfac16098dfdc6c8f61c10 Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 3 Oct 2026 03:57:24 +0800 Subject: [PATCH] =?UTF-8?q?agents:=20Claude=20Desktop's=20tiers=20each=20t?= =?UTF-8?q?ake=20a=20model=20of=20their=20own=20(WilianWeng=20on=20Discord?= =?UTF-8?q?:=20desktop=E4=B8=AD=E8=B0=83=E7=94=A8=E5=AD=90agent=E6=97=B6?= =?UTF-8?q?=EF=BC=8Cclaude=E6=97=A0=E6=B3=95=E8=AF=86=E5=88=AB=E6=A8=A1?= =?UTF-8?q?=E5=9E=8B=E8=A7=92=E8=89=B2)=20=E2=80=94=20Desktop's=20Code=20t?= =?UTF-8?q?ab=20runs=20Claude=20Code=20with=20every=20ANTHROPIC=5FDEFAULT?= =?UTF-8?q?=5F=5FMODEL=20set=20to=20""=20unless=20the=20gateway's=20?= =?UTF-8?q?/v1/models=20tags=20a=20model=20with=20anthropic=5Ffamily=5Ftie?= =?UTF-8?q?r=20(shortnameIdentityOverrides=20in=20its=20app.asar,=202.7032?= =?UTF-8?q?),=20so=20a=20subagent=20on=20sonnet=20or=20haiku=20asked=20for?= =?UTF-8?q?=20Claude=20Code's=20own=20claude-sonnet-=E2=80=A6,=20which=20m?= =?UTF-8?q?agpie=20doesn't=20serve,=20and=20ran=20on=20the=20chat's=20mode?= =?UTF-8?q?l.=20Claude=20Desktop=20now=20has=20opus,=20sonnet,=20haiku=20a?= =?UTF-8?q?nd=20fable=20pickers=20(the=20tiers'=20square,=20as=20Claude=20?= =?UTF-8?q?Code's),=20kept=20in=20claude-desktop.tiers.json:=20the=20model?= =?UTF-8?q?=20picked=20is=20tagged=20with=20its=20tier=20and=20is=5Ffamily?= =?UTF-8?q?=5Fdefault,=20a=20Claude=20model=20magpie=20serves=20is=20tagge?= =?UTF-8?q?d=20with=20its=20own=20tier=20while=20that=20tier=20has=20none?= =?UTF-8?q?=20picked,=20and=20a=20request=20for=20Claude=20Code's=20own=20?= =?UTF-8?q?id=20of=20a=20tier=20no=20row=20is=20tagged=20with=20(a=20model?= =?UTF-8?q?=20picked=20for=20two=20tiers=20carries=20the=20first)=20goes?= =?UTF-8?q?=20to=20the=20tier's=20pick.=20The=20tiers'=20square=20and=20pi?= =?UTF-8?q?cker=20work=20without=20a=20model=20field=20to=20follow=20(Not?= =?UTF-8?q?=20set:=20a=20Claude=20model=20of=20the=20tier,=20else=20the=20?= =?UTF-8?q?chat's=20model).=20Desktop=20reads=20/v1/models=20at=20start-up?= =?UTF-8?q?.=20TestClaudeDesktopTiers=20(gateway,=20agent)=20and=20desktop?= =?UTF-8?q?-tiers.test.cjs=20(fails=20without=20the=20app.js=20change);=20?= =?UTF-8?q?not=20tried=20against=20a=20real=20Claude=20Desktop.=20go=20vet?= =?UTF-8?q?=20./internal/...,=20go=20build=20-tags=20nogui=20(darwin,=20GO?= =?UTF-8?q?OS=3Dlinux),=20GOOS=3Dwindows=20go=20build,=20go=20test=20-tags?= =?UTF-8?q?=20nogui=20-count=3D1=20./...=20under=20a=20temp=20HOME=20pass.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/agent/claudedesktop.go | 34 ++++++- internal/agent/claudedesktop_test.go | 40 ++++++++ internal/gateway/desktop.go | 105 +++++++++++++++++++ internal/gateway/desktop_tier_test.go | 119 ++++++++++++++++++++++ internal/gui/assets/app.js | 14 ++- internal/gui/assets/i18n.js | 3 + internal/gui/tests/desktop-tiers.test.cjs | 97 ++++++++++++++++++ 7 files changed, 405 insertions(+), 7 deletions(-) create mode 100644 internal/gateway/desktop_tier_test.go create mode 100644 internal/gui/tests/desktop-tiers.test.cjs diff --git a/internal/agent/claudedesktop.go b/internal/agent/claudedesktop.go index 68f8c1866..e00e1c85c 100644 --- a/internal/agent/claudedesktop.go +++ b/internal/agent/claudedesktop.go @@ -27,6 +27,7 @@ import ( "bytes" "encoding/json" "errors" + "fmt" "os" "path/filepath" "runtime" @@ -154,7 +155,7 @@ func claudeDesktop(home string) *Agent { return wiringOff("Claude Desktop", p.prof, func(k string) (string, bool) { return edit.GetJSON(p.prof, k) }, "inferenceGatewayBaseUrl", gateway.URL(), "inferenceGatewayApiKey", gateway.TokenFor("claude-desktop")) }, - Fields: []Field{{ + Fields: append([]Field{{ Key: "provider", Label: "provider", Get: func() string { if desktopWired(p) { @@ -179,10 +180,39 @@ func claudeDesktop(home string) *Agent { return []Option{{Value: magpieID, Label: "magpie", Icon: "magpie", Note: "Desktop's third-party gateway: Code and Cowork on magpie's models, no Anthropic sign-in (restart Desktop)"}} }, - }}, + }}, desktopTierFields(p)...), } } +// desktopTierFields pick the model each of Claude Code's tiers runs on in +// Desktop's Code tab, its subagents' sonnet, haiku or opus among them +// (gateway.DesktopTiers). Unset, a Claude model magpie serves stands in for +// its own tier, else the chat's model does. Desktop reads them from the +// gateway's /v1/models when it starts. +func desktopTierFields(p desktopPaths) []Field { + var fields []Field + for _, tier := range gateway.DesktopTierNames { + fields = append(fields, Field{ + Key: tier, Label: tier, Quiet: true, + Get: func() string { return gateway.DesktopTiers()[tier] }, + Set: func(v string) error { + v = gateway.DesktopCatalogID(v) + if v != "" && !isMagpie(v) { + return fmt.Errorf("%s: %q is not a model magpie serves", tier, v) + } + return gateway.SetDesktopTier(tier, v) + }, + Options: func(map[string]string) []Option { + if !desktopWired(p) { + return nil + } + return viaMagpie("claude-desktop", "") + }, + }) + } + return fields +} + // desktopWired: _meta.json lists magpie's profile. func desktopWired(p desktopPaths) bool { entries, _, err := desktopEntries(p.meta) diff --git a/internal/agent/claudedesktop_test.go b/internal/agent/claudedesktop_test.go index 0148f9dd5..78aa34f55 100644 --- a/internal/agent/claudedesktop_test.go +++ b/internal/agent/claudedesktop_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/provider" ) // desktopSandbox is a home of its own with nothing of this machine's in @@ -307,3 +308,42 @@ func TestClaudeDesktopRefusesOddFiles(t *testing.T) { t.Fatal("entries that aren't a list were taken") } } + +// each of Claude Code's tiers in Desktop's Code tab can have a model of its +// own (WilianWeng): offered once Desktop is on magpie, set by the catalog id +// or by the id Desktop is shown, and taken away with "" +func TestClaudeDesktopTiers(t *testing.T) { + home, _ := desktopSandbox(t) + if err := provider.Save(provider.Provider{ID: "v", Name: "V", Chat: "http://127.0.0.1:1/v1", Key: "k", Models: []string{"a", "b"}}); err != nil { + t.Fatal(err) + } + a := claudeDesktop(home) + f := a.Field("sonnet") + if f == nil || !f.Quiet { + t.Fatal("no quiet sonnet field") + } + if len(f.Options(nil)) != 0 { + t.Fatal("tiers offered before Desktop is on magpie") + } + if err := a.Field("provider").Set("magpie"); err != nil { + t.Fatal(err) + } + if len(f.Options(nil)) != 2 { + t.Fatalf("options: %+v", f.Options(nil)) + } + if err := f.Set("v/a"); err != nil { + t.Fatal(err) + } + if err := a.Field("haiku").Set(gateway.DesktopID(provider.Entry{ID: "v/b"})); err != nil { + t.Fatal(err) + } + if f.Get() != "v/a" || a.Field("haiku").Get() != "v/b" || a.Field("opus").Get() != "" { + t.Fatalf("tiers: %v", gateway.DesktopTiers()) + } + if err := f.Set("nope/x"); err == nil { + t.Fatal("a model magpie doesn't serve was taken") + } + if err := f.Set(""); err != nil || f.Get() != "" { + t.Fatalf("unset: %v %q", err, f.Get()) + } +} diff --git a/internal/gateway/desktop.go b/internal/gateway/desktop.go index 7ffb99cb2..4d15ebf49 100644 --- a/internal/gateway/desktop.go +++ b/internal/gateway/desktop.go @@ -147,6 +147,16 @@ func desktopModels(entries []provider.Entry) []map[string]any { for _, e := range entries { names[desktopName(e)]++ } + // the tier each model stands in for: the user's pick (a model picked + // for two is tagged with the first, desktopTierTurn sends the other), + // else a Claude model's own + picked := DesktopTiers() + tierOf := map[string]string{} + for _, t := range DesktopTierNames { + if id := picked[t]; id != "" && tierOf[id] == "" { + tierOf[id] = t + } + } data := make([]map[string]any, 0, len(entries)) for _, e := range entries { m := modelObject(e) @@ -158,11 +168,103 @@ func desktopModels(entries []provider.Entry) []map[string]any { if m["id"] = claudeLooking(e); m["id"] != e.ID { m["description"] = e.ID + " in magpie" } + if t := tierOf[e.ID]; t != "" { + m["anthropic_family_tier"], m["is_family_default"] = t, true + } else if t := claudeTier(e.ID); t != "" && picked[t] == "" { + m["anthropic_family_tier"] = t + } data = append(data, m) } return data } +// Claude Desktop's Code tab runs Claude Code with ANTHROPIC_DEFAULT__MODEL +// set to "" for every tier, unless the gateway's /v1/models tags a model +// with anthropic_family_tier (shortnameIdentityOverrides in its app.asar, +// 2.7032: the first so tagged, or the one also is_family_default). Untagged, +// a subagent on "sonnet" or "haiku" asked for Claude Code's own +// claude-sonnet-… and that, unserved, went to the chat's model: every +// subagent ran on it, whatever its tier (WilianWeng on Discord). The user +// picks a model per tier in magpie; a Claude model magpie serves stands in +// for its own tier while its tier has none picked. +var DesktopTierNames = []string{"opus", "sonnet", "haiku", "fable"} + +func desktopTiersPath() string { return filepath.Join(settings.Dir(), "claude-desktop.tiers.json") } + +// DesktopTiers is the catalog id picked for each of Claude Desktop's tiers. +func DesktopTiers() map[string]string { + out := map[string]string{} + b, err := os.ReadFile(desktopTiersPath()) + if err == nil { + json.Unmarshal(b, &out) + } + return out +} + +// SetDesktopTier picks the model (a catalog id) Claude Desktop runs a tier +// on; "" takes the pick away. +func SetDesktopTier(tier, id string) error { + tiers := DesktopTiers() + if id == "" { + delete(tiers, tier) + } else { + tiers[tier] = id + } + if len(tiers) == 0 { + if err := os.Remove(desktopTiersPath()); err != nil && !os.IsNotExist(err) { + return err + } + return nil + } + b, _ := json.MarshalIndent(tiers, "", " ") + if err := os.MkdirAll(settings.Dir(), 0o755); err != nil { + return err + } + return os.WriteFile(desktopTiersPath(), append(b, '\n'), 0o600) +} + +// DesktopCatalogID is the catalog id of a model as Claude Desktop names it: +// one of its aliases or the catalog id itself. +func DesktopCatalogID(id string) string { + if c, ok := aliased(id); ok { + return c + } + return id +} + +// claudeTier is the tier a model id is a Claude model of (claude-opus-4-8, +// a provider's anthropic/claude-sonnet-5), "" when it is none. +func claudeTier(id string) string { + m := strings.ToLower(strings.TrimSuffix(id, "[1m]")) + if i := strings.LastIndex(m, "/"); i >= 0 { + m = m[i+1:] + } + if !claudeFamily.MatchString(m) { + return "" + } + for _, t := range DesktopTierNames { + if strings.Contains(m, t) { + return t + } + } + return "" +} + +// desktopTierTurn is the model picked for the tier of a Claude model +// Desktop's Claude Code asked for by Claude Code's own id, which magpie +// doesn't serve: a subagent on a tier no model is tagged for, or on one a +// model picked for two tiers isn't tagged with. "" when there is none. +func desktopTierTurn(asked string) string { + if !unserved(asked) || strings.Contains(asked, "/") { + return "" + } + t := claudeTier(asked) + if t == "" { + return "" + } + return DesktopTiers()[t] +} + func desktopName(e provider.Entry) string { if e.Name != "" { return e.Name @@ -235,6 +337,9 @@ func desktopTurn(asked string, body []byte) string { if asked == "" { return asked } + if m := desktopTierTurn(asked); m != "" { + return m + } tools := hasTools(body) desktopPicked.Lock() defer desktopPicked.Unlock() diff --git a/internal/gateway/desktop_tier_test.go b/internal/gateway/desktop_tier_test.go new file mode 100644 index 000000000..d266ab001 --- /dev/null +++ b/internal/gateway/desktop_tier_test.go @@ -0,0 +1,119 @@ +package gateway + +import ( + "encoding/json" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// Claude Desktop's Code tab runs a subagent on a tier only when the +// gateway's /v1/models tags a model with it; untagged, every subagent ran on +// the chat's model (WilianWeng). A Claude model is tagged with its own tier, +// a model the user picks for a tier with that one as its default, and Claude +// Code's own id of a tier no row carries goes to the tier's pick. +func TestClaudeDesktopTiers(t *testing.T) { + f := &fake{reply: sse( + `event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"m","type":"message","role":"assistant","model":"m1","content":[],"usage":{"input_tokens":1,"output_tokens":0}}}`, + `event: message_stop`+"\n"+`data: {"type":"message_stop"}`)} + up := setup(t, provider.Anthropic, f) + if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Anthropic: up.URL, + Models: []string{"m1", "claude-sonnet-5", "m2"}}); err != nil { + t.Fatal(err) + } + desktop := Token + "-claude-desktop" + type row struct { + Tier string `json:"anthropic_family_tier"` + Default bool `json:"is_family_default"` + } + rows := func() map[string]row { + t.Helper() + req := httptest.NewRequest("GET", "/v1/models?limit=1000", nil) + req.Header.Set("x-api-key", desktop) + rec := httptest.NewRecorder() + New().Handler().ServeHTTP(rec, req) + var list struct { + Data []struct { + ID string `json:"id"` + Description string `json:"description"` + row + } `json:"data"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &list); err != nil { + t.Fatal(err) + } + out := map[string]row{} + for _, d := range list.Data { + id := strings.TrimSuffix(d.Description, " in magpie") + if d.Description == "" { + id = d.ID + } + out[id] = d.row + } + return out + } + send := func(model string) string { + t.Helper() + f.got = nil + req := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(`{"model":"`+model+`","max_tokens":32000,"stream":true,"tools":[{"name":"Bash","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":"hi"}]}`)) + req.Header.Set("x-api-key", desktop) + rec := httptest.NewRecorder() + New().Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("%s: %d %s", model, rec.Code, rec.Body) + } + return modelOf(f.got) + } + + // nothing picked: the Claude model stands in for its own tier + got := rows() + if r := got["fake/claude-sonnet-5"]; r.Tier != "sonnet" || r.Default { + t.Fatalf("claude-sonnet-5 unpicked: %+v", r) + } + if r := got["fake/m1"]; r.Tier != "" { + t.Fatalf("m1 unpicked: %+v", r) + } + + // m1 picked for opus and sonnet, m2 for haiku + for tier, id := range map[string]string{"opus": "fake/m1", "sonnet": "fake/m1", "haiku": "fake/m2"} { + if err := SetDesktopTier(tier, id); err != nil { + t.Fatal(err) + } + } + got = rows() + if r := got["fake/m1"]; r.Tier != "opus" || !r.Default { + t.Fatalf("m1 picked for opus and sonnet: %+v", r) + } + if r := got["fake/m2"]; r.Tier != "haiku" || !r.Default { + t.Fatalf("m2 picked for haiku: %+v", r) + } + if r := got["fake/claude-sonnet-5"]; r.Tier != "" { + t.Fatalf("claude-sonnet-5 with sonnet picked: %+v", r) + } + // Claude Code's own ids of a tier go to its pick, sonnet's too, which + // no row is tagged with; a Claude model magpie serves stays as asked + for asked, want := range map[string]string{ + "claude-sonnet-4-6": "m1", "claude-opus-4-8[1m]": "m1", "claude-3-5-haiku-20241022": "m2", + "claude-haiku-4-5-20251001": "m2", "claude-sonnet-5": "claude-sonnet-5", + } { + if got := send(asked); got != want { + t.Errorf("%s: sent %q, want %q", asked, got, want) + } + } + if DesktopCatalogID(aliasFor("fake/m1")) != "fake/m1" || DesktopCatalogID("fake/m2") != "fake/m2" { + t.Fatal("DesktopCatalogID") + } + + // unpicked again, the file goes + for _, tier := range DesktopTierNames { + if err := SetDesktopTier(tier, ""); err != nil { + t.Fatal(err) + } + } + if _, err := os.Stat(desktopTiersPath()); !os.IsNotExist(err) { + t.Fatalf("tiers file left: %v", err) + } +} diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 778818fc1..607ad9a6b 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -1519,8 +1519,11 @@ const LAUNCH_GLYPH = "M2.5 3.5h11v9h-11zM5 6.5l2 1.75L5 10M8.5 10h2.5"; function tierMenu(a) { const tiers = a.fields.filter((f) => TIERS.includes(f.label)); if (!tiers.length || !tiers.some((f) => f.options.length)) return null; + // Claude Desktop has no model of its own here: a tier unset runs on a + // Claude model of that tier magpie serves, else on the chat's model const main = a.fields.find((f) => f.key === "model"); - const mainName = optionFor(main, main.value)?.label || main.value; + const mainName = main && (optionFor(main, main.value)?.label || main.value); + const unset = main ? t("same as model ({model})", { model: mainName }) : t("a Claude model of the tier, else the chat's model"); // a tier's effort, offered while there are levels to pick (Claude Code // through magpie); unset, the tier runs at the effort Claude Code asks const effortOf = (f) => a.fields.find((e) => e.label === f.label + " effort" && (e.options.length || e.value)); @@ -1529,11 +1532,11 @@ function tierMenu(a) { const name = (f) => optionFor(f, f.value)?.label || f.value; return { key: "tiers", label: "tiers", value: "", menu: true, custom: custom.length > 0, - summary: custom.length ? custom.map((f) => level(effortOf(f)) ? `${f.label} (${level(effortOf(f))})` : f.label).join(", ") : t("same as model"), + summary: custom.length ? custom.map((f) => level(effortOf(f)) ? `${f.label} (${level(effortOf(f))})` : f.label).join(", ") : main ? t("same as model") : t("not set"), options: tiers.flatMap((f) => { const model = { - value: f.key, label: f.label, icon: optionFor(f, f.value)?.icon || optionFor(main, main.value)?.icon, - note: f.value ? name(f) : t("same as model ({model})", { model: mainName }), + value: f.key, label: f.label, icon: optionFor(f, f.value)?.icon || (main && optionFor(main, main.value)?.icon), + note: f.value ? name(f) : unset, }; const e = effortOf(f); return e ? [model, { value: e.key, label: t(e.label), effortOf: e, note: level(e) || t("the effort Claude Code asks for") }] : [model]; @@ -2071,7 +2074,8 @@ function openPicker(agent, field, anchor, ev, only) { // the agent's own default: magpie's wiring comes out and the key is removed if (FOLLOWS_MODEL.includes(field.label)) { const main = agent.fields.find((f) => f.key === "model"); - options.unshift({ value: "", label: t("Same as model"), note: optionFor(main, main.value)?.label || main.value, icon: optionFor(main, main.value)?.icon, reset: true }); + options.unshift(main ? { value: "", label: t("Same as model"), note: optionFor(main, main.value)?.label || main.value, icon: optionFor(main, main.value)?.icon, reset: true } + : { value: "", label: t("Not set"), note: t("a Claude model of the tier, else the chat's model"), icon: agent.icon, reset: true }); } else if (!only && !field.menu && !field.onPick && !options.some((o) => o.value === "")) options.unshift({ value: "", label: t("Default"), note: t("what {agent} ships with", { agent: agent.name }), icon: agent.icon, reset: true }); // Default is the agent as installed; this is the agent as it was before // magpie, beside it so the two aren't taken for each other diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 5c8b182c8..3b80a6e46 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -171,6 +171,9 @@ const I18N = { "magpie is Codex's provider; the Codex app is in its API state, with magpie's models only": "magpie 作为 Codex 的供应商,Codex 应用显示为 API 登录状态,只列出 magpie 的模型", "same as model": "同主模型", "same as model ({model})": "同主模型({model})", + "a Claude model of the tier, else the chat's model": "该档位的 Claude 模型,没有则用对话的模型", + "not set": "未设置", + "Not set": "未设置", "Same as model": "同主模型", "{agent} stays signed in; magpie just stops offering it": "{agent} 仍保持登录,只是 magpie 不再提供它", "You removed it from magpie.": "你已把它从 magpie 中移除。", diff --git a/internal/gui/tests/desktop-tiers.test.cjs b/internal/gui/tests/desktop-tiers.test.cjs new file mode 100644 index 000000000..b4756d58f --- /dev/null +++ b/internal/gui/tests/desktop-tiers.test.cjs @@ -0,0 +1,97 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Claude Desktop's Code tab runs Claude Code, whose opus/sonnet/haiku/fable +// tiers each take a model of their own from magpie (WilianWeng). Desktop has +// no model field here for them to follow: the tiers' square says what an +// unset one runs on instead, and its picker's reset entry is "Not set", not +// "Same as model". 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 models = [{ value: "magpie/v/glm", label: "GLM" }, { value: "magpie/v/flash", label: "Flash" }]; +const tiers = ["opus", "sonnet", "haiku", "fable"]; +const fresh = () => ({ + agents: [{ + id: "claude-desktop", name: "Claude Desktop", path: "/test/claude_desktop_config.json", icon: "claude-color", + fields: [ + { key: "provider", label: "provider", value: "magpie", options: [{ value: "magpie", label: "magpie" }] }, + ...tiers.map((tier) => ({ key: tier, label: tier, value: tier === "haiku" ? "magpie/v/flash" : "", options: models })), + ], + }], + profiles: [], +}); + +function server(lang, sets) { + let cur = fresh(); + return async (route) => { + const req = route.request(), url = new URL(req.url()); + 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 route.fulfill({ json: { ...cur, settings: { lang, theme: "light" } } }); + if (url.pathname === "/api/set") { + const body = req.postDataJSON(); + sets.push(body); + cur = JSON.parse(JSON.stringify(cur)); + cur.agents.find((a) => a.id === body.agent).fields.find((f) => f.key === body.field).value = body.value; + return route.fulfill({ json: { ...cur, settings: { lang, theme: "light" } } }); + } + if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] }); + if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } }); + if (url.pathname === "/api/agents/cli") return route.fulfill({ json: { agents: {}, pending: false } }); + if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } }); + if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } }); + if (url.pathname.startsWith("/api/")) return route.fulfill({ 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 W = { + en: { unset: "a Claude model of the tier, else the chat's model", reset: "Not set", summary: "tiers: haiku" }, + zh: { unset: "该档位的 Claude 模型,没有则用对话的模型", reset: "未设置", summary: "分档:haiku" }, +}; + +const cd = '.row.agent[data-id="claude-desktop"]'; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + test(`${engine} ${lang}: Claude Desktop's tiers are picked from their square`, async (t) => { + const w = W[lang]; + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await browser.newPage({ viewport: { width: 1100, height: 700 } }); + page.setDefaultTimeout(5000); + const errors = [], sets = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, sets)); + t.after(() => browser.close()); + await page.goto("http://magpie.test/"); + await page.locator(cd).waitFor(); + + const square = page.locator(`${cd} .field.extra[data-key="tiers"]`); + assert.equal(await square.count(), 1, "no tiers square"); + assert.ok((await square.getAttribute("aria-label")).startsWith(w.summary), await square.getAttribute("aria-label")); + const y = await page.evaluate(() => scrollY); + await square.click(); + await page.locator("#pop:not([hidden]) #list li").first().waitFor(); + const rows = await page.locator("#list li").evaluateAll((es) => es.map((e) => [e.querySelector(".v")?.textContent, e.querySelector(".n")?.textContent || ""])); + assert.deepEqual(rows.map((r) => r[0]), tiers); + assert.equal(rows[0][1], w.unset); + assert.equal(rows[2][1], "Flash"); + + // sonnet's picker: the reset entry, then magpie's models; GLM picked + await page.locator("#list li").nth(1).click(); + await page.locator("#pop:not([hidden]) #list li", { hasText: "GLM" }).first().waitFor(); + const first = await page.locator("#list li").first().evaluate((e) => [e.querySelector(".v")?.textContent, e.querySelector(".n")?.textContent || ""]); + assert.deepEqual(first, [w.reset, w.unset]); + await page.locator("#list li", { hasText: "GLM" }).first().click(); + await page.waitForFunction(() => document.querySelector("#status")?.textContent); + assert.deepEqual(sets, [{ agent: "claude-desktop", field: "sonnet", value: "magpie/v/glm" }]); + assert.equal(await page.evaluate(() => scrollY), y, "a click scrolled the page"); + assert.deepEqual(errors, []); + }); + } +}