diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 5a01bdae9..695167b7f 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -91,7 +91,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`). A model's right-click *Test on account…* (tmr11235 on X; a provider with two or more accounts or keys that are on, `TestPicks`) pins its test to one of them (`TestOn`, `accountNamed`, `keyNamed`, the GUI's `account`; `TestModelTestPinnedToAKey`, `TestModelTestPinnedToAnAccount`, `model-test-account.test.cjs`), and every result names the account or key it went to (`Result.Account`, `testedAccount`), so the status line says which one answered. Test models and `magpie providers` still test with routing's pick. 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, app updates, 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. App updates take a proxy of their own, Settings › Network › App updates (`settings.UpdateProxy`, `magpie settings set updateProxy `; moonlityu on X: models direct, updates through a proxy): "" follows the global proxy as before, a proxy given to one `magpie update --proxy` run comes first, and it covers the feed, the notes and the release's file (`updateProxy` in [`update.go`](../../internal/update/update.go); `TestUpdateTakesItsOwnProxy`, `settings-update-proxy.test.cjs`). Per-model proxies within one provider are not offered: a proxy belongs to a provider, an account or a key, and a model that needs the other route is a second provider on the same URL. `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). A saved proxy can be an SSH server (`ssh://host:port`, a user, a password and/or a private key; @laiuuui on X, whose VPS gives only SSH): magpie logs in itself with golang.org/x/crypto/ssh, no ssh command, and resolves the `@id` to a SOCKS5 server of its own on loopback (`socks5h://magpie:@127.0.0.1:`, which takes only that login), carrying each CONNECT as a direct-tcpip channel, as `ssh -D` does. It logs in on the first request, keeps the connection with keepalive@openssh.com every 20s (15s with no answer ends it), and logs in again once when a channel finds it dead (`sshTunnel` in [`ssh.go`](../../internal/netproxy/ssh.go)). Save logs in first, so a refused login is said there and nothing is kept; the host key is trusted on first use and kept as `HostKey` (authorized_keys form, the page shows its SHA256 fingerprint), and a server showing another key is refused (`HostKeyChangedError`) until Advanced › Trust a new key. The key is a secret as the password is: `WithoutProxyPasswords`, `MergeProxies`, `KeepSecretsOf`. An `ssh://` typed as an address is refused: its login belongs to a saved proxy. Every request to the server needs it to allow forwarding: macOS 27's sshd hangs up on a forward (also with OpenSSH's own `ssh -W`), and that is said as "won't forward connections" (`SSHForwardWhy`). A failed proxy says why (`netproxy.Why`: an English template the page translates, its `{addr}`, `{was}`, `{now}` filled; `fail` in api.go sends it as `code: proxy_why`, a check as `why`/`addr`): `Explain` reads Go's error, and `ExplainServer`, for a check the user asked for only, reads the server's first bytes when the text can't tell, since Go reads a real OpenSSH banner ("SSH-2.0-OpenSSH_9.6p1 Ubuntu-3ubuntu13.20") as an HTTP status line with a bad code. Each save is tested at once. `TestSavedProxyChoice`, `TestDanglingProxyReferenceFailsClosed`, `TestSavedProxiesTravelWithProviders`, `TestSSHProxyCarriesRequests`, `TestSSHProxyRefusesAChangedHostKey`, `TestSSHProxySaysWhyItFailed`, `TestProxyFailureNamesAnSSHServer`, `TestSavedSSHProxyAPI`, `TestSavedSSHProxyThatWontForward` (an SSH server in the test, `netproxy/sshtest`, never the network), `saved-proxies.test.cjs`, `saved-ssh-proxy.test.cjs`, `provider-proxy-missing.test.cjs`. | [`proxies.go`](../../internal/settings/proxies.go), [`netproxy.go`](../../internal/netproxy/netproxy.go), [`ssh.go`](../../internal/netproxy/ssh.go), [`why.go`](../../internal/netproxy/why.go), [`proxies.go`](../../internal/gui/proxies.go) | +| 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, app updates, 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. App updates take a proxy of their own, Settings › Network › App updates (`settings.UpdateProxy`, `magpie settings set updateProxy `; moonlityu on X: models direct, updates through a proxy): "" follows the global proxy as before, a proxy given to one `magpie update --proxy` run comes first, and it covers the feed, the notes and the release's file (`updateProxy` in [`update.go`](../../internal/update/update.go); `TestUpdateTakesItsOwnProxy`, `settings-update-proxy.test.cjs`). Per-model proxies within one provider are not offered: a proxy belongs to a provider, an account or a key, and a model that needs the other route is a second provider on the same URL. `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). A saved proxy can be an SSH server (`ssh://host:port`, a user, a password and/or a private key; @laiuuui on X, whose VPS gives only SSH): magpie logs in itself with golang.org/x/crypto/ssh, no ssh command, and resolves the `@id` to a SOCKS5 server of its own on loopback (`socks5h://magpie:@127.0.0.1:`, which takes only that login), carrying each CONNECT as a direct-tcpip channel, as `ssh -D` does. It logs in on the first request, keeps the connection with keepalive@openssh.com every 20s (15s with no answer ends it), and logs in again once when a channel finds it dead (`sshTunnel` in [`ssh.go`](../../internal/netproxy/ssh.go)). Save logs in first, so a refused login is said there and nothing is kept; the host key is trusted on first use and kept as `HostKey` (authorized_keys form, the page shows its SHA256 fingerprint), and a server showing another key is refused (`HostKeyChangedError`) until Advanced › Trust a new key. The key is a secret as the password is: `WithoutProxyPasswords`, `MergeProxies`, `KeepSecretsOf`. An `ssh://` typed as an address is refused: its login belongs to a saved proxy. Every request to the server needs it to allow forwarding: macOS 27's sshd hangs up on a forward (also with OpenSSH's own `ssh -W`), and that is said as "won't forward connections" (`SSHForwardWhy`). A failed proxy says why (`netproxy.Why`: an English template the page translates, its `{addr}`, `{was}`, `{now}` filled; `fail` in api.go sends it as `code: proxy_why`, a check as `why`/`addr`): `Explain` reads Go's error, and `ExplainServer`, for a check the user asked for only, reads the server's first bytes when the text can't tell, since Go reads a real OpenSSH banner ("SSH-2.0-OpenSSH_9.6p1 Ubuntu-3ubuntu13.20") as an HTTP status line with a bad code. Each save is tested at once. A Test (Settings, and the provider editor's Saved mode) asks Cloudflare's trace page through the proxy, only on a click: its latency runs from the request written to the answer's first byte, so a new connection's dial, tunnel and TLS don't count and a second Test reads like the first, and the exit's region is named in the reader's language (IcyLiqu1d on X). An editor opened before Settings was read draws its picker again once the saved proxies are in. `TestSavedProxyLatencyIsTheRoundTrip`, `provider-proxy-pick-test.test.cjs`, `TestSavedProxyChoice`, `TestDanglingProxyReferenceFailsClosed`, `TestSavedProxiesTravelWithProviders`, `TestSSHProxyCarriesRequests`, `TestSSHProxyRefusesAChangedHostKey`, `TestSSHProxySaysWhyItFailed`, `TestProxyFailureNamesAnSSHServer`, `TestSavedSSHProxyAPI`, `TestSavedSSHProxyThatWontForward` (an SSH server in the test, `netproxy/sshtest`, never the network), `saved-proxies.test.cjs`, `saved-ssh-proxy.test.cjs`, `provider-proxy-missing.test.cjs`. | [`proxies.go`](../../internal/settings/proxies.go), [`netproxy.go`](../../internal/netproxy/netproxy.go), [`ssh.go`](../../internal/netproxy/ssh.go), [`why.go`](../../internal/netproxy/why.go), [`proxies.go`](../../internal/gui/proxies.go) | ## Remote magpie diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 28dba5688..a7c964332 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -3769,6 +3769,9 @@ body:not(.side-nav) #addSheet > .row-head.stuck::before { opacity: 1; box-shadow .editor .proxy-row input.proxy-url.off { display: none; } .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; } +.editor .proxy-row .proxy-test { flex: none; } +.editor .proxy-row .proxy-saved[hidden] + .proxy-test { display: none; } +.editor .proxy-pick .hint.err { color: var(--red); } .saved-proxy .sub { overflow-wrap: anywhere; } .proxy-form { flex-wrap: wrap; } .proxy-form .proxy-controls { justify-content: flex-end; flex: 1 1 100%; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index d64ceff56..af90a363f 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -7862,6 +7862,8 @@ function proxyPicker() { const row = el("div", "proxy-row"); row.append(seg, addr, saved); box.append(row, login, hint); + // its Test is in proxies.js (IcyLiqu1d on X) + (!prefs || savedProxyList().length) && import("./proxies.js").then(() => proxyPickTest(box, saved, hint), () => {}); return box; } diff --git a/internal/gui/assets/proxies.js b/internal/gui/assets/proxies.js index 95b24e2c6..d915110be 100644 --- a/internal/gui/assets/proxies.js +++ b/internal/gui/assets/proxies.js @@ -16,14 +16,59 @@ function proxyWhy(o) { } // a check's failure, said as magpie explained it when it could const proxyFailed = (out) => (out.why ? proxyWhy(out) : out.error || ""); -function testSavedProxy(id) { +// the country or region a check left from, by the trace page's ISO code, +// named in the reader's language (IcyLiqu1d on X); a code Intl doesn't +// know (Cloudflare's XX, T1) as it came +function proxyRegion(loc) { + try { return new Intl.DisplayNames([intlLang()], { type: "region" }).of(loc) || loc; } catch { return loc || ""; } +} +// a check as one line: the latency and where it left from, or why it failed +function proxyCheckLine(out) { + if (!out.ok) return t("Unreachable: {error}", { error: proxyFailed(out) }); + return [t("Reachable, {ms} ms", { ms: out.ms }), out.loc && proxyRegion(out.loc)].filter(Boolean).join(" · "); +} +// testSavedProxy asks the server to test one saved proxy, only when a +// Test (or a Save) is clicked; then draws with what it found +function testSavedProxy(id, draw = renderSettings) { proxyChecks[id] = { busy: true }; - renderSettings(); - api("proxies/test", { id }) + draw(); + return api("proxies/test", { id }) .then((o) => { proxyChecks[id] = { out: o }; }) .catch((e) => { proxyChecks[id] = { out: { ok: false, error: t(e.message) } }; }) - .finally(renderSettings); + .finally(draw); } +// proxyPickTest: the provider editor's Test beside its saved proxy. What +// it found is said where the picker's hint is, until another mode or +// proxy is chosen. An editor opened before Settings was read draws its +// picker again once the saved proxies are in, their names and Saved mode +// with them. +window.proxyPickTest = function (box, saved, hint) { + if (!prefs) return void loadSettings().then(() => box.isConnected && savedProxyList().length && box.replaceWith(proxyPicker()), () => {}); + if (!savedProxyList().length || saved.nextElementSibling?.classList.contains("proxy-test")) return; + const test = el("button", "text proxy-test", t("Test")); + test.type = "button"; + let ref = ""; + const draw = () => { + const chk = proxyChecks[ref.slice(1)]; + test.disabled = !!chk?.busy; + test.textContent = chk?.busy ? t("Testing…") : t("Test"); + if (!chk?.out || draft?.proxyMode !== "saved" || draft.proxyRef !== ref) return; + hint.textContent = hint.title = proxyCheckLine(chk.out); + hint.classList.toggle("err", !chk.out.ok); + }; + test.onclick = () => { + ref = draft?.proxyRef || ""; + if (ref) testSavedProxy(ref.slice(1), draw); + }; + // another proxy chosen (the button's name) or another mode (its + // hidden) puts the hint back + new MutationObserver(() => { + hint.textContent = t(PROXY_HINT[draft?.proxyMode || ""]); + hint.title = ""; + hint.classList.remove("err"); + }).observe(saved, { childList: true, characterData: true, subtree: true, attributeFilter: ["hidden"] }); + saved.after(test); +}; window.renderSavedProxies = function (s) { const box = $("#proxiesList"); box.replaceChildren(); @@ -46,9 +91,11 @@ window.renderSavedProxies = function (s) { const addr = ssh ? bareSSH(p.url) : p.url; const line = [ssh ? "SSH " + (p.user ? p.user + "@" : "") + addr : 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: proxyFailed(out) })); + else if (out) line.push(proxyCheckLine(out)); if (p.uses?.length) line.push(t("Used by {n}", { n: p.uses.length })); - sub.textContent = sub.title = line.join(" · "); + sub.textContent = line.join(" · "); + // the exit's own address, for whoever checks it against the proxy's + sub.title = [sub.textContent, !chk?.busy && out?.ok && out.ip].filter(Boolean).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")); diff --git a/internal/gui/proxies.go b/internal/gui/proxies.go index 120658402..9f93b7aa9 100644 --- a/internal/gui/proxies.go +++ b/internal/gui/proxies.go @@ -6,8 +6,10 @@ import ( "errors" "fmt" "net/http" + "net/http/httptrace" "strings" "sync" + "sync/atomic" "time" "github.com/yetone/magpie/internal/netproxy" @@ -357,9 +359,24 @@ func sshTested(p settings.NamedProxy, out proxyTestJSON) proxyTestJSON { return out } +// testProxy asks the trace page through addr. Its Ms is the latency +// through the proxy: from the request written to the answer's first +// byte, one round trip to the trace page and back through the proxy. +// The whole request's time would count a new connection's dial, tunnel +// and TLS on a first Test and not on the next one, which reuses it. func testProxy(ctx context.Context, addr string) proxyTestJSON { + // the transport calls these from its own goroutines + start := time.Now() + var wrote, first atomic.Int64 + ctx = httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{ + WroteRequest: func(httptrace.WroteRequestInfo) { wrote.Store(int64(time.Since(start))) }, + GotFirstResponseByte: func() { first.Store(int64(time.Since(start))) }, + }) leg := throughLeg(netproxy.With(ctx, addr), proxyTestClient) out := proxyTestJSON{Ms: leg.Ms, IP: leg.IP, Loc: leg.Loc, At: time.Now().Unix()} + if w, f := wrote.Load(), first.Load(); w > 0 && f > w { + out.Ms = max(time.Duration(f-w).Milliseconds(), 1) + } switch { case leg.Error != "": out.Error = redactProxyErr(leg.Error) diff --git a/internal/gui/proxies_test.go b/internal/gui/proxies_test.go index 656ddc028..bc4553c64 100644 --- a/internal/gui/proxies_test.go +++ b/internal/gui/proxies_test.go @@ -1,14 +1,18 @@ package gui import ( + "context" "encoding/json" "fmt" + "net" "net/http" "net/http/httptest" "os" "path/filepath" "strings" + "sync/atomic" "testing" + "time" "github.com/yetone/magpie/internal/netproxy" "github.com/yetone/magpie/internal/netproxy/sshtest" @@ -141,6 +145,50 @@ func TestSavedProxyTest(t *testing.T) { } } +// A proxy's latency is the round trip through it to the trace page, the +// same on a first Test, which dials, as on the next, which doesn't: a +// slow dial is left out, a slow answer is in. The exit's country comes +// with it. +func TestSavedProxyLatencyIsTheRoundTrip(t *testing.T) { + call, _ := proxiesRig(t) + const answer, dialing = 100 * time.Millisecond, 1500 * time.Millisecond + proxy := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + time.Sleep(answer) + fmt.Fprint(rw, "fl=1\nip=203.0.113.9\nloc=JP\n") + })) + t.Cleanup(proxy.Close) + old := proxyTraceURL + proxyTraceURL = "http://trace.example.invalid/cdn-cgi/trace" + t.Cleanup(func() { proxyTraceURL = old }) + base := &http.Transport{Proxy: netproxy.Func} + dial := (&net.Dialer{}).DialContext + var dials atomic.Int32 + base.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { + dials.Add(1) + time.Sleep(dialing) + return dial(ctx, network, addr) + } + t.Cleanup(base.CloseIdleConnections) + oldClient := proxyTestClient + proxyTestClient = &http.Client{Transport: netproxy.Dispatch(base)} + t.Cleanup(func() { proxyTestClient = oldClient }) + call("/api/proxies/save", `{"name":"Tokyo","url":"`+proxy.URL+`"}`) + id := settings.Load().Proxies[0].ID + for i := range 2 { + _, body := call("/api/proxies/test", `{"id":"`+id+`"}`) + var out proxyTestJSON + if err := json.Unmarshal([]byte(body), &out); err != nil || !out.OK || out.Loc != "JP" || out.IP != "203.0.113.9" { + t.Fatalf("test %d: %s", i, body) + } + if out.Ms < answer.Milliseconds() || out.Ms >= dialing.Milliseconds() { + t.Fatalf("test %d took %d ms; want the answer's %v and not the dial's %v", i, out.Ms, answer, dialing) + } + } + if dials.Load() == 0 { + t.Fatal("the proxy was never dialled, so its dial wasn't left out") + } +} + // An SSH server is saved from its host, user and password: the save logs // in first, so a refused login is said there and nothing is kept, and a // kept one shows the host key it trusts. Its test goes through the diff --git a/internal/gui/tests/provider-proxy-pick-test.test.cjs b/internal/gui/tests/provider-proxy-pick-test.test.cjs new file mode 100644 index 000000000..57ce9a1ad --- /dev/null +++ b/internal/gui/tests/provider-proxy-pick-test.test.cjs @@ -0,0 +1,113 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A provider's saved proxy is tested from its editor (IcyLiqu1d on X): a +// Test beside the saved proxy picked, shown only in Saved mode, asks +// /api/proxies/test for that proxy and nothing before it is clicked. The +// answer, its latency and the exit's region in the reader's language, or +// why it failed, is said where the picker's hint is, until another proxy +// or mode is chosen. In every language, both engines, wide and narrow. +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 relay = { + id: "relay", name: "Relay", 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 }, proxy: "@px1", +}; +const proxies = [ + { id: "px1", name: "Tokyo", url: "http://10.0.0.1:8080", uses: [{ provider: "relay" }] }, + { id: "px2", name: "Down", url: "socks5://10.0.0.9:1080" }, +]; + +function serve(lang, posts) { + const providers = { providers: [relay], presets: [], excluded: [], gateway: { running: true, window: true } }; + const settings = { theme: "light", lang, proxy: "", proxySource: "off", proxies, version: "test", dir: "/test", lanURLs: [] }; + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings }); + if (url.pathname === "/api/settings") return json(settings); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/proxies/test") { + const { id } = req.postDataJSON(); + posts.push({ test: id }); + return json(id === "px1" ? { ok: true, ms: 42, ip: "203.0.113.9", loc: "JP", at: 1 } : { ok: false, error: "connect: connection refused", at: 1 }); + } + 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 }); + }; +} + +// the region the trace page's JP names, as the reader's language says it +const japan = { en: "Japan", zh: "日本", "zh-TW": "日本", ja: "日本", de: "Japan" }; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(japan)) { + for (const width of [900, 420]) { + test(`${engine} ${lang} ${width}px: a provider's saved proxy is tested from its editor`, 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: 800 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = [], posts = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, posts)); + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: "Relay" }).click(); + const adv = page.locator(".editor details.advanced"); + await adv.waitFor({ state: "attached" }); + if (!(await adv.evaluate((d) => d.open))) await adv.locator(":scope > summary").click(); + const row = page.locator(".editor .proxy-row"); + const test = row.locator("button.proxy-test"); + const hint = page.locator(".editor .proxy-pick .hint"); + const tr = (k, v) => page.evaluate(([k, v]) => t(k, v), [k, v]); + await test.waitFor(); + await row.locator("button.proxy-saved").getByText("Tokyo", { exact: true }).waitFor(); + assert.equal(await test.textContent(), await tr("Test")); + assert.deepEqual(posts, [], "nothing is tested before Test is clicked"); + const savedHint = await tr("Requests to it go through this saved proxy, kept in Settings"); + assert.equal(await hint.textContent(), savedHint); + + const grey = await hint.evaluate((e) => getComputedStyle(e).color); + // the latency and the exit's region, in the reader's language + await test.click(); + const ok = (await tr("Reachable, {ms} ms", { ms: 42 })) + " · " + japan[lang]; + await page.waitForFunction(([s]) => document.querySelector(".editor .proxy-pick .hint")?.textContent === s, [ok]); + assert.deepEqual(posts, [{ test: "px1" }]); + assert.equal(await hint.evaluate((e) => e.classList.contains("err")), false); + assert.equal(await test.isDisabled(), false); + + // another proxy chosen puts the hint back; its failure says why, in red + await row.locator("button.proxy-saved").click(); + await page.locator(".proto-menu .pm-item", { hasText: "Down" }).click(); + await page.waitForFunction(([s]) => document.querySelector(".editor .proxy-pick .hint")?.textContent === s, [savedHint]); + await test.click(); + const bad = await tr("Unreachable: {error}", { error: "connect: connection refused" }); + await page.waitForFunction(([s]) => document.querySelector(".editor .proxy-pick .hint")?.textContent === s, [bad]); + assert.deepEqual(posts.at(-1), { test: "px2" }); + assert.equal(await hint.evaluate((e) => e.classList.contains("err")), true); + assert.notEqual(await hint.evaluate((e) => getComputedStyle(e).color), grey, "a failure isn't the hint's grey"); + + // another mode: the Test goes, the hint is that mode's + await page.locator(".editor .proxy-mode .opt").first().click(); + await page.waitForFunction(() => !document.querySelector(".editor .proxy-pick .hint")?.classList.contains("err")); + assert.equal(await test.isVisible(), false, "Test is for a saved proxy only"); + assert.equal(await hint.textContent(), await tr("Follows the proxy in Settings")); + + const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + assert(over <= 0, `the page scrolls sideways by ${over}px`); + assert.equal(posts.length, 2, "one request a click"); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/gui/tests/saved-proxies.test.cjs b/internal/gui/tests/saved-proxies.test.cjs index f63d9b90c..cf1f9108a 100644 --- a/internal/gui/tests/saved-proxies.test.cjs +++ b/internal/gui/tests/saved-proxies.test.cjs @@ -1,6 +1,7 @@ // 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. +// each with a Test that says its latency and the exit's region (IcyLiqu1d +// on X), 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"); @@ -31,7 +32,7 @@ function server(lang, posts) { 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/test") { posts.push({ test: req.postDataJSON().id }); return json({ ok: true, ms: 42, ip: "203.0.113.9", loc: "JP", at: 1 }); } if (url.pathname === "/api/proxies/save") { const b = req.postDataJSON(); posts.push({ save: b }); @@ -49,11 +50,11 @@ function server(lang, posts) { } 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)" }, + en: { test: "Test", add: "Add proxy", name: "Name", save: "Save", del: "Delete", saved: "Saved", ok: "Reachable, 42 ms · Japan", 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 · Japan", pass: "Passwort (optional)" }, }; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { @@ -84,6 +85,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // Test shows the answer await rows.nth(1).getByRole("button", { name: l.test, exact: true }).click(); await rows.nth(1).getByText(l.ok).waitFor(); + // the exit's address is there for whoever checks it, not in the line + assert.match(await rows.nth(1).locator(".sub").getAttribute("title"), /203\.0\.113\.9$/); + assert.equal(posts.filter((p) => p.test).length, 1, "a test only when Test is clicked"); // adding: a blank password isn't sent as one await list.getByRole("button", { name: l.add, exact: true }).click();