diff --git a/docs/reference.md b/docs/reference.md index 993e78457..e094314dd 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1363,8 +1363,12 @@ it. The gateway listens on `127.0.0.1:3425` (`MAGPIE_ADDR` changes it) and starts with the app; `magpie serve` runs it alone. For reverse-proxied or container deployments, set `MAGPIE_PUBLIC_URL=https://magpie.example.com` to the base -URL shown in the console and CLI, including connection examples. Local -agent configs still use the local gateway address. +URL shown in the console and CLI, including connection examples. While +other machines are let in (Share on local network, or a `MAGPIE_ADDR` on +the network), the Gateway page's Connect starts at it until you pick +another address there, Settings › About lists it beside the local URL, and +`magpie web` shows it as the gateway's address. Local agent configs still +use the local gateway address. Building an app or agent that should use magpie, or get a row on the Agents page: see [Integrating your app or agent](integrating.md). diff --git a/internal/gui/api.go b/internal/gui/api.go index 6530cd9e6..f3ae8b222 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -330,6 +330,11 @@ type settingsJSON struct { Version string `json:"version"` Dir string `json:"dir"` // where magpie keeps its files, as shown Gateway string `json:"gateway"` // the local endpoint + // PublicURL is MAGPIE_PUBLIC_URL while other machines are let in + // (shared, or MAGPIE_ADDR on the network): where they reach the + // gateway, shown beside the local address agents here are pointed at + // (#1551) + PublicURL string `json:"publicURL,omitempty"` // MAGPIE_ADDR, when it sets the gateway's address over Settings' port AddrEnv string `json:"addrEnv,omitempty"` // Dir is the data folder beside a portable magpie (#508) @@ -501,6 +506,9 @@ func searchState(s *settingsJSON) { func settingsState() settingsJSON { s := settingsJSON{Settings: settings.Load(), Version: Version, Dir: tilde(settings.Dir()), Portable: settings.Portable() != "", Gateway: gateway.URL()} s.AddrEnv = os.Getenv("MAGPIE_ADDR") + if s.LAN || gateway.OnNetwork() { + s.PublicURL = gateway.PublicURL() + } s.WSL = runtime.GOOS == "windows" s.Web = webPage.Load() s.GatewayOn, s.GatewayWhy = gatewayMode(s.Web) diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 5d7153552..ee0c362f9 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -5600,10 +5600,14 @@ function renderGateway() { const fix = gatewayFixButton(g, older); if (fix) who.append(fix); if (gatewayFix.err && gatewayFix.when === gatewayFixWhen(g)) who.append(el("div", "sub old err", gatewayFix.err)); + // served to other machines' browsers (magpie web), the address shown is + // the one they reach, MAGPIE_PUBLIC_URL's, not this computer's loopback + // (#1551) + const shown = web && g.publicURL || g.url; const url = el("button", "url"); - url.append(el("code", "", g.url)); + url.append(el("code", "", shown)); url.title = t("Copy the gateway URL"); - url.onclick = () => copy(g.url, t("Gateway URL")); + url.onclick = () => copy(shown, t("Gateway URL")); box.append(dot, who, url); } @@ -5905,8 +5909,10 @@ function renderConnect() { const urls = [g.url, ...(g.lanURLs || [])]; // the address picked is kept (coeo91): an address not offered right now // (the network not up yet after a start) shows this computer's, and the - // pick comes back with it - connectURL = urls.includes(connectWant) ? connectWant : g.url; + // pick comes back with it. With none picked, MAGPIE_PUBLIC_URL is where + // it starts: it says the address other machines use (#1551) + const first = g.publicURL && urls.includes(g.publicURL) ? g.publicURL : g.url; + connectURL = urls.includes(connectWant) ? connectWant : first; // a gateway MAGPIE_ADDR puts on the network (a Docker image's, whose // host is another machine to it) is shown with a gateway key everywhere const remote = connectURL !== g.url || !!g.onNetwork; @@ -5938,7 +5944,7 @@ function renderConnect() { const b = el("div", "val"); if (urls.length > 1) b.append(connectPick("connectAddress", "Address", base, - urls.map((u) => ({ v: u, name: f.base(u), note: t(u === g.url ? "This computer" : "Local network") })), connectURL, + urls.map((u) => ({ v: u, name: f.base(u), note: t(u === g.url ? "This computer" : u === g.publicURL ? "Public address" : "Local network") })), connectURL, (u) => { connectWant = u; keepPick("magpie.connectAddress", u); renderConnect(); })); else b.append(el("code", "", base)); b.append(copyBtn(base, "Base URL")); @@ -19491,6 +19497,8 @@ function renderSettings() { row(t("Config folder"), s.portable ? t("Portable: everything magpie keeps, in the data folder beside it") : t("providers, profiles and these settings"), s.dir, copyBtn(s.dir, t("Path")), open); renderCLI(row(t("Command line"), t("Checking your shells…"), "")); row(t("Gateway URL"), t("the address every agent is pointed at"), s.gateway, copyBtn(s.gateway, t("Gateway URL"))); + // MAGPIE_PUBLIC_URL, where other machines reach it (#1551) + if (s.publicURL) row(t("Public address"), t("MAGPIE_PUBLIC_URL: where other computers reach the gateway, with a gateway key"), s.publicURL, copyBtn(s.publicURL, t("Public address"))).id = "publicURLRow"; const join = el("button", "discord"); join.innerHTML = DISCORD_SVG; join.append(el("span", "", t("Join Discord"))); @@ -20694,7 +20702,8 @@ function renderSearch(s, keep) { } // the same search as an MCP server of the gateway's (Kayphoon on // Discord), for an agent to mount as its web_search tool - const mcpURL = (s.gateway || providers?.gateway?.url || `http://127.0.0.1:${s.port || 3425}`).replace(/\/+$/, "") + "/mcp/magpie/web-search"; + // a page other machines open (magpie web) shows MAGPIE_PUBLIC_URL's (#1551) + const mcpURL = ((web && s.publicURL) || s.gateway || providers?.gateway?.url || `http://127.0.0.1:${s.port || 3425}`).replace(/\/+$/, "") + "/mcp/magpie/web-search"; const mcp = row(t("MCP server"), t("Cursor, Claude Desktop and other agents can add this search as an MCP server (Streamable HTTP) with one web_search tool. From another computer, send a gateway key as Authorization: Bearer ."), el("code", "", mcpURL), copyBtn(mcpURL, t("Address"))); mcp.id = "searchMcpRow"; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 094fe2fef..0bb97e8f8 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -750,6 +750,8 @@ const I18N = { "Privacy": "隐私", "Mask secrets": "脱敏密钥", "Local network": "局域网", + "Public address": "公网地址", + "MAGPIE_PUBLIC_URL: where other computers reach the gateway, with a gateway key": "MAGPIE_PUBLIC_URL:其他电脑访问网关的地址,需带网关密钥", "Share on local network": "局域网共享", "Gateway port": "网关端口", "Agents magpie connected move with it. Now {url}": "改了之后,已接入 magpie 的 Agent 会一起换过去。当前 {url}", @@ -5012,6 +5014,8 @@ const I18N = { "Privacy": "隱私", "Mask secrets": "脫敏金鑰", "Local network": "區域網", + "Public address": "公開位址", + "MAGPIE_PUBLIC_URL: where other computers reach the gateway, with a gateway key": "MAGPIE_PUBLIC_URL:其他電腦連到閘道的位址,需帶閘道金鑰", "Share on local network": "區域網共享", "Gateway port": "閘道連接埠", "Agents magpie connected move with it. Now {url}": "改了之後,已接入 magpie 的 Agent 會一起換過去。目前 {url}", @@ -9245,6 +9249,8 @@ const I18N = { "Privacy": "プライバシー", "Mask secrets": "シークレットをマスク", "Local network": "ローカルネットワーク", + "Public address": "公開アドレス", + "MAGPIE_PUBLIC_URL: where other computers reach the gateway, with a gateway key": "MAGPIE_PUBLIC_URL:他のコンピュータがゲートウェイに接続するアドレス(ゲートウェイキーが必要)", "Share on local network": "ローカルネットワークで共有", "Gateway port": "ゲートウェイのポート", "Agents magpie connected move with it. Now {url}": "magpie に接続したエージェントも一緒に移ります。現在 {url}", @@ -13493,6 +13499,8 @@ const I18N = { "Privacy": "Datenschutz", "Mask secrets": "Geheimnisse maskieren", "Local network": "Lokales Netzwerk", + "Public address": "Öffentliche Adresse", + "MAGPIE_PUBLIC_URL: where other computers reach the gateway, with a gateway key": "MAGPIE_PUBLIC_URL: wo andere Computer das Gateway erreichen, mit einem Gateway-Schlüssel", "Share on local network": "Im lokalen Netzwerk freigeben", "Gateway port": "Port des Zugangspunkts", "Agents magpie connected move with it. Now {url}": "Mit magpie verbundene Agenten ziehen mit um. Jetzt {url}", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 83ea867ae..bd28498e6 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -338,6 +338,9 @@ type gatewayJSON struct { URL string `json:"url"` LAN bool `json:"lan"` LANURLs []string `json:"lanURLs,omitempty"` + // PublicURL is MAGPIE_PUBLIC_URL when it is among LANURLs: Connect + // starts there until the user picks an address (#1551) + PublicURL string `json:"publicURL,omitempty"` // OnNetwork: MAGPIE_ADDR puts it beyond loopback (a server, a Docker // image), so every caller is shown a gateway key, and LAN is true too: // callers from elsewhere, a container's host among them, need one @@ -736,6 +739,9 @@ func providersState() providersJSON { s.Gateway.LAN = settings.Load().LAN || s.Gateway.OnNetwork if s.Gateway.LAN { s.Gateway.LANURLs = gateway.LANURLs() + if u := gateway.PublicURL(); slices.Contains(s.Gateway.LANURLs, u) { + s.Gateway.PublicURL = u + } } for _, e := range cat { if e.Group == "" { diff --git a/internal/gui/public_url_test.go b/internal/gui/public_url_test.go index c2c6cb2be..0eefa66b5 100644 --- a/internal/gui/public_url_test.go +++ b/internal/gui/public_url_test.go @@ -56,6 +56,13 @@ func TestPublicURLInConsole(t *testing.T) { if !g.OnNetwork { t.Error("MAGPIE_ADDR 0.0.0.0 not said to be on the network") } + // #1551: Connect starts at the public URL, and Settings shows it + if g.PublicURL != want { + t.Errorf("Gateway page's public URL: %q, want %q", g.PublicURL, want) + } + if got := settingsState().PublicURL; got != want { + t.Errorf("Settings' public URL: %q, want %q", got, want) + } b, err = json.Marshal(g) if err != nil { t.Fatal(err) @@ -100,3 +107,38 @@ func TestGatewayOnNetworkInConsole(t *testing.T) { t.Errorf("gateway on loopback, not shared: %+v", g) } } + +// #1551: MAGPIE_PUBLIC_URL is offered where other machines are let in, +// and nowhere else: on loopback, not shared, nothing reaches the gateway +// through it without a key it can't take. +func TestPublicURLOnlyWhereOffered(t *testing.T) { + h := t.TempDir() + testenv.SetHome(t, h) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) + t.Setenv("XDG_DATA_HOME", filepath.Join(h, ".local", "share")) + t.Setenv("MAGPIE_PUBLIC_URL", "https://magpie.example.com") + t.Setenv("MAGPIE_ADDR", "127.0.0.1:3425") + if err := settings.Save(settings.Settings{LAN: false}); err != nil { + t.Fatal(err) + } + if g := providersState().Gateway; g.PublicURL != "" { + t.Errorf("loopback, not shared: Gateway page offers %q", g.PublicURL) + } + if u := settingsState().PublicURL; u != "" { + t.Errorf("loopback, not shared: Settings shows %q", u) + } + if err := settings.Save(settings.Settings{LAN: true}); err != nil { + t.Fatal(err) + } + if g := providersState().Gateway; g.PublicURL != "https://magpie.example.com" { + t.Errorf("shared: Gateway page's public URL %q", g.PublicURL) + } + t.Setenv("MAGPIE_PUBLIC_URL", "") + if g := providersState().Gateway; g.PublicURL != "" { + t.Errorf("no MAGPIE_PUBLIC_URL: Gateway page's public URL %q", g.PublicURL) + } + if u := settingsState().PublicURL; u != "" { + t.Errorf("no MAGPIE_PUBLIC_URL: Settings shows %q", u) + } +} diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index 8005aa79b..a1800a8f0 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -1779,6 +1779,14 @@ about the gateway: loopback, open to the network (listening beyond loopback with nothing shared), and a network address that needs an enabled gateway key. English and Chinese, Chromium and WebKit, with `/api/plugins` faked. +`public-url-default.test.cjs` checks that Connect starts at MAGPIE_PUBLIC_URL, +labelled Public address, with the snippets on it, until an address is +picked, and that a pick (this computer's) is kept after a reload (#1551). +About shows the public URL beside the local one; magpie web shows it as the +gateway's address and the MCP server's, the app keeps those local. Without +MAGPIE_PUBLIC_URL Connect starts at this computer's. Every language, +Chromium and WebKit, at 1100 and 420 wide. + `provider-picks-stay.test.cjs` checks that the models picked in one provider's editor never go to another's (#464): a Refresh or a Forget whose list comes back after the editor was left for another provider's leaves that diff --git a/internal/gui/tests/fixtures/caller-keys.cjs b/internal/gui/tests/fixtures/caller-keys.cjs index 4cd6bb78a..db14a09e8 100644 --- a/internal/gui/tests/fixtures/caller-keys.cjs +++ b/internal/gui/tests/fixtures/caller-keys.cjs @@ -24,8 +24,11 @@ function fixture(lang, theme, events, options = {}) { const secrets = new Map([["laptop", "fixture-laptop"], ["server", "fixture-server"], ["work", "fixture-work"]]); // options.lanURLs is the test's own list, so it can take the network away const lanURLs = options.lanURLs || ["http://192.168.1.10:3999", "http://10.0.0.10:3999"]; + // options.publicURL is MAGPIE_PUBLIC_URL's, offered while shared (#1551) + const publicURL = () => lan && options.publicURL ? { publicURL: options.publicURL } : {}; const lanState = () => ({ lang, theme, lan, - lanURLs: lan ? lanURLs : [], fx: { rate: 7.2, at: new Date().toISOString() } }); + lanURLs: lan ? lanURLs : [], fx: { rate: 7.2, at: new Date().toISOString() }, + ...(options.publicURL ? { gateway: "http://127.0.0.1:3999", ...publicURL() } : {}) }); const rows = [ { callerKeyId: "laptop", callerKeyName: "Laptop", in: 100, out: 10, cost: 0.1 }, { callerKeyId: "server", callerKeyName: "Server", in: 200, out: 20, cost: 0.2 }, @@ -52,13 +55,13 @@ function fixture(lang, theme, events, options = {}) { 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, web: false })};` }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = ${JSON.stringify({ lang, theme, web: !!options.web })};` }); if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); if (url.pathname === "/favicon.ico") return route.fulfill({ status: 204 }); if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme } }); if (url.pathname === "/api/providers") return json({ providers: [{ id: "relay", name: "Relay", icon: "generic", models: [{ id: "m", name: "Model", on: true }], agents: [] }], - gateway: { running: true, window: true, mine: true, url: "http://127.0.0.1:3999", lan, lanURLs: lan ? lanURLs : [], calls: [], groups: [] }, + gateway: { running: true, window: true, mine: true, url: "http://127.0.0.1:3999", lan, lanURLs: lan ? lanURLs : [], ...publicURL(), calls: [], groups: [] }, }); if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); if (url.pathname === "/api/settings/lan") { diff --git a/internal/gui/tests/public-url-default.test.cjs b/internal/gui/tests/public-url-default.test.cjs new file mode 100644 index 000000000..636bcbe80 --- /dev/null +++ b/internal/gui/tests/public-url-default.test.cjs @@ -0,0 +1,112 @@ +const assert = require("node:assert/strict"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); +const { fixture } = require("./fixtures/caller-keys.cjs"); + +// #1551 (everpcpc): magpie web in Docker behind a reverse proxy, with +// MAGPIE_PUBLIC_URL=https://magpie.example.com. The page is opened from +// other machines, yet Gateway's Connect started at http://127.0.0.1:3425, +// and so did the copied snippets and the gateway's own address. With no +// address picked, Connect now starts at the public URL, labelled as such, +// the snippets with it, and About shows it beside the local address agents +// here use. An address the user picked, this computer's included, still +// wins after a reload. Served to other machines (magpie web), the +// gateway's address and Settings' MCP server show the public URL too; in +// the app they stay this computer's. Without MAGPIE_PUBLIC_URL nothing +// changes: Connect starts at this computer's. +const PUBLIC = "https://magpie.example.com"; +const LOCAL = "http://127.0.0.1:3999"; +const LANGS = ["en", "zh", "zh-TW", "ja", "de"]; +const words = { + en: "Public address", zh: "公网地址", "zh-TW": "公開位址", ja: "公開アドレス", de: "Öffentliche Adresse", +}; + +async function setup(t, engine, lang, width, options) { + 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(6000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", fixture(lang, "light", [], { lan: true, ...options })); + const open = async () => { + await page.goto("http://magpie.test/?view=gateway"); + await page.locator("#connectAddress").waitFor(); + }; + const shown = (sel) => page.locator(sel).textContent(); + const settingsTab = async (tab) => { + if (!(await page.locator("#view-settings").isVisible())) await page.locator("#prefs").click(); + await page.locator("#setTab-" + tab).click(); + }; + const fits = async (where) => assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, where + " wider than the window"); + return { page, errors, open, shown, settingsTab, fits }; +} + +// the snippets carry the gateway key Connect picked for an address +// elsewhere; its read redraws Connect, which closes a menu open +const keyed = (page, base) => page.waitForFunction((u) => { + const s = document.querySelector("#connect pre.snip")?.textContent || ""; + return s.includes(u) && s.includes("fixture-laptop"); +}, base); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of LANGS) { + for (const width of [1100, 420]) { + test(`${engine} ${lang} ${width}: Connect starts at MAGPIE_PUBLIC_URL until an address is picked`, async (t) => { + const { page, errors, open, shown, settingsTab, fits } = await setup(t, engine, lang, width, { lanURLs: [PUBLIC], publicURL: PUBLIC }); + + // nothing picked yet: the public URL, with a gateway key, in the + // snippet too + await open(); + assert.equal(await shown("#connectAddress"), PUBLIC + "/v1"); + await keyed(page, PUBLIC + "/v1"); + assert.doesNotMatch(await shown("#connect pre.snip"), /127\.0\.0\.1/); + // in the app, the gateway's own address stays this computer's + assert.equal(await shown("#gateway .url code"), LOCAL); + await page.locator("#connectAddress").click(); + assert.match(await page.locator(".proto-menu .pm-item", { hasText: "magpie.example.com" }).textContent(), new RegExp(words[lang])); + await fits("Gateway"); + + // the user's own pick, this computer, wins over the public URL + await page.locator(".proto-menu .pm-item", { hasText: "127.0.0.1" }).click(); + await page.locator(".proto-menu").waitFor({ state: "detached" }); + assert.equal(await shown("#connectAddress"), LOCAL + "/v1"); + await open(); + assert.equal(await shown("#connectAddress"), LOCAL + "/v1"); + + // About keeps the local address agents use, and shows the public one + await settingsTab("about"); + await page.locator("#publicURLRow").waitFor(); + assert.match(await shown("#publicURLRow .who"), new RegExp(words[lang])); + assert.equal(await shown("#publicURLRow code"), PUBLIC); + assert.match(await shown("#about"), /127\.0\.0\.1:3999/); + await fits("About"); + await settingsTab("models"); + assert.equal(await shown("#searchMcpRow code"), LOCAL + "/mcp/magpie/web-search"); + assert.deepEqual(errors, []); + }); + } + } + for (const width of [1100, 420]) { + test(`${engine} ${width}: magpie web shows MAGPIE_PUBLIC_URL as the gateway's address`, async (t) => { + const { page, errors, open, shown, settingsTab } = await setup(t, engine, "en", width, { lanURLs: [PUBLIC], publicURL: PUBLIC, web: true }); + await open(); + assert.equal(await shown("#connectAddress"), PUBLIC + "/v1"); + await keyed(page, PUBLIC + "/v1"); + assert.equal(await shown("#gateway .url code"), PUBLIC); + await settingsTab("models"); + assert.equal(await shown("#searchMcpRow code"), PUBLIC + "/mcp/magpie/web-search"); + assert.deepEqual(errors, []); + }); + } + test(`${engine}: without MAGPIE_PUBLIC_URL Connect starts at this computer's address`, async (t) => { + const { page, errors, open, shown, settingsTab } = await setup(t, engine, "en", 1100, { lanURLs: ["http://192.168.1.10:3999"], web: true }); + await open(); + assert.equal(await shown("#connectAddress"), LOCAL + "/v1"); + assert.equal(await shown("#gateway .url code"), LOCAL); + await settingsTab("about"); + await page.locator("#about .row").first().waitFor(); + assert.equal(await page.locator("#publicURLRow").count(), 0); + assert.deepEqual(errors, []); + }); +}