From a6d84e13a9eeb7cdc07cc97fd2aa777d7690f0ad Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 12 Nov 2026 01:27:46 +0800 Subject: [PATCH] agent: Claude Desktop can use this computer's LAN HTTPS address for SSH remote sessions (zyc-bit on X, #4546) Desktop's built-in SSH remote sessions hand the profile's gateway address and key to the remote host. magpie wrote 127.0.0.1 and this computer's own key there, so the host refused it (provider_loopback; a non-loopback address must be https), the gateway turned the key away from another machine, and 3p mode's sshHostAllowlist (empty) allowed no host. Desktop's row gets a "gateway" picker, drawn only while LAN sharing is on and an address of this computer is https (gateway.LANURLs: HTTPS on, or MAGPIE_PUBLIC_URL): "This computer" (default, loopback) or that address. The pick is settings.DesktopGateway (carried by the settings save, kept by KeepOwn). desktopOn / desktopCheck / desktopKeyApplied write and compare desktopGateway() and the key at it (agentKeyAt: the sharing key). On a non-loopback address sshHostAllowlist is seeded once with ["*"] (desktopSeedOnce; the user may narrow it, never rewritten). The pick holds only while it is still one of the https addresses; Agent.Gateway is desktopGateway, so Rekey (after the sharing toggle, and now after the HTTPS toggle) sets Desktop again, back to loopback when sharing goes off. desktopIsOurGateway takes this computer's LAN addresses; realReachProbe no longer verifies the certificate (magpie's CA is not trusted on this computer), which read a LAN https address as unreachable. Run (mica, sandbox HOME): go test ./internal/agent ./internal/settings ./internal/settingsapi ok; ./internal/gui ok except TestPanelHiddenByWailsMarksPageOutOfSight, flaky the same on origin/main fc615339f (#5322); go vet darwin, linux (nogui) and windows on the three packages; gofmt clean. TestDesktopPointedAtLANHTTPS is red when desktopOn writes loopback and when the key is not the sharing key. GUI desktop-gateway-address.test.cjs 20/20 (chromium + webkit, en zh zh-TW ja de, 1100 and 420px), red 20/20 with the field left in the "nothing to pick" filter's absence; i18n-keys, desktop-*, click-scroll files. Not tried: a real Desktop SSH session to a remote host, the remote host trusting magpie's CA (it must, or use an imported certificate), the real Claude Desktop app. Windows and Linux runs only vetted. --- docs/subsystems/agent-wiring.md | 1 + internal/agent/claudedesktop.go | 93 +++++++----- internal/agent/claudedesktop_gateway.go | 136 ++++++++++++++++++ internal/agent/claudedesktop_gateway_test.go | 87 +++++++++++ internal/agent/reach.go | 5 +- internal/agent/rewire.go | 4 +- internal/gui/assets/app.js | 2 +- internal/gui/https.go | 5 + internal/gui/settings_keep_test.go | 1 + .../tests/desktop-gateway-address.test.cjs | 100 +++++++++++++ internal/settings/settings.go | 22 ++- internal/settingsapi/settingsapi.go | 1 + 12 files changed, 417 insertions(+), 40 deletions(-) create mode 100644 internal/agent/claudedesktop_gateway.go create mode 100644 internal/agent/claudedesktop_gateway_test.go create mode 100644 internal/gui/tests/desktop-gateway-address.test.cjs diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 5ba240d27..1d7565011 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -181,6 +181,7 @@ something else shows up as drift. - Claude Desktop's tiers also write magpie's profile's `inferenceModels` (`desktopSyncModels` in [`claudedesktop_models.go`](../../internal/agent/claudedesktop_models.go)), the list `gateway.DesktopInferenceModels` gives (see [gateway routing](gateway-routing.md)): on a tier's `Set`, as Desktop comes on magpie, and on the agent's `Sync`, so a provider saved or removed reaches it through `SyncCatalog`. Desktop 4.4212 reads no `/v1/models` while such a list has no bare tier word as a name (`adminListObviatesDiscovery` in its app.asar) and names an entry by its `labelOverride`, else its catalog's name, else the id, so every entry carries the `display_name` `/v1/models` gives its row as `labelOverride`; without it every `mythos-magpie-` read as that id once a tier was picked (chengming0v0 on Discord, `TestDesktopInferenceModelsNamed`), and a catalog-named Claude model reads as that name too ("Opus 5.5 · ") while the list is written. It is written through temp-and-rename and only when it changed, and taken away when no tier is picked. The list is magpie's only while its hash is one magpie recorded (`desktopModelsMark` in the stash, the next hash recorded before each write); any other list, the user's own or one carried from their own gateway profile, is never written over or taken away. A pick that runs as a Claude model (`behavesAs`) is told its own window in Claude Code's `modelSettings` (`claudeBudget.behaves`), since Claude Code would otherwise run it at that Claude model's. A model picked for two tiers is listed for the second by an id of its own (`gateway.DesktopTierAliases`), and Claude Code's settings carry that id's window and reasoning levels as they carry the first's (`claudeCapabilities`, the `modelSettings` budgets; `TestClaudeDesktopModelsSharedTier`, `TestClaudeCapabilitiesDesktopSharedTier`). Desktop reads the list as it starts. Not tried against a real Desktop 4.29 or later; a Desktop below 2 (no mythos word) is given the mythos ids `/v1/models` gives 2 and up. `TestClaudeDesktopModelsList`. - Claude Desktop's "subagent effort" (`desktopSubagentEffortField`, `settings.DesktopSubagentEffort`) is also Quiet and Live. Default keeps the effort the request asks for, including disabled thinking; it never selects a new default. A picked level works independently of the subagent model: no model pick, the same model and an unavailable model pick all still take the effort. While wired, the field offers the selected model's levels, or the standard levels when its model is inherited or unavailable; a model marked reasonless offers none. The stored pick survives model changes. A disconnected preference can be saved or cleared without connecting Desktop or showing restart advice, so profile restoration and Disconnect can restore a value saved before connecting; reconnect returns to the last live pick. `subEffortTitle` gives Desktop the Claude Code default explanation; Codex's default meaning is unchanged. The gateway fits each attempt to its actual model and preserves fixed group-member efforts (see [gateway routing](gateway-routing.md)). - Claude Desktop picks its userData in its main process before any window opens: while a 3p configuration is applied and `deploymentMode` isn't `"1p"`, it is `Claude-3p` (Desktop 2.7032's `index.pre.js`, `app.setPath("userData", …-3p)`). So turning Desktop onto magpie shows none of the chats, projects and Code sessions of the Anthropic sign-in, which stay in `Claude` (xgddm88 on X: 之前的工程和会话记录全没了). magpie writes nothing in `Claude` but `deploymentMode` in its `claude_desktop_config.json`, and reads its `config.json` for the language; Off brings that history back. A row not yet connected says so before it is turned on (`CONNECT_BEFORE` in `app.js`), the opened row once it is on (`CONNECT_COST`), and the notice after each change (`noticeClaudedesktop3`, `noticeClaudedesktop4`; `TestClaudeDesktopKeepsTheSignedInHistory`, `desktop-history.test.cjs`). Opus beside the gateway's other models in that mode comes from a Claude subscription added in magpie. With `disableDeploymentModeChooser` unset Desktop's login screen would offer Claude.ai sign-in too; magpie still seeds it (as CC Switch does), so the way back is Off. The drift check asks Desktop's own question (`desktop3p`, `m4` in 4.4212's and 2.7032's `index.pre.js`): Desktop is off magpie only when Claude-3p's `deploymentMode` is `"1p"` and the applied profile leaves the chooser on. The `Claude` folder's `deploymentMode` isn't read, and Desktop 4.4212 deletes Claude-3p's itself (a stored `"1p"` with no claude.ai sign-in is dropped at start, `deploymentMode written { mode: undefined }`), so a missing one is still magpie (dev_quj on X; `TestClaudeDesktopModeAsDesktopReadsIt`). +- Claude Desktop's gateway address (`gateway` field, `DesktopGateway` in settings, [`claudedesktop_gateway.go`](../../internal/agent/claudedesktop_gateway.go); zyc-bit and ZYar-er on X, #4546). Desktop's built-in SSH remote sessions hand the profile's address and key to the remote host, which refuses a loopback address (`provider_loopback`), a non-https one off loopback ("must use https (or http on loopback)") and any host the profile's `sshHostAllowlist` (empty in 3p mode) doesn't list. So while LAN sharing is on and an address of this computer is https (`gateway.LANURLs`, HTTPS on or a `MAGPIE_PUBLIC_URL`), the row offers it beside "This computer"; the profile then holds that address and the sharing key (`agentKeyAt`), and `sshHostAllowlist` is seeded once with `["*"]` (`desktopSeedOnce`; the user may narrow it, magpie never writes it again). The pick holds only while it is still one of `desktopLANURLs()` (the first one where the network moved, loopback with sharing off): `Agent.Gateway` is `desktopGateway`, and `Rekey` runs after the sharing and HTTPS toggles, which sets Desktop again. `desktopIsOurGateway` takes this computer's own LAN addresses too, and `realReachProbe` doesn't verify a certificate (magpie's CA isn't trusted here). The remote host must trust magpie's CA (or use an imported certificate) for Desktop's requests from there. (`TestDesktopPointedAtLANHTTPS`, `desktop-gateway-address.test.cjs`) - Claude Desktop's 3p mode runs in a userData of its own (`Claude-3p`), whose `config.json` (Desktop's own settings, not `claude_desktop_config.json`) starts with no `locale`, so Desktop on magpie came up in the system's language rather than the one picked signed in with Anthropic (memory and Osal on Discord). Turning Desktop onto magpie copies that one key, `locale`, from the signed-in userData's `config.json` (`Claude`, `%APPDATA%\Claude` on Windows, the first set's before the others) into `Claude-3p/config.json` when that file is missing or a JSON object without one (`desktopCarryLocale` in [`claudedesktop.go`](../../internal/agent/claudedesktop.go)); only a name Desktop takes for a catalog is carried. A `locale` already in `Claude-3p`, Desktop's or set by hand, is never written over, and no other key of that file is ever written. Off removes the file only when magpie made it and it still holds nothing but the language carried (`TestClaudeDesktopCarriesTheLanguage`, `TestClaudeDesktopKeepsThe3pLanguage`, `TestClaudeDesktopUserEditsThenReapply`). Desktop shows the language only where its 3p window has that catalog: the window is Desktop's bundled UI (`Resources/ion-dist`, 11 catalogs and no Chinese in 2.7032, 2.9939, 3.6556.2, 4.4212.0 and 4.23118.0 (11-05; packed as `Resources/ion-dist.asar` from 4.4212.0; 4.23118.0's `frame-shell` catalogs in `app.asar` are the same 11), while 3.6556.2's main process has `zh-Hans` and `zh-Hant` for the signed-in window). On every start that window asks the main process for its own pick (`requestLocaleChange`: its localStorage, else `navigator.languages` mapped onto its 11, else `en-US`), and the main process writes it into `Claude-3p/config.json`. So a Chinese `locale` there, carried or set by hand, is `en-US` again after each start, written by Desktop and not by magpie (Dx25 on Discord, Windows); nothing magpie writes can keep it. So the GUI says it to a Chinese reader: Claude Desktop's opened row on Agents has a line that Desktop on magpie is Anthropic's gateway window, with no Chinese, and that its Chinese comes back once disconnected, and the switch-on notice says the same in Chinese (GZXYMH on X, `desktop-lang.test.cjs`). - Claude Desktop's sessions (Code and Cowork, `claude-code-sessions` and `local-agent-mode-sessions`) are kept in the userData Desktop runs in, keyed by account and organization (the claude.ai login signed in; in 3p the install id in `ant-did` and the profile's organization, both stable). So on magpie, in `Claude-3p`, the sessions made signed in with Anthropic are out of sight but untouched in `Claude`, and they show again when Desktop is switched back (lambdua on X: "切换账号,对话都不见"); claude.ai chats live on Anthropic's servers and 3p never shows them as they are. magpie never writes or removes a session. Desktop imports them itself (Settings → Import: the signed-in userData, `~/.claude/projects`, other `Claude*` folders, and Claude.ai's own chats and projects, through a Claude.ai sign-in in the importer (`arm: "direct"`, `remotePull` in 4.16336's `getImportCapabilities`) or its data export zip), copying under new ids that go on on the gateway and leaving the originals, but in 3p only when the profile's policy `claudeAiImport.enabled` is true (off by default, 3p only, from 1.28929.0). magpie's profile gets `"claudeAiImport":{"enabled":true,"bannerBehavior":"detect"}` once per folder set (`desktopSeedImport`, marked in the stash as `claude-desktop.import`): on the switch on and, for a Desktop already on magpie, from `Sync` at magpie's start. A `claudeAiImport` already there is kept, and one the user removes is not written again (`TestClaudeDesktopOffersItsSessionImport`). The opened row and the notice after On point there (`noticeClaudedesktop5`; Jacky_yyyyyyyy on X asked to go on with the earlier chats on magpie). - Claude Desktop's 3p mode reads its MCP servers (Settings → Developer, its connector list) from `Claude-3p/claude_desktop_config.json`, a file of its own, so on magpie the servers the user added signed in with Anthropic, in `Claude/claude_desktop_config.json`, were gone from the list (aa86222 on Discord: connectors didn't sync). Turning Desktop onto magpie copies each of those `mcpServers` entries that `Claude-3p` has none of the same name for (`desktopCarryMCP` in [`claudedesktop.go`](../../internal/agent/claudedesktop.go)); one of that name already there, the user's or the Library's (which writes both files), stays. `Sync` does it once for a Desktop already on magpie (`claude-desktop.mcp-seen`), so a server the user takes out in 3p isn't brought back. What was copied is stashed (`claude-desktop.mcp`), and off takes back each one still as copied; one the user changed since stays (`TestClaudeDesktopCarriesTheMCPServers`, `TestClaudeDesktopMCPKeepsThe3pServers`, `TestClaudeDesktopSyncCarriesTheMCPServersOnce`). Claude's file is never written. A claude.ai account's connectors can't come along: Desktop calls them through claude.ai with that account (`/api/organizations//mcp/servers//tools/call`, refused with `no_active_org` without one, Desktop 2.7032), and 3p mode has no account; Anthropic's docs say "Made by Anthropic" connectors are only in standard Desktop, and others reach 3p through `managedMcpServers` or plugins (claude.com/docs/third-party/claude-desktop/extensions). diff --git a/internal/agent/claudedesktop.go b/internal/agent/claudedesktop.go index d323b0d79..6225a673a 100644 --- a/internal/agent/claudedesktop.go +++ b/internal/agent/claudedesktop.go @@ -190,6 +190,7 @@ func claudeDesktop(home string) *Agent { } return "" }, + Gateway: desktopGateway, Fields: append([]Field{{ Key: "provider", Label: "provider", Get: func() string { @@ -198,39 +199,12 @@ func claudeDesktop(home string) *Agent { } return "" }, - Set: func(v string) error { - on := desktopOn - if v == "" { - on = desktopOff - } - desktopAdoptStash(ps) - src := desktopLocaleFrom(ps) - for _, p := range ps { - if src != "" { - p.app = src - } - 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() - // and a running distro's, which a Code tab session with - // WSL as its host runs on (a stopped one is written on - // the round after it starts) - for _, a := range wslAgents() { - if strings.HasPrefix(a.ID, "claude@wsl:") && a.Sync != nil { - _ = a.Sync() - } - } - return nil - }, + Set: func(v string) error { return desktopApply(home, ps, v) }, 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(home, ps), desktopSubagentField(ps), desktopSubagentEffortField(ps))...), + }, desktopGatewayField(ps, func() error { return desktopApply(home, ps, magpieID) })}, append(desktopTierFields(home, ps), desktopSubagentField(ps), desktopSubagentEffortField(ps))...), // a Desktop already on magpie gets the import and tool search // policies too (desktopSeedImport, desktopSeedToolSearch), and a // profile for magpie's gateway it applies a key the gateway takes @@ -334,7 +308,8 @@ func desktopCheck(p desktopPaths) string { if !desktop3p(p, prof) { return "Claude Desktop's deploymentMode (Claude-3p/claude_desktop_config.json) is 1p now, so it signs in with Anthropic rather than using magpie" } - want := agentKey("claude-desktop") + gw := desktopGateway() + want := desktopKey(gw) return wiringOff("Claude Desktop", prof, func(k string) (string, bool) { v, ok := edit.GetJSON(prof, k) if k != "inferenceGatewayApiKey" { @@ -351,7 +326,7 @@ func desktopCheck(p desktopPaths) string { return want, true // a key of magpie's other than Desktop's own } return open, ok - }, "inferenceGatewayBaseUrl", gateway.URL(), "inferenceGatewayApiKey", want) + }, "inferenceGatewayBaseUrl", gw, "inferenceGatewayApiKey", want) } // desktop3p: Desktop starts in its 3p mode with prof, the gateway profile @@ -420,7 +395,7 @@ func desktopKeyApplied(p desktopPaths) error { if f == "" { return nil } - want := agentKey("claude-desktop") + want := desktopKey(desktopGateway()) v, _ := edit.GetJSON(f, "inferenceGatewayApiKey") // a key Desktop sealed that magpie can't open is left as it is if open, known := desktopOpen("inferenceGatewayApiKey", v); !known || desktopKeyTaken(open, want) { @@ -433,6 +408,37 @@ func desktopKeyApplied(p desktopPaths) error { return edit.SetJSON(f, kvs...) } +// desktopApply turns Desktop's wiring on for v == magpieID, off for "", +// or writes it again where the address or key changed. +func desktopApply(home string, ps []desktopPaths, v string) error { + on := desktopOn + if v == "" { + on = desktopOff + } + desktopAdoptStash(ps) + src := desktopLocaleFrom(ps) + for _, p := range ps { + if src != "" { + p.app = src + } + 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() + // and a running distro's, which a Code tab session with + // WSL as its host runs on (a stopped one is written on + // the round after it starts) + for _, a := range wslAgents() { + if strings.HasPrefix(a.ID, "claude@wsl:") && a.Sync != nil { + _ = a.Sync() + } + } + return nil +} + // 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, the chat's model runs it, or, for a chat @@ -616,11 +622,12 @@ const ( desktopLocale = "claude-desktop.locale" desktopImport = "claude-desktop.import" desktopSearch = "claude-desktop.tool-search" + desktopSSH = "claude-desktop.ssh-hosts" desktopMCP = "claude-desktop.mcp" desktopMCPSeen = "claude-desktop.mcp-seen" ) -var desktopStashKeys = []string{desktopStashed, desktopMode, desktopMode3p, desktopApplied, desktopMade, desktopProfile, desktopLocale, desktopImport, desktopSearch, desktopMCP, desktopMCPSeen, desktopModelsMark} +var desktopStashKeys = []string{desktopStashed, desktopMode, desktopMode3p, desktopApplied, desktopMade, desktopProfile, desktopLocale, desktopImport, desktopSearch, desktopSSH, desktopMCP, desktopMCPSeen, desktopModelsMark} // desktopAdoptStash moves the stash a packaged Desktop's folders got // before they had keys of their own (when magpie wrote only one set) onto @@ -697,10 +704,11 @@ func desktopOn(p desktopPaths) error { return err } } + gw := desktopGateway() kvs := []edit.KV{ {Path: "inferenceProvider", Value: "gateway"}, - {Path: "inferenceGatewayBaseUrl", Value: gateway.URL()}, - {Path: "inferenceGatewayApiKey", Value: agentKey("claude-desktop")}, + {Path: "inferenceGatewayBaseUrl", Value: gw}, + {Path: "inferenceGatewayApiKey", Value: desktopKey(gw)}, {Path: "inferenceGatewayAuthScheme", Value: "bearer"}, } // policies seeded once: the user may tighten them in Desktop @@ -719,6 +727,13 @@ func desktopOn(p desktopPaths) error { if err := desktopSeedToolSearch(p); err != nil { return err } + // pointed at an address of this computer's for SSH remote sessions, + // which 3p mode allows no host for until the profile says so + if gw != gateway.URL() { + if err := desktopSeedSSH(p); err != nil { + return err + } + } // a profile for magpie's gateway the user applied since magpie's // (one imported from another computer) stays applied, its connectors @@ -1125,7 +1140,13 @@ func desktopOwnGatewayProfile(p desktopPaths) []byte { // (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() == "" { + if err != nil { + return false + } + if desktopOurAddress(a) { + return true + } + if a.Port() == "" { return false } ours, err := url.Parse(gateway.URL()) diff --git a/internal/agent/claudedesktop_gateway.go b/internal/agent/claudedesktop_gateway.go new file mode 100644 index 000000000..67337d580 --- /dev/null +++ b/internal/agent/claudedesktop_gateway.go @@ -0,0 +1,136 @@ +package agent + +import ( + "fmt" + "net/url" + "slices" + "strings" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/settings" +) + +// Desktop's built-in SSH remote sessions run its Code tab on another +// machine, which is handed the profile's gateway address and key +// (Desktop 2.x, the sshRemoteSessions beta). They are refused when the +// address is this computer's own ("provider_loopback": that endpoint is +// this computer, which a remote host cannot reach), and a non-loopback +// address must be https (the profile's schema: "must use https (or http on +// loopback)"), and the profile's sshHostAllowlist, empty by default in 3p +// mode, says which hosts may be used at all (zyc-bit and ZYar-er on X, +// #4546). So Desktop can be given, instead of 127.0.0.1, one of this +// computer's https:// addresses (gateway.LANURLs) with the LAN sharing +// key, which the gateway takes from other machines: the setting is +// DesktopGateway, the "gateway" field of Desktop's row, offered while +// sharing is on and an address is https. Loopback stays the default. + +// desktopLANURLs are the addresses Desktop may be pointed at beyond +// loopback: this computer's https:// ones, while the gateway is shared (its +// key beyond loopback is the sharing key, keyAt). +func desktopLANURLs() []string { + if access.LANSecret() == "" { + return nil + } + var out []string + for _, u := range gateway.LANURLs() { + if strings.HasPrefix(u, "https://") { + out = append(out, u) + } + } + return out +} + +// desktopGateway is the address Desktop's profile gets: the one picked in +// DesktopGateway while it is still one of this computer's https addresses +// (the first, where the network's address changed since), else the gateway's +// own on loopback. +func desktopGateway() string { + pick := settings.Load().DesktopGateway + if pick == "" { + return gateway.URL() + } + urls := desktopLANURLs() + switch { + case slices.Contains(urls, pick): + return pick + case len(urls) > 0: + return urls[0] + } + return gateway.URL() +} + +// desktopKey is the key Desktop's profile gets at gw. +func desktopKey(gw string) string { return agentKeyAt("claude-desktop", gw) } + +// desktopSeedSSH puts Desktop's sshHostAllowlist in the profile, seeded once with every +// host where the profile is pointed beyond loopback and has none: 3p mode +// refuses every host without it, and the address was picked to reach one. +// The user may narrow it in Desktop's window, or take it away; magpie never +// writes it again (desktopSeedOnce). +func desktopSeedSSH(p desktopPaths) error { + return desktopSeedOnce(p, desktopSSH, "sshHostAllowlist", []string{"*"}) +} + +// desktopGatewayField picks where Desktop reaches the gateway: this +// computer (loopback), or one of its https addresses for SSH remote +// sessions. +func desktopGatewayField(ps []desktopPaths, apply func() error) Field { + return Field{ + Key: "gateway", Label: "gateway", + Get: func() string { + if g := desktopGateway(); g != gateway.URL() { + return g + } + return "" + }, + Set: func(v string) error { + v = strings.TrimRight(strings.TrimSpace(v), "/") + if v != "" && !slices.Contains(desktopLANURLs(), v) { + return fmt.Errorf("Claude Desktop can be pointed at %q only while magpie is shared on the local network and serves https:// there (Settings > Network and sharing: Share on local network, HTTPS)", v) + } + if err := settings.SetDesktopGateway(v); err != nil { + return err + } + if !desktopWiredAny(ps) { + return nil + } + return apply() + }, + Options: func(map[string]string) []Option { + urls := desktopLANURLs() + if !desktopWiredAny(ps) || len(urls) == 0 { + return nil + } + out := []Option{{Value: "", Label: "This computer", Note: gateway.URL()}} + for _, u := range urls { + out = append(out, Option{Value: u, Label: u}) + } + return out + }, + } +} + +// desktopOurAddress: a is an address of this computer's own that other +// machines reach the gateway at (gateway.LANURLs, or the one Desktop is +// pointed at), as a profile exported here holds it. +func desktopOurAddress(a *url.URL) bool { + for _, l := range append(gateway.LANURLs(), settings.Load().DesktopGateway) { + u, err := url.Parse(l) + if err == nil && u.Hostname() == a.Hostname() && portOf(u) == portOf(a) { + return true + } + } + return false +} + +// portOf is u's port, its scheme's own where it has none. +func portOf(u *url.URL) string { + if p := u.Port(); p != "" { + return p + } + if u.Scheme == "https" { + return "443" + } + return "80" +} diff --git a/internal/agent/claudedesktop_gateway_test.go b/internal/agent/claudedesktop_gateway_test.go new file mode 100644 index 000000000..308255d0b --- /dev/null +++ b/internal/agent/claudedesktop_gateway_test.go @@ -0,0 +1,87 @@ +package agent + +import ( + "strings" + "testing" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/gateway" +) + +// Desktop's SSH remote sessions are handed the profile's address and key +// (#4546): loopback is refused there, and the key must be one the gateway +// takes from another machine. +func TestDesktopPointedAtLANHTTPS(t *testing.T) { + home, p := desktopSandbox(t) + t.Setenv("MAGPIE_PUBLIC_URL", "https://magpie.example.test") + if err := access.ConfigureLAN(true, false); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { access.ConfigureLAN(false, false) }) + lan := "https://magpie.example.test" + if len(desktopLANURLs()) == 0 { + t.Fatalf("no https address offered: %v (LANURLs %v)", desktopLANURLs(), gateway.LANURLs()) + } + a := claudeDesktop(home) + f := a.Field("gateway") + if f == nil { + t.Fatal("no gateway field") + } + if len(f.Options(nil)) != 0 { + t.Fatal("offered while Desktop is off magpie") + } + if err := a.Field("provider").Set("magpie"); err != nil { + t.Fatal(err) + } + prof := p.prof + if v, _ := edit.GetJSON(prof, "inferenceGatewayBaseUrl"); v != gateway.URL() { + t.Fatalf("default address %q, want loopback", v) + } + if strings.Contains(readFile(prof), "sshHostAllowlist") { + t.Fatal("hosts allowed while Desktop reaches loopback") + } + if len(f.Options(nil)) < 2 { + t.Fatalf("options %v", f.Options(nil)) + } + if err := f.Set("http://evil.test:1"); err == nil { + t.Fatal("an address that isn't ours was taken") + } + if err := f.Set(lan); err != nil { + t.Fatal(err) + } + if v, _ := edit.GetJSON(prof, "inferenceGatewayBaseUrl"); v != lan { + t.Fatalf("address %q, want %q:\n%s", v, lan, readFile(prof)) + } + open, _ := edit.GetJSON(prof, "inferenceGatewayApiKey") + if o, _ := desktopOpen("inferenceGatewayApiKey", open); o != access.LANSecret() { + t.Fatalf("key %q is not the sharing key", o) + } + if !strings.Contains(readFile(prof), `"sshHostAllowlist"`) || !strings.Contains(readFile(prof), `"*"`) { + t.Fatalf("no SSH host allowed:\n%s", readFile(prof)) + } + if d := a.Drift(); d != nil { + t.Fatalf("drift on its own address: %+v", d) + } + // back to this computer + if err := f.Set(""); err != nil { + t.Fatal(err) + } + if v, _ := edit.GetJSON(prof, "inferenceGatewayBaseUrl"); v != gateway.URL() { + t.Fatalf("address %q after taking it back", v) + } + // sharing off: the pick can't hold, and Rekey puts loopback back + if err := f.Set(lan); err != nil { + t.Fatal(err) + } + on := OnGateway() + if err := access.ConfigureLAN(false, false); err != nil { + t.Fatal(err) + } + if _, err := Rekey(on); err != nil { + t.Fatal(err) + } + if v, _ := edit.GetJSON(prof, "inferenceGatewayBaseUrl"); v != gateway.URL() { + t.Fatalf("address %q with sharing off", v) + } +} diff --git a/internal/agent/reach.go b/internal/agent/reach.go index 94ff25d1e..458cae813 100644 --- a/internal/agent/reach.go +++ b/internal/agent/reach.go @@ -2,6 +2,7 @@ package agent import ( "cmp" + "crypto/tls" "encoding/json" "net" "net/http" @@ -36,7 +37,9 @@ var reachAge = 20 * time.Second var reachProbe = realReachProbe func realReachProbe(base string) bool { - c := &http.Client{Timeout: 2 * time.Second} + // a certificate magpie made itself isn't one this computer trusts, and + // whether something answers is all that is asked here + c := &http.Client{Timeout: 2 * time.Second, Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}} res, err := c.Get(strings.TrimSuffix(base, "/") + "/v1/models") if err != nil { return false diff --git a/internal/agent/rewire.go b/internal/agent/rewire.go index 477853112..6c4787180 100644 --- a/internal/agent/rewire.go +++ b/internal/agent/rewire.go @@ -4,6 +4,8 @@ import ( "context" "fmt" "strings" + + "github.com/yetone/magpie/internal/settings" ) // The gateway's port is set in Settings (Magic_zero on Discord): every @@ -60,7 +62,7 @@ func Rewire(as []*Agent) (moved []string, err error) { func Rekey(as []*Agent) (moved []string, err error) { var away []*Agent for _, a := range as { - if a.Gateway != nil && onAnotherMachine(a.Gateway()) { + if a.Gateway != nil && (onAnotherMachine(a.Gateway()) || a.ID == "claude-desktop" && settings.Load().DesktopGateway != "") { away = append(away, a) } } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index d5492cbd1..0044bf8da 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -504,7 +504,7 @@ function renderAgents() { const fields = el("div", "fields"); const wide = (f) => f.label === "model" || f.label === "large" || f.label === "executor" || f.label === "planner"; // a field with nothing to pick and nothing set isn't drawn (#1499) - const none = (f) => (f.key === "effort" || toggled(f) || f.label === "subagents" || f.label === SUB_EFFORT || f.label === SUB_MODEL || f.label === AUTO_MODE || f.label === MEMORIES || f.label === COMPACT_MODEL || f.label === "sign-in" || f.key === "small" || asideAccount(a, f)) && !f.options.length && !f.value; + const none = (f) => (f.key === "effort" || toggled(f) || f.label === "subagents" || f.label === "gateway" || f.label === SUB_EFFORT || f.label === SUB_MODEL || f.label === AUTO_MODE || f.label === MEMORIES || f.label === COMPACT_MODEL || f.label === "sign-in" || f.key === "small" || asideAccount(a, f)) && !f.options.length && !f.value; const shownFields = a.fields.filter((f) => !grouped(a, f) && !none(f) && !codexOwnSub(a, f) && !codexRowed(a, f) && !hermesBot(f)); const tiers = tierMenu(a); if (tiers) shownFields.push(tiers); diff --git a/internal/gui/https.go b/internal/gui/https.go index d80de6f43..867cd9b81 100644 --- a/internal/gui/https.go +++ b/internal/gui/https.go @@ -6,6 +6,7 @@ import ( "net/http" "path/filepath" + "github.com/yetone/magpie/internal/agent" "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/mtls" "github.com/yetone/magpie/internal/settings" @@ -74,6 +75,9 @@ func httpsRoutes(mux *http.ServeMux, w Windows) { fail(rw, errFarPage) return } + // Claude Desktop pointed at this computer's https address follows + // the scheme (agent.Rekey) + on := agent.OnGateway() if in.On { if c, _ := gateway.ImportedFiles(); c == "" { if _, _, err := gateway.CA(); err != nil { @@ -86,6 +90,7 @@ func httpsRoutes(mux *http.ServeMux, w Windows) { fail(rw, err) return } + _, _ = agent.Rekey(on) writeJSON(rw, httpsNow()) }) // the user's own certificate and key: the PEM files' text, any split diff --git a/internal/gui/settings_keep_test.go b/internal/gui/settings_keep_test.go index bd1d4682c..fde17f2ed 100644 --- a/internal/gui/settings_keep_test.go +++ b/internal/gui/settings_keep_test.go @@ -174,6 +174,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) { CodexSubagentModel: "codex/gpt-6-astra", CodexServiceTier: "priority", DesktopSubagentModel: "fake/m2", + DesktopGateway: "https://192.168.1.20:3425", DshCompactModel: "fake/m1", CodexCompactModel: "fake/m1", ChinaMirror: true, diff --git a/internal/gui/tests/desktop-gateway-address.test.cjs b/internal/gui/tests/desktop-gateway-address.test.cjs new file mode 100644 index 000000000..5c6af135b --- /dev/null +++ b/internal/gui/tests/desktop-gateway-address.test.cjs @@ -0,0 +1,100 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Claude Desktop's gateway address (#4546): drawn only while magpie offers +// an https address of this computer, picked from the app's own menu. All +// APIs and assets are intercepted; no backend or external network is used. +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 LAN = "https://192.168.1.20:3425"; +const fresh = (offer) => ({ + agents: [{ + id: "claude-desktop", name: "Claude Desktop", path: "/test/claude_desktop_config.json", icon: "claude-color", wired: true, + fields: [ + { key: "provider", label: "provider", value: "magpie", options: [{ value: "magpie", label: "magpie" }] }, + { key: "gateway", label: "gateway", value: "", options: offer ? [{ value: "", label: "This computer" }, { value: LAN, label: LAN }] : [] }, + ], + }], + profiles: [], +}); + +function server(lang, fixture) { + 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 json({ ...fixture.state, settings: { lang, theme: "light" } }); + if (url.pathname === "/api/set") { + const body = req.postDataJSON(); + fixture.sets.push(body); + fixture.state = JSON.parse(JSON.stringify(fixture.state)); + fixture.state.agents[0].fields.find((f) => f.key === body.field).value = body.value; + return json({ ...fixture.state, settings: { lang, theme: "light" } }); + } + if (url.pathname === "/api/gateway/trace") return json({ mine: true, now: new Date().toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [] }); + 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 === "/api/plugins") return json({ plugins: [] }); + 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 cd = '.row.agent[data-id="claude-desktop"]'; +const written = (page) => page.waitForResponse((r) => new URL(r.url()).pathname === "/api/set"); +const engines = process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"]; +const langs = process.env.LANGS ? process.env.LANGS.split(",") : ["en", "zh", "zh-TW", "ja", "de"]; + +async function open(browser, lang, width, fixture, errors) { + const page = await browser.newPage({ viewport: { width, height: 760 } }); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, fixture)); + await page.goto("http://magpie.test/"); + await page.locator(cd).waitFor(); + return page; +} + +for (const engine of engines) { + for (const lang of langs) { + for (const width of [1100, 420]) { + test(`${engine} ${lang} ${width}px: Desktop's gateway address is drawn only when offered`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(async () => { await browser.close(); }); + const errors = []; + const off = await open(browser, lang, width, { state: fresh(false), sets: [] }, errors); + await off.locator(`${cd} .ag-link`).click(); + await off.locator(`${cd} .ag-exp`).waitFor(); + assert.equal(await off.locator(`${cd} .field[data-key="gateway"]`).count(), 0, "nothing to pick: not drawn"); + + const fixture = { state: fresh(true), sets: [] }; + const page = await open(browser, lang, width, fixture, errors); + await page.locator(`${cd} .ag-link`).click(); + await page.locator(`${cd} .ag-exp`).waitFor(); + const f = page.locator(`${cd} .field[data-key="gateway"]`); + assert.equal(await f.count(), 1, "drawn while an https address is offered"); + await f.click(); + await page.locator("#pop:not([hidden]) #list li").first().waitFor(); + assert.equal(await page.locator("select").count(), 0, "no native select"); + const items = await page.locator("#pop #list li").allInnerTexts(); + assert(items.some((s) => s.includes(LAN)), `the address is offered: ${items}`); + const wrote = written(page); + await page.locator("#pop #list li", { hasText: LAN }).first().click(); + await wrote; + assert.deepEqual(fixture.sets, [{ agent: "claude-desktop", field: "gateway", value: LAN }]); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "no sideways scroll"); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 48b147f8e..6a23b2da7 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -837,6 +837,12 @@ type Settings struct { // subagent tool turns on. "" leaves them on the model their lead asks // for; tool-less helpers and the lead's own turns are never moved. DesktopSubagentModel string `json:"desktopSubagentModel,omitempty"` + // DesktopGateway is the https:// address of this computer that Claude + // Desktop's profile is pointed at instead of loopback, so its built-in + // SSH remote sessions can reach the gateway ("" for this computer's + // own 127.0.0.1). It is one of LANURLs, and holds only while sharing is + // on (agent.desktopGateway). + DesktopGateway string `json:"desktopGateway,omitempty"` // DesktopSubagentEffort fixes Desktop's subagent tool turns at this // reasoning level. Empty keeps the effort each request asks for. DesktopSubagentEffort string `json:"desktopSubagentEffort,omitempty"` @@ -1586,7 +1592,8 @@ func (s Settings) Compact() int { // KeepOwn puts back cur's settings that are this computer's own, which a // sync or a restored backup never brings from another: the window's size, // place and whether it was maximised, the proxy (and plugin downloads'), the gateway's port, whether it -// is shared on the local network and the addresses let in to it, what +// is shared on the local network and the addresses let in to it, the +// address Claude Desktop is pointed at (DesktopGateway), what // its MCP router says of itself, the Dock, gateway mode, whether WSL is // looked in, whether agents' sign-ins are read, when allowances are read, the terminal app a session resumes // in, the quick panel's shortcut, whether the local masking model is on @@ -1613,6 +1620,7 @@ func (s *Settings) KeepOwn(cur Settings) { s.QuotaReads = cur.QuotaReads s.NoAccountDiscovery = cur.NoAccountDiscovery s.LAN, s.AllowIPs, s.MTLS, s.HTTPS = cur.LAN, cur.AllowIPs, cur.MTLS, cur.HTTPS + s.DesktopGateway = cur.DesktopGateway // an address of this computer s.RouterNote, s.RouterAllTools = cur.RouterNote, cur.RouterAllTools s.FetchPrivate = cur.FetchPrivate s.SessionTerminal = cur.SessionTerminal @@ -2134,6 +2142,18 @@ func SetHTTPS(on bool) error { return save(s, false) } +// SetDesktopGateway sets DesktopGateway alone, from what the file holds +// now. A settings file that can't be read is left as it is, with the error. +func SetDesktopGateway(u string) error { + defer lockFile()() + s, err := loadChecked() + if err != nil { + return err + } + s.DesktopGateway = strings.TrimSpace(u) + return save(s, false) +} + // SetQuitNoAsk sets QuitNoAsk alone, from what the file holds now (the // Quit question's "Don't ask again"). A settings file that can't be read // is left as it is, with the error. diff --git a/internal/settingsapi/settingsapi.go b/internal/settingsapi/settingsapi.go index efe4cbac2..1dcc594ec 100644 --- a/internal/settingsapi/settingsapi.go +++ b/internal/settingsapi/settingsapi.go @@ -369,6 +369,7 @@ func Merge(body []byte, cur settings.Settings, web bool) (settings.Settings, err // in their Agents rows in.CodexSubagentModel = cur.CodexSubagentModel in.DesktopSubagentModel = cur.DesktopSubagentModel + in.DesktopGateway = cur.DesktopGateway // Desktop's address, set in its row in.CodexServiceTier = cur.CodexServiceTier // codex-service-tier // and the model DeepSeek Harness compacts on, set in its row in.DshCompactModel = cur.DshCompactModel