gateway: advertise MAGPIE_PUBLIC_URL in the console and CLIs (#373)
This commit is contained in:
@@ -508,7 +508,22 @@ adding one; use an account you can afford to lose.
|
||||
### Connecting anything else
|
||||
|
||||
The gateway listens on `127.0.0.1:3425` (`MAGPIE_ADDR` changes it) and starts
|
||||
with the app; `magpie serve` runs it alone. It exposes:
|
||||
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.
|
||||
|
||||
A reverse proxy must enforce authentication itself, or you must enable
|
||||
Settings → Share on local network and use an enabled gateway key
|
||||
(Gateway → Gateway keys) for external clients. A public URL with no port of
|
||||
its own — a reverse proxy's `https://magpie.example.com` — is the address
|
||||
`magpie web` prints for its own page too, so the proxy must forward `/v1`
|
||||
and `/v1beta` to the gateway's port and the rest to the page's. When the
|
||||
proxy and magpie run on the same machine, requests forwarded over loopback
|
||||
are treated as local and need no key, so the proxy must authenticate those
|
||||
clients itself.
|
||||
|
||||
It exposes:
|
||||
|
||||
| Path | API |
|
||||
| ------------------------ | -------------------------- |
|
||||
@@ -688,7 +703,9 @@ Inside the container
|
||||
magpie only sees the container's own address (Docker's 172.17.x), so set
|
||||
`-e MAGPIE_PUBLIC_URL=http://<the host's or NAS's address>:3425` (the port
|
||||
published on the host) for the address it shows and prints to be the one
|
||||
other machines use.
|
||||
other machines use; behind a reverse proxy, set it to that external base URL
|
||||
and follow the [authentication requirements above](#connecting-anything-else),
|
||||
especially when the proxy reaches magpie over loopback.
|
||||
|
||||
For the browser UI run the image with `magpie web --addr 0.0.0.0:3430 --no-open`
|
||||
in place of the default `serve`, and open
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
)
|
||||
|
||||
// Codex stays on the local gateway even when its advertised URL changes.
|
||||
func TestCodexPublicURL(t *testing.T) {
|
||||
home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, "model = \"gpt-5.5\"\n")
|
||||
t.Setenv("MAGPIE_PUBLIC_URL", "https://magpie.example.com/magpie///")
|
||||
cx := codex(home)
|
||||
if err := cx.Fields[0].Set("fake/m1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg := read(); !strings.Contains(cfg, `openai_base_url = "`+gateway.URL()+gateway.CodexPath+`"`) ||
|
||||
!strings.Contains(cfg, `base_url = "`+gateway.URL()+`/v1"`) {
|
||||
t.Fatalf("local URL not written:\n%s", cfg)
|
||||
}
|
||||
t.Setenv("MAGPIE_PUBLIC_URL", "")
|
||||
if got := codex(home).Check(); got != "" {
|
||||
t.Fatalf("wiring changed after removing public URL: %s", got)
|
||||
}
|
||||
if err := codex(home).Fields[0].Set("gpt-5.4"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg := read(); strings.Contains(cfg, "openai_base_url") {
|
||||
t.Fatalf("local URL not removed:\n%s", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
// Gemini keeps its local wiring and restores the original URL across changes
|
||||
// to the advertised URL, including a second application of magpie.
|
||||
func TestGeminiPublicURL(t *testing.T) {
|
||||
home, _ := codexHome(t, "", "")
|
||||
t.Setenv("MAGPIE_PUBLIC_URL", "https://magpie.example.com/")
|
||||
path := filepath.Join(home, ".gemini", ".env")
|
||||
if err := edit.SetEnvFile(path, edit.KV{Path: "GOOGLE_GEMINI_BASE_URL", Value: "https://gemini.example.com"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gm := gemini(home)
|
||||
if err := gm.Field("model").Set("fake/m1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := edit.GetEnvFile(path, "GOOGLE_GEMINI_BASE_URL"); got != gateway.URL() {
|
||||
t.Fatalf("base URL: %q", got)
|
||||
}
|
||||
for _, public := range []string{"https://another.example.com", ""} {
|
||||
t.Setenv("MAGPIE_PUBLIC_URL", public)
|
||||
if got := gemini(home).Check(); got != "" {
|
||||
t.Fatalf("wiring changed with public URL %q: %s", public, got)
|
||||
}
|
||||
if err := gemini(home).Field("model").Set("fake/m1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := gemini(home).Field("model").Set("gemini-2.5-pro"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := edit.GetEnvFile(path, "GOOGLE_GEMINI_BASE_URL"); got != "https://gemini.example.com" {
|
||||
t.Fatalf("restored base URL: %q", got)
|
||||
}
|
||||
}
|
||||
+40
-11
@@ -2,12 +2,14 @@ package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
@@ -42,26 +44,53 @@ func migrateLANKeyBestEffort() {
|
||||
access.MigrateLegacyLANKeyBestEffort()
|
||||
}
|
||||
|
||||
// publicURL is MAGPIE_PUBLIC_URL, the base URL other machines are told to
|
||||
// reach the gateway at, without its trailing slashes: a magpie in a
|
||||
// container sees only the container's own addresses, never the host's.
|
||||
func publicURL() string { return strings.TrimRight(os.Getenv("MAGPIE_PUBLIC_URL"), "/") }
|
||||
func logInvalidPublicURL() {
|
||||
log.Printf("ignoring invalid MAGPIE_PUBLIC_URL: expected an HTTP or HTTPS address with a host")
|
||||
}
|
||||
|
||||
// lanPublicURL is publicURL with a scheme, as a link needs.
|
||||
func lanPublicURL() string {
|
||||
u := publicURL()
|
||||
if u != "" && !strings.Contains(u, "://") {
|
||||
var warnInvalidPublicURL = sync.OnceFunc(logInvalidPublicURL)
|
||||
|
||||
// publicURL is the validated MAGPIE_PUBLIC_URL, with a scheme and without
|
||||
// trailing slashes. An invalid value is treated as unset and warned once.
|
||||
func publicURL() string {
|
||||
u := strings.TrimSpace(os.Getenv("MAGPIE_PUBLIC_URL"))
|
||||
if u == "" {
|
||||
return ""
|
||||
}
|
||||
// Keep a scheme-only value invalid after trimming its slashes.
|
||||
hasScheme := strings.Contains(u, "://")
|
||||
u = strings.TrimRight(u, "/")
|
||||
if !hasScheme {
|
||||
u = "http://" + u
|
||||
}
|
||||
parsed, err := url.Parse(u)
|
||||
// A query, a fragment or credentials would be lost or shown when the
|
||||
// address is joined with a path, so only a plain base URL is taken.
|
||||
if err != nil || parsed.Host == "" || (parsed.Scheme != "http" && parsed.Scheme != "https") ||
|
||||
parsed.RawQuery != "" || parsed.Fragment != "" || parsed.User != nil {
|
||||
warnInvalidPublicURL()
|
||||
return ""
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
// PublicURL is MAGPIE_PUBLIC_URL, with a scheme; "" when it isn't set.
|
||||
func PublicURL() string { return lanPublicURL() }
|
||||
func PublicURL() string { return publicURL() }
|
||||
|
||||
// OpenToAnyone: the gateway listens beyond loopback (MAGPIE_ADDR) and isn't
|
||||
// shared, so anyone who reaches it is let in with any key. Shared, it asks
|
||||
// for an enabled gateway key instead.
|
||||
func OpenToAnyone() bool {
|
||||
if settings.Load().LAN {
|
||||
return false
|
||||
}
|
||||
h, _, err := net.SplitHostPort(Addr())
|
||||
return err == nil && h != "localhost" && !net.ParseIP(h).IsLoopback()
|
||||
}
|
||||
|
||||
// PublicHost is MAGPIE_PUBLIC_URL's host, "" when it isn't set.
|
||||
func PublicHost() string {
|
||||
u, err := url.Parse(lanPublicURL())
|
||||
u, err := url.Parse(publicURL())
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
@@ -94,7 +123,7 @@ func inContainer(root string) bool {
|
||||
// gateway at: MAGPIE_PUBLIC_URL when set, else one per IPv4 address this
|
||||
// computer has there.
|
||||
func LANURLs() []string {
|
||||
if u := lanPublicURL(); u != "" {
|
||||
if u := publicURL(); u != "" {
|
||||
return []string{u}
|
||||
}
|
||||
var out []string
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
func TestPublicURL(t *testing.T) {
|
||||
t.Setenv("MAGPIE_ADDR", "0.0.0.0:3499")
|
||||
t.Setenv("MAGPIE_PUBLIC_URL", "")
|
||||
if err := os.Unsetenv("MAGPIE_PUBLIC_URL"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := PublicURL(); got != "" {
|
||||
t.Fatalf("unset: %q, want no public URL", got)
|
||||
}
|
||||
for _, c := range []struct{ public, want string }{
|
||||
{"", ""},
|
||||
{"https://magpie.example.com", "https://magpie.example.com"},
|
||||
{"https://magpie.example.com/", "https://magpie.example.com"},
|
||||
{"https://magpie.example.com/magpie///", "https://magpie.example.com/magpie"},
|
||||
{"http://magpie.example.com:3425/", "http://magpie.example.com:3425"},
|
||||
{"http://[::1]:3425/", "http://[::1]:3425"},
|
||||
{"magpie.example.com", "http://magpie.example.com"},
|
||||
{"nas.lan:3425///", "http://nas.lan:3425"},
|
||||
{"[fd00::20]:3425", "http://[fd00::20]:3425"},
|
||||
{"///", ""},
|
||||
{"ftp://magpie.example.com", ""},
|
||||
{"//magpie.example.com", ""},
|
||||
{"https:///magpie", ""},
|
||||
{"http://", ""},
|
||||
{"https:///", ""},
|
||||
{"ftp://", ""},
|
||||
{"https://magpie.example.com:bad", ""},
|
||||
{"https://magpie.example.com/%zz", ""},
|
||||
{" https://magpie.example.com", "https://magpie.example.com"},
|
||||
{"\thttps://magpie.example.com/magpie/ ", "https://magpie.example.com/magpie"},
|
||||
{"https://magpie.example.com/magpie?x=1", ""},
|
||||
{"https://magpie.example.com/magpie#frag", ""},
|
||||
{"https://user:pass@magpie.example.com", ""},
|
||||
} {
|
||||
t.Run(c.public, func(t *testing.T) {
|
||||
t.Setenv("MAGPIE_PUBLIC_URL", c.public)
|
||||
if got := PublicURL(); got != c.want {
|
||||
t.Errorf("%q, want %q", got, c.want)
|
||||
}
|
||||
invalid := c.public != "" && c.want == ""
|
||||
if invalid {
|
||||
if got := publicURL(); got != "" {
|
||||
t.Errorf("invalid public URL: %q", got)
|
||||
}
|
||||
if got := PublicHost(); got != "" {
|
||||
t.Errorf("invalid public host: %q", got)
|
||||
}
|
||||
if got := ContainerAddrs(); got != inContainer("/") {
|
||||
t.Errorf("invalid URL must be treated as unset in a container: %v", got)
|
||||
}
|
||||
for _, got := range LANURLs() {
|
||||
if !strings.HasPrefix(got, "http://") {
|
||||
t.Errorf("invalid LAN URL: %q", got)
|
||||
}
|
||||
}
|
||||
} else if c.public != "" {
|
||||
if got := LANURLs(); len(got) != 1 || got[0] != c.want {
|
||||
t.Errorf("LAN URLs: %v, want [%s]", got, c.want)
|
||||
}
|
||||
if ContainerAddrs() {
|
||||
t.Error("valid public URL still says the addresses are a container's")
|
||||
}
|
||||
}
|
||||
if got := Addr(); got != "0.0.0.0:3499" {
|
||||
t.Errorf("listen address changed: %q", got)
|
||||
}
|
||||
if got := URL(); got != "http://127.0.0.1:3499" {
|
||||
t.Errorf("local URL changed: %q", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicURLWarningOnce(t *testing.T) {
|
||||
// Reset the warning so the assertion does not depend on test order.
|
||||
warn := warnInvalidPublicURL
|
||||
warnInvalidPublicURL = sync.OnceFunc(logInvalidPublicURL)
|
||||
t.Cleanup(func() { warnInvalidPublicURL = warn })
|
||||
var logs bytes.Buffer
|
||||
writer := log.Writer()
|
||||
log.SetOutput(&logs)
|
||||
t.Cleanup(func() { log.SetOutput(writer) })
|
||||
t.Setenv("MAGPIE_ADDR", "127.0.0.1:3499")
|
||||
t.Setenv("MAGPIE_PUBLIC_URL", "")
|
||||
PublicURL()
|
||||
if logs.Len() != 0 {
|
||||
t.Fatalf("unset URL warned: %q", logs.String())
|
||||
}
|
||||
t.Setenv("MAGPIE_PUBLIC_URL", "nas.lan:3425")
|
||||
PublicURL()
|
||||
if logs.Len() != 0 {
|
||||
t.Fatalf("valid URL warned: %q", logs.String())
|
||||
}
|
||||
t.Setenv("MAGPIE_PUBLIC_URL", "ftp://nas.lan")
|
||||
if got := PublicURL(); got != "" {
|
||||
t.Fatalf("invalid URL: %q, want no public URL", got)
|
||||
}
|
||||
if got := strings.Count(logs.String(), "ignoring invalid MAGPIE_PUBLIC_URL"); got != 1 {
|
||||
t.Fatalf("first invalid URL: %q, want exactly one warning", logs.String())
|
||||
}
|
||||
logs.Reset()
|
||||
for _, u := range []string{"ftp://nas.lan", "https:///magpie", "https://nas.lan:bad"} {
|
||||
t.Setenv("MAGPIE_PUBLIC_URL", u)
|
||||
for range 3 {
|
||||
PublicURL()
|
||||
PublicHost()
|
||||
LANURLs()
|
||||
ContainerAddrs()
|
||||
}
|
||||
}
|
||||
if logs.Len() != 0 {
|
||||
t.Fatalf("subsequent calls warned again: %q", logs.String())
|
||||
}
|
||||
}
|
||||
|
||||
// OpenToAnyone: the gateway listens beyond loopback (MAGPIE_ADDR) and no key
|
||||
// is shared, so anyone who reaches it is let in — the console says so, as
|
||||
// keyNote does.
|
||||
func TestOpenToAnyone(t *testing.T) {
|
||||
h := t.TempDir()
|
||||
t.Setenv("HOME", 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"))
|
||||
for _, c := range []struct {
|
||||
addr string
|
||||
lan bool
|
||||
want bool
|
||||
}{
|
||||
{"127.0.0.1:3425", false, false},
|
||||
{"127.0.0.1:3425", true, false},
|
||||
{"0.0.0.0:3425", false, true},
|
||||
{"0.0.0.0:3425", true, false},
|
||||
{"10.0.0.5:3425", false, true},
|
||||
{"10.0.0.5:3425", true, false},
|
||||
} {
|
||||
t.Setenv("MAGPIE_ADDR", c.addr)
|
||||
if err := settings.Save(settings.Settings{LAN: c.lan}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := OpenToAnyone(); got != c.want {
|
||||
t.Errorf("%s shared=%v: %v, want %v", c.addr, c.lan, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2838,7 +2838,7 @@ function renderConnect() {
|
||||
note.replaceChildren();
|
||||
note.classList.toggle("brief", connectFolded);
|
||||
if (connectFolded) note.append(el("code", "", base), copyBtn(base, "Base URL"));
|
||||
else note.textContent = t(remote ? "Local network · an enabled gateway key is required" : g.lan && gatewayKeys?.length ? "Use a gateway key to track usage" : "Loopback only · the key can be anything");
|
||||
else note.textContent = t(g.open ? "Open to the network · anyone who reaches it can use any key" : remote ? "Local network · an enabled gateway key is required" : g.lan && gatewayKeys?.length ? "Use a gateway key to track usage" : "Loopback only · the key can be anything");
|
||||
|
||||
box.append(...field("API", segs(Object.entries(FLAVORS).map(([k, v]) => [k, v.name]), flavor, (id) => { flavor = id; localStorage.setItem("magpie.flavor", id); renderConnect(); }), t(f.note)));
|
||||
|
||||
|
||||
@@ -916,6 +916,7 @@ const I18N = {
|
||||
"which endpoint {p} is reached through": "通过哪个入口访问 {p}",
|
||||
"{what} copied": "已复制{what}",
|
||||
"Connect": "接入",
|
||||
"Open to the network · anyone who reaches it can use any key": "已开放到网络 · 任何能连上的人用任意密钥都能访问",
|
||||
"Loopback only · the key can be anything": "仅限本机回环 · 密钥可以随意填",
|
||||
"Chat Completions, the API most tools speak. Anything with an OpenAI base-URL setting works.": "Chat Completions,多数工具使用的 API。任何可设置 OpenAI base URL 的工具都能用。",
|
||||
"OpenAI's newer API: reasoning, built-in tool items, encrypted reasoning. Codex speaks this.": "OpenAI 较新的 API:推理、内置工具项、加密推理。Codex 使用它。",
|
||||
|
||||
@@ -158,6 +158,7 @@ type gatewayJSON struct {
|
||||
URL string `json:"url"`
|
||||
LAN bool `json:"lan"`
|
||||
LANURLs []string `json:"lanURLs,omitempty"`
|
||||
Open bool `json:"open,omitempty"` // listens beyond loopback with no key: anyone reaching it is let in
|
||||
Running bool `json:"running"`
|
||||
Mine bool `json:"mine"` // this process serves it
|
||||
Window bool `json:"window"` // the magpie serving it shows its routing
|
||||
@@ -431,7 +432,7 @@ func providersState() providersJSON {
|
||||
s.Presets = append(s.Presets, presetJSON{PresetDef: pr, Added: have[pr.ID], ZhipuTeam: team})
|
||||
}
|
||||
cat := provider.Catalog()
|
||||
s.Gateway = gatewayJSON{URL: gateway.URL(), Models: len(cat), Calls: []gateway.Call{}, Groups: []gwGroupJSON{}}
|
||||
s.Gateway = gatewayJSON{URL: gateway.URL(), Open: gateway.OpenToAnyone(), Models: len(cat), Calls: []gateway.Call{}, Groups: []gwGroupJSON{}}
|
||||
s.Gateway.LAN = settings.Load().LAN
|
||||
if s.Gateway.LAN {
|
||||
s.Gateway.LANURLs = gateway.LANURLs()
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/fx"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// Settings shows the local address agents use; the Gateway page advertises
|
||||
// the public URL for its copy buttons and snippets.
|
||||
func TestPublicURLInConsole(t *testing.T) {
|
||||
h := t.TempDir()
|
||||
t.Setenv("HOME", 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_ADDR", "0.0.0.0:3425")
|
||||
t.Setenv("MAGPIE_PUBLIC_URL", "https://magpie.example.com/magpie///")
|
||||
|
||||
// Seed the rate the Settings page reads, so it needs no network.
|
||||
cache := fx.CachePath()
|
||||
if err := os.MkdirAll(filepath.Dir(cache), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := json.Marshal(fx.Rate{CNYPerUSD: 7.25, At: time.Now()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(cache, b, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fx.Reset()
|
||||
t.Cleanup(fx.Reset)
|
||||
|
||||
if err := settings.Save(settings.Settings{LAN: true, LANKey: "sk-magpie-test"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "https://magpie.example.com/magpie"
|
||||
if got := settingsState().Gateway; got != gateway.URL() {
|
||||
t.Errorf("Settings: %q, want %q", got, gateway.URL())
|
||||
}
|
||||
g := providersState().Gateway
|
||||
if g.URL != gateway.URL() {
|
||||
t.Errorf("Gateway address: %q, want the local %q", g.URL, gateway.URL())
|
||||
}
|
||||
if len(g.LANURLs) != 1 || g.LANURLs[0] != want {
|
||||
t.Errorf("LAN addresses: %v, want [%s]", g.LANURLs, want)
|
||||
}
|
||||
if g.Open {
|
||||
t.Error("a gateway shared with a key is not open to anyone")
|
||||
}
|
||||
b, err = json.Marshal(g)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var state map[string]any
|
||||
if err := json.Unmarshal(b, &state); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if state["lan"] != true {
|
||||
t.Fatalf("LAN state missing from gateway page: %s", b)
|
||||
}
|
||||
}
|
||||
|
||||
// The console warns about a gateway left open to the network: listening
|
||||
// beyond loopback with nothing shared.
|
||||
func TestGatewayOpenInConsole(t *testing.T) {
|
||||
h := t.TempDir()
|
||||
t.Setenv("HOME", 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_ADDR", "0.0.0.0:3425")
|
||||
t.Setenv("MAGPIE_PUBLIC_URL", "")
|
||||
if err := settings.Save(settings.Settings{LAN: false}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if g := providersState().Gateway; !g.Open {
|
||||
t.Errorf("open gateway not reported: %+v", g)
|
||||
}
|
||||
if err := settings.Save(settings.Settings{LAN: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if g := providersState().Gateway; g.Open {
|
||||
t.Errorf("sharing turns the open warning off: %+v", g)
|
||||
}
|
||||
}
|
||||
@@ -1020,10 +1020,16 @@ a first use, a signed-in account still listed stays under it, and a file that
|
||||
reads shows none of it. English and Chinese, Chromium and WebKit, with
|
||||
`/api/plugins` faked.
|
||||
|
||||
`public-url.test.cjs` checks the address MAGPIE_PUBLIC_URL puts beside this
|
||||
computer's on the Gateway page's Connect section, and what its hint says
|
||||
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.
|
||||
|
||||
With Node.js and Playwright available:
|
||||
|
||||
```sh
|
||||
node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/rollup-short.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs internal/gui/tests/omarchy.test.cjs internal/gui/tests/brand.test.cjs internal/gui/tests/library-loading.test.cjs internal/gui/tests/provider-typed.test.cjs node --test internal/gui/tests/signin-callback.test.cjs internal/gui/tests/routing-steady.test.cjs internal/gui/tests/old-webkit.test.cjs internal/gui/tests/session-terminal.test.cjs internal/gui/tests/text-size.test.cjs internal/gui/tests/zcode-site.test.cjs internal/gui/tests/rail-tip.test.cjs internal/gui/tests/sync-update.test.cjs internal/gui/tests/plugin-signin.test.cjs internal/gui/tests/plugin-market.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/routing-wb-refused.test.cjs internal/gui/tests/routing-blocked.test.cjs internal/gui/tests/routing-zcode-blocked.test.cjs internal/gui/tests/routing-shape.test.cjs internal/gui/tests/market-have.test.cjs internal/gui/tests/sessions-today.test.cjs internal/gui/tests/routing-side-calls.test.cjs internal/gui/tests/import-all-skills.test.cjs internal/gui/tests/routing-flood.test.cjs internal/gui/tests/routing-busy.test.cjs internal/gui/tests/own-skill.test.cjs internal/gui/tests/routing-manual.test.cjs internal/gui/tests/tray-usages.test.cjs internal/gui/tests/provider-remove.test.cjs internal/gui/tests/signin-link.test.cjs internal/gui/tests/tray-inuse.test.cjs internal/gui/tests/codex-auto-reset.test.cjs internal/gui/tests/routing-auto-reset.test.cjs internal/gui/tests/claude-usage-asked.test.cjs internal/gui/tests/claude-risk.test.cjs internal/gui/tests/library-toggle-status.test.cjs internal/gui/tests/library-all.test.cjs internal/gui/tests/routing-reroute-title.test.cjs internal/gui/tests/plain-names.test.cjs internal/gui/tests/panel-effort.test.cjs internal/gui/tests/agent-models-all-hidden.test.cjs internal/gui/tests/omp-roles.test.cjs internal/gui/tests/claude-effort.test.cjs internal/gui/tests/remote-magpie.test.cjs internal/gui/tests/qoder-cn-tile.test.cjs internal/gui/tests/provider-levels-scroll.test.cjs internal/gui/tests/signin-paste-codex.test.cjs internal/gui/tests/signin-paste-key.test.cjs internal/gui/tests/usage-alert.test.cjs internal/gui/tests/quota-families.test.cjs internal/gui/tests/provider-search.test.cjs internal/gui/tests/webdav-settings-refresh.test.cjs internal/gui/tests/lan-docker.test.cjs internal/gui/tests/plugin-key-hint.test.cjs internal/gui/tests/update-hide.test.cjs internal/gui/tests/tray-logos.test.cjs internal/gui/tests/routing-proxy.test.cjs internal/gui/tests/sse-body.test.cjs internal/gui/tests/remote-group-served.test.cjs internal/gui/tests/plugin-move-overflow.test.cjs internal/gui/tests/routing-time.test.cjs internal/gui/tests/unlisted-models.test.cjs internal/gui/tests/plugin-updates.test.cjs internal/gui/tests/request-archive.test.cjs internal/gui/tests/group-member-fast.test.cjs internal/gui/tests/providers-off-fold.test.cjs internal/gui/tests/account-return.test.cjs internal/gui/tests/usage-ledger-detail.test.cjs internal/gui/tests/usage-ledger-chart.test.cjs internal/gui/tests/usage-chart-axis.test.cjs internal/gui/tests/panel-usage.test.cjs internal/gui/tests/usage-refresh.test.cjs internal/gui/tests/usage-ledger-content.test.cjs internal/gui/tests/claude-direct.test.cjs internal/gui/tests/signin-again.test.cjs internal/gui/tests/sessions-calendar-fill.test.cjs internal/gui/tests/editor-short-window.test.cjs internal/gui/tests/group-from-model-add.test.cjs internal/gui/tests/sync-other-kind.test.cjs internal/gui/tests/web-page.test.cjs internal/gui/tests/balance-parts.test.cjs internal/gui/tests/search-api.test.cjs internal/gui/tests/provider-file-error.test.cjs internal/gui/tests/sessions-manage.test.cjs internal/gui/tests/number-units.test.cjs internal/gui/tests/sessions-bar-names.test.cjs internal/gui/tests/model-suffix-own.test.cjs internal/gui/tests/routing-effort-change.test.cjs internal/gui/tests/every-skill.test.cjs internal/gui/tests/header-centre.test.cjs internal/gui/tests/strip-scrollbar.test.cjs
|
||||
node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/rollup-short.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs internal/gui/tests/omarchy.test.cjs internal/gui/tests/brand.test.cjs internal/gui/tests/library-loading.test.cjs internal/gui/tests/provider-typed.test.cjs node --test internal/gui/tests/signin-callback.test.cjs internal/gui/tests/routing-steady.test.cjs internal/gui/tests/old-webkit.test.cjs internal/gui/tests/session-terminal.test.cjs internal/gui/tests/text-size.test.cjs internal/gui/tests/zcode-site.test.cjs internal/gui/tests/rail-tip.test.cjs internal/gui/tests/sync-update.test.cjs internal/gui/tests/plugin-signin.test.cjs internal/gui/tests/plugin-market.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/routing-wb-refused.test.cjs internal/gui/tests/routing-blocked.test.cjs internal/gui/tests/routing-zcode-blocked.test.cjs internal/gui/tests/routing-shape.test.cjs internal/gui/tests/market-have.test.cjs internal/gui/tests/sessions-today.test.cjs internal/gui/tests/routing-side-calls.test.cjs internal/gui/tests/import-all-skills.test.cjs internal/gui/tests/routing-flood.test.cjs internal/gui/tests/routing-busy.test.cjs internal/gui/tests/own-skill.test.cjs internal/gui/tests/routing-manual.test.cjs internal/gui/tests/tray-usages.test.cjs internal/gui/tests/provider-remove.test.cjs internal/gui/tests/signin-link.test.cjs internal/gui/tests/tray-inuse.test.cjs internal/gui/tests/codex-auto-reset.test.cjs internal/gui/tests/routing-auto-reset.test.cjs internal/gui/tests/claude-usage-asked.test.cjs internal/gui/tests/claude-risk.test.cjs internal/gui/tests/library-toggle-status.test.cjs internal/gui/tests/library-all.test.cjs internal/gui/tests/routing-reroute-title.test.cjs internal/gui/tests/plain-names.test.cjs internal/gui/tests/panel-effort.test.cjs internal/gui/tests/agent-models-all-hidden.test.cjs internal/gui/tests/omp-roles.test.cjs internal/gui/tests/claude-effort.test.cjs internal/gui/tests/remote-magpie.test.cjs internal/gui/tests/qoder-cn-tile.test.cjs internal/gui/tests/provider-levels-scroll.test.cjs internal/gui/tests/signin-paste-codex.test.cjs internal/gui/tests/signin-paste-key.test.cjs internal/gui/tests/usage-alert.test.cjs internal/gui/tests/quota-families.test.cjs internal/gui/tests/provider-search.test.cjs internal/gui/tests/webdav-settings-refresh.test.cjs internal/gui/tests/lan-docker.test.cjs internal/gui/tests/plugin-key-hint.test.cjs internal/gui/tests/update-hide.test.cjs internal/gui/tests/tray-logos.test.cjs internal/gui/tests/routing-proxy.test.cjs internal/gui/tests/sse-body.test.cjs internal/gui/tests/remote-group-served.test.cjs internal/gui/tests/plugin-move-overflow.test.cjs internal/gui/tests/routing-time.test.cjs internal/gui/tests/unlisted-models.test.cjs internal/gui/tests/plugin-updates.test.cjs internal/gui/tests/request-archive.test.cjs internal/gui/tests/group-member-fast.test.cjs internal/gui/tests/providers-off-fold.test.cjs internal/gui/tests/account-return.test.cjs internal/gui/tests/usage-ledger-detail.test.cjs internal/gui/tests/usage-ledger-chart.test.cjs internal/gui/tests/usage-chart-axis.test.cjs internal/gui/tests/panel-usage.test.cjs internal/gui/tests/usage-refresh.test.cjs internal/gui/tests/usage-ledger-content.test.cjs internal/gui/tests/claude-direct.test.cjs internal/gui/tests/signin-again.test.cjs internal/gui/tests/sessions-calendar-fill.test.cjs internal/gui/tests/editor-short-window.test.cjs internal/gui/tests/group-from-model-add.test.cjs internal/gui/tests/sync-other-kind.test.cjs internal/gui/tests/web-page.test.cjs internal/gui/tests/balance-parts.test.cjs internal/gui/tests/search-api.test.cjs internal/gui/tests/provider-file-error.test.cjs internal/gui/tests/sessions-manage.test.cjs internal/gui/tests/number-units.test.cjs internal/gui/tests/sessions-bar-names.test.cjs internal/gui/tests/model-suffix-own.test.cjs internal/gui/tests/routing-effort-change.test.cjs internal/gui/tests/every-skill.test.cjs internal/gui/tests/header-centre.test.cjs internal/gui/tests/public-url.test.cjs internal/gui/tests/strip-scrollbar.test.cjs
|
||||
```
|
||||
|
||||
If Playwright is installed outside the repository, set `NODE_PATH` to the
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// MAGPIE_PUBLIC_URL is the address other machines are told to reach the
|
||||
// gateway at: the connect page offers it beside this computer's loopback
|
||||
// address, and its hint tells the truth about the states — loopback, open to
|
||||
// the network (listening beyond loopback with nothing shared, which is the
|
||||
// Docker image's default), and a network address that needs a gateway key.
|
||||
// English and Chinese, Chromium and WebKit; no backend, the API is faked
|
||||
// here.
|
||||
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 network = "https://magpie.example.com";
|
||||
const cases = [
|
||||
{
|
||||
name: "loopback",
|
||||
gateway: { url: "http://127.0.0.1:3999", lan: false, open: false, lanURLs: [] },
|
||||
note: "loopback",
|
||||
},
|
||||
{
|
||||
name: "open",
|
||||
gateway: { url: "http://127.0.0.1:3999", lan: false, open: true, lanURLs: [] },
|
||||
note: "open",
|
||||
},
|
||||
{
|
||||
name: "network address",
|
||||
gateway: { url: "http://127.0.0.1:3999", lan: true, open: false, lanURLs: [network] },
|
||||
note: "loopback",
|
||||
picks: "remote",
|
||||
},
|
||||
];
|
||||
const words = {
|
||||
en: {
|
||||
loopback: "Loopback only · the key can be anything",
|
||||
open: "Open to the network · anyone who reaches it can use any key",
|
||||
remote: "Local network · an enabled gateway key is required",
|
||||
},
|
||||
zh: {
|
||||
loopback: "仅限本机回环 · 密钥可以随意填",
|
||||
open: "已开放到网络 · 任何能连上的人用任意密钥都能访问",
|
||||
remote: "局域网接入需要已启用的网关密钥",
|
||||
},
|
||||
};
|
||||
|
||||
function server(language, gateway) {
|
||||
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:"${language}",theme:"light",web:false};` });
|
||||
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: language, theme: "light" } });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], gateway });
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
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 });
|
||||
};
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": the gateway's network address and its connection hint", async (t) => {
|
||||
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
for (const language of ["en", "zh"]) {
|
||||
await t.test(language, async (t) => {
|
||||
const context = await browser.newContext({ viewport: { width: 1100, height: 1000 }, reducedMotion: "reduce" });
|
||||
t.after(() => context.close());
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const gateway = { running: true, mine: true, window: true, models: 0, calls: [], groups: [] };
|
||||
await page.route("**/*", server(language, gateway));
|
||||
const w = words[language];
|
||||
const note = page.locator("#connectNote");
|
||||
for (const c of cases) {
|
||||
await t.test(c.name, async () => {
|
||||
Object.assign(gateway, c.gateway);
|
||||
await page.goto("http://magpie.test/?view=gateway");
|
||||
await note.waitFor();
|
||||
assert.equal(await note.textContent(), w[c.note]);
|
||||
if (!c.picks) return;
|
||||
await page.locator("#connectAddress").click();
|
||||
await page.locator(".proto-menu .pm-item", { hasText: network }).click();
|
||||
assert.equal(await note.textContent(), w[c.picks]);
|
||||
const base = await page.locator("#connect .val").first().locator("code").textContent();
|
||||
assert(base.startsWith(network), base);
|
||||
});
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
+15
-5
@@ -5,7 +5,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"net"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
@@ -237,7 +236,7 @@ func models(args []string) error {
|
||||
if agentID != "" {
|
||||
explainHidden(agentID, hidden)
|
||||
}
|
||||
fmt.Println(faint.Render(" " + gateway.URL() + "/v1"))
|
||||
fmt.Println(faint.Render(" " + advertisedURL() + "/v1"))
|
||||
return bad
|
||||
}
|
||||
|
||||
@@ -797,7 +796,7 @@ func keyNote() string {
|
||||
if s := settings.Load(); s.LAN {
|
||||
return "(anything works from this machine; from others, an enabled gateway key — magpie gateway-key add <name>)"
|
||||
}
|
||||
if h, _, err := net.SplitHostPort(gateway.Addr()); err == nil && h != "localhost" && !net.ParseIP(h).IsLoopback() {
|
||||
if gateway.OpenToAnyone() {
|
||||
return "(anything works, from anyone who reaches it — share it from Settings to require a key)"
|
||||
}
|
||||
return "(anything works; the gateway only listens on localhost)"
|
||||
@@ -823,14 +822,25 @@ func shareLines() []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// advertisedURL is what the CLIs print for other machines: the public
|
||||
// address when MAGPIE_PUBLIC_URL is valid, otherwise the one reached from
|
||||
// this machine.
|
||||
func advertisedURL() string {
|
||||
if u := gateway.PublicURL(); u != "" {
|
||||
return u
|
||||
}
|
||||
return gateway.URL()
|
||||
}
|
||||
|
||||
// serve: `magpie serve` — the gateway alone, in the foreground.
|
||||
func serve() error {
|
||||
s := gateway.New()
|
||||
go stats.Run(version, "serve")
|
||||
go catalog.KeepFresh() // new models' prices, in a gateway left running
|
||||
public := advertisedURL()
|
||||
fmt.Println(green.Render("●"), "magpie gateway on", bold.Render(gateway.URL()))
|
||||
fmt.Println(muted.Render(" OpenAI "), gateway.URL()+"/v1/chat/completions", muted.Render("·"), gateway.URL()+"/v1/responses")
|
||||
fmt.Println(muted.Render(" Anthropic"), gateway.URL()+"/v1/messages")
|
||||
fmt.Println(muted.Render(" OpenAI "), public+"/v1/chat/completions", muted.Render("·"), public+"/v1/responses")
|
||||
fmt.Println(muted.Render(" Anthropic"), public+"/v1/messages")
|
||||
fmt.Println(muted.Render(" key "), gateway.Token, muted.Render(keyNote()))
|
||||
for _, l := range shareLines() {
|
||||
fmt.Println(l)
|
||||
|
||||
@@ -42,6 +42,27 @@ func TestKeyNote(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The CLIs print the address other machines are told to reach the gateway
|
||||
// at: a valid MAGPIE_PUBLIC_URL, otherwise the one reached from this
|
||||
// machine, so `magpie models` and the serve banner never print a bad one.
|
||||
func TestAdvertisedURL(t *testing.T) {
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("MAGPIE_ADDR", "127.0.0.1:3425")
|
||||
for _, c := range []struct{ public, want string }{
|
||||
{"", "http://127.0.0.1:3425"},
|
||||
{"https://magpie.example.com", "https://magpie.example.com"},
|
||||
{"nas.lan:3425/", "http://nas.lan:3425"},
|
||||
{"ftp://magpie.example.com", "http://127.0.0.1:3425"},
|
||||
{"https://magpie.example.com/magpie?x=1", "http://127.0.0.1:3425"},
|
||||
} {
|
||||
t.Setenv("MAGPIE_PUBLIC_URL", c.public)
|
||||
if got := advertisedURL(); got != c.want {
|
||||
t.Errorf("MAGPIE_PUBLIC_URL=%q: %q, want %q", c.public, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Shared, the serve banner (docker logs) says where other machines reach
|
||||
// the gateway: MAGPIE_PUBLIC_URL when a container sets it.
|
||||
func TestShareLines(t *testing.T) {
|
||||
|
||||
+1
-1
@@ -57,7 +57,7 @@ func webCmd(args []string) error {
|
||||
if os.Getenv("MAGPIE_WEB_KEY") != "" {
|
||||
carries = "MAGPIE_WEB_KEY"
|
||||
}
|
||||
fmt.Println(muted.Render(" the link carries " + carries + " · gateway " + gateway.URL() + " · Ctrl-C to stop"))
|
||||
fmt.Println(muted.Render(" the link carries " + carries + " · gateway " + advertisedURL() + " · Ctrl-C to stop"))
|
||||
if open {
|
||||
openInBrowser(w.Link)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user