From 35f43e66656b7fe148dac2a18e7e37d3ca297da0 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 28 Sep 2026 18:49:05 +0800 Subject: [PATCH] =?UTF-8?q?gateway:=20Claude=20Desktop=20keeps=20every=20m?= =?UTF-8?q?agpie=20model=20(#148)=20=E2=80=94=20its=20gateway=20check=20dr?= =?UTF-8?q?ops=20any=20id=20naming=20another=20vendor's=20model=20(deepsee?= =?UTF-8?q?k,=20kimi,=20gpt,=20codex,=20glm,=20qwen=E2=80=A6=20anywhere=20?= =?UTF-8?q?in=20it,=20anthropic/=20in=20front=20or=20not),=20so=20anthropi?= =?UTF-8?q?c/deepseek/deepseek-flash=20was=20turned=20away=20and,=20asked?= =?UTF-8?q?=20without=20the=20magpie-claude-desktop=20key,=20/v1/models=20?= =?UTF-8?q?gave=20it=20bare=20ids=20it=20kept=20none=20of=20("returned=200?= =?UTF-8?q?=20usable=20models=20{=20rawCount:=2013=20}").=20A=20model=20wh?= =?UTF-8?q?ose=20id=20doesn't=20already=20read=20as=20Claude's=20is=20list?= =?UTF-8?q?ed=20to=20it=20as=20anthropic/magpie-,=20a=20hash=20of?= =?UTF-8?q?=20its=20magpie=20id=20that=20magpie=20serves=20again=20(/v1/me?= =?UTF-8?q?ssages,=20count=5Ftokens,=20/v1/models/{id},=20with=20[1m]=20to?= =?UTF-8?q?o),=20its=20name=20as=20display=5Fname=20and=20its=20magpie=20i?= =?UTF-8?q?d=20as=20description;=20Desktop=20is=20known=20by=20its=20Elect?= =?UTF-8?q?ron=20User-Agent=20(=E2=80=A6=20Claude/=20Chrome/=E2=80=A6?= =?UTF-8?q?)=20as=20well=20as=20by=20the=20key.=20Checked=20with=20Desktop?= =?UTF-8?q?'s=20own=20checks=20cut=20out=20of=20its=20app.asar=20against?= =?UTF-8?q?=20a=20sandbox=20gateway:=204=20of=204=20kept,=20was=200?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/gateway/desktop.go | 122 +++++++++++++++++++++++++++++++ internal/gateway/desktop_test.go | 67 ++++++++++++++++- internal/gateway/gateway.go | 42 ++++------- 3 files changed, 204 insertions(+), 27 deletions(-) create mode 100644 internal/gateway/desktop.go diff --git a/internal/gateway/desktop.go b/internal/gateway/desktop.go new file mode 100644 index 000000000..90aacc01f --- /dev/null +++ b/internal/gateway/desktop.go @@ -0,0 +1,122 @@ +package gateway + +import ( + "fmt" + "hash/fnv" + "net/http" + "regexp" + "strings" + + "github.com/yetone/magpie/internal/provider" +) + +// Claude Desktop, pointed at a third-party gateway, keeps a model only when +// its id reads as Anthropic's: it says claude, sonnet, opus, haiku, fable, +// mythos or anthropic, and nowhere names another vendor's model. Its check +// (qo in its app.asar, 2.7032) is +// +// Vxe.test(id) ? false : Ko.test(id) || ["claude",…,"anthropic"].some(w => id.includes(w)) +// +// on the lowercased id, with Vxe the list below. It runs on /v1/models rows, +// on Models entries typed in by hand ("model routing must reference an +// Anthropic model") and on the model a session is started with, so +// anthropic/deepseek/deepseek-flash is turned away for its "deepseek". +var ( + desktopDenied = regexp.MustCompile(`ark-code|astron|command-r|deepseek|doubao|gemini|gemma|glm|gpt|grok|hermes|hy3|kimi|lfm|\bling\b|llama|longcat|mimo|minimax|mistral|mixtral|moonshot|nemotron|openai|phi-|qianfan|qwen|tc-code|\bunic\b|yi-|stepfun|step-3|seed-|bytedance|hunyuan|granite|amazon\.nova|nova-|devstral|ministral|ernie|codex|arcee|trinity|abab|phi\d|\bk2\.|\bm2\.|jamba|arctic|solar|mercury|zamba|kat-coder|\bds-|dpsk`) + desktopTier = regexp.MustCompile(`^(sonnet|opus|haiku|fable|mythos)(-[\d.]+)?$`) + desktopWords = []string{"claude", "sonnet", "opus", "haiku", "fable", "mythos", "anthropic"} +) + +// desktopAccepts is Claude Desktop's check of a gateway model id. +func desktopAccepts(id string) bool { + l := strings.ToLower(id) + if desktopTier.MatchString(l) { + return true + } + if desktopDenied.MatchString(l) { + return false + } + for _, w := range desktopWords { + if strings.Contains(l, w) { + return true + } + } + return false +} + +// desktopAlias is the prefix of the id a model is listed by to Claude +// Desktop when its own id names no Claude model: anthropic/magpie-, +// the number a hash of magpie's id, so it stays the model's while the +// catalog changes around it. Desktop's list of other vendors' names grows +// from release to release, so no part of such a model's id is shown to it; +// its display_name and description carry the model's name and magpie id. +const desktopAlias = "anthropic/magpie-" + +func aliasFor(id string) string { + h := fnv.New64a() + h.Write([]byte(id)) + return fmt.Sprintf("%s%010d", desktopAlias, h.Sum64()%1e10) +} + +// claudeLooking is a model's id as Claude Desktop is shown it: as it is when +// it already reads as a Claude model's, else its alias (unprefixed serves it +// again). +func claudeLooking(id string) string { + if desktopAccepts(id) && !strings.HasPrefix(id, desktopAlias) { + return id + } + return aliasFor(id) +} + +// desktopModels is /v1/models as Claude Desktop is shown it: every model by +// an id it keeps (claudeLooking), named so the picker tells them apart — +// it shows the name, not the id, and folds rows of one name into one entry. +func desktopModels(entries []provider.Entry) []map[string]any { + names := map[string]int{} + for _, e := range entries { + names[desktopName(e)]++ + } + data := make([]map[string]any, 0, len(entries)) + for _, e := range entries { + m := modelObject(e) + name := desktopName(e) + if names[name] > 1 && name != e.ID { + name += " (" + e.ID + ")" + } + m["display_name"] = name + if m["id"] = claudeLooking(e.ID); m["id"] != e.ID { + m["description"] = e.ID + " in magpie" + } + data = append(data, m) + } + return data +} + +func desktopName(e provider.Entry) string { + if e.Name != "" { + return e.Name + } + return e.ID +} + +// aliased is the catalog id an anthropic/magpie- alias stands for. +func aliased(id string) (string, bool) { + id = strings.TrimSuffix(id, "[1m]") + if !strings.HasPrefix(id, desktopAlias) { + return "", false + } + for _, e := range provider.Catalog() { + if aliasFor(e.ID) == id { + return e.ID, true + } + } + return "", false +} + +// isClaudeDesktop is a request from Claude Desktop's own gateway client: its +// Electron session's User-Agent ("Mozilla/5.0 … Claude/2.7032.0 Chrome/…"), +// which says nothing of it before the first slash. +func isClaudeDesktop(r *http.Request) bool { + ua := r.Header.Get("User-Agent") + return strings.HasPrefix(ua, "Mozilla/") && strings.Contains(ua, " Claude/") +} diff --git a/internal/gateway/desktop_test.go b/internal/gateway/desktop_test.go index cd81a19c9..355a388bc 100644 --- a/internal/gateway/desktop_test.go +++ b/internal/gateway/desktop_test.go @@ -42,7 +42,7 @@ func TestAnthropicPrefixedModel(t *testing.T) { req.Header.Set("x-api-key", Token+"-claude-desktop") rec = httptest.NewRecorder() New().Handler().ServeHTTP(rec, req) - if !strings.Contains(rec.Body.String(), `"id":"anthropic/fake/m1"`) { + if !strings.Contains(rec.Body.String(), `"id":"`+aliasFor("fake/m1")+`"`) { t.Fatalf("Claude Desktop's list: %s", rec.Body) } if claudeLooking("devin/claude-opus-5-5") != "devin/claude-opus-5-5" { @@ -52,3 +52,68 @@ func TestAnthropicPrefixedModel(t *testing.T) { t.Fatalf("unprefixed changed %q", got) } } + +// Claude Desktop turns away any id naming another vendor's model, prefix +// or not (#148): deepseek, kimi, gpt, codex… get an alias it keeps, which +// magpie serves again, and it is known by its User-Agent without the key +func TestClaudeDesktopAliases(t *testing.T) { + for id, want := range map[string]bool{ + "claude-sonnet-4-5": true, "anthropic/claude-x": true, "opus": true, "sonnet-4.5": true, + "anthropic/deepseek/deepseek-flash": false, "anthropic/kimi-k2": false, "anthropic/gpt-5": false, + "anthropic/openai/codex-mini": false, "fake/m1": false, "deepseek/claude-distill": false, + } { + if desktopAccepts(id) != want { + t.Errorf("desktopAccepts(%q) = %v", id, !want) + } + } + for _, id := range []string{"deepseek/deepseek-flash", "moonshot/kimi-k2.5", "openai/gpt-5.5", "codex/gpt-5-codex", "zai/glm-5"} { + a := claudeLooking(id) + if !desktopAccepts(a) || !strings.HasPrefix(a, desktopAlias) || a != claudeLooking(id) { + t.Errorf("%s listed as %s", id, a) + } + } + + 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"}`)} + setup(t, provider.Anthropic, f) + req := httptest.NewRequest("GET", "/v1/models?limit=1000", nil) + req.Header.Set("x-api-key", Token) + req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Claude/2.9939.2 Chrome/138.0.0.0 Electron/37.0.0 Safari/537.36") + rec := httptest.NewRecorder() + New().Handler().ServeHTTP(rec, req) + var list struct { + Data []struct{ ID, DisplayName, Description string } `json:"data"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &list); err != nil { + t.Fatal(err) + } + alias := aliasFor("fake/m1") + var row *struct{ ID, DisplayName, Description string } + for i := range list.Data { + if list.Data[i].ID == alias { + row = &list.Data[i] + } + if !desktopAccepts(list.Data[i].ID) { + t.Errorf("Desktop would drop %q", list.Data[i].ID) + } + } + if row == nil || row.Description != "fake/m1 in magpie" { + t.Fatalf("Claude Desktop by its User-Agent: %s", rec.Body) + } + for _, asked := range []string{alias, alias + "[1m]"} { + f.calls = 0 + code, body := post(t, "/v1/messages", `{"model":"`+asked+`","max_tokens":10,"stream":true,"messages":[{"role":"user","content":"hi"}]}`) + if code != 200 || f.calls != 1 { + t.Fatalf("%s: %d %s", asked, code, body) + } + } + rec = httptest.NewRecorder() + New().Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/v1/models/"+alias, nil)) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"fake/m1"`) { + t.Fatalf("GET /v1/models/%s: %d %s", alias, rec.Code, rec.Body) + } + if _, ok := aliased(desktopAlias + "0000000000"); ok { + t.Fatal("an alias no model has resolved") + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 9fd39eae7..df53e2f7e 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -47,6 +47,9 @@ func agentOf(r *http.Request) string { if id, ok := strings.CutPrefix(callerKey(r), Token+"-"); ok && id != "" { return usage.AgentOf(id) } + if isClaudeDesktop(r) { + return "claude-desktop" + } return usage.AgentOf(r.Header.Get("User-Agent")) } @@ -333,13 +336,13 @@ func catalogFor(r *http.Request) []provider.Entry { func (s *Server) models(w http.ResponseWriter, r *http.Request) { data := []map[string]any{} - desktop := agentOf(r) == "claude-desktop" - for _, e := range catalogFor(r) { - m := modelObject(e) - if desktop { - m["id"] = claudeLooking(e.ID) + shown := catalogFor(r) + if agentOf(r) == "claude-desktop" { + data = desktopModels(shown) + } else { + for _, e := range shown { + data = append(data, modelObject(e)) } - data = append(data, m) } out := map[string]any{"object": "list", "data": data, "has_more": false} if len(data) > 0 { @@ -359,13 +362,14 @@ func (s *Server) model(w http.ResponseWriter, r *http.Request) { writeError(w, provider.Chat, 404, "unknown model "+id) } -// unprefixed is the model magpie serves by an id with "anthropic/" put in -// front of it. Claude Desktop, pointed at a third-party gateway, takes only -// models whose id says claude, sonnet, opus, haiku or anthropic, so any of -// magpie's is asked for there as anthropic/. An id that is magpie's -// as it stands (a provider named anthropic) is left alone. With the key -// magpie-claude-desktop, /v1/models lists them so. +// unprefixed is the model magpie serves by an id Claude Desktop was given +// for it (claudeLooking): anthropic/magpie-, or, as it listed them +// before, "anthropic/" put in front of magpie's id. An id that is magpie's +// as it stands (a provider named anthropic) is left alone. func unprefixed(id string) string { + if real, ok := aliased(id); ok { + return real + } rest, ok := strings.CutPrefix(id, "anthropic/") if !ok || rest == "" { return id @@ -379,20 +383,6 @@ func unprefixed(id string) string { return rest } -// claudeLooking is a model's id as Claude Desktop is shown it, to the key -// magpie-claude-desktop: it takes only an id that says claude, sonnet, opus, -// haiku or anthropic, so any other is put after anthropic/ (unprefixed -// serves it again). -func claudeLooking(id string) string { - l := strings.ToLower(id) - for _, w := range []string{"claude", "sonnet", "opus", "haiku", "anthropic"} { - if strings.Contains(l, w) { - return id - } - } - return "anthropic/" + id -} - // countTokens answers Anthropic's count_tokens: through the provider when // it implements counting, else a rough estimate. A failed connection or // limited key yields to the next key; other failures reach the client.