Claude Code in a terminal holds every subagent to one model through
CLAUDE_CODE_SUBAGENT_MODEL (its "subagents" field), and Codex through
magpie's own setting (settings.CodexSubagentModel). Claude Desktop runs
its Code tab's Claude Code with CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST=1,
and Claude Code 2.1.295 then ignores CLAUDE_CODE_SUBAGENT_MODEL,
CLAUDE_CODE_SUBAGENT_MODEL_FORCE and the tier variables in its settings
files ("Ignoring … this session's provider routing is managed by the
host"). The env Desktop 2.31226 builds for the Code tab has no key for it
either. So Desktop's subagents ran on the lead's model or on a tier's, and
only the tiers could be picked.
Claude Desktop's row now has a "subagent model" square, the same square
and strings as Codex's. It is magpie's setting
(settings.DesktopSubagentModel), which the gateway applies
(desktopSubagentPick):
- Only a claude-desktop request with x-claude-code-agent-id and tools is
moved: a subagent's turn. The lead's turns, the tool-less helper calls
Claude Code makes inside a subagent (on the haiku tier's model),
terminal Claude Code and every other agent stay as asked.
- It is applied after desktopTurn, the tiers and the groups. A turn
already on the model set isn't marked as moved. Route.Subagent,
Route.Model and the ledger's Requested keep the model asked for; Kind
stays empty.
- The model set must be served by its exact id (Resolve takes any model
name under a provider that is on), enabled, and allowed to a gateway key
held to some models (groupAllowed for a group). Otherwise the subagent
stays on the model asked for and the trace says why, in the reasons
Codex's subagent model already has.
- count_tokens counts on the same model.
- It is read on each request, so Desktop needn't restart. The field is
Live (a new Field flag): /api/set and `magpie <agent> <field> <value>`
leave Desktop's restart notice out after it, unless the pick connected
Desktop. Codex's subagent model is unchanged.
- The getter follows a provider renamed since it was set (RenamedRef).
The setter takes any provider/model or group/<id>, also one not served
now (a restored profile), refuses a bare name, and keeps a Desktop
alias by its catalog id. Options are shown while Desktop is on magpie.
- POST /api/settings keeps it; a stopped WSL distro's field copy keeps
Live.
- The Routing page says why a Desktop subagent was moved or kept
(subagentWhy, for a route with a subagent pick and no kind). "it is
disabled in magpie" gets its zh, zh-TW, ja and de, which Codex's kept
reason lacked as well.
- Unset, the pick costs one held settings read (no body decode, no
catalog build).
Not changed: a Desktop on another computer that reaches magpie with a
named gateway key is read as Claude Code (agentOf), so none of Desktop's
routing applies to it, this included. There is no fallback when the model
set has a smaller window than the lead's.
Verified at this head, on 20769439, under a temporary HOME with Go's
caches pinned:
- Each new test fails with the guarantee it names broken by hand (a real
FAIL, not a compile error), then passes restored. 48 Go breaks were
first run on 8f34bbcd: settings trim and bare-name refusal; setter
validation and clear; RenamedRef in the getter and in Unserved; the
exact served check and served groups; the serve pick, each guard
(agent id, tools, claude-desktop only, unset, same and resolved model);
the named id kept in Route.Model, Kind and the ledger's Requested; each
kept reason (unserved, disabled, held model, held group); groupAllowed;
the next request reading a change; the session pick kept; count_tokens;
the unset pick allocating; Live on the field, not on the tiers or on
Codex's, copied by WSL; options while unwired and wired; alias
conversion; the settings keep line; the GUI and CLI notice rules.
Re-run at this head:
- no tools guard: TestDesktopSubagentLeavesOtherRequests/helper,
`sent "m2", want m1`
- no agent-id guard: TestDesktopSubagentLeavesOtherRequests/lead,
`sent "m2", want m1`
- no count_tokens pick: TestDesktopSubagentCountTokens,
`count sent "m1" to "/v1/messages/count_tokens", want m2`
- Resolve instead of the exact served check: TestDesktopSubagentUnserved,
`fake/missing: "", want "magpie doesn't serve it now"`
- no Live rule in /api/set: TestDesktopSubagentModelNotice (gui),
`wired Live pick notice "Claude Desktop reads this at start-up …"`
- no keep line in POST /api/settings: TestSettingsSaveKeepsWhatItDoesNotSend,
`DesktopSubagentModel: after a save of the Settings page, was fake/m2`
GUI breaks (0 pass / 2 fail in each engine): renderSteps' new aside
removed (Desktop's moved story missing); the four "it is disabled in
magpie" translations removed (the kept story keeps the English reason);
the Default note's translation removed.
- go test -tags nogui ./...: 52 packages ok, no failure.
- go test -race -count=20 -run '^TestDesktopSubagent' ./internal/gateway: ok.
- gofmt -l on the changed files: nothing. go vet ./...,
GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...,
go build, GOOS=linux go build -tags nogui, GOOS=windows go build: exit 0.
- Playwright 1.62.1: desktop-subagent-model.test.cjs (en, zh, zh-TW, ja,
de; 1100 and 560 wide) with codex-subagent-model, codex-subagents-lead,
codex-start-model-field, desktop-tiers, desktop-model-menu,
subagent-effort and every routing-*.test.cjs: 472/472 in Chromium and
in WebKit. The whole suite: Chromium 4580/4580; WebKit 4570/4572. The
two are red on 20769439 untouched as well: group-fold.test.cjs 3 of 3
alone (195a1009b, fixed upstream since by a125d5c9), usage-fold.test.cjs
4 of 9 alone there and 4 of 9 here ("as many accounts on the first
screen as before the curves: 12 of 29").
- The built binary in a temporary HOME, `magpie serve` on a free port, a
fake Anthropic upstream, requests shaped like Desktop's Claude Code:
`magpie claude-desktop subagent_model fake/m2` printed no restart
advice; a subagent's turn and its count went to m2; the lead's turn,
a subagent's tool-less call, terminal Claude Code's and a subagent turn
after `… subagent_model default` went to m1; claude-desktop.model stayed
fake/m1; the ledger kept requested fake/m1.
- Not tried: a real Claude Desktop or Cowork (that needs the live
gateway), Linux and Windows machines (GOOS vet and build only),
WebKitGTK.
Maintainer's review on origin/main c4c3cafa2 (#2081), under a scratchpad
HOME with Go's caches pinned, machine load 120-330:
- Claude Code 2.1.299's bundled source has the "Ignoring … this
session's provider routing is managed by the host" path, with
CLAUDE_CODE_SUBAGENT_MODEL_FORCE in the set it ignores.
- Breaks re-run: no tools guard -> TestDesktopSubagentLeavesOtherRequests/
helper `sent "m2", want m1` and TestDesktopSubagentCountTokens helper
count; no count_tokens pick -> TestDesktopSubagentCountTokens `count
sent "m1" … want m2`; the Routing page's subagentWhy aside removed ->
desktop-subagent-model 0 pass / 2 fail (webkit, zh).
- go test -tags nogui ./internal/{gateway,agent,settings,gui,cli,provider}:
ok on 2fbbd1694 (agent with -timeout 40m: 1857s under the load; the
default 10m timed out mid TestClaudeNewSessionEffortLastsModelSwitch, a
test this change doesn't touch). After rebasing onto c4c3cafa2, the
Desktop/Subagent/SettingsSave/Live/Notice tests of those six packages: ok.
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui,
GOOS=windows go build: ok.
- desktop-subagent-model.test.cjs now runs at 1100 and 420 (was 560):
20/20, chromium and webkit, en zh zh-TW ja de. codex-subagent-model,
desktop-tiers, routing-purpose-state, routing-request-model,
routing-sealed-task: all pass in both engines.
- usage-fold's "29 accounts" case passed 4 of 4 alone in WebKit here.
- Not repeated: the author's built-binary run; a real Claude Desktop or
Cowork; Linux and Windows machines.
Decisions on the author's questions: Live is kept as named, and Codex's
subagent model is left as it is; a subagent's tool-less helper calls stay
on the model they asked for, being Claude Code's own housekeeping rather
than the subagent's work.
Reported-by: Koohoko (#2081)
612 lines
21 KiB
Go
612 lines
21 KiB
Go
package agent
|
|
|
|
// Claude Desktop runs on a third-party gateway in its "3p" deployment mode:
|
|
// no Anthropic sign-in, and its Code and Cowork tabs work on any plan (a
|
|
// Free account signed in sees only "Get Claude Code" there). The mode is
|
|
// claude_desktop_config.json's deploymentMode, in its own folder and in
|
|
// Claude-3p beside it; the gateway is a profile in Claude-3p/configLibrary,
|
|
// the one _meta.json applies:
|
|
//
|
|
// Claude/claude_desktop_config.json {"deploymentMode":"3p",…}
|
|
// Claude-3p/claude_desktop_config.json {"deploymentMode":"3p",…}
|
|
// Claude-3p/configLibrary/<id>.json {"inferenceProvider":"gateway",
|
|
// "inferenceGatewayBaseUrl":"http://127.0.0.1:3425",
|
|
// "inferenceGatewayApiKey":"magpie-claude-desktop",
|
|
// "inferenceGatewayAuthScheme":"bearer",
|
|
// "disableDeploymentModeChooser":true,"coworkEgressAllowedHosts":["*"]}
|
|
// Claude-3p/configLibrary/_meta.json {"appliedId":"<id>",
|
|
// "entries":[…,{"id":"<id>","name":"magpie"}]}
|
|
//
|
|
// as CC Switch writes them (claude_desktop_config.rs). The folders are in
|
|
// ~/Library/Application Support on macOS, %LOCALAPPDATA% on Windows (the
|
|
// MSIX package's LocalCache\Local for a packaged Desktop) and
|
|
// $XDG_CONFIG_HOME on Linux, as internal/desktopdir finds them. A
|
|
// packaged Desktop gets all of it twice, in the package's folders and the
|
|
// real ones: up to 2.x it reads the package's copy, from 2.31226 the real
|
|
// %LOCALAPPDATA%\Claude-3p (desktopdir.Sets). With no inferenceModels Desktop lists the
|
|
// gateway's /v1/models, which the gateway gives it by ids it keeps (see
|
|
// gateway/desktop.go). Desktop reads all this at start-up only.
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/desktopdir"
|
|
"github.com/yetone/magpie/internal/edit"
|
|
"github.com/yetone/magpie/internal/gateway"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// desktopProfileID is magpie's profile in Desktop's configLibrary: a
|
|
// UUID like the ones Desktop makes, its last part "magpie" in hex.
|
|
const desktopProfileID = "00000000-0000-4000-8000-6d6167706965"
|
|
|
|
// desktopPaths are the files and folders magpie writes for Claude Desktop.
|
|
type desktopPaths struct {
|
|
key string // the stash's keys end with it: "" or ".package"
|
|
dir, dir3p string // Claude, Claude-3p
|
|
config, config3p string // their claude_desktop_config.json
|
|
library, meta, prof string // configLibrary, its _meta.json, magpie's profile
|
|
}
|
|
|
|
func desktopPathsOf(dir, dir3p string) desktopPaths {
|
|
lib := filepath.Join(dir3p, "configLibrary")
|
|
return desktopPaths{
|
|
dir: dir, dir3p: dir3p,
|
|
config: filepath.Join(dir, "claude_desktop_config.json"),
|
|
config3p: filepath.Join(dir3p, "claude_desktop_config.json"),
|
|
library: lib, meta: filepath.Join(lib, "_meta.json"), prof: filepath.Join(lib, desktopProfileID+".json"),
|
|
}
|
|
}
|
|
|
|
// desktopDirs are Desktop's Claude and Claude-3p folders on goos: the ones
|
|
// magpie writes deploymentMode and its profile into (desktopdir.Find).
|
|
func desktopDirs(goos, home string, getenv func(string) string) (string, string) {
|
|
d := desktopdir.Find(goos, home, getenv)
|
|
return d.Mode, d.ThreeP
|
|
}
|
|
|
|
// desktopSets are those of every set of Desktop's folders, Find's first:
|
|
// for a packaged Desktop the package's and the real ones, each with its
|
|
// own stash.
|
|
func desktopSets(goos, home string, getenv func(string) string) []desktopPaths {
|
|
var out []desktopPaths
|
|
for _, d := range desktopdir.Sets(goos, home, getenv) {
|
|
p := desktopPathsOf(d.Mode, d.ThreeP)
|
|
if d.Package != "" {
|
|
p.key = ".package"
|
|
}
|
|
out = append(out, p)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// DesktopConfigs3p are the claude_desktop_config.json files Claude Desktop
|
|
// reads in its 3p mode: there its whole userData is Claude-3p, its MCP
|
|
// servers too (%LOCALAPPDATA%\Claude-3p on Windows, and the MSIX package's;
|
|
// Claude-3p beside Claude elsewhere).
|
|
func DesktopConfigs3p(home string) []string {
|
|
var out []string
|
|
for _, p := range desktopSets(desktopdir.OS, home, os.Getenv) {
|
|
out = append(out, p.config3p)
|
|
}
|
|
return out
|
|
}
|
|
|
|
func claudeDesktop(home string) *Agent {
|
|
sets := desktopdir.Sets(desktopdir.OS, home, os.Getenv)
|
|
ps := desktopSets(desktopdir.OS, home, os.Getenv)
|
|
p := ps[0]
|
|
return &Agent{
|
|
ID: "claude-desktop", Name: "Claude Desktop", Icon: "claude-color", Aliases: []string{"claude-app"},
|
|
Dir: p.dir, Path: p.config,
|
|
detect: func() bool {
|
|
// its own data (%APPDATA%\Claude on Windows, or the MSIX
|
|
// package's), the folder magpie writes or Claude-3p
|
|
for _, s := range sets {
|
|
for _, d := range s.All() {
|
|
if isDir(d) {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
// installed on Windows and not yet opened: none of them yet
|
|
return desktopdir.Installed(desktopdir.OS, home, os.Getenv)
|
|
},
|
|
Notice: func() string {
|
|
if desktopWiredAny(ps) {
|
|
return noticeClaudedesktop1.String()
|
|
}
|
|
return noticeClaudedesktop2.String()
|
|
},
|
|
Check: func() string {
|
|
if !desktopWiredAny(ps) {
|
|
return ""
|
|
}
|
|
for _, p := range desktopRead(ps) {
|
|
if msg := desktopCheck(p); msg != "" {
|
|
if len(ps) > 1 {
|
|
msg += " (" + p.dir3p + ")"
|
|
}
|
|
return msg
|
|
}
|
|
}
|
|
return ""
|
|
},
|
|
Fields: append([]Field{{
|
|
Key: "provider", Label: "provider",
|
|
Get: func() string {
|
|
if desktopWiredAny(ps) {
|
|
return magpieID
|
|
}
|
|
return ""
|
|
},
|
|
Set: func(v string) error {
|
|
on := desktopOn
|
|
if v == "" {
|
|
on = desktopOff
|
|
}
|
|
desktopAdoptStash(ps)
|
|
for _, p := range ps {
|
|
if err := on(p); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
// its Code tab is Claude Code, told what Desktop's ids for
|
|
// magpie's models can do while that one runs on magpie
|
|
_ = claude(home).Sync()
|
|
return nil
|
|
},
|
|
Options: func(map[string]string) []Option {
|
|
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)"}}
|
|
},
|
|
}}, append(desktopTierFields(ps), desktopSubagentField(ps))...),
|
|
}
|
|
}
|
|
|
|
// desktopRead are the sets of Desktop's folders whose wiring counts: the
|
|
// one whose Claude-3p Desktop ran in last, which is where it reads
|
|
// deploymentMode and the gateway from, or every set when it has run in
|
|
// none. Magpie writes both of a packaged Desktop's sets, not knowing the
|
|
// build: 2.31226's MSIX keeps Claude-3p out of the package
|
|
// (ExcludedDirectory), so the package's copy is one Desktop no longer
|
|
// reads, and one gone from there (emptied by an update) isn't Desktop off
|
|
// magpie (dumplings on Discord: "配置已变更" while Desktop ran on magpie).
|
|
func desktopRead(ps []desktopPaths) []desktopPaths {
|
|
var newest time.Time
|
|
var at []desktopPaths
|
|
for _, p := range ps {
|
|
if t := desktopdir.LastRun(p.dir3p); t.After(newest) {
|
|
newest, at = t, []desktopPaths{p}
|
|
}
|
|
}
|
|
if at == nil {
|
|
return ps
|
|
}
|
|
return at
|
|
}
|
|
|
|
// desktopCheck is what keeps one set of Desktop's folders off magpie's
|
|
// gateway, "" for nothing.
|
|
func desktopCheck(p desktopPaths) string {
|
|
m, _ := edit.GetJSON(p.config, "deploymentMode")
|
|
m3, _ := edit.GetJSON(p.config3p, "deploymentMode")
|
|
if m != "3p" || m3 != "3p" {
|
|
return "Claude Desktop's deploymentMode (claude_desktop_config.json) is no longer 3p, so it signs in with Anthropic rather than using magpie"
|
|
}
|
|
if id, _ := edit.GetJSON(p.meta, "appliedId"); id != desktopProfileID {
|
|
return "Claude Desktop uses another gateway configuration now (appliedId in configLibrary/_meta.json), not magpie's"
|
|
}
|
|
return wiringOff("Claude Desktop", p.prof, func(k string) (string, bool) { return edit.GetJSON(p.prof, k) },
|
|
"inferenceGatewayBaseUrl", gateway.URL(), "inferenceGatewayApiKey", agentKey("claude-desktop"))
|
|
}
|
|
|
|
// 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(ps []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 !desktopWiredAny(ps) {
|
|
return nil
|
|
}
|
|
return viaMagpie("claude-desktop", "")
|
|
},
|
|
})
|
|
}
|
|
return fields
|
|
}
|
|
|
|
// desktopSubagentField picks the model every subagent turn in Desktop's
|
|
// Code tab and Cowork runs on, whatever its lead or tier asked for. It
|
|
// writes nothing to Desktop's config, which has no key for it, and the
|
|
// Claude Code it runs ignores CLAUDE_CODE_SUBAGENT_MODEL in ~/.claude
|
|
// while Desktop manages its provider: it is magpie's setting
|
|
// (settings.DesktopSubagentModel), which the gateway reads on each
|
|
// request (gateway desktopSubagentPick), so it is Live and a change needs
|
|
// no restart of Desktop. Labelled as Codex's "subagent model", it gets the
|
|
// same square on the Agents page. A Desktop alias picked is kept by its
|
|
// catalog id.
|
|
func desktopSubagentField(ps []desktopPaths) Field {
|
|
return Field{
|
|
Key: "subagent_model", Label: "subagent model", Quiet: true, Live: true,
|
|
Get: provider.DesktopSubagentModel,
|
|
Set: func(v string) error {
|
|
return provider.SetDesktopSubagentModel(gateway.DesktopCatalogID(v))
|
|
},
|
|
Options: func(map[string]string) []Option {
|
|
if !desktopWiredAny(ps) {
|
|
return nil
|
|
}
|
|
return viaMagpie("claude-desktop", "")
|
|
},
|
|
}
|
|
}
|
|
|
|
// desktopWired: _meta.json lists magpie's profile.
|
|
func desktopWired(p desktopPaths) bool {
|
|
entries, _, err := desktopEntries(p.meta)
|
|
return err == nil && slices.ContainsFunc(entries, desktopOurs)
|
|
}
|
|
|
|
// desktopWiredAny: any set of Desktop's folders is on magpie.
|
|
func desktopWiredAny(ps []desktopPaths) bool { return slices.ContainsFunc(ps, desktopWired) }
|
|
|
|
// desktopEntries reads _meta.json's entries, and whether the file is there.
|
|
func desktopEntries(meta string) ([]json.RawMessage, bool, error) {
|
|
b, err := edit.Read(meta)
|
|
if err != nil || b == nil {
|
|
return nil, false, err
|
|
}
|
|
if len(bytes.TrimSpace(b)) == 0 {
|
|
return nil, true, nil
|
|
}
|
|
var doc map[string]json.RawMessage
|
|
if err := json.Unmarshal(b, &doc); err != nil {
|
|
return nil, true, errors.New(meta + ": not a JSON object")
|
|
}
|
|
var entries []json.RawMessage
|
|
if raw, ok := doc["entries"]; ok {
|
|
if err := json.Unmarshal(raw, &entries); err != nil {
|
|
return nil, true, errors.New(meta + ": entries is not a list")
|
|
}
|
|
}
|
|
return entries, true, nil
|
|
}
|
|
|
|
func desktopEntryID(raw json.RawMessage) string {
|
|
var e struct {
|
|
ID string `json:"id"`
|
|
}
|
|
json.Unmarshal(raw, &e)
|
|
return e.ID
|
|
}
|
|
|
|
func desktopOurs(raw json.RawMessage) bool { return desktopEntryID(raw) == desktopProfileID }
|
|
|
|
// desktopObject: the file is missing, empty or a JSON object — one magpie
|
|
// can edit without losing anything.
|
|
func desktopObject(path string) error {
|
|
b, err := edit.Read(path)
|
|
if err != nil || len(bytes.TrimSpace(b)) == 0 {
|
|
return err
|
|
}
|
|
var m map[string]json.RawMessage
|
|
if json.Unmarshal(b, &m) != nil {
|
|
return errors.New(path + ": not a JSON object")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// The stash keeps what Desktop had before magpie: each file's
|
|
// deploymentMode ("" when it had none), the profile applied, and the
|
|
// files and folders magpie made, so switching off puts all of it back.
|
|
// It also keeps magpie's profile as it was when switched off, the
|
|
// settings the user made in it from Desktop's window among them, so
|
|
// switching on again brings them back (#2035).
|
|
// A package's folders keep theirs under the same keys ending in ".package".
|
|
const (
|
|
desktopStashed = "claude-desktop.on"
|
|
desktopMode = "claude-desktop.mode"
|
|
desktopMode3p = "claude-desktop.mode3p"
|
|
desktopApplied = "claude-desktop.applied"
|
|
desktopMade = "claude-desktop.made"
|
|
desktopProfile = "claude-desktop.profile"
|
|
)
|
|
|
|
var desktopStashKeys = []string{desktopStashed, desktopMode, desktopMode3p, desktopApplied, desktopMade, desktopProfile}
|
|
|
|
// desktopAdoptStash moves the stash a packaged Desktop's folders got
|
|
// before they had keys of their own (when magpie wrote only one set) onto
|
|
// the package's keys: the stash is theirs when the package's folders are
|
|
// on magpie and the real ones aren't.
|
|
func desktopAdoptStash(ps []desktopPaths) {
|
|
var pkg, real *desktopPaths
|
|
for i := range ps {
|
|
if ps[i].key == ".package" {
|
|
pkg = &ps[i]
|
|
} else {
|
|
real = &ps[i]
|
|
}
|
|
}
|
|
if pkg == nil || real == nil || !desktopWired(*pkg) || desktopWired(*real) {
|
|
return
|
|
}
|
|
m := stashLoad()
|
|
if m[desktopStashed] == "" || m[desktopStashed+pkg.key] != "" {
|
|
return
|
|
}
|
|
kv := map[string]string{}
|
|
for _, k := range desktopStashKeys {
|
|
kv[k+pkg.key], kv[k] = m[k], ""
|
|
}
|
|
stash(kv)
|
|
}
|
|
|
|
// desktopOn points Claude Desktop at the gateway: deploymentMode 3p in both
|
|
// config files, magpie's profile written and applied. Every other key, and
|
|
// every other profile, stays as it is.
|
|
func desktopOn(p desktopPaths) error {
|
|
// nothing is written unless every file can be
|
|
for _, f := range []string{p.config, p.config3p, p.prof} {
|
|
if err := desktopObject(f); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
entries, _, err := desktopEntries(p.meta)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
wired := slices.ContainsFunc(entries, desktopOurs)
|
|
if !wired {
|
|
var made []string
|
|
for _, f := range []string{p.dir, p.config, p.dir3p, p.config3p, p.library, p.meta} {
|
|
if _, err := os.Stat(f); err != nil {
|
|
made = append(made, f)
|
|
}
|
|
}
|
|
mode, _ := edit.GetJSON(p.config, "deploymentMode")
|
|
mode3p, _ := edit.GetJSON(p.config3p, "deploymentMode")
|
|
applied, _ := edit.GetJSON(p.meta, "appliedId")
|
|
k := p.key
|
|
forget(desktopMode+k, desktopMode3p+k, desktopApplied+k, desktopMade+k)
|
|
stash(map[string]string{desktopStashed + k: "1", desktopMode + k: mode, desktopMode3p + k: mode3p,
|
|
desktopApplied + k: applied, desktopMade + k: strings.Join(made, "\n")})
|
|
}
|
|
|
|
// the profile: the gateway's address and key set, Desktop's own
|
|
// settings in it (the user's, from its window) kept, and those it had
|
|
// when switched off put back (#2035)
|
|
if b, _ := edit.Read(p.prof); len(bytes.TrimSpace(b)) == 0 {
|
|
if err := os.MkdirAll(p.library, 0o755); err != nil {
|
|
return err
|
|
}
|
|
was := []byte("{}\n")
|
|
if kept := unstash(desktopProfile + p.key); kept != "" && desktopObjectBytes([]byte(kept)) {
|
|
was = []byte(kept)
|
|
} else if own := desktopOwnGatewayProfile(p); own != nil {
|
|
was = own
|
|
}
|
|
if err := os.WriteFile(p.prof, was, 0o600); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
kvs := []edit.KV{
|
|
{Path: "inferenceProvider", Value: "gateway"},
|
|
{Path: "inferenceGatewayBaseUrl", Value: gateway.URL()},
|
|
{Path: "inferenceGatewayApiKey", Value: agentKey("claude-desktop")},
|
|
{Path: "inferenceGatewayAuthScheme", Value: "bearer"},
|
|
}
|
|
// policies seeded once: the user may tighten them in Desktop
|
|
if _, ok := edit.GetJSON(p.prof, "disableDeploymentModeChooser"); !ok {
|
|
kvs = append(kvs, edit.KV{Path: "disableDeploymentModeChooser", Value: true})
|
|
}
|
|
if _, ok := edit.GetJSON(p.prof, "coworkEgressAllowedHosts"); !ok {
|
|
kvs = append(kvs, edit.KV{Path: "coworkEgressAllowedHosts", Value: []string{"*"}})
|
|
}
|
|
if err := edit.SetJSON(p.prof, kvs...); err != nil {
|
|
return err
|
|
}
|
|
|
|
// _meta.json: magpie's entry (where it was, if it was), applied
|
|
if !wired {
|
|
entry, _ := json.Marshal(map[string]string{"id": desktopProfileID, "name": "magpie"})
|
|
entries = append(entries, entry)
|
|
if err := edit.SetJSON(p.meta, edit.KV{Path: "entries", Value: entries}); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if err := edit.SetJSON(p.meta, edit.KV{Path: "appliedId", Value: desktopProfileID}); err != nil {
|
|
return err
|
|
}
|
|
|
|
// the mode last: until here Desktop still starts as it did
|
|
for _, f := range []string{p.config3p, p.config} {
|
|
if err := edit.SetJSON(f, edit.KV{Path: "deploymentMode", Value: "3p"}); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// desktopOff puts Claude Desktop back as it was before magpie: each
|
|
// deploymentMode as it was (gone where there was none), the profile it had
|
|
// applied, magpie's profile and entry removed, and the files and folders
|
|
// magpie made gone again if nothing else went into them.
|
|
func desktopOff(p desktopPaths) error {
|
|
entries, _, err := desktopEntries(p.meta)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
k := p.key
|
|
stashed := unstash(desktopStashed+k) != ""
|
|
mode, mode3p, applied := unstash(desktopMode+k), unstash(desktopMode3p+k), unstash(desktopApplied+k)
|
|
var made []string
|
|
if m := unstash(desktopMade + k); m != "" {
|
|
made = strings.Split(m, "\n")
|
|
}
|
|
if !stashed && !slices.ContainsFunc(entries, desktopOurs) {
|
|
return nil
|
|
}
|
|
|
|
for f, was := range map[string]string{p.config: mode, p.config3p: mode3p} {
|
|
if cur, _ := edit.GetJSON(f, "deploymentMode"); cur != "3p" {
|
|
continue // changed since, by Desktop or the user: theirs
|
|
}
|
|
if was != "" {
|
|
err = edit.SetJSON(f, edit.KV{Path: "deploymentMode", Value: was})
|
|
} else {
|
|
err = edit.DelJSON(f, "deploymentMode")
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
if slices.ContainsFunc(entries, desktopOurs) {
|
|
entries = slices.DeleteFunc(entries, desktopOurs)
|
|
if len(entries) == 0 && slices.Contains(made, p.meta) {
|
|
err = edit.DelJSON(p.meta, "entries")
|
|
} else {
|
|
if entries == nil {
|
|
entries = []json.RawMessage{}
|
|
}
|
|
err = edit.SetJSON(p.meta, edit.KV{Path: "entries", Value: entries})
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if id, _ := edit.GetJSON(p.meta, "appliedId"); id == desktopProfileID {
|
|
// the profile applied before, if it is still there, else the first
|
|
// one left, else none
|
|
next := ""
|
|
if applied != "" && applied != desktopProfileID && slices.ContainsFunc(entries, func(e json.RawMessage) bool { return desktopEntryID(e) == applied }) {
|
|
next = applied
|
|
} else if len(entries) > 0 {
|
|
next = desktopEntryID(entries[0])
|
|
}
|
|
if next != "" {
|
|
err = edit.SetJSON(p.meta, edit.KV{Path: "appliedId", Value: next})
|
|
} else {
|
|
err = edit.DelJSON(p.meta, "appliedId")
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
// the profile goes, and what is in it is kept for the next on: the
|
|
// settings the user made in it are theirs (#2035)
|
|
if b, err := os.ReadFile(p.prof); err == nil && desktopObjectBytes(b) && !desktopEmpty(b) {
|
|
stash(map[string]string{desktopProfile + k: string(b)})
|
|
}
|
|
if err := os.Remove(p.prof); err != nil && !errors.Is(err, os.ErrNotExist) {
|
|
return err
|
|
}
|
|
|
|
// what magpie made, deepest first: a file only if it is an empty
|
|
// object now, a folder only if it is empty
|
|
for _, f := range slices.Backward(made) {
|
|
st, err := os.Stat(f)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
if st.IsDir() {
|
|
os.Remove(f)
|
|
continue
|
|
}
|
|
if b, _ := os.ReadFile(f); desktopEmpty(b) {
|
|
os.Remove(f)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// desktopOwnGatewayProfile is the profile the user made themselves in
|
|
// Desktop's window for magpie's gateway, the one applied before magpie
|
|
// applied its own: its settings (chat tab, default effort, allowed hosts
|
|
// and whatever Desktop adds) start magpie's profile, so switching on
|
|
// doesn't trade them for magpie's defaults (#2035). A profile for another
|
|
// gateway, Bedrock or Vertex is not one: its models and settings are for
|
|
// somewhere else. nil when there is none.
|
|
func desktopOwnGatewayProfile(p desktopPaths) []byte {
|
|
id, _ := edit.GetJSON(p.meta, "appliedId")
|
|
if id == desktopProfileID {
|
|
id = unstash(desktopApplied + p.key)
|
|
}
|
|
if id == "" || id == desktopProfileID || filepath.Base(id) != id || strings.HasPrefix(id, ".") {
|
|
return nil
|
|
}
|
|
b, err := os.ReadFile(filepath.Join(p.library, id+".json"))
|
|
if err != nil || !desktopObjectBytes(b) {
|
|
return nil
|
|
}
|
|
var prof struct {
|
|
Provider string `json:"inferenceProvider"`
|
|
BaseURL string `json:"inferenceGatewayBaseUrl"`
|
|
}
|
|
if json.Unmarshal(b, &prof) != nil || prof.Provider != "gateway" || !desktopIsOurGateway(prof.BaseURL) {
|
|
return nil
|
|
}
|
|
return b
|
|
}
|
|
|
|
// desktopIsOurGateway: u is magpie's gateway, by its port on this machine
|
|
// (127.0.0.1, localhost or ::1, with or without /v1).
|
|
func desktopIsOurGateway(u string) bool {
|
|
a, err := url.Parse(strings.TrimSpace(u))
|
|
if err != nil || a.Port() == "" {
|
|
return false
|
|
}
|
|
ours, err := url.Parse(gateway.URL())
|
|
if err != nil || a.Port() != ours.Port() {
|
|
return false
|
|
}
|
|
h := a.Hostname()
|
|
if h == ours.Hostname() || h == "localhost" {
|
|
return true
|
|
}
|
|
ip := net.ParseIP(h)
|
|
return ip != nil && ip.IsLoopback()
|
|
}
|
|
|
|
// desktopObjectBytes: b is a JSON object.
|
|
func desktopObjectBytes(b []byte) bool {
|
|
var m map[string]json.RawMessage
|
|
return json.Unmarshal(b, &m) == nil && m != nil
|
|
}
|
|
|
|
func desktopEmpty(b []byte) bool {
|
|
var m map[string]json.RawMessage
|
|
return json.Unmarshal(b, &m) == nil && len(m) == 0
|
|
}
|
|
|
|
// what claudedesktop says after a change (notice.go)
|
|
var (
|
|
noticeClaudedesktop1 = newNotice("Claude Desktop reads this at start-up — quit and reopen it to run on magpie (Code and Cowork, no Anthropic sign-in).")
|
|
noticeClaudedesktop2 = newNotice("Claude Desktop reads this at start-up — quit and reopen it to sign in with Anthropic again.")
|
|
)
|