From 58fb070953ab8b5e542aacbf90cc601e710ddeec Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 11 Nov 2026 12:24:41 +0800 Subject: [PATCH] settings: named proxies, chosen as inherit, direct or a saved one anywhere a proxy is (@tsingchao on X) Settings > Network keeps named proxies (name, address, optional login) with a Test that says reachable and the latency. Everywhere a proxy can be chosen (global, plugin downloads, a provider, a key, a Claude account) now has a Saved mode beside the others; the value is "@". Addresses typed before are read exactly as before, nothing is migrated or overridden. netproxy.Parse/Resolve/Redact/EnvWith/Dispatch resolve a reference at the lowest layer, so a proxy edited once reaches the gateway, usage reads, sign-ins and the plugin host at the next request; Claude Code's settings.json env (a snapshot) is rewritten by provider.ProxyEdited. A reference this computer lacks fails closed (DeadProxy), says the proxy's name in the request error and as "Proxy missing: {name}" on the provider row, and never goes direct. The password lives in settings.json (0600), is never read back by the page, logged, or put in Settings sync. The list rides with the providers part of a sync (Bundle.Proxies, MergeProxies by id, passwords only with keys). A proxy in use can't be deleted (409). The saved list's page code is in proxies.js, loaded when Settings draws it; app.js grew by Saved-mode helpers only, paid for by 16 long comments cut (core budget unchanged, no raise). Run (mote refused ssh all session, so Go and GUI went through win-run on xiaomi-gpu, Windows 11; gofmt and darwin/linux-nogui/windows go vet were clean on mote before it went down, at the pre-sync tree): - go test settings, netproxy, backup, settingsapi, davsync: ok on Windows (earlier on mote: also gui, provider, plugin with real Bun, gateway). - saved-proxies.test.cjs 20 of 20 (chromium+webkit, en zh zh-TW ja de, 420px) twice more on Windows; provider-proxy-missing.test.cjs 20 of 20. One webkit de 420px run of saved-proxies failed once under 4-way concurrency and passed 3 of 3 alone; not reproduced. - TestCoreScriptBudget ok after the move (it was 3.4KB over before). Red on this tree and on origin/main alike (Windows run, not mine): settings TestSharedCheckedReadsOnceAndKnowsUnknown; provider Codex keychain/Git tests; plugin TestHostRunsAsMagpieBun, TestPiPackage; gui TestGatewayHeldByAContainer and others; old-webkit "compat.js is the first" (headerpresets.js) and ":has() (Safari 15.4)" on origin/main 245f07b19. Broken by hand: restore skipping Proxies (TestSavedProxiesTravelWithProviders red), Parse returning nil for a dangling ref (netproxy tests red), the Proxy-missing badge disabled (provider-proxy-missing 0 of 20), and the Claude env snapshot failing open (found by reading, test added). Not tried: real vendors, the real Claude Code, a real two-computer sync, the macOS suite and the whole GUI suite on this final tree (mote down; the whole suite ran to test ~3700 on the earlier tree with reds owned by others). A proxy missing whose sender never had it is named by its id. --- docs/subsystems/providers-accounts.md | 1 + internal/backup/auto.go | 1 + internal/backup/backup.go | 22 ++ internal/backup/saved_proxies_test.go | 95 +++++++ internal/davsync/davsync.go | 16 +- internal/davsync/scoped_keys_test.go | 16 ++ internal/gui/api.go | 8 +- internal/gui/assets/app.css | 7 + internal/gui/assets/app.js | 149 ++++++----- internal/gui/assets/i18n.js | 40 +++ internal/gui/assets/index.html | 2 + internal/gui/assets/proxies.js | 89 +++++++ internal/gui/providers.go | 5 + internal/gui/proxies.go | 247 +++++++++++++++++ internal/gui/proxies_test.go | 138 ++++++++++ internal/gui/tests/old-webkit.test.cjs | 4 +- .../gui/tests/provider-proxy-missing.test.cjs | 68 +++++ internal/gui/tests/saved-proxies.test.cjs | 113 ++++++++ internal/netproxy/named_test.go | 139 ++++++++++ internal/netproxy/netproxy.go | 45 +++- internal/plugin/host.go | 4 + internal/plugin/saved_proxy_test.go | 92 +++++++ internal/provider/claude_proxy_env.go | 10 + internal/provider/claude_proxy_env_test.go | 40 +++ internal/provider/proxy.go | 61 +++++ internal/settings/proxies.go | 252 ++++++++++++++++++ internal/settings/proxies_test.go | 92 +++++++ internal/settings/settings.go | 29 +- internal/settingsapi/settingsapi.go | 24 +- 29 files changed, 1715 insertions(+), 94 deletions(-) create mode 100644 internal/backup/saved_proxies_test.go create mode 100644 internal/gui/assets/proxies.js create mode 100644 internal/gui/proxies.go create mode 100644 internal/gui/proxies_test.go create mode 100644 internal/gui/tests/provider-proxy-missing.test.cjs create mode 100644 internal/gui/tests/saved-proxies.test.cjs create mode 100644 internal/netproxy/named_test.go create mode 100644 internal/plugin/saved_proxy_test.go create mode 100644 internal/settings/proxies.go create mode 100644 internal/settings/proxies_test.go diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index da19aba4f..574e50d84 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -86,6 +86,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Local servers | A preset of `KindLocal` (Ollama, LM Studio, oMLX, MLX-Serve) is at its server's default port on this machine. Another address — a port, or another computer — is given in the window's editor, in its Server address field, shown first above the key and never folded (a folded one read as an LM Studio whose base URL can't be changed, mengxiangziyou on X), or in the TUI (asked on adding, `w` after); on the command line with `address=` (`atAddress` in `providers_cli.go`: every URL moves, from the preset's when the provider was saved with none, and `address=` alone puts a local server back at its preset's), or the URLs themselves (`url=`, `anthropic=`, `responses=`). `AtAddress` replaces only each URL's scheme, host and port, each API keeping its path; `AddressOf` is the address an editor starts from. The window sends the URLs moved only when the address was changed, so a Save doesn't move URLs set apart (another app's import). A provider of the user's own (no preset) has `w` in the TUI too: each base URL it has is asked in turn, typed in as it is, Enter alone keeping one (`customURLsAsk`). | [`local_address.go`](../../internal/provider/local_address.go), [`providers_cli.go`](../../internal/cli/providers_cli.go) | | Protocol detection | Works out which of Chat, Responses, Anthropic Messages and Gemini generateContent a base URL speaks when a provider is added. Each is asked at the URL as it takes it (`DetectBase`); Gemini's at the `…/v1beta` beside a typed `…/v1` or bare host, a Gemini model from the list picked for it, with the key in `x-goog-api-key` (#1346). Each API is asked with a model that chats, if the list has one; an embedding or rerank model (`catalog.ServesOf`) is asked only on Chat's URL, at its `/embeddings` or `/rerank` with the smallest body and no extra body, as the gateway's `retrieve` asks it, and the other APIs say why they weren't asked (heatonz on Discord: a vendor of only those detected nothing, asked to chat; `TestDetectEmbeddingOnly`). A saved provider whose list has nothing to chat with tests on such a model (`testModel`, `TestTestEmbeddingOnly`), and its editor and the add form's Fetch models say the models need no pick (`retrieval` in the list's answer and the provider's JSON, `provider-retrieval-only.test.cjs`). A model's test (Test models, a model's right-click, `magpie provider test`) asks the account or key a request for it goes to: `provider.AccountsFor` and `provider.KeysFor` ([`route_accounts.go`](../../internal/provider/route_accounts.go)), which the gateway's `perKeyEvery` routes by too, its usage and spend caps aside (one the user lets serve it, `AccountModels`; whose own list or plan has it, `Account.Lists`, `PlanServing`, `Serving`; in the user's order, `AccountsOn`), so a pool whose accounts list different models (a newapi plugin's) asks the one whose list has it, and one every account is barred from isn't asked. The provider's Test picks each endpoint's model from every account's and asks it of the account that serves it (`routedTo`), and with keys the first key with a model of its own to test (`testWith`). The request log's row names the account asked (`loggedAs`; #4992, `TestModelTestAsksTheAccountThatServesIt`). Detection, endpoint tests and model tests share `probe`, which adds `anthropic-version` only for Anthropic Messages; OpenAI probes omit that default so a relay that refuses it can answer. A Chat or Responses URL typed without its version (CRS's `…/openai`, Cyrus_4433 on X: CRS serves `/openai/v1/chat/completions` and `/openai/responses`, and answers anything else 404 `Not Found`) that is answered 404 is asked once more under `/v1` (`missingV1`, not for an account, Azure, Bedrock or Vertex); answered there, the saved provider's URL takes the `/v1` (`setV1`), the result carries it (`Result.V1`), Detect hands it on as the base, and the editor's URL field follows (`draft.onV1`), so Save doesn't put it back. A model's own 404 at both stays a 404 and changes nothing. CRS lists at `/api/v1/models`, which `catalog.RelayOpenAIList` adds to an unversioned `…/openai` base's list URLs, and a list answered there adds `/v1` as `fixV1` does (`TestCRSOpenAIBaseTestsUnderV1`, `TestCRSOpenAIBaseListsAtAPI`, `TestCRSOpenAIBaseDetectsV1`, `TestModel404KeepsBase`, `provider-test-v1.test.cjs`). A model's test that the vendor turns away with its word that the model is served on another API (`catalog.WrongEndpoint`, the gateway's words) asks the next API the provider has a URL for, as the gateway's `usable` takes it (the model's picked or listed API, else each API it isn't named-only on), with a key that sees the model there (`keySeeing`); that API's answer is the model's, and with none left, or every one saying it, the first stays. As Codex the next API is asked with Codex's headers, as the gateway sends them on Responses and Chat; as Claude Code it isn't, since the gateway sends Claude Code's on Messages alone (#3766, `TestTestModelsMovesToTheAPIServingIt`, `TestTestModelsKeepsAModelOnItsAPI`, `TestTestModelsAsAClientMovesAsTheGatewayDoes`). User-supplied headers still apply through `Sign`. The editor asks with the form as it stands, before any Save (#1545): the URL, key and models typed (`picked`, else the saved picks, else the vendor list); a key not typed again is the saved provider's, or for an unsaved copy the copied one's (`copyOf`). The probe writes nothing and adds no provider, and the route stays behind `magpie web`'s key. An endpoint or model test fails fast and can be stopped (RIck on Discord: 测试模型 took long to fail and couldn't be cancelled): a probe on magpie's own client that has no connection in `connectWait` (10s) fails then (`connecting`, an httptrace `GotConn`), and a host that couldn't be reached (no connection, DNS, refused, a bad certificate) fails the run's other models at once (`withUnreached`, `TestTestModelsUnreachedHostFailsOnce`); a stream that breaks off before an answer is a failure. While a test runs its Test models and endpoints' Test read Stop, which aborts the window's request and posts `provider/teststop` with the test's `run`, ending the vendor's request on the server too (`testRuns` in [`providers.go`](../../internal/gui/providers.go), since WebView2 doesn't end the request when a fetch is aborted; `TestProviderTestStops`, `model-test-stop.test.cjs`). | [`detect.go`](../../internal/provider/detect.go), [`test.go`](../../internal/provider/test.go) | | A pasted curl command | A curl command from a vendor's docs pasted into a custom provider's Base URL or API key fills the editor in (@mark_li21 on X). `curlOf` reads it as a shell would (lines joined by `\`, cmd's `^` or PowerShell's backtick; `curl.exe`; quotes and escapes), and takes: the API its URL's endpoint names (`…/chat/completions` Chat, `…/messages` Anthropic Messages, `…/responses` Responses) with the base URL before it, spelled as that API wants it (`respellURL`: Anthropic at its root, `/v1` after a bare host); the key from `Authorization: Bearer`, `x-api-key` or `api-key`, unless it only stands for one (`$OPENAI_API_KEY`, `${X}`, `%X%`, ``, `YOUR_API_KEY`), when the key's box is left empty and focused; and the `model` of its JSON body, added to a new provider's models (a saved one's picks are left alone, since adding to none would narrow what it serves). A preset's editor takes only the key. A note (`editorError`, kind `note`) says what was taken, a placeholder like `{WorkspaceId}` left in the URL, and a URL with no known endpoint. Text that isn't a curl command pastes as before, several keys included. Tested on the docs' own examples (`fixtures/curl`). | [`app.js`](../../internal/gui/assets/app.js) (`curlOf`, `fromCurl`), [`provider-curl-paste.test.cjs`](../../internal/gui/tests/provider-curl-paste.test.cjs) | +| Saved proxies | `settings.Proxies` holds named proxies (`NamedProxy`: id, name, address, optional login), kept in Settings › Network. Wherever a proxy is chosen (global, plugin downloads, a provider, a key, a Claude account) the value is "" (inherit), `direct`, an address as typed, or `@` for a saved one (@tsingchao on X). Addresses as typed are untouched. `netproxy.Parse`, `Resolve`, `Redact`, `EnvWith` and `Dispatch` resolve an `@id` at the lowest layer, so an edit reaches every user at the next request; a Claude Code `settings.json` env is a snapshot and is rewritten after an edit (`provider.ProxyEdited`). An `@id` this computer lacks fails closed (`netproxy.DeadProxy`, the request error and the provider row say "Proxy missing: {name}", `provider.ProxyGone`); it never goes direct. The password is written to settings.json (0600) and never read back by the page, logged or put in `Settings` sync; the list rides with the providers part of a sync (`backup.Bundle.Proxies`, `settings.MergeProxies`, passwords only with keys). A proxy in use cannot be deleted (409). `TestSavedProxyChoice`, `TestDanglingProxyReferenceFailsClosed`, `TestSavedProxiesTravelWithProviders`, `saved-proxies.test.cjs`, `provider-proxy-missing.test.cjs`. | [`proxies.go`](../../internal/settings/proxies.go), [`netproxy.go`](../../internal/netproxy/netproxy.go), [`proxies.go`](../../internal/gui/proxies.go) | ## Remote magpie diff --git a/internal/backup/auto.go b/internal/backup/auto.go index 8f0365e50..3c6e86cf9 100644 --- a/internal/backup/auto.go +++ b/internal/backup/auto.go @@ -406,6 +406,7 @@ func autoCollect(app string) (Bundle, error) { s := *b.Settings s.Proxy, s.ProxyCustom = "", "" s.PluginProxy, s.PluginProxyCustom = "", "" + s.Proxies = nil b.Settings = &s } return b, err diff --git a/internal/backup/backup.go b/internal/backup/backup.go index 8e9d7bdc7..17fbb9981 100644 --- a/internal/backup/backup.go +++ b/internal/backup/backup.go @@ -93,6 +93,10 @@ type Bundle struct { // the providers they serve come with them. Their sign-ins don't, as a // subscription's don't. Nil from a magpie before them. Plugins *[]plugin.Entry `json:"plugins,omitempty"` + // Proxies are the proxies kept by name, which providers, accounts and + // Settings name as "@id". They travel with the providers, passwords + // only when the providers' keys do; nil from a magpie before them. + Proxies *[]settings.NamedProxy `json:"proxies,omitempty"` // Sync can carry one part's credentials without changing the others' // Keys policy; these are absent from older backups and whole collects. ProvidersKeys *bool `json:"providersKeys,omitempty"` @@ -161,6 +165,8 @@ func (b Bundle) scopedKeys(part string) bool { own = b.SettingsKeys case "library": own = b.LibraryKeys + case "providers": + own = b.ProvidersKeys } if own != nil { return *own @@ -236,6 +242,14 @@ func Collect(keys bool, app string) (Bundle, error) { searches = append(searches, a) } b.Searches = &searches + // the saved proxies ride with the providers that name them + proxies := settings.Load().Proxies + if !keys { + proxies = settings.WithoutProxyPasswords(proxies) + } + if len(proxies) > 0 { + b.Proxies = &proxies + } // a settings.json that can't be read stops it too: carried as the // defaults, it would put them over the settings where it is put back, // or on every other computer sync mirrors it to (#2269) @@ -244,6 +258,8 @@ func Collect(keys bool, app string) (Bundle, error) { if err != nil { return b, err } + // the saved proxies hold passwords and are this computer's own (KeepOwn) + s.Proxies = nil if !keys { s.LANKey, s.LANKeyID = "", "" s.OTel.Headers = nil @@ -431,6 +447,12 @@ func Restore(b Bundle, parts Parts) (Result, error) { r.SignIns = &res } if parts.Providers { + // the proxies first: a provider's choice of one is checked against them + if b.Proxies != nil { + if err := settings.RestoreProxies(*b.Proxies, b.scopedKeys("providers")); err != nil { + return r, fmt.Errorf("putting the saved proxies in: %w", err) + } + } for name, data := range b.Icons { if f := provider.IconFile(name); f != "" && len(data) <= provider.MaxIcon { if _, err := os.Stat(f); err != nil { diff --git a/internal/backup/saved_proxies_test.go b/internal/backup/saved_proxies_test.go new file mode 100644 index 000000000..638710329 --- /dev/null +++ b/internal/backup/saved_proxies_test.go @@ -0,0 +1,95 @@ +package backup + +import ( + "strings" + "testing" + + "github.com/yetone/magpie/internal/netproxy" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// A provider that names a saved proxy ("@id") works on the computer it is +// carried to with no setup: the list goes with the providers, the passwords +// only when their keys do. One that still names a proxy this computer lacks +// fails, and says which (@tsingchao on X). +func TestSavedProxiesTravelWithProviders(t *testing.T) { + for _, keys := range []bool{false, true} { + t.Run(map[bool]string{false: "keyless", true: "keys"}[keys], func(t *testing.T) { + home(t) + s := settings.Load() + s.Proxies = []settings.NamedProxy{{ID: "px1", Name: "Office", URL: "http://10.0.0.1:8080", User: "me", Pass: "hunter2"}} + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + id, err := provider.Add(provider.Provider{Name: "Via office", Chat: "https://a.example.com/v1", Key: "sk-a", Models: []string{"m"}, Proxy: "@px1"}) + if err != nil { + t.Fatal(err) + } + b, err := Collect(keys, "test") + if err != nil { + t.Fatal(err) + } + if b.Proxies == nil || len(*b.Proxies) != 1 { + t.Fatalf("the bundle holds no saved proxy: %+v", b.Proxies) + } + if b.Settings != nil && len(b.Settings.Proxies) != 0 { + t.Fatal("the list rides in Settings too, passwords and all") + } + if got := (*b.Proxies)[0].Pass; keys != (got != "") { + t.Fatalf("password in the bundle = %q with keys=%v", got, keys) + } + + home(t) // the other computer, which has no proxies + if _, err := Restore(b, Parts{Providers: true}); err != nil { + t.Fatal(err) + } + if provider.ProxyGone(mustProvider(t, id)) != "" { + t.Fatal("the provider's proxy is missing after the restore") + } + u, err := netproxy.Parse("@px1") + if err != nil || u.Host != "10.0.0.1:8080" { + t.Fatalf("Parse(@px1) = %v, %v", u, err) + } + if pass, _ := u.User.Password(); keys != (pass == "hunter2") { + t.Fatalf("restored password %q with keys=%v", pass, keys) + } + + // no list came (an older magpie): fails closed, naming the proxy it was + s2 := settings.Load() + s2.Proxies = nil + if err := settings.Save(s2); err != nil { + t.Fatal(err) + } + if _, err := netproxy.Parse("@px1"); err == nil || !strings.Contains(err.Error(), "Office") { + t.Fatalf("a missing proxy's error must name it: %v", err) + } + if got := provider.ProxyGone(mustProvider(t, id)); got != "Office" { + t.Fatalf("ProxyGone = %q, want Office", got) + } + }) + } +} + +func mustProvider(t *testing.T, id string) provider.Provider { + t.Helper() + for _, p := range provider.All() { + if p.ID == id { + return p + } + } + t.Fatalf("no provider %q", id) + return provider.Provider{} +} + +func TestMergeProxies(t *testing.T) { + cur := []settings.NamedProxy{{ID: "a", Name: "Home", URL: "http://h:1", Pass: "mine"}, {ID: "b", Name: "Lab", URL: "http://l:1"}} + in := []settings.NamedProxy{{ID: "a", Name: "Home", URL: "http://h:2"}, {ID: "c", Name: "lab", URL: "http://c:1", Pass: "theirs"}} + got := settings.MergeProxies(cur, in, false) + if len(got) != 3 || got[0].URL != "http://h:2" || got[0].Pass != "mine" || got[1].ID != "b" || got[2].Pass != "" || got[2].Name == "lab" { + t.Fatalf("%+v", got) + } + if got = settings.MergeProxies(cur, in, true); got[0].Pass != "" && got[2].Pass != "theirs" { + t.Fatalf("%+v", got) + } +} diff --git a/internal/davsync/davsync.go b/internal/davsync/davsync.go index 045742812..fce06376e 100644 --- a/internal/davsync/davsync.go +++ b/internal/davsync/davsync.go @@ -880,6 +880,9 @@ func hashes(b backup.Bundle) map[string]string { if b.Plugins != nil && len(*b.Plugins) > 0 { // as before them, without one providers = append(providers, map[string][]plugin.Entry{"plugins": *b.Plugins}) } + if b.Proxies != nil && len(*b.Proxies) > 0 { // as before them, without one + providers = append(providers, map[string][]settings.NamedProxy{"proxies": *b.Proxies}) + } lib := b.Library if lib != nil && lib.Subagents != nil && len(*lib.Subagents) == 0 { // as before them, without one c := *lib @@ -915,7 +918,7 @@ func hashes(b backup.Bundle) map[string]string { func unset(b backup.Bundle, p string) bool { switch p { case "providers": - return len(b.Providers) == 0 && len(b.Groups) == 0 + return len(b.Providers) == 0 && len(b.Groups) == 0 && (b.Proxies == nil || len(*b.Proxies) == 0) case "settings": var s settings.Settings if b.Settings != nil { @@ -1008,6 +1011,17 @@ func take(to *backup.Bundle, from backup.Bundle, part string) { } to.Providers, to.Icons, to.Groups, to.Searches, to.Order, to.GroupOrder = ps, from.Icons, from.Groups, searches, from.Order, from.GroupOrder to.Plugins = from.Plugins + if from.Proxies != nil { // the saved proxies the providers name, their passwords as the keys are + px := slices.Clone(*from.Proxies) + if !keys && to.Proxies != nil && (to.Keys || (to.ProvidersKeys != nil && *to.ProvidersKeys)) { + for i := range px { + if j := slices.IndexFunc(*to.Proxies, func(o settings.NamedProxy) bool { return o.ID == px[i].ID }); j >= 0 && px[i].Pass == "" { + px[i].Pass = (*to.Proxies)[j].Pass + } + } + } + to.Proxies = &px + } to.ProvidersKeys = backup.Flag(keys || (to.ProvidersKeys != nil && *to.ProvidersKeys)) to.Keys = to.Keys || keys // the whole-bundle bit follows it, for a magpie that reads no per-part ones: it keeps the server's keys on its own upload then case "settings": diff --git a/internal/davsync/scoped_keys_test.go b/internal/davsync/scoped_keys_test.go index 62e365090..e0b4887c9 100644 --- a/internal/davsync/scoped_keys_test.go +++ b/internal/davsync/scoped_keys_test.go @@ -282,3 +282,19 @@ func TestTakeScopedPartCredentials(t *testing.T) { } } } + +// A providers upload carries the saved proxies they name, and a keyless one +// keeps the passwords the server already has. +func TestTakeSavedProxies(t *testing.T) { + to := backup.Bundle{Version: backup.BundleVersion, Keys: true, ProvidersKeys: backup.Flag(true), + Proxies: &[]settings.NamedProxy{{ID: "px1", Name: "Office", URL: "http://o:1", Pass: "server"}}} + from := backup.Bundle{Version: backup.BundleVersion, ProvidersKeys: backup.Flag(false), + Proxies: &[]settings.NamedProxy{{ID: "px1", Name: "Office", URL: "http://o:2"}, {ID: "px2", Name: "Home", URL: "http://h:1"}}} + take(&to, from, "providers") + if to.Proxies == nil || len(*to.Proxies) != 2 || (*to.Proxies)[0].URL != "http://o:2" || (*to.Proxies)[0].Pass != "server" { + t.Fatalf("%+v", to.Proxies) + } + if backup.Bundle(to).Proxies == nil || hashes(to)["providers"] == hashes(backup.Bundle{Version: backup.BundleVersion})["providers"] { + t.Fatal("a change in the saved proxies doesn't change the providers' hash") + } +} diff --git a/internal/gui/api.go b/internal/gui/api.go index 1cc278063..9e24ca63c 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -458,8 +458,10 @@ type settingsJSON struct { Web bool `json:"web,omitempty"` // the proxy vendor requests go through now, and where it came from: // settings, environment, system, off or none - ProxyNow string `json:"proxyNow"` - ProxySource string `json:"proxySource"` + // SavedProxies are the named proxies, without their passwords + SavedProxies []savedProxyJSON `json:"proxies"` + ProxyNow string `json:"proxyNow"` + ProxySource string `json:"proxySource"` // whether magpie opens at login: the system's record, not a setting; // LoginAllow, the record is there but the user switched it off in // System Settings › Login Items, which is where it's allowed again @@ -864,6 +866,7 @@ func settingsState() settingsJSON { s.NotifyProblem = notifyProblem() } s.ProxyNow, s.ProxySource = netproxy.Describe() + s.Settings.Proxies, s.SavedProxies = nil, savedProxies() // passwords stay on disk s.NoAccountsEnv = settings.AccountDiscoveryOff() && !s.NoAccountDiscovery for _, name := range []string{"MAGPIE_OTEL_ENABLED", "MAGPIE_OTEL_ENDPOINT", "MAGPIE_OTEL_HEADERS", "MAGPIE_OTEL_METRICS", "MAGPIE_OTEL_BODIES", "MAGPIE_OTEL_BODIES_WHOLE", "MAGPIE_OTEL_SESSIONS"} { if _, ok := os.LookupEnv(name); ok { @@ -2036,6 +2039,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { // Settings › Proxy's Test (#2076): the address Cloudflare sees a request // from through the proxy in force, and without it mux.HandleFunc("POST /api/proxy/check", handleProxyCheck) + proxyRoutes(mux) mux.HandleFunc("POST /api/settings/codex-titles", func(rw http.ResponseWriter, r *http.Request) { var in struct{ Model string } if err := json.NewDecoder(r.Body).Decode(&in); err != nil { diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 297044555..21f151856 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -3429,6 +3429,13 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .editor .proxy-row .proxy-mode { flex: none; } .editor .proxy-row input.proxy-url { flex: 1 1 auto; width: auto; min-width: 0; } .editor .proxy-row input.proxy-url.off { visibility: hidden; } +.editor .proxy-row .gone { display: none; } +.editor .proxy-row .proxy-saved { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: left; } +.saved-proxy .sub { overflow-wrap: anywhere; } +.proxy-form { flex-wrap: wrap; } +.proxy-form .proxy-controls { justify-content: flex-end; flex: 1 1 100%; } +.proxy-form .proxy-credential { flex: 1 1 10rem; min-width: 0; } +.proxy-form .sub.err { flex: 1 1 100%; } .editor :is(input.concurrency, input.queue-limit, input.queue-wait)[type] { width: 12em; max-width: 100%; } .editor input[type="number"] { -moz-appearance: textfield; } .editor input[type="number"]::-webkit-inner-spin-button, .editor input[type="number"]::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 90e07a5c0..2b8ae4077 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -288,11 +288,6 @@ const PENCIL = "M3.5 12.5l.5-2.5 6.8-6.8a1.2 1.2 0 0 1 1.7 0l.3.3a1.2 1.2 0 0 1 const PUZZLE = "M6.2 2.8h2.3a1.3 1.3 0 1 1 2.5 0h2.2V5a1.3 1.3 0 1 0 0 2.6v5.6H3V7.6a1.3 1.3 0 1 1 0-2.6V2.8z"; // A brand icon: colour logos are images, mono logos take the text colour. -// Nothing is ever invented: a model with no known vendor keeps the slot -// empty, and a custom provider shows a plain outline ("generic"). -// A page redrawn whole (the Providers page, as a dialog opens or closes) -// hands its icons to keptIcons first and the new rows take them back: a -// logo made afresh loads its picture again and blinks out for a moment. let keptIcons = null; function keepIcons(...roots) { keptIcons = new Map(); @@ -2686,9 +2681,6 @@ function updatedSay() { // ---------- installing the agents not here (#727) ---------- // Under the list, the agents magpie knows that aren't on this machine, each // with its vendor's install commands to copy into a terminal: the vendor's -// installer first, then Homebrew's or npm's. magpie doesn't run them — a -// new computer may have no Node.js for npm yet, and an installer may ask -// for things in the terminal. Folded unless no agent is here at all. let installInfo = []; // [{ id, name, icon, commands: [{ via, command }] }] @@ -2864,10 +2856,6 @@ const isHidden = (a) => hiddenIds().includes(a.id); // unhideCleared: a hidden agent whose settings change so that nothing is set // on it any more goes under Not set up, its hiding dropped (Hu9956, #842): -// put back to its defaults it kept Hidden and its Show until the switch was -// turned on and off. One hidden while nothing was set on it stays hidden -// until something on it changes. True when the arrangement is saved, which -// renders the list again. const agentSeen = new Map(); // each agent's settings when last rendered const agentSig = (a) => JSON.stringify([!!a.wired, !!a.added, !!a.drift, a.fields.filter((f) => !tweak(f)).map((f) => [f.key, f.value || ""])]); function unhideCleared() { @@ -4628,9 +4616,6 @@ function score(q, o) { // popTop is the highest a popover's top edge may go, pad under the window's // own chrome: on a Mac window the traffic lights are drawn over the page's // header.top, so a list that opens upward in a short window stops under it -// rather than over them (#1573, lyston11). Elsewhere the header is the -// page's own row and the edge is pad, as it always was. The header's -// measured bottom already counts the text size (--zoom). function popTop(pad) { const b = document.body.classList; if (!b.contains("window") || !b.contains("mac")) return pad; @@ -6124,6 +6109,7 @@ function renderProviders(quiet) { if (p.off) name.append(el("span", "badge off", t("Switched off"))); if (p.self) name.append(Object.assign(el("span", "badge" + (p.keepSelf ? "" : " off"), t("This magpie")), { title: selfNote(p) })); if (p.move && p.move.state !== "plugin") name.append(deprecatedBadge()); + if (p.proxyGone) name.append(Object.assign(el("span", "badge off", t("Proxy missing: {name}", { name: p.proxyGone })), { title: t("This provider's proxy isn't on this computer, so its requests fail until another is picked") })); const n = p.models.filter((m) => m.on).length; // rate windows: what it bills at now (#2463) if (p.rateNow > 0) { @@ -7187,9 +7173,6 @@ function renderAdd() { // one moved onto its plugin stays where it was, signing in through it; // a deprecated one whose plugin is installed is that plugin's row alone // (ARNO on Discord: Qoder CN twice), and one with no account isn't - // offered at all: it is the Plugins page's, installed from there - // (yetone: 对于新用户来说,这里应该只显示内置的 provider), unless it is - // signing in now. A search naming one finds it there. const named = (x) => !f || x.name.toLowerCase().includes(f) || x.agent.includes(f) || "subscription".includes(f); const subs = SUBS.filter((x) => !(replacedSub(x.agent) || unusedSub(x.agent)) || signing?.agent === x.agent).map((x) => subOf(x.agent)).filter(named); const inPlugins = f && SUBS.some((x) => unusedSub(x.agent) && signing?.agent !== x.agent && named(subOf(x.agent))); @@ -7702,7 +7685,39 @@ const PROXY_HINT = { "": "Follows the proxy in Settings", direct: "Requests to it go direct, whatever the proxy in Settings", custom: "Requests to it go through this proxy: http://, https:// or socks5://", + saved: "Requests to it go through this saved proxy, kept in Settings", }; +// the named proxies of Settings › Network, chosen as "@id" wherever a proxy can be +function savedProxyList() { return prefs?.proxies || []; } +function savedProxyName(ref) { + const p = savedProxyList().find((x) => x.id === String(ref || "").slice(1)); + return p ? p.name : t("A proxy that is gone"); +} +// a Saved mode beside the others, once a proxy is saved (or one is chosen) +function withSavedMode(modes, saved) { + return savedProxyList().length || saved ? [...modes, ["saved", t("Saved")]] : modes; +} +function firstSavedRef() { + const p = savedProxyList()[0]; + return p ? "@" + p.id : ""; +} +// savedProxyButton: the saved proxy chosen, a menu of the others +function savedProxyButton(ref, onPick) { + const b = el("button", "text proxy-saved", ref ? savedProxyName(ref) : t("Choose a proxy")); + b.type = "button"; + b.setAttribute("aria-haspopup", "menu"); + b.title = b.textContent; + b.onclick = (e) => { + e.stopPropagation(); + const opts = savedProxyList().map((x) => ({ v: "@" + x.id, name: x.name, literalName: true })); + openProtoMenu(b, opts, ref || "", (v) => { + ref = v; + b.textContent = b.title = savedProxyName(v); + onPick(v); + }, "Choose a proxy"); + }; + return b; +} function proxyPicker() { const box = el("div", "stack proxy-pick"); const hint = el("div", "hint", t(PROXY_HINT[draft.proxyMode || ""])); @@ -7710,16 +7725,28 @@ function proxyPicker() { addr.className = "proxy-url"; addr.classList.toggle("off", draft.proxyMode !== "custom"); const login = proxyLoginRow(addr, (v) => { draft.proxyURL = v; }); - const seg = segs([["", t("Global proxy")], ["direct", t("Direct")], ["custom", t("Custom")]], draft.proxyMode || "", (v) => { - draft.proxyMode = v; + const saved = savedProxyButton(draft.proxyRef, (v) => { draft.proxyRef = v; }); + const place = (v) => { addr.classList.toggle("off", v !== "custom"); + addr.classList.toggle("gone", v === "saved"); login.classList.toggle("off", v !== "custom"); + login.classList.toggle("gone", v === "saved"); + saved.hidden = v !== "saved"; + }; + const seg = segs(withSavedMode([["", t("Global proxy")], ["direct", t("Direct")], ["custom", t("Custom")]], draft.proxyMode === "saved"), draft.proxyMode || "", (v) => { + draft.proxyMode = v; + if (v === "saved" && !draft.proxyRef) { + draft.proxyRef = firstSavedRef(); + saved.textContent = saved.title = savedProxyName(draft.proxyRef); + } + place(v); hint.textContent = t(PROXY_HINT[v]); }); seg.classList.add("proxy-mode"); + place(draft.proxyMode || ""); // its room kept while not asked for: a pick never moves the dialog const row = el("div", "proxy-row"); - row.append(seg, addr); + row.append(seg, addr, saved); box.append(row, login, hint); return box; } @@ -7975,8 +8002,11 @@ function proxyDraft(p) { const v = (p?.proxy || "").trim(); // each account's own (accountProxies), by its name in lower case const accountProxies = {}; - for (const [u, x] of Object.entries(p?.accountProxies || {})) accountProxies[u] = { mode: x === "direct" ? "direct" : "custom", url: x === "direct" ? "" : x }; - return { proxyMode: !v ? "" : v === "direct" ? "direct" : "custom", proxyURL: v && v !== "direct" ? v : "", accountProxies }; + for (const [u, x] of Object.entries(p?.accountProxies || {})) { + accountProxies[u] = x === "direct" ? { mode: "direct", url: "" } : x.startsWith("@") ? { mode: "saved", url: "", ref: x } : { mode: "custom", url: x }; + } + const ref = v.startsWith("@"); + return { proxyMode: !v ? "" : v === "direct" ? "direct" : ref ? "saved" : "custom", proxyURL: v && v !== "direct" && !ref ? v : "", proxyRef: ref ? v : "", accountProxies }; } // asTyped: the editor's form as it stands, for Refresh and the Tests to // ask with before a Save — a key just pasted over the saved one is the one @@ -8013,6 +8043,7 @@ const CERT_FIELDS = ["clientCert", "clientKey", "serverCA"]; // has no address yet. function proxyOfDraft() { if (draft.proxyMode === "direct") return "direct"; + if (draft.proxyMode === "saved") return draft.proxyRef || null; if (draft.proxyMode !== "custom") return ""; return (draft.proxyURL || "").trim() || null; } @@ -8020,9 +8051,6 @@ function proxyOfDraft() { // accountProxyPicker: one proxy per account of a subscription holding // several (gakki: one Codex account through one proxy, another through // another) — the provider's own (the row above), none, or its own address. -// Each account is a line of its name over the same row as the provider's, -// the address's room kept while it isn't asked for, so a pick moves -// nothing. null for a subscription with one account: the row above is its. const ACCOUNT_PROXY_HINT = "Each account can go through a proxy of its own; Provider's proxy is the one above"; function accountProxyPicker(a, p) { const ls = [...(a?.logins || [])]; @@ -8100,14 +8128,27 @@ function proxyLine(it) { addr.className = "proxy-url"; addr.classList.toggle("off", cur.mode !== "custom"); const login = proxyLoginRow(addr, (v) => { draft.accountProxies[k] = { ...(draft.accountProxies[k] || { mode: "custom" }), url: v }; }); - const seg = segs([["", t("Provider's proxy")], ["direct", t("Direct")], ["custom", t("Custom")]], cur.mode || "", (v) => { - draft.accountProxies[k] = { ...(draft.accountProxies[k] || {}), mode: v }; + const saved = savedProxyButton(cur.ref, (v) => { draft.accountProxies[k] = { ...(draft.accountProxies[k] || {}), ref: v }; }); + const place = (v) => { addr.classList.toggle("off", v !== "custom"); + addr.classList.toggle("gone", v === "saved"); login.classList.toggle("off", v !== "custom"); + login.classList.toggle("gone", v === "saved"); + saved.hidden = v !== "saved"; + }; + const seg = segs(withSavedMode([["", t("Provider's proxy")], ["direct", t("Direct")], ["custom", t("Custom")]], cur.mode === "saved"), cur.mode || "", (v) => { + const now = { ...(draft.accountProxies[k] || {}), mode: v }; + if (v === "saved" && !now.ref) { + now.ref = firstSavedRef(); + saved.textContent = saved.title = savedProxyName(now.ref); + } + draft.accountProxies[k] = now; + place(v); }); seg.classList.add("proxy-mode"); + place(cur.mode || ""); const row = el("div", "proxy-row"); - row.append(seg, addr); + row.append(seg, addr, saved); line.append(who, row, login); return line; } @@ -8118,6 +8159,7 @@ function accountProxiesOfDraft() { const out = {}; for (const [u, x] of Object.entries(draft.accountProxies || {})) { if (x.mode === "direct") out[u] = "direct"; + else if (x.mode === "saved" && x.ref) out[u] = x.ref; else if (x.mode === "custom") { const v = (x.url || "").trim(); if (!v) return { missing: u }; @@ -8514,9 +8556,6 @@ const BIRD = ` api === "anthropic" ? "https://…" : api === "gemini" // respellURL turns a base URL into the one protocol api is asked at: the // root for Anthropic, which adds /v1 itself, …/v1 for OpenAI's two, // …/v1beta for Gemini's (as Google's SDKs add it). -// WORKSPACE stands for a Bailian workspace's id in a decision API's -// address (provider.WorkspaceID); workspaceOf is the id url has in its -// place in tmpl ("" for none), or null when url isn't at tmpl's host. const WORKSPACE = "{WorkspaceId}"; function workspaceOf(tmpl, url) { if (!tmpl || !url) return null; @@ -15764,9 +15802,6 @@ function unrollSheet(view, sheet, e) { // unrollInView: the agents' scroll unrolls under the button clicked for it, // and in a view with no more room below (the panel at its tallest, the // window scrolled to its end) the view goes down with it, led by the scroll's -// foot frame by frame, so what unrolls comes into sight — but never so far -// that the button goes out of it at the top. The reader scrolling meanwhile -// has the view from then on. function unrollInView(fold, button, e) { const v = fold.closest(".view"); if (!v || !scrollOnPurpose(e, UNROLL.ms + 400)) return; @@ -15820,9 +15855,6 @@ let quotaHist = []; // each account's windows over time, for the curves (#651) // quotasOpened: the reader opened what shows the allowances (the Usage // page's Overview, the tray panel's Allowances tab, a menu bar cell, either // brought back to the front): an asked read (#1588, #1518), which reads -// every account again, so opening within QUOTAS_OPEN_GAP of the last one -// (tabs, focus and visibility both firing) asks nothing. Refresh always -// asks, saved Claude accounts too ("all", #5380). const QUOTAS_OPEN_GAP = 30e3; let quotasAskedAt = -Infinity; function quotasOpened() { @@ -19838,9 +19870,6 @@ function searchSettings(q) { // Settings' Command line (PAMI on Discord): whether `magpie` in a terminal // opened now runs this app, in each shell, and a button that puts it there // — a link in a folder already on PATH, on Windows the app's folder first -// in the user's PATH. A shell's profile is written only from that shell's -// own button, with the file it names. Asked once a load and again after -// half a minute: each shell is run to read its PATH. let cliView = null, cliAt = 0, cliAsk = null; const exeName = (p) => String(p || "").split(/[\\/]/).pop(); function renderCLI(r) { @@ -20051,6 +20080,7 @@ function renderSettings() { renderPluginCheckins(s); renderTrayUsage(s, keep); renderProxy(s, keep); + window.renderSavedProxies ? renderSavedProxies(s) : import("./proxies.js").then(() => renderSavedProxies(s), () => {}); renderGitHubToken(s); renderImages(s, keep); renderSearch(s, keep); @@ -20723,7 +20753,7 @@ function proxyDisplay(value) { return (value || "").replace(/^(\w+:\/\/)?[^/?#]*@/, "$1"); } function renderProxy(s, keep) { - const cur = !s.proxy ? "auto" : s.proxy === "direct" ? "off" : "custom"; + const cur = !s.proxy ? "auto" : s.proxy === "direct" ? "off" : s.proxy.startsWith("@") ? "saved" : "custom"; const sub = $("#proxySub"); sub.textContent = { settings: t("Requests to vendors without a proxy of their own, and update checks, go through {proxy}", { proxy: proxyDisplay(s.proxyNow) }), @@ -20734,7 +20764,7 @@ function renderProxy(s, keep) { }[s.proxySource] || ""; const row = proxyRow(s, keep, { key: "proxy", box: $("#proxySegs"), cur, state: proxyState, - modes: [["auto", t("Auto")], ["off", t("Off")], ["custom", t("Custom")]], + modes: withSavedMode([["auto", t("Auto")], ["off", t("Off")], ["custom", t("Custom")]], cur === "saved"), again: () => renderProxy(s, keep), }); renderProxyCheck(s, row); @@ -20745,12 +20775,12 @@ const proxyState = { custom: false }; const pluginProxyState = { custom: false }; function renderPluginProxy(s, keep) { const v = (s.pluginProxy || "").trim(); - const cur = !v ? "auto" : v === "direct" ? "off" : "custom"; + const cur = !v ? "auto" : v === "direct" ? "off" : v.startsWith("@") ? "saved" : "custom"; $("#pluginProxySub").textContent = cur === "auto" ? t("Plugins, npm and GitHub go through the proxy above") - : cur === "off" ? t("Plugins, npm and GitHub go direct") : t("Plugins, npm and GitHub go through {proxy}", { proxy: proxyDisplay(v) }); + : cur === "off" ? t("Plugins, npm and GitHub go direct") : t("Plugins, npm and GitHub go through {proxy}", { proxy: v.startsWith("@") ? savedProxyName(v) : proxyDisplay(v) }); proxyRow(s, keep, { key: "pluginProxy", box: $("#pluginProxySegs"), cur, state: pluginProxyState, - modes: [["auto", t("Same as above")], ["off", t("Direct")], ["custom", t("Custom")]], + modes: withSavedMode([["auto", t("Same as above")], ["off", t("Direct")], ["custom", t("Custom")]], cur === "saved"), again: () => renderPluginProxy(s, keep), }); } @@ -20767,6 +20797,7 @@ function proxyRow(s, keep, o) { o.state.custom = id === "custom"; if (id === "auto") savePrefs({ ...keep, [o.key]: "" }); else if (id === "off") savePrefs({ ...keep, [o.key]: "direct" }); + else if (id === "saved") savePrefs({ ...keep, [o.key]: firstSavedRef() }); else o.again(); }; if (mode === "custom") { @@ -20818,6 +20849,7 @@ function proxyRow(s, keep, o) { box.append(auth); if (o.state.custom) queueMicrotask(() => i.focus()); } + if (mode === "saved") row.append(savedProxyButton(s[o.key], (v) => savePrefs({ ...keep, [o.key]: v }))); const modes = segs(o.modes, mode, pick); // WebKit doesn't focus clicked buttons modes.onpointerdown = () => { picking = true; }; @@ -22764,13 +22796,6 @@ function savePrefs(body) { // ---------- where the reader is ---------- // For every view (gui-shell.md, "A click never moves"): -// - A view moves only for the reader (wheel, touch, scroll keys, Tab, a -// drag); any other scroll (a shorter redraw, WebKit centring a focused -// field, code) is put back before paint. -// - What the reader clicks stays put on screen while the click redraws -// around it, till they scroll, click again or it settles. A shorter page -// keeps room at its foot; data-unrolls goes down with what it opens. -// Code scrolls only with the reader's event: scrollOnPurpose(e). let purposeUntil = 0, held = null; // guardUntil is purposeUntil when the window is the click guard's own (a // field brought back into sight, backToReader): it lets that scroll stand, @@ -22995,9 +23020,6 @@ const onScreen = (n, v) => n.getBoundingClientRect().top - v.getBoundingClientRe // Only a play that moves it counts: a colour or a fade easing in (the hover // of the button just clicked, its label fading to its new words) leaves it // where it is. Were those passed over too, the page would be held by -// something further up while the button slid away, and snap back to the -// button once its hover had faded — and a button slid out from under the -// pointer and back fades its hover again, so the page swung between the two. const MOVES = /^(transform|translate|rotate|scale|top|bottom|left|right|inset|margin|offset-|position)/; const moving = (a) => a.playState === "running" && (a.transitionProperty ? MOVES.test(a.transitionProperty) : !a.effect?.getKeyframes || a.effect.getKeyframes().some((k) => Object.keys(k).some((p) => MOVES.test(p.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase()))))); @@ -23047,9 +23069,6 @@ function standIn(h) { // where the held parts are in the page, and how tall it is: what the hold // left (h.lay), and a redraw changes, a scroll not. Only parts that scroll // with the page and are in it: one drawn again (the Usage page's tabs, the -// agents' list under an agent opened or closed) or stuck to the view's edge -// (Settings' tabs, sticky) read as moved at every scroll, and for the hold's -// 4s every scroll was put back (issennknight on macOS 13) const scrolls = (n, v) => { for (; n && n !== v; n = n.parentElement) if (/sticky|fixed/.test(getComputedStyle(n).position)) return false; return !!n; }; function laid(h) { const at = []; @@ -23095,9 +23114,6 @@ let heldWidth = innerWidth; // It is the reader's place that is kept instead: where they were, or as far // down as the page goes, while it is laid out again. Crossing SIDE_AT, the // browser clamps the view to each layout it passes through (app.css's -// side-nav rules before layoutNav has moved the tabs, then a part a few -// pixels short of its new height), and the page ended short of its foot: -// at the foot of Settings, 960 to 1440 wide in WebKit left it 6px up (#911). let relaidUntil = 0; const relaid = new ResizeObserver(() => { if (performance.now() > relaidUntil) { relaid.disconnect(); return; } @@ -24219,9 +24235,6 @@ setInterval(async () => { // the Usage head is made tight, as at a narrow window, wherever its sum // would be cut (#1599, sean908): between 640px and the width its tabs, its // periods with Custom named and the refresh need, the sum was the one -// thing left to give way, and read ≈$0. for ≈$0.001. Tight, Custom is its -// icon and the sum may go to a line of its own, whole, in every language. -// Decided on the next frame, as the class changes the head's height. { const head = $("#usageCost").parentElement; let frame = 0; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index db3f164a5..f96d0911b 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2691,6 +2691,16 @@ const I18N = { // a provider's own proxy (#237) "Global proxy": "全局代理", "Direct": "直连", + "Proxy missing: {name}": "缺少代理:{name}", + "This provider's proxy isn't on this computer, so its requests fail until another is picked": "此提供商选用的代理不在这台电脑上,选择其他代理前请求会失败", + "Proxies": "代理", + "Add proxy": "添加代理", + "Choose a proxy": "选择代理", + "A proxy that is gone": "已删除的代理", + "Reachable, {ms} ms": "可连接,{ms} 毫秒", + "Unreachable: {error}": "无法连接:{error}", + "Used by {n}": "{n} 处在用", + "Requests to it go through this saved proxy, kept in Settings": "发往它的请求走这个已保存的代理,在设置中维护", "Follows the proxy in Settings": "跟随设置里的代理", "Requests to it go direct, whatever the proxy in Settings": "发往它的请求直连,不走设置里的代理", "Requests to it go through this proxy: http://, https:// or socks5://": "发往它的请求走这个代理:http://、https:// 或 socks5://", @@ -7695,6 +7705,16 @@ const I18N = { "Extra body: {why}": "額外請求體:{why}", "Global proxy": "全域代理", "Direct": "直連", + "Proxy missing: {name}": "缺少代理:{name}", + "This provider's proxy isn't on this computer, so its requests fail until another is picked": "此供應商選用的代理不在這台電腦上,選擇其他代理前請求會失敗", + "Proxies": "代理", + "Add proxy": "新增代理", + "Choose a proxy": "選擇代理", + "A proxy that is gone": "已刪除的代理", + "Reachable, {ms} ms": "可連線,{ms} 毫秒", + "Unreachable: {error}": "無法連線:{error}", + "Used by {n}": "{n} 處使用中", + "Requests to it go through this saved proxy, kept in Settings": "發往它的請求走這個已儲存的代理,在設定中維護", "Follows the proxy in Settings": "跟隨設定裡的代理", "Requests to it go direct, whatever the proxy in Settings": "發往它的請求直連,不走設定裡的代理", "Requests to it go through this proxy: http://, https:// or socks5://": "發往它的請求走這個代理:http://、https:// 或 socks5://", @@ -12676,6 +12696,16 @@ const I18N = { "Extra body: {why}": "追加ボディ: {why}", "Global proxy": "グローバルプロキシ", "Direct": "直接接続", + "Proxy missing: {name}": "プロキシがありません:{name}", + "This provider's proxy isn't on this computer, so its requests fail until another is picked": "このプロバイダのプロキシはこのコンピュータにないため、別のプロキシを選ぶまでリクエストは失敗します", + "Proxies": "プロキシ", + "Add proxy": "プロキシを追加", + "Choose a proxy": "プロキシを選択", + "A proxy that is gone": "削除されたプロキシ", + "Reachable, {ms} ms": "接続できます、{ms} ms", + "Unreachable: {error}": "接続できません:{error}", + "Used by {n}": "{n} 件で使用中", + "Requests to it go through this saved proxy, kept in Settings": "このプロバイダへのリクエストは保存済みのプロキシを経由します。設定で管理します", "Follows the proxy in Settings": "設定のプロキシに従う", "Requests to it go direct, whatever the proxy in Settings": "設定のプロキシに関係なく、このプロバイダへのリクエストは直接送られます", "Requests to it go through this proxy: http://, https:// or socks5://": "このプロバイダへのリクエストはこのプロキシを経由します:http://、https://、socks5://", @@ -17688,6 +17718,16 @@ const I18N = { "Extra body: {why}": "Zusätzlicher Body: {why}", "Global proxy": "Globaler Proxy", "Direct": "Direkt", + "Proxy missing: {name}": "Proxy fehlt: {name}", + "This provider's proxy isn't on this computer, so its requests fail until another is picked": "Der Proxy dieses Anbieters ist auf diesem Computer nicht vorhanden; Anfragen schlagen fehl, bis ein anderer gewählt ist", + "Proxies": "Proxys", + "Add proxy": "Proxy hinzufügen", + "Choose a proxy": "Proxy wählen", + "A proxy that is gone": "Ein gelöschter Proxy", + "Reachable, {ms} ms": "Erreichbar, {ms} ms", + "Unreachable: {error}": "Nicht erreichbar: {error}", + "Used by {n}": "An {n} Stellen verwendet", + "Requests to it go through this saved proxy, kept in Settings": "Anfragen gehen über diesen gespeicherten Proxy, der in den Einstellungen verwaltet wird", "Follows the proxy in Settings": "Folgt dem Proxy aus den Einstellungen", "Requests to it go direct, whatever the proxy in Settings": "Anfragen gehen direkt, unabhängig vom Proxy in den Einstellungen", "Requests to it go through this proxy: http://, https:// or socks5://": "Anfragen gehen über diesen Proxy: http://, https:// oder socks5://", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index a4c75cc62..33722fd1f 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -356,6 +356,8 @@
+
Proxies
+
GitHub
Gateway
diff --git a/internal/gui/assets/proxies.js b/internal/gui/assets/proxies.js new file mode 100644 index 000000000..cff386e6a --- /dev/null +++ b/internal/gui/assets/proxies.js @@ -0,0 +1,89 @@ +// Settings › Network's saved proxies: their rows, the test and the form. +// app.js imports this when Settings draws them, so it weighs nothing on the core. + +let proxyForm = null; // { id, name, url, user, hasPass, err } while one is added or edited +const proxyChecks = {}; // id -> { busy, out } +window.renderSavedProxies = function (s) { + const box = $("#proxiesList"); + box.replaceChildren(); + const done = (ns) => { prefs = ns; proxyForm = null; renderSettings(); }; + for (const p of s.proxies || []) { + if (proxyForm && proxyForm.id === p.id) { box.append(proxyFormRow(done)); continue; } + const r = el("div", "row pref saved-proxy"); + const who = el("div", "who"); + const sub = el("div", "sub"); + who.append(el("div", "name", p.name), sub); + const chk = proxyChecks[p.id]; + const out = chk?.out || p.check; + const line = [p.user ? p.user + "@" + p.url : p.url]; + if (chk?.busy) line.push(t("Testing…")); + else if (out) line.push(out.ok ? t("Reachable, {ms} ms", { ms: out.ms }) : t("Unreachable: {error}", { error: out.error || "" })); + if (p.uses?.length) line.push(t("Used by {n}", { n: p.uses.length })); + sub.textContent = sub.title = line.join(" · "); + sub.classList.toggle("err", !!out && !out.ok && !chk?.busy); + const val = el("div", "val"); + const test = el("button", "text", chk?.busy ? t("Testing…") : t("Test")); + test.disabled = !!chk?.busy; + test.onclick = () => { + proxyChecks[p.id] = { busy: true }; + renderSettings(); + api("proxies/test", { id: p.id }) + .then((o) => { proxyChecks[p.id] = { out: o }; }) + .catch((e) => { proxyChecks[p.id] = { out: { ok: false, error: t(e.message) } }; }) + .finally(renderSettings); + }; + const edit = el("button", "text", t("Edit")); + edit.onclick = () => { proxyForm = { id: p.id, name: p.name, url: p.url, user: p.user || "", hasPass: !!p.hasPass }; renderSettings(); }; + const del = el("button", "text", t("Delete")); + del.disabled = !!p.uses?.length; + del.onclick = () => writingPrefs(api("proxies/delete", { id: p.id })).then(done).catch(statusTErr); + val.append(test, edit, del); + r.append(who, val); + box.append(r); + } + if (proxyForm && !proxyForm.id) box.append(proxyFormRow(done)); + else if (!proxyForm) { + const r = el("div", "row pref"); + const add = el("button", "text", t("Add proxy")); + add.onclick = () => { proxyForm = { id: "", name: "", url: "", user: "", hasPass: false }; renderSettings(); }; + r.append(el("div", "who", ""), el("div", "val")); + r.lastChild.append(add); + box.append(r); + } +}; +function proxyFormRow(done) { + const f = proxyForm; + const r = el("div", "row pref proxy-form"); + const name = input(f.name, t("Name")); + const url = input(f.url, "http://127.0.0.1:7890"); + const user = input(f.user, t("Username (optional)")); + const pass = input("", f.hasPass ? "••••••••" : t("Password (optional)"), "password"); + name.setAttribute("aria-label", t("Name")); + url.setAttribute("aria-label", t("Proxy address")); + user.setAttribute("aria-label", t("Username (optional)")); + pass.setAttribute("aria-label", t("Password (optional)")); + const err = el("div", "sub err", f.err || ""); + const save = el("button", "text", t("Save")); + const cancel = el("button", "text", t("Cancel")); + const body = () => { + const b = { id: f.id, name: name.value.trim(), url: url.value.trim(), user: user.value.trim() }; + if (pass.value) b.pass = pass.value; // blank keeps the saved password + return b; + }; + save.onclick = () => { + if (!name.value.trim() || !url.value.trim()) return (name.value.trim() ? url : name).focus(); + const b = body(); + Object.assign(f, { name: b.name, url: b.url, user: b.user }); + writingPrefs(api("proxies/save", b)).then(done).catch((e) => { f.err = t(e.message); renderSettings(); }); + }; + cancel.onclick = () => { proxyForm = null; renderSettings(); }; + for (const x of [name, url, user, pass]) { + x.className = "proxy-credential"; + x.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") save.onclick(); else if (e.key === "Escape") cancel.onclick(); }; + } + const val = el("div", "proxy-controls"); + val.append(name, url, user, pass, cancel, save); + r.append(val, err); + err.hidden = !f.err; + return r; +} diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 4104579fb..dfb089771 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -425,6 +425,10 @@ type providerJSON struct { // Move is where a built-in subscription stands with the community // plugin that can run it (provider.Move): set for those that have one Move *moveJSON `json:"move,omitempty"` + // ProxyGone names a saved proxy this provider (or one of its accounts) + // chooses that isn't on this computer: its requests fail until another + // is picked, as a missing proxy never means a direct connection. + ProxyGone string `json:"proxyGone,omitempty"` // a subscription account's rests in force, by its user in lower case: // its own and each of its models' (maxleebeta on Discord: WorkBuddy's // 429 "将在 … 重置" rested a model, credits left, and nothing here said so) @@ -904,6 +908,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs } out.Key.Set = p.Key != "" out.Key.Masked = provider.Mask(p.Key) + out.ProxyGone = provider.ProxyGone(p) if provider.BuiltinRetired(p.ID) { // only its plugin's row is listed now: built-in accounts not moved // yet are providersJSON.Unmoved's diff --git a/internal/gui/proxies.go b/internal/gui/proxies.go new file mode 100644 index 000000000..51c7e3c1f --- /dev/null +++ b/internal/gui/proxies.go @@ -0,0 +1,247 @@ +package gui + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/netproxy" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// Named proxies (the Network page's list): kept once, chosen by reference +// wherever a proxy can be chosen. The page is sent the address without its +// login, the username and whether a password is set; the password is +// written and never read back, as the GitHub token is. + +// savedProxyJSON is a saved proxy as the page sees it. +type savedProxyJSON struct { + ID string `json:"id"` + Name string `json:"name"` + URL string `json:"url"` + User string `json:"user,omitempty"` + HasPass bool `json:"hasPass,omitempty"` + // Uses is where it is chosen: Settings' own two, then providers, + // accounts and keys + Uses []proxyUseJSON `json:"uses,omitempty"` + Check *proxyTestJSON `json:"check,omitempty"` +} + +type proxyUseJSON struct { + Where string `json:"where,omitempty"` // "global" or "plugins"; else a provider + Provider string `json:"provider,omitempty"` + Account string `json:"account,omitempty"` +} + +// proxyTestJSON is one connectivity check: whether a request got through +// the proxy, how long it took, and where it left from. +type proxyTestJSON struct { + OK bool `json:"ok"` + Ms int64 `json:"ms,omitempty"` + IP string `json:"ip,omitempty"` + Loc string `json:"loc,omitempty"` + Error string `json:"error,omitempty"` + At int64 `json:"at"` +} + +// proxyTestClient makes the check's request; a test swaps its own. +var proxyTestClient = http.DefaultClient + +var ( + proxyTestsMu sync.Mutex + proxyTests = map[string]proxyTestJSON{} +) + +func savedProxies() []savedProxyJSON { + cur := settings.Load() + var out []savedProxyJSON + proxyTestsMu.Lock() + defer proxyTestsMu.Unlock() + for _, p := range cur.Proxies { + ref := settings.ProxyRef(p.ID) + row := savedProxyJSON{ID: p.ID, Name: p.Name, URL: p.URL, User: p.User, HasPass: p.Pass != ""} + if strings.TrimSpace(cur.Proxy) == ref { + row.Uses = append(row.Uses, proxyUseJSON{Where: "global"}) + } + if strings.TrimSpace(cur.PluginProxy) == ref { + row.Uses = append(row.Uses, proxyUseJSON{Where: "plugins"}) + } + for _, u := range provider.ProxyUses(p.ID) { + row.Uses = append(row.Uses, proxyUseJSON{Provider: u.Provider, Account: u.Account}) + } + if c, ok := proxyTests[p.ID]; ok { + c := c + row.Check = &c + } + out = append(out, row) + } + return out +} + +// proxyIn is what the page sends to save or test a proxy. A nil Pass keeps +// the saved password (an edit that left it blank). +type proxyIn struct { + ID string `json:"id"` + Name string `json:"name"` + URL string `json:"url"` + User string `json:"user"` + Pass *string `json:"pass"` +} + +func (in proxyIn) named(cur []settings.NamedProxy) settings.NamedProxy { + p := settings.NamedProxy{ID: strings.TrimSpace(in.ID), Name: in.Name, URL: in.URL, User: strings.TrimSpace(in.User)} + if in.Pass != nil { + p.Pass = *in.Pass + } else { + for _, c := range cur { + if c.ID == p.ID { + p.Pass = c.Pass + } + } + } + return p +} + +func handleProxySave(rw http.ResponseWriter, r *http.Request) { + var in proxyIn + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + s := settings.Load() + p := in.named(s.Proxies) + found := false + if p.ID == "" { + p.ID = settings.NewProxyID() + if in.Pass == nil { + p.Pass = "" + } + } + for i := range s.Proxies { + if s.Proxies[i].ID == p.ID { + s.Proxies[i], found = p, true + } + } + if !found { + s.Proxies = append(s.Proxies, p) + } + if err := settings.Save(s); err != nil { + fail(rw, err) + return + } + provider.ProxyEdited() // Claude Code's env holds an address, not the name + // what it was checked as no longer says anything about it + proxyTestsMu.Lock() + delete(proxyTests, p.ID) + proxyTestsMu.Unlock() + writeJSON(rw, settingsState()) +} + +func handleProxyDelete(rw http.ResponseWriter, r *http.Request) { + var in struct { + ID string `json:"id"` + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + s := settings.Load() + var keep []settings.NamedProxy + for _, p := range s.Proxies { + if p.ID != in.ID { + keep = append(keep, p) + } + } + if len(keep) == len(s.Proxies) { + writeJSON(rw, settingsState()) + return + } + for _, row := range savedProxies() { + if row.ID == in.ID && len(row.Uses) > 0 { + rw.Header().Set("Content-Type", "application/json") + rw.WriteHeader(http.StatusConflict) + _ = json.NewEncoder(rw).Encode(map[string]any{"error": "the proxy is in use", "uses": row.Uses}) + return + } + } + s.Proxies = keep + if err := settings.Save(s); err != nil { + fail(rw, err) + return + } + proxyTestsMu.Lock() + delete(proxyTests, in.ID) + proxyTestsMu.Unlock() + writeJSON(rw, settingsState()) +} + +// handleProxyTest asks the trace page through one saved proxy (by id), or +// through one being typed (its address and login, unsaved). +func handleProxyTest(rw http.ResponseWriter, r *http.Request) { + var in proxyIn + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + cur := settings.Load().Proxies + var p settings.NamedProxy + if strings.TrimSpace(in.ID) != "" { + for _, c := range cur { + if c.ID == strings.TrimSpace(in.ID) { + p = c + } + } + if p.ID == "" { + fail(rw, fmt.Errorf("the saved proxy isn't there")) + return + } + if strings.TrimSpace(in.URL) != "" { // an edit not yet saved + p = in.named(cur) + } + } else { + p = in.named(cur) + p.Name = "test" + } + addr, err := p.Address() + if err != nil { + fail(rw, err) + return + } + // a typed address is checked as saving would + if err := settings.CheckProxy(addr); err != nil { + fail(rw, err) + return + } + out := testProxy(r.Context(), addr) + if in.ID != "" && strings.TrimSpace(in.URL) == "" { + proxyTestsMu.Lock() + proxyTests[p.ID] = out + proxyTestsMu.Unlock() + } + writeJSON(rw, out) +} + +func testProxy(ctx context.Context, addr string) proxyTestJSON { + leg := throughLeg(netproxy.With(ctx, addr), proxyTestClient) + out := proxyTestJSON{Ms: leg.Ms, IP: leg.IP, Loc: leg.Loc, At: time.Now().Unix()} + switch { + case leg.Error != "": + out.Error = redactProxyErr(leg.Error) + case !leg.Proxied: + out.Error = "the request didn't go to the proxy" + default: + out.OK = true + } + return out +} + +func proxyRoutes(mux *http.ServeMux) { + mux.HandleFunc("POST /api/proxies/save", handleProxySave) + mux.HandleFunc("POST /api/proxies/delete", handleProxyDelete) + mux.HandleFunc("POST /api/proxies/test", handleProxyTest) +} diff --git a/internal/gui/proxies_test.go b/internal/gui/proxies_test.go new file mode 100644 index 000000000..7ddaa1dad --- /dev/null +++ b/internal/gui/proxies_test.go @@ -0,0 +1,138 @@ +package gui + +import ( + "encoding/json" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +func proxiesRig(t *testing.T) (call func(path, body string) (int, string), state func() settingsJSON) { + t.Helper() + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + os.MkdirAll(filepath.Join(home, ".config"), 0o755) + h := Handler(nil, nil) + call = func(path, body string) (int, string) { + rec := httptest.NewRecorder() + method := "POST" + if body == "" { + method = "GET" + } + h.ServeHTTP(rec, httptest.NewRequest(method, path, strings.NewReader(body))) + return rec.Code, rec.Body.String() + } + state = func() settingsJSON { + code, body := call("/api/settings", "") + if code != 200 { + t.Fatalf("settings %d %s", code, body) + } + var s settingsJSON + if err := json.Unmarshal([]byte(body), &s); err != nil { + t.Fatal(err) + } + return s + } + return call, state +} + +// A saved proxy is added, edited (a blank password keeps the saved one), +// chosen by Settings and a provider, and refused deletion while chosen. The +// page is never sent the password, in a save's answer or in the state. +func TestSavedProxiesAPI(t *testing.T) { + call, state := proxiesRig(t) + const pass = "hunter2:/@secret" + code, body := call("/api/proxies/save", `{"name":"Office","url":"127.0.0.1:7890","user":"me","pass":"`+pass+`"}`) + if code != 200 || strings.Contains(body, "hunter2") { + t.Fatalf("save: %d %s", code, body) + } + s := state() + if len(s.SavedProxies) != 1 { + t.Fatalf("state: %+v", s.SavedProxies) + } + px := s.SavedProxies[0] + if px.Name != "Office" || px.URL != "127.0.0.1:7890" || px.User != "me" || !px.HasPass || !strings.HasPrefix(px.ID, "px") { + t.Fatalf("saved: %+v", px) + } + if _, raw := call("/api/settings", ""); strings.Contains(raw, "hunter2") || strings.Contains(raw, "secret") { + t.Fatalf("the password is in the state: %s", raw) + } + // an edit with no password sent keeps it + if code, _ := call("/api/proxies/save", `{"id":"`+px.ID+`","name":"Office","url":"127.0.0.1:7891","user":"me"}`); code != 200 { + t.Fatal(code) + } + if got := settings.Load().Proxies[0]; got.Pass != pass || got.URL != "127.0.0.1:7891" { + t.Fatalf("after an edit: %+v", got) + } + // a name twice, and a login in the address, are refused + if code, _ := call("/api/proxies/save", `{"name":"office","url":"127.0.0.1:1"}`); code != 400 { + t.Fatalf("a second Office: %d", code) + } + if code, _ := call("/api/proxies/save", `{"name":"B","url":"http://u:p@127.0.0.1:1"}`); code != 400 { + t.Fatalf("a login in the address: %d", code) + } + // chosen by Settings and by a provider: deletion is refused, naming both + ref := settings.ProxyRef(px.ID) + cur := settings.Load() + cur.Proxy = ref + if err := settings.Save(cur); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m"}, Proxy: ref}); err != nil { + t.Fatal(err) + } + code, body = call("/api/proxies/delete", `{"id":"`+px.ID+`"}`) + if code != 409 || !strings.Contains(body, "global") || !strings.Contains(body, "Relay") { + t.Fatalf("delete in use: %d %s", code, body) + } + // a provider can't choose one that isn't there + if err := provider.Save(provider.Provider{ID: "relay2", Name: "Relay2", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m"}, Proxy: "@nope"}); err == nil { + t.Fatal("a provider saved with a proxy that isn't there") + } + // let go of both: it goes + cur = settings.Load() + cur.Proxy = "" + settings.Save(cur) + provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m"}}) + if code, body := call("/api/proxies/delete", `{"id":"`+px.ID+`"}`); code != 200 || len(state().SavedProxies) != 0 { + t.Fatalf("delete: %d %s", code, body) + } +} + +// The check goes through the proxy named, with its login, and says whether +// it was reached and how long it took; an unsaved one is checked as typed. +func TestSavedProxyTest(t *testing.T) { + call, state := proxiesRig(t) + client, proxyURL, asked := proxyCheckRig(t) + old := proxyTestClient + proxyTestClient = client + t.Cleanup(func() { proxyTestClient = old }) + _, body := call("/api/proxies/test", `{"url":"`+proxyURL+`"}`) + var out proxyTestJSON + if err := json.Unmarshal([]byte(body), &out); err != nil || !out.OK || out.IP != "203.0.113.9" || *asked != 1 { + t.Fatalf("typed: %s (%v), asked %d", body, err, *asked) + } + call("/api/proxies/save", `{"name":"Up","url":"`+proxyURL+`"}`) + call("/api/proxies/save", `{"name":"Down","url":"http://127.0.0.1:1"}`) + for _, p := range state().SavedProxies { + _, body := call("/api/proxies/test", `{"id":"`+p.ID+`"}`) + var out proxyTestJSON + json.Unmarshal([]byte(body), &out) + if (p.Name == "Up") != out.OK { + t.Fatalf("%s: %s", p.Name, body) + } + } + for _, p := range state().SavedProxies { + if p.Check == nil || (p.Name == "Up") != p.Check.OK { + t.Fatalf("the last check of %s isn't kept: %+v", p.Name, p.Check) + } + } +} diff --git a/internal/gui/tests/old-webkit.test.cjs b/internal/gui/tests/old-webkit.test.cjs index 2bad8732c..7b69efe27 100644 --- a/internal/gui/tests/old-webkit.test.cjs +++ b/internal/gui/tests/old-webkit.test.cjs @@ -151,7 +151,7 @@ test("compat.js is the first of the page's own scripts", async () => { // open, claudemode.js when a Claude provider's editor opens, ctxtext.js // when a context window part is opened, resetask.js when a Codex reset's // Use is pressed, quotaall.js when a provider has two accounts, - // quitask.js when a Quit asks first, checkinnow.js when Settings' Check + // quitask.js when a Quit asks first, proxies.js when Settings draws its saved proxies, checkinnow.js when Settings' Check // in now for one account is pressed, autobackup.js when Settings draws // Sync, scrollends.js on the window's first scroll, profilerename.js // when a saved profile's Rename is pressed, keyspend.js when the @@ -174,7 +174,7 @@ test("compat.js is the first of the page's own scripts", async () => { // navicons.js (the sidebar lists' marks) with the first list drawn; // the checks above // still read them - for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); + for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); }); test("the styles hold up in Safari 15.0", async () => { diff --git a/internal/gui/tests/provider-proxy-missing.test.cjs b/internal/gui/tests/provider-proxy-missing.test.cjs new file mode 100644 index 000000000..9ec9024ea --- /dev/null +++ b/internal/gui/tests/provider-proxy-missing.test.cjs @@ -0,0 +1,68 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A provider synced here that names a saved proxy this computer lacks +// (@tsingchao on X) says so on its row, with the proxy's name; one whose +// proxy is there, or that has none, says nothing. +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 base = { + icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "", + models: [{ id: "model-a", name: "Model A", on: true }], agents: [], fallback: [], headers: {}, + key: { set: true, masked: "sk-…one" }, keyList: [], balanceToken: { takes: false, set: false }, +}; +const rows = [ + { ...base, id: "gone", name: "Via Office", proxy: "@px1", proxyGone: "Office" }, + { ...base, id: "fine", name: "Plain Relay", proxy: "" }, +]; + +function serve(lang) { + const providers = { providers: rows, presets: [], excluded: [], gateway: { running: true, window: true } }; + const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; + return async (route) => { + const url = new URL(route.request().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(state); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/groups") return json({ groups: [] }); + 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 badge = { + en: "Proxy missing: Office", zh: "缺少代理:Office", "zh-TW": "缺少代理:Office", + ja: "プロキシがありません:Office", de: "Proxy fehlt: Office", +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(badge)) { + for (const width of [1000, 420]) { + test(`${engine} ${lang} ${width}px: a provider's missing saved proxy is named on its row`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + await page.goto("http://magpie.test/?view=providers"); + const gone = page.locator('.row.provider[data-id="gone"]'); + await gone.waitFor(); + assert.equal(await gone.locator(".badge", { hasText: badge[lang] }).count(), 1); + assert.equal(await page.locator('.row.provider[data-id="fine"] .badge', { hasText: badge[lang].split("Office")[0] }).count(), 0); + const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + assert(over <= 0, `the page scrolls sideways by ${over}px`); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/gui/tests/saved-proxies.test.cjs b/internal/gui/tests/saved-proxies.test.cjs new file mode 100644 index 000000000..e350bc3cc --- /dev/null +++ b/internal/gui/tests/saved-proxies.test.cjs @@ -0,0 +1,113 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Named proxies (@tsingchao on X): Settings > Network keeps a list of them, +// each with a Test, and the global proxy picks one as "@id" in a Saved mode. +// A saved proxy in use can't be deleted; a password is typed, never shown. +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"); +function server(lang, posts) { + let cur = { + theme: "light", lang, tray: "panel", currency: "usd", textSize: 100, + proxy: "", proxyNow: "", proxySource: "off", pluginProxy: "", + trayUsageEvery: 3, version: "test", dir: "/test", lanURLs: [], + visionModels: [], imageGenModels: [], workbuddyCheckins: [], + proxies: [ + { id: "px1", name: "Office", url: "http://10.0.0.1:8080", user: "me", hasPass: true, uses: [{ where: "plugins" }] }, + { id: "px2", name: "Home", url: "socks5://192.168.1.2:1080" }, + ], + fx: { rate: 7.2, at: new Date().toISOString(), stale: false }, + }; + 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 = ${JSON.stringify({ 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({ agents: [], profiles: [], settings: { lang, theme: "light" }, fx: cur.fx }); + if (url.pathname === "/api/settings") { + if (req.method() === "POST") { const body = req.postDataJSON(); posts.push(body); cur = { ...cur, ...body, proxies: cur.proxies }; } + return json(cur); + } + if (url.pathname === "/api/proxies/test") { posts.push({ test: req.postDataJSON().id }); return json({ ok: true, ms: 42, at: 1 }); } + if (url.pathname === "/api/proxies/save") { + const b = req.postDataJSON(); + posts.push({ save: b }); + cur = { ...cur, proxies: [...cur.proxies, { id: "px3", name: b.name, url: b.url, user: b.user, hasPass: !!b.pass }] }; + return json(cur); + } + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + 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)]; + return route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const labels = { + en: { test: "Test", add: "Add proxy", name: "Name", save: "Save", del: "Delete", saved: "Saved", ok: "Reachable, 42 ms", pass: "Password (optional)" }, + zh: { test: "测试", add: "添加代理", name: "名称", save: "保存", del: "删除", saved: "已保存", ok: "可连接,42 毫秒", pass: "密码(可选)" }, + "zh-TW": { test: "測試", add: "新增代理", name: "名稱", save: "儲存", del: "刪除", saved: "已儲存", ok: "可連線,42 毫秒", pass: "密碼(選填)" }, + ja: { test: "テスト", add: "プロキシを追加", name: "名前", save: "保存", del: "削除", saved: "保存しました", ok: "接続できます、42 ms", pass: "パスワード(任意)" }, + de: { test: "Testen", add: "Proxy hinzufügen", name: "Name", save: "Speichern", del: "Löschen", saved: "Gespeichert", ok: "Erreichbar, 42 ms", pass: "Passwort (optional)" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(labels)) { + const l = labels[lang]; + for (const width of [1100, 420]) { + test(`${engine} ${lang} ${width}px: saved proxies are listed, tested and chosen`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const context = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(4000); + page.setDefaultNavigationTimeout(60000); + const posts = [], errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, posts)); + await page.goto("http://magpie.test/?view=settings&tab=network"); + const list = page.locator("#proxiesList"); + await list.getByText("Office", { exact: true }).waitFor(); + const rows = list.locator(".saved-proxy"); + assert.equal(await rows.count(), 2); + // the address shows without the password, and one in use can't be deleted + const first = await rows.nth(0).textContent(); + assert(first.includes("10.0.0.1:8080") && !first.includes("hunter"), first); + assert.equal(await rows.nth(0).getByRole("button", { name: l.del, exact: true }).isDisabled(), true); + assert.equal(await rows.nth(1).getByRole("button", { name: l.del, exact: true }).isDisabled(), false); + + // Test shows the answer + await rows.nth(1).getByRole("button", { name: l.test, exact: true }).click(); + await rows.nth(1).getByText(l.ok).waitFor(); + + // adding: a blank password isn't sent as one + await list.getByRole("button", { name: l.add, exact: true }).click(); + await list.getByLabel(l.name, { exact: true }).fill("Lab"); + await list.getByLabel(l.pass, { exact: true }).fill("s3cret"); + await list.locator("input").nth(1).fill("http://lab:3128"); + await list.getByRole("button", { name: l.save, exact: true }).click(); + await list.getByText("Lab", { exact: true }).waitFor(); + const save = posts.find((p) => p.save).save; + assert.deepEqual([save.name, save.url, save.pass], ["Lab", "http://lab:3128", "s3cret"]); + assert.equal(await page.evaluate(() => document.body.textContent.includes("s3cret")), false, "the password is never shown"); + + // the global proxy picks one as @id + const global = page.locator("#proxySegs"); + const response = page.waitForResponse((r) => r.url().endsWith("/api/settings") && r.request().method() === "POST"); + await global.getByRole("button", { name: l.saved, exact: true }).click(); + await response; + assert.equal(posts.filter((p) => "proxy" in p).at(-1).proxy, "@px1"); + await global.locator("button.proxy-saved").getByText("Office", { exact: true }).waitFor(); + + const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + assert(over <= 0, `the page scrolls sideways by ${over}px`); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/netproxy/named_test.go b/internal/netproxy/named_test.go new file mode 100644 index 000000000..b28cc3fb9 --- /dev/null +++ b/internal/netproxy/named_test.go @@ -0,0 +1,139 @@ +package netproxy + +import ( + "context" + "io" + "net/http" + "net/url" + "strings" + "testing" + + "github.com/yetone/magpie/internal/settings" +) + +func savedVia(t *testing.T, tr http.RoundTripper, choice string) (string, error) { + t.Helper() + req, _ := http.NewRequestWithContext(With(context.Background(), choice), http.MethodGet, "http://vendor.example/v1/models", nil) + res, err := tr.RoundTrip(req) + if err != nil { + return "", err + } + defer res.Body.Close() + b, _ := io.ReadAll(res.Body) + return string(b), nil +} + +// A request whose choice names a saved proxy goes through it, with the +// login kept beside the address; editing the proxy moves the next request +// to the new address, with no restart and no other place told; a deleted +// one fails the request, which never goes direct. +func TestSavedProxyChoice(t *testing.T) { + clearProxyEnv(t) + first := fakeHTTPProxy(t, loginUser, loginPass) + second := fakeHTTPProxy(t, "other", "secret") + save := func(ps ...settings.NamedProxy) { + t.Helper() + if err := settings.Save(settings.Settings{Proxies: ps}); err != nil { + t.Fatal(err) + } + } + save(settings.NamedProxy{ID: "pxa", Name: "A", URL: first.URL, User: loginUser, Pass: loginPass}) + base := &http.Transport{Proxy: Func} + tr := Dispatch(base) + t.Cleanup(base.CloseIdleConnections) + + if got, err := savedVia(t, tr, "@pxa"); err != nil || got != "carried http://vendor.example/v1/models" { + t.Fatalf("through the saved proxy: %q, %v", got, err) + } + // the same name, another address and login: the next request follows + save(settings.NamedProxy{ID: "pxa", Name: "A", URL: second.URL, User: "other", Pass: "secret"}) + if got, err := savedVia(t, tr, "@pxa"); err != nil || got != "carried http://vendor.example/v1/models" { + t.Fatalf("after the edit: %q, %v", got, err) + } + // a wrong password is refused by the proxy, so the login is the saved one + save(settings.NamedProxy{ID: "pxa", Name: "A", URL: second.URL, User: "other", Pass: "wrong"}) + if got, err := savedVia(t, tr, "@pxa"); err == nil && !strings.Contains(got, "refused") { + t.Fatalf("a wrong saved password was carried: %q", got) + } + // deleted: the request fails, it doesn't leave direct + save() + if got, err := savedVia(t, tr, "@pxa"); err == nil { + t.Fatalf("a request naming a deleted proxy was carried: %q", got) + } + if _, err := Parse("@pxa"); err == nil { + t.Fatal("Parse accepted a deleted proxy") + } +} + +// Settings' own proxy may name a saved one: every request without its own +// choice takes it, and a CLI magpie starts gets its address in *_PROXY; a +// deleted one points a CLI nowhere rather than direct. +func TestSavedProxyAsTheGlobalOne(t *testing.T) { + clearProxyEnv(t) + p := fakeHTTPProxy(t, loginUser, loginPass) + if err := settings.Save(settings.Settings{ + Proxy: "@pxg", + Proxies: []settings.NamedProxy{{ID: "pxg", Name: "G", URL: p.URL, User: loginUser, Pass: loginPass}}, + }); err != nil { + t.Fatal(err) + } + if body, code := throughSaved(t, "http://vendor.example/v1/models"); code != 200 || body != "carried http://vendor.example/v1/models" { + t.Fatalf("through the global saved proxy: %d %q", code, body) + } + env := func() string { + for _, e := range EnvWith("", []string{}) { + if k, v, _ := strings.Cut(e, "="); k == "HTTPS_PROXY" { + return v + } + } + return "" + } + if eu, err := url.Parse(env()); err != nil || eu.Host != strings.TrimPrefix(p.URL, "http://") { + t.Fatalf("a CLI's HTTPS_PROXY is %q, %v", env(), err) + } + // what Settings shows names neither part of the login nor the reference + assertHiddenFor(t, "@pxg") + // the proxy deleted while the choice stays: nothing goes direct + if err := settings.Save(settings.Settings{Proxy: "@pxg"}); err == nil { + t.Fatal("saved a choice naming a proxy that isn't there") + } + cur := settings.Load() + cur.Proxies = nil + cur.Proxy = "" + if err := settings.Save(cur); err != nil { + t.Fatal(err) + } +} + +func assertHiddenFor(t *testing.T, choice string) { + t.Helper() + shown, _ := Describe() + for _, secret := range []string{loginUser, loginPass, loginUserEnc, loginPassEnc, "p@ss", "p%40ss", "corp"} { + if strings.Contains(shown, secret) || strings.Contains(Redact(choice), secret) { + t.Fatalf("shows %q: %q / %q", secret, shown, Redact(choice)) + } + } +} + +// A dangling reference (a proxy a sync carried a choice for, which this +// computer doesn't have) points a CLI at nothing, and a request to nowhere. +func TestDanglingProxyReferenceFailsClosed(t *testing.T) { + clearProxyEnv(t) + got := EnvWith("@nothere", []string{}) + found := false + for _, e := range got { + if k, v, _ := strings.Cut(e, "="); strings.EqualFold(k, "HTTPS_PROXY") { + found = true + if v != DeadProxy { + t.Fatalf("HTTPS_PROXY = %q, want the dead proxy", v) + } + } + } + if !found { + t.Fatalf("no HTTPS_PROXY in %v: a CLI would go direct", got) + } + req, _ := http.NewRequestWithContext(With(context.Background(), "@nothere"), http.MethodGet, "http://vendor.example/", nil) + if u, err := Func(req); err == nil { + t.Fatalf("Func gave %v, nil for a reference to nothing", u) + } +} diff --git a/internal/netproxy/netproxy.go b/internal/netproxy/netproxy.go index 49eb94373..f07ba522c 100644 --- a/internal/netproxy/netproxy.go +++ b/internal/netproxy/netproxy.go @@ -12,6 +12,7 @@ package netproxy import ( "context" + "fmt" "net" "net/http" "net/url" @@ -171,6 +172,19 @@ func choiceOf(ctx context.Context) string { return c } +// Resolve is a proxy choice as the proxy it stands for: a saved proxy +// (settings.NamedProxy, "@id") as its address with its login, any other +// choice as it is. A reference to a proxy that isn't there is kept as it +// is, and Parse refuses it: a request meant for a proxy never goes +// direct for want of one. +func Resolve(choice string) string { + choice = strings.TrimSpace(choice) + if a, ok := settings.ResolveProxy(choice); ok { + return a + } + return choice +} + // forChoice is the proxy a provider's own choice names; nil for "direct". func forChoice(c string) (*url.URL, error) { if c == "direct" { @@ -231,7 +245,7 @@ func (d *dispatch) RoundTrip(req *http.Request) (*http.Response, error) { if d.moved() { d.CloseIdleConnections() } - r := route{choice: choiceOf(req.Context()), h1: HTTP1 != nil && HTTP1(req.URL) || http1Asked(req) || overHTTP1(req.Context()) || h2BrokenFor(req), unchecked: uncheckedHost(req), client: clientRoute(req)} + r := route{choice: Resolve(choiceOf(req.Context())), h1: HTTP1 != nil && HTTP1(req.URL) || http1Asked(req) || overHTTP1(req.Context()) || h2BrokenFor(req), unchecked: uncheckedHost(req), client: clientRoute(req)} t := d.base if r != (route{}) { t = d.transport(r) @@ -270,7 +284,7 @@ func Watch() func() bool { var seen bool return func() bool { // Shared, not Load: this runs on every request - now := strings.TrimSpace(settings.Shared().Proxy) + now := Resolve(settings.Shared().Proxy) mu.Lock() defer mu.Unlock() moved := seen && proxy != now @@ -388,6 +402,12 @@ func EnvWith(choice string, env []string) []string { if s == "" { s = strings.TrimSpace(settings.Load().Proxy) } + if settings.IsProxyRef(s) { + // a saved proxy that is gone: the CLI goes nowhere, not direct + if _, ok := settings.ResolveProxy(s); !ok { + return withProxy(env, DeadProxy, nil) + } + } switch s { case "direct": return withProxy(env, "", nil) @@ -446,9 +466,23 @@ func withProxy(env []string, p string, bypass []string) []string { "ALL_PROXY="+p, "all_proxy="+p, "NO_PROXY="+nos, "no_proxy="+nos) } -// Parse reads a proxy address; a bare host:port is an HTTP proxy. +// DeadProxy is where a CLI is sent for a saved proxy that is gone: a port +// nothing listens on, so its requests fail where a missing proxy would +// have sent them straight out. +const DeadProxy = "http://127.0.0.1:9" + +// Parse reads a proxy address; a bare host:port is an HTTP proxy. A saved +// proxy ("@id") is read as the address it stands for, its login in it; +// one that is gone is an error. func Parse(s string) (*url.URL, error) { s = strings.TrimSpace(s) + if settings.IsProxyRef(s) { + a, ok := settings.ResolveProxy(s) + if !ok { + return nil, fmt.Errorf("the saved proxy %q isn't on this computer (deleted, or never synced here); pick another in Settings", settings.ProxyLabel(settings.ProxyID(s))) + } + s = a + } if !strings.Contains(s, "://") { s = "http://" + s } @@ -486,6 +520,11 @@ func Redact(raw string) string { if err != nil { return "" } + if settings.IsProxyRef(raw) { + // a saved proxy shown as its address, with no login + u.User = nil + return u.String() + } if u.User == nil { return raw } diff --git a/internal/plugin/host.go b/internal/plugin/host.go index 221e0551d..6fcfde067 100644 --- a/internal/plugin/host.go +++ b/internal/plugin/host.go @@ -1918,6 +1918,10 @@ func forHost(choice string) string { if u, err := netproxy.Parse(c); err == nil { return netproxy.ForBun(u.String()) } + if settings.IsProxyRef(c) { + // a saved proxy that is gone: the request goes nowhere, not direct + return netproxy.DeadProxy + } return c } } diff --git a/internal/plugin/saved_proxy_test.go b/internal/plugin/saved_proxy_test.go new file mode 100644 index 000000000..fc8fc0fbe --- /dev/null +++ b/internal/plugin/saved_proxy_test.go @@ -0,0 +1,92 @@ +package plugin + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "path/filepath" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/netproxy" + "github.com/yetone/magpie/internal/settings" +) + +// A plugin's request whose choice names a saved proxy goes through it; +// editing the saved proxy moves the next request to the new address, and +// one whose proxy was deleted fails and never goes direct. +func TestPluginSavedProxy(t *testing.T) { + sandbox(t) + var mu sync.Mutex + hits := map[string]int{} + proxy := func(name string) *httptest.Server { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + hits[name]++ + mu.Unlock() + fmt.Fprint(w, name) + })) + t.Cleanup(srv.Close) + return srv + } + one, two := proxy("one"), proxy("two") + t.Setenv("FAKE_BASE", "http://vendor.invalid/v1") + t.Setenv("FAKE_USAGE", "http://vendor.invalid/usage") + t.Setenv("FAKE_MODELS", "http://vendor.invalid/models") + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + abs, _ := filepath.Abs("testdata/fake/index.js") + if _, err := Add(ctx, abs); err != nil { + t.Fatal(err) + } + if _, err := Providers(ctx); err != nil { + t.Fatal(err) + } + if _, err := APIKey(ctx, "fakeco", 0, nil, "k1", NewAccount); err != nil { + t.Fatal(err) + } + save := func(addr string) { + t.Helper() + var ps []settings.NamedProxy + if addr != "" { + ps = []settings.NamedProxy{{ID: "pxp", Name: "P", URL: addr}} + } + if err := settings.Save(settings.Settings{Proxies: ps}); err != nil { + t.Fatal(err) + } + } + fetch := func(choice string) (string, error) { + res, err := Fetch(netproxy.With(ctx, choice), FetchRequest{Provider: "fakeco", Model: "fake-1", NPM: "@ai-sdk/openai-compatible", + URL: "http://vendor.invalid/v1/chat/completions", Method: "POST", Body: []byte(`{}`)}) + if err != nil { + return "", err + } + defer res.Body.Close() + b, err := io.ReadAll(res.Body) + return string(b), err + } + save(one.URL) + if b, err := fetch("@pxp"); err != nil || b != "one" { + t.Fatalf("through the saved proxy: %q, %v", b, err) + } + save(two.URL) + if b, err := fetch("@pxp"); err != nil || b != "two" { + t.Fatalf("after the edit: %q, %v", b, err) + } + save("") + mu.Lock() + n := hits["one"] + hits["two"] + mu.Unlock() + if b, err := fetch("@pxp"); err == nil { + t.Fatalf("a deleted proxy's request was carried: %q", b) + } + mu.Lock() + m := hits["one"] + hits["two"] + mu.Unlock() + if m != n { + t.Fatalf("the request went through a proxy after its saved proxy was deleted") + } +} diff --git a/internal/provider/claude_proxy_env.go b/internal/provider/claude_proxy_env.go index ae09cac5a..63faf6f64 100644 --- a/internal/provider/claude_proxy_env.go +++ b/internal/provider/claude_proxy_env.go @@ -22,6 +22,7 @@ import ( "encoding/json" "errors" "fmt" + "github.com/yetone/magpie/internal/settings" "log" "os" "path/filepath" @@ -103,6 +104,10 @@ func claudeAccountProxy(user string) string { return "" } u, err := netproxy.Parse(v) + if err != nil && settings.IsProxyRef(v) { + // a saved proxy that is gone: sessions fail, they don't leave direct + return netproxy.DeadProxy + } if err != nil || u.Host == "" { return "" } @@ -243,3 +248,8 @@ func syncClaudeProxyEnvNow() { log.Printf("claude: writing the account's proxy to settings.json: %v", err) } } + +// ProxyEdited has Claude Code's env follow a saved proxy that was edited: +// its settings.json holds the address as a snapshot, so an account that +// chose the proxy by name needs it written again. +func ProxyEdited() { syncClaudeProxyEnvNow() } diff --git a/internal/provider/claude_proxy_env_test.go b/internal/provider/claude_proxy_env_test.go index 1b9921a34..64dd76477 100644 --- a/internal/provider/claude_proxy_env_test.go +++ b/internal/provider/claude_proxy_env_test.go @@ -10,6 +10,8 @@ import ( "time" "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/netproxy" + "github.com/yetone/magpie/internal/settings" ) // claudeTwoAccounts signs Claude Code in to a@example.com, then to @@ -242,3 +244,41 @@ func TestClaudeAccountProxyLogsNoCredentials(t *testing.T) { } } } + +// An account that chose a saved proxy has Claude Code's env hold its +// address with the login; editing the saved proxy writes the new one, and +// deleting it leaves a proxy that goes nowhere, not direct. +func TestClaudeAccountSavedProxy(t *testing.T) { + settingsPath := claudeTwoAccounts(t) + saved := func(url string) { + t.Helper() + var ps []settings.NamedProxy + if url != "" { + ps = []settings.NamedProxy{{ID: "pxc", Name: "C", URL: url, User: "me", Pass: "pw"}} + } + s := settings.Load() + s.Proxies = ps + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + } + saved("10.0.0.9:8080") + if err := Save(Provider{ID: "claude", AccountProxies: map[string]string{"b@example.com": "@pxc"}}); err != nil { + t.Fatal(err) + } + if v := claudeEnvOf(t, settingsPath, "HTTPS_PROXY"); v != "http://me:pw@10.0.0.9:8080" { + t.Fatalf("HTTPS_PROXY = %q", v) + } + saved("10.0.0.10:9090") + ProxyEdited() + if v := claudeEnvOf(t, settingsPath, "HTTPS_PROXY"); v != "http://me:pw@10.0.0.10:9090" { + t.Fatalf("after the edit HTTPS_PROXY = %q", v) + } + s := settings.Load() + s.Proxies = nil + settings.Save(s) + ProxyEdited() + if v := claudeEnvOf(t, settingsPath, "HTTPS_PROXY"); v != netproxy.DeadProxy { + t.Fatalf("with the saved proxy gone HTTPS_PROXY = %q, want a proxy that goes nowhere", v) + } +} diff --git a/internal/provider/proxy.go b/internal/provider/proxy.go index b20c1d6fe..475c02056 100644 --- a/internal/provider/proxy.go +++ b/internal/provider/proxy.go @@ -210,3 +210,64 @@ func checkAccountProxies(m map[string]string) error { } return nil } + +// ProxyUse is a place a saved proxy is chosen: a provider (Account empty), +// or an account or key of one. +type ProxyUse struct { + Provider string `json:"provider"` + Account string `json:"account,omitempty"` +} + +// ProxyUses lists where the saved proxy id is chosen among the providers, so +// that deleting it can say what would lose it. Settings' own two (global, +// plugin downloads) are the caller's. +func ProxyUses(id string) []ProxyUse { + ref := settings.ProxyRef(id) + var out []ProxyUse + for _, p := range storedFile().Providers { + name := p.Name + if name == "" { + name = p.ID + } + if strings.TrimSpace(p.Proxy) == ref { + out = append(out, ProxyUse{Provider: name}) + } + accts := make([]string, 0, len(p.AccountProxies)) + for a, v := range p.AccountProxies { + if strings.TrimSpace(v) == ref { + accts = append(accts, a) + } + } + slices.Sort(accts) + for _, a := range accts { + out = append(out, ProxyUse{Provider: name, Account: a}) + } + } + return out +} + +// ProxyGone is the name of a saved proxy p chooses (its own, or an +// account's) that isn't on this computer, "" when none is missing: what a +// sync from a magpie that didn't bring the proxy list leaves. +func ProxyGone(p Provider) string { + gone := func(v string) string { + v = strings.TrimSpace(v) + if !settings.IsProxyRef(v) { + return "" + } + if _, ok := settings.ResolveProxy(v); ok { + return "" + } + return settings.ProxyLabel(settings.ProxyID(v)) + } + if n := gone(p.Proxy); n != "" { + return n + } + keys := slices.Sorted(maps.Keys(p.AccountProxies)) + for _, k := range keys { + if n := gone(p.AccountProxies[k]); n != "" { + return n + } + } + return "" +} diff --git a/internal/settings/proxies.go b/internal/settings/proxies.go new file mode 100644 index 000000000..c9d53a9af --- /dev/null +++ b/internal/settings/proxies.go @@ -0,0 +1,252 @@ +package settings + +import ( + "crypto/rand" + "encoding/hex" + "fmt" + "net/url" + "slices" + "strings" +) + +// NamedProxy is a proxy the user keeps once, by name, and picks wherever a +// proxy can be chosen: Settings' own, plugin downloads', a provider's, a +// key's, an account's. Each of those holds the reference "@"+ID instead of +// an address, so one edit here applies to all of them. The address has no +// login in it; User and Pass are kept apart, in settings.json (0600) as +// GitHubToken is, and the page is never sent the password. This computer's +// own (KeepOwn), left out of a backup, as Proxy is. +type NamedProxy struct { + ID string `json:"id"` + Name string `json:"name"` + // URL is http://, https:// or socks5:// (host:port means http), with + // no user and password in it. + URL string `json:"url"` + User string `json:"user,omitempty"` + Pass string `json:"pass,omitempty"` +} + +// ProxyRefPrefix starts a proxy choice that names a NamedProxy by its id. +// No address starts with it, so it never collides with an inline value. +const ProxyRefPrefix = "@" + +// IsProxyRef is whether a proxy choice names a saved proxy. +func IsProxyRef(choice string) bool { + return strings.HasPrefix(strings.TrimSpace(choice), ProxyRefPrefix) +} + +// ProxyRef is the choice that names the saved proxy id. +func ProxyRef(id string) string { return ProxyRefPrefix + id } + +// ProxyID is the id a reference names, "" for a choice that isn't one. +func ProxyID(choice string) string { + choice = strings.TrimSpace(choice) + if !strings.HasPrefix(choice, ProxyRefPrefix) { + return "" + } + return strings.TrimPrefix(choice, ProxyRefPrefix) +} + +// Address is the proxy as a request takes it, with its login in it. Never +// shown or logged: netproxy.Redact is what a line of text may carry. +func (p NamedProxy) Address() (string, error) { + u, err := url.Parse(withScheme(strings.TrimSpace(p.URL))) + if err != nil || u.Host == "" { + return "", fmt.Errorf("proxy %q has no usable address", p.Name) + } + if p.User != "" || p.Pass != "" { + if p.Pass != "" { + u.User = url.UserPassword(p.User, p.Pass) + } else { + u.User = url.User(p.User) + } + } + return u.String(), nil +} + +// ResolveProxy is the address a proxy choice stands for: a reference's +// saved proxy (its login in it), any other choice as it is. ok is false +// for a reference to a proxy that isn't there (deleted, or brought by a +// sync from a computer whose list this one doesn't have): the caller fails +// the request, as a choice never turns into a direct connection. +func ResolveProxy(choice string) (addr string, ok bool) { + choice = strings.TrimSpace(choice) + id := ProxyID(choice) + if id == "" { + return choice, true + } + for _, p := range Shared().Proxies { + if p.ID == id { + a, err := p.Address() + return a, err == nil + } + } + return choice, false +} + +// NewProxyID is an id for a saved proxy. +func NewProxyID() string { + b := make([]byte, 5) + _, _ = rand.Read(b) + return "px" + hex.EncodeToString(b) +} + +func validProxyID(id string) bool { + if id == "" || len(id) > 40 { + return false + } + for _, c := range id { + if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '_') { + return false + } + } + return true +} + +// checkProxies refuses a list of saved proxies that couldn't be used. +func checkProxies(ps []NamedProxy) error { + seen := map[string]bool{} + names := map[string]bool{} + for i := range ps { + p := &ps[i] + p.Name, p.URL = strings.TrimSpace(p.Name), strings.TrimSpace(p.URL) + if !validProxyID(p.ID) { + return fmt.Errorf("a saved proxy's id is lower-case letters, digits, - and _, not %q", p.ID) + } + if seen[p.ID] { + return fmt.Errorf("two saved proxies have the id %q", p.ID) + } + seen[p.ID] = true + if p.Name == "" { + return fmt.Errorf("a saved proxy needs a name") + } + k := strings.ToLower(p.Name) + if names[k] { + return fmt.Errorf("two saved proxies are named %q", p.Name) + } + names[k] = true + if p.URL == "direct" || strings.HasPrefix(p.URL, ProxyRefPrefix) { + return fmt.Errorf("proxy %q: type its address, like http://127.0.0.1:7890", p.Name) + } + if err := checkAddress(p.URL); err != nil { + return fmt.Errorf("proxy %q: %w", p.Name, err) + } + if u, err := url.Parse(withScheme(p.URL)); err != nil || u.User != nil { + return fmt.Errorf("proxy %q: the username and password go in their own fields, not in the address", p.Name) + } + } + return nil +} + +func withScheme(raw string) string { + if !strings.Contains(raw, "://") { + return "http://" + raw + } + return raw +} + +func checkAddress(p string) error { + u, err := url.Parse(withScheme(p)) + if err != nil || u.Host == "" || !slices.Contains([]string{"http", "https", "socks5", "socks5h"}, u.Scheme) { + return fmt.Errorf("proxy must look like http://127.0.0.1:7890 or socks5://127.0.0.1:1080") + } + return nil +} + +// CheckProxyIn is CheckProxy for a choice made beside the list ps (a +// Settings being saved holds its own). +func CheckProxyIn(p string, ps []NamedProxy) error { + p = strings.TrimSpace(p) + if IsProxyRef(p) { + id := ProxyID(p) + if !slices.ContainsFunc(ps, func(n NamedProxy) bool { return n.ID == id }) { + return fmt.Errorf("the saved proxy %q isn't there", id) + } + return nil + } + return CheckProxy(p) +} + +// ProxyLabel is how a saved proxy is named in a message: its name, else the +// name it had (ProxyNames), else its id. +func ProxyLabel(id string) string { + s := Shared() + for _, p := range s.Proxies { + if p.ID == id { + return p.Name + } + } + if n := s.ProxyNames[id]; n != "" { + return n + } + return id +} + +func rememberProxyNames(m map[string]string, ps []NamedProxy) map[string]string { + for _, p := range ps { + if m == nil { + m = map[string]string{} + } + m[p.ID] = p.Name + } + return m +} + +// WithoutProxyPasswords is ps with each password left out: what goes +// where credentials don't. +func WithoutProxyPasswords(ps []NamedProxy) []NamedProxy { + out := slices.Clone(ps) + for i := range out { + out[i].Pass = "" + } + return out +} + +// MergeProxies is cur with the proxies another computer sent put in: one +// with the same id takes the sent name, address and login (its password +// too when keys, else it keeps cur's); one cur lacks is added, its name +// made unique here. A proxy only cur has stays: a sync never takes away +// what a choice here may name. +func MergeProxies(cur, in []NamedProxy, keys bool) []NamedProxy { + out := slices.Clone(cur) + taken := map[string]bool{} + for _, p := range out { + taken[strings.ToLower(p.Name)] = true + } + for _, n := range in { + if i := slices.IndexFunc(out, func(p NamedProxy) bool { return p.ID == n.ID }); i >= 0 { + old := out[i] + if !keys { + n.Pass = old.Pass + } + if !strings.EqualFold(old.Name, n.Name) && taken[strings.ToLower(n.Name)] { + n.Name = old.Name + } + out[i] = n + continue + } + if !keys { + n.Pass = "" + } + base, k := n.Name, 2 + for taken[strings.ToLower(n.Name)] { + n.Name = fmt.Sprintf("%s %d", base, k) + k++ + } + taken[strings.ToLower(n.Name)] = true + out = append(out, n) + } + return out +} + +// RestoreProxies puts the proxies another computer sent into this one's +// (MergeProxies), where a restore or a sync brings them. +func RestoreProxies(in []NamedProxy, keys bool) error { + s := Load() + merged := MergeProxies(s.Proxies, in, keys) + if slices.Equal(merged, s.Proxies) { + return nil + } + s.Proxies = merged + return Save(s) +} diff --git a/internal/settings/proxies_test.go b/internal/settings/proxies_test.go new file mode 100644 index 000000000..e7817f40e --- /dev/null +++ b/internal/settings/proxies_test.go @@ -0,0 +1,92 @@ +package settings + +import ( + "strings" + "testing" +) + +func savedFixture() []NamedProxy { + return []NamedProxy{ + {ID: "pxone", Name: "Office", URL: "127.0.0.1:7890", User: "me@corp", Pass: "p@ss:w/rd"}, + {ID: "pxtwo", Name: "Home", URL: "socks5://127.0.0.1:1080"}, + } +} + +// A choice that names a saved proxy resolves to its address with the login +// in it; an inline address is as typed; a reference to a proxy that isn't +// there is not resolved, so a request fails and never goes direct. +func TestResolveProxy(t *testing.T) { + if err := Save(Settings{Proxies: savedFixture()}); err != nil { + t.Fatal(err) + } + got, ok := ResolveProxy("@pxone") + if !ok || got != "http://me%40corp:p%40ss%3Aw%2Frd@127.0.0.1:7890" { + t.Fatalf("resolved %q, %v", got, ok) + } + if got, ok := ResolveProxy("@pxtwo"); !ok || got != "socks5://127.0.0.1:1080" { + t.Fatalf("resolved %q, %v", got, ok) + } + if got, ok := ResolveProxy("http://10.0.0.1:3128"); !ok || got != "http://10.0.0.1:3128" { + t.Fatalf("inline: %q, %v", got, ok) + } + if got, ok := ResolveProxy("direct"); !ok || got != "direct" { + t.Fatalf("direct: %q, %v", got, ok) + } + if _, ok := ResolveProxy("@gone"); ok { + t.Fatal("a reference to a proxy that isn't saved resolved") + } +} + +func TestSavedProxiesAreChecked(t *testing.T) { + bad := map[string][]NamedProxy{ + "no name": {{ID: "a", URL: "127.0.0.1:1"}}, + "same id": {{ID: "a", Name: "x", URL: "127.0.0.1:1"}, {ID: "a", Name: "y", URL: "127.0.0.1:2"}}, + "same name": {{ID: "a", Name: "x", URL: "127.0.0.1:1"}, {ID: "b", Name: "X", URL: "127.0.0.1:2"}}, + "login in url": {{ID: "a", Name: "x", URL: "http://u:p@127.0.0.1:1"}}, + "not an address": {{ID: "a", Name: "x", URL: "ftp://127.0.0.1:1"}}, + "direct": {{ID: "a", Name: "x", URL: "direct"}}, + "a reference": {{ID: "a", Name: "x", URL: "@b"}}, + "an id with a @": {{ID: "@a", Name: "x", URL: "127.0.0.1:1"}}, + } + for name, ps := range bad { + if err := Save(Settings{Proxies: ps}); err == nil { + t.Errorf("%s: saved", name) + } + } + if err := Save(Settings{Proxies: savedFixture()}); err != nil { + t.Fatal(err) + } +} + +// Settings' own two choices may name a saved proxy, and only one that exists. +func TestSettingsProxyNamesASavedOne(t *testing.T) { + if err := Save(Settings{Proxy: "@pxone", Proxies: savedFixture()}); err != nil { + t.Fatal(err) + } + if s := Load(); s.Proxy != "@pxone" || s.ProxyCustom != "" { + t.Fatalf("saved %+v", s) + } + if err := Save(Settings{Proxy: "@nope", Proxies: savedFixture()}); err == nil { + t.Fatal("a reference to a proxy that isn't saved was saved") + } + err := Save(Settings{PluginProxy: "@nope", Proxies: savedFixture()}) + if err == nil || !strings.Contains(err.Error(), "plugin downloads") { + t.Fatalf("plugin downloads' reference to nothing: %v", err) + } + if err := Save(Settings{Proxy: "http://1.2.3.4:5"}); err != nil { + t.Fatalf("an inline address as it always was: %v", err) + } +} + +// The list is this computer's own: a restore or a sync leaves it as it is. +func TestSavedProxiesAreKept(t *testing.T) { + if err := Save(Settings{Proxies: savedFixture()}); err != nil { + t.Fatal(err) + } + cur := Load() + var s Settings + s.KeepOwn(cur) + if len(s.Proxies) != 2 || s.Proxies[0].Pass != "p@ss:w/rd" { + t.Fatalf("KeepOwn left %+v", s.Proxies) + } +} diff --git a/internal/settings/settings.go b/internal/settings/settings.go index b7c70a944..e47303f33 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -139,7 +139,14 @@ type Settings struct { PluginProxy string `json:"pluginProxy,omitempty"` // PluginProxyCustom is PluginProxy's ProxyCustom. PluginProxyCustom string `json:"pluginProxyCustom,omitempty"` - OTel OTel `json:"otel,omitempty"` + // Proxies are the proxies kept by name (NamedProxy); a proxy choice + // "@"+id anywhere (Proxy, PluginProxy, a provider's, a key's, an + // account's) uses one. This computer's own (KeepOwn). + Proxies []NamedProxy `json:"proxies,omitempty"` + // ProxyNames remembers each saved proxy's name by id, so a choice that + // outlives its proxy can still say which one it was. This computer's own. + ProxyNames map[string]string `json:"proxyNames,omitempty"` + OTel OTel `json:"otel,omitempty"` // GitHubToken is a GitHub token the library's requests to GitHub's // API carry, raising its rate limit from 60 requests an hour to 5,000. // It is a secret: the Settings page is told only a masked one, and a @@ -1558,7 +1565,7 @@ func (s *Settings) KeepOwn(cur Settings) { s.UIFont, s.CodeFont = cur.UIFont, cur.CodeFont s.Window, s.Proxy, s.Port, s.Dock, s.DockWindow, s.Lightweight = cur.Window, cur.Proxy, cur.Port, cur.Dock, cur.DockWindow, cur.Lightweight s.DockNever, s.DockSettled = cur.DockNever, cur.DockSettled - s.ProxyCustom = cur.ProxyCustom + s.ProxyCustom, s.Proxies, s.ProxyNames = cur.ProxyCustom, cur.Proxies, cur.ProxyNames s.PluginProxy, s.PluginProxyCustom = cur.PluginProxy, cur.PluginProxyCustom s.WindowMaximised, s.KeepAwake, s.KeepAwakeDisplay = cur.WindowMaximised, cur.KeepAwake, cur.KeepAwakeDisplay s.WindowAt = cur.WindowAt @@ -1958,6 +1965,10 @@ func CheckProxy(p string) error { if p == "" || p == "direct" { return nil } + if IsProxyRef(p) { + // a saved proxy: one that is there now + return CheckProxyIn(p, Load().Proxies) + } raw := p if !strings.Contains(raw, "://") { raw = "http://" + raw @@ -2398,18 +2409,22 @@ func saveOwn(s Settings, recording, reads bool) error { if err := s.OTel.Check(); err != nil { return err } - s.Proxy = strings.TrimSpace(s.Proxy) - if err := CheckProxy(s.Proxy); err != nil { + if err := checkProxies(s.Proxies); err != nil { return err } - if s.Proxy != "" && s.Proxy != "direct" { + s.ProxyNames = rememberProxyNames(s.ProxyNames, s.Proxies) + s.Proxy = strings.TrimSpace(s.Proxy) + if err := CheckProxyIn(s.Proxy, s.Proxies); err != nil { + return err + } + if s.Proxy != "" && s.Proxy != "direct" && !IsProxyRef(s.Proxy) { s.ProxyCustom = s.Proxy } s.PluginProxy = strings.TrimSpace(s.PluginProxy) - if err := CheckProxy(s.PluginProxy); err != nil { + if err := CheckProxyIn(s.PluginProxy, s.Proxies); err != nil { return fmt.Errorf("plugin downloads: %w", err) } - if s.PluginProxy != "" && s.PluginProxy != "direct" { + if s.PluginProxy != "" && s.PluginProxy != "direct" && !IsProxyRef(s.PluginProxy) { s.PluginProxyCustom = s.PluginProxy } s.Vision = strings.TrimSpace(s.Vision) diff --git a/internal/settingsapi/settingsapi.go b/internal/settingsapi/settingsapi.go index f34b6dc11..55695ecd9 100644 --- a/internal/settingsapi/settingsapi.go +++ b/internal/settingsapi/settingsapi.go @@ -286,17 +286,19 @@ func Merge(body []byte, cur settings.Settings, web bool) (settings.Settings, err // Bark has its own route (bark); the page never sees its key in.BarkServer, in.BarkKey, in.BarkDaily = cur.BarkServer, cur.BarkKey, cur.BarkDaily - in.Port = cur.Port // set on its own (port), which moves the gateway - in.CORSOrigins = cur.CORSOrigins // set on its own (cors) - in.AllowIPs = cur.AllowIPs // set on its own (allowips) - in.MTLS = cur.MTLS // set on its own (mtls) - in.HTTPS = cur.HTTPS // set on its own (https) - in.FetchPrivate = cur.FetchPrivate // in settings.json only - in.RouterNote = cur.RouterNote // set on its own (the Library's servers/hub-note) - in.RouterAllTools = cur.RouterAllTools // set on its own (the Library's servers/hub-tools) - in.GitHubToken = cur.GitHubToken // set on its own (github-token), never sent to the page - in.ProxyCustom = cur.ProxyCustom // set by settings.Save from the proxy, never by the page - in.PluginProxyCustom = cur.PluginProxyCustom // and plugin downloads' from theirs + in.Port = cur.Port // set on its own (port), which moves the gateway + in.CORSOrigins = cur.CORSOrigins // set on its own (cors) + in.AllowIPs = cur.AllowIPs // set on its own (allowips) + in.MTLS = cur.MTLS // set on its own (mtls) + in.HTTPS = cur.HTTPS // set on its own (https) + in.FetchPrivate = cur.FetchPrivate // in settings.json only + in.RouterNote = cur.RouterNote // set on its own (the Library's servers/hub-note) + in.RouterAllTools = cur.RouterAllTools // set on its own (the Library's servers/hub-tools) + in.GitHubToken = cur.GitHubToken // set on its own (github-token), never sent to the page + in.ProxyCustom = cur.ProxyCustom // set by settings.Save from the proxy, never by the page + in.PluginProxyCustom = cur.PluginProxyCustom // and plugin downloads' from theirs + in.ProxyNames = cur.ProxyNames + in.Proxies = cur.Proxies // set on its own (proxies), the password never sent to the page in.RequestArchive = cur.RequestArchive // the Gateway page's, set on its own in.RequestArchiveMaxMB = cur.RequestArchiveMaxMB // in settings.json only in.ClaudeRunsMost = cur.ClaudeRunsMost // magpie claude-code runs, or settings.json (#2956)