agents: Claude Desktop's tiers each take a model of their own (WilianWeng on Discord: desktop中调用子agent时,claude无法识别模型角色) — Desktop's Code tab runs Claude Code with every ANTHROPIC_DEFAULT_<TIER>_MODEL set to "" unless the gateway's /v1/models tags a model with anthropic_family_tier (shortnameIdentityOverrides in its app.asar, 2.7032), so a subagent on sonnet or haiku asked for Claude Code's own claude-sonnet-…, which magpie doesn't serve, and ran on the chat's model. Claude Desktop now has opus, sonnet, haiku and fable pickers (the tiers' square, as Claude Code's), kept in claude-desktop.tiers.json: the model picked is tagged with its tier and is_family_default, a Claude model magpie serves is tagged with its own tier while that tier has none picked, and a request for Claude Code's own id of a tier no row is tagged with (a model picked for two tiers carries the first) goes to the tier's pick. The tiers' square and picker work without a model field to follow (Not set: a Claude model of the tier, else the chat's model). Desktop reads /v1/models at start-up. TestClaudeDesktopTiers (gateway, agent) and desktop-tiers.test.cjs (fails without the app.js change); not tried against a real Claude Desktop. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME pass.

This commit is contained in:
yetone
2026-10-03 03:57:24 +08:00
parent 94cadbc34d
commit f55747ce82
7 changed files with 405 additions and 7 deletions
+32 -2
View File
@@ -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)
+40
View File
@@ -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())
}
}
+105
View File
@@ -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_<TIER>_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()
+119
View File
@@ -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)
}
}
+9 -5
View File
@@ -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
+3
View File
@@ -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 中移除。",
+97
View File
@@ -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, []);
});
}
}