lan: a LazyCat app offers the box's LAN address, or says how to forward the port

mtoolstec on X (after v0.1.3432) runs magpie from the magpie-lzcapp
package on a LazyCat box. Settings -> Share on local network offered
https://magpie.<box>.heiyu.space/v1, which only devices with LazyCat's
client reach, and http://172.28.3.65:3425/v1, the container bridge,
named "Other containers on this host", which nothing off the box
reaches. Other devices on his LAN wanted http://192.168.0.100:3425/v1.
The package runs magpie on the app's bridge network, and LazyCat
publishes an app's ports only on heiyu.space, not on the box's LAN
address. Its env names the app's domain, never the box's LAN IP.

- On the box's own network (network_mode: host, as LazyCat's Emby, Lucky
  and LAN Sheriff run), magpie now finds the box's LAN addresses. It sees
  the box's bridges/veths, or host.lzcapp is one of its own addresses, and
  takes the IPv4 of the default route's interface, minus host.lzcapp.
  LANURLs lists them first and the app domain after. A MAGPIE_PUBLIC_URL
  of the user's own (not the domain) stays first, and a pinned
  MAGPIE_ADDR still serves only that address. The sidebar names the box
  address, not the domain.
- On a bridge network that address can't be known. The domain is listed
  alone, named "LazyCat client", and the container-bridge address is no
  longer offered under LazyCat (ContainerHostURL ""). The row under the
  address, in Settings and on the Gateway page, says to forward the port
  with LazyCat's "LAN port forwarding" app (局域网端口转发工具). The CLI
  banner (serve, web) says the same.
- New settings/gateway fields: lanLazyCat, lanLazyCatBox; lazyCat,
  lazyCatBox (and boot.js's sideGateway). Strings are in zh, zh-TW, ja
  and de.
- host.lzcapp is looked up only under LAZYCAT_APP_DOMAIN, with a 2s
  timeout and no lock held. An answer is kept; a failure is retried after
  a minute.

Package side: the magpie-lzcapp package (lazycat-contrib, czyt) needs
network_mode: host plus host.lzcapp upstreams and the net.* permissions,
or its usage needs the port-forward steps. An issue is filed there.

Run (mote, macOS, at this tree on origin/main ce6ae593c; then rebased
onto ab084fdf2; api.go, providers.go and i18n.js changed there too and
merged clean):
- gofmt -l: clean. go vet: darwin for gateway/gui/cli; CGO_ENABLED=0
  GOOS=linux -tags nogui ./... and GOOS=windows ./...: ok.
- go test -timeout 45m ./...: ok (before the string reword; after it,
  internal/cli and internal/gateway again: ok).
- wsl-run (Ubuntu 24.04): the LazyCat/default-route/LAN tests in
  internal/gateway and internal/cli: ok.
- GUI: lan-lazycat (new: 2 engines x 5 languages x 1100/420px, 20 tests),
  i18n-keys, i18n-en-no-cjk, gui-de/ja/zh-tw, lan-docker and
  side-gateway-lan: 85 pass, 0 fail. A wider set (lan-*, gateway-*, connect-*,
  key-page, sidebar, phone-*, remote-magpie and others; 835 tests) was
  run before the reword. Its reds were the i18n placeholder check
  (fixed: no <box IP> in the string), and phone-connect-menu 420 (#4706,
  #4707) and remote-magpie (#4398). Those last two are red the same alone
  on origin/main b03a37476 on mote.
- Real Linux containers (Docker on xiaomi-gpu), with a test binary
  printing what the real functions find. LAZYCAT_APP_DOMAIN was set and
  host.lzcapp added as host-gateway.
  - bridge: ifaces [lo eth0], LANURLs [https://magpie.snyht3.heiyu.space],
    ContainerHostURL "".
  - --network host: ifaces [lo services1 eth0 docker0], defaultIfaces
    [eth0], LANURLs [http://192.168.65.3:3425 https://magpie...],
    ContainerHostURL "".
- Broken by hand: LANURLs without the box branch and ContainerHostURL
  without the LazyCat check turn TestLazyCatOffersTheBoxAddress red (6
  failures). The old settings.js turns lan-lazycat red (10 of 10,
  chromium).

Not tried: no LazyCat box is at hand. Not checked on a real box: lzcos's
interface names on the host network, where host.lzcapp points in host
mode, and which interface holds the default route.

At the rebased head: gofmt clean; go vet of internal/gui, gateway and
cli; their Budget/LazyCat/LAN/Container/PublicURL/Parity tests ok; GUI
lan-lazycat, i18n-keys, i18n-en-no-cjk, lan-docker, side-gateway-lan:
76 pass, 0 fail.
This commit is contained in:
yetone
2026-11-10 07:34:29 +08:00
parent ab084fdf25
commit 16a2dfac9c
12 changed files with 519 additions and 16 deletions
+8 -1
View File
@@ -1473,8 +1473,15 @@ func keyNote() string {
const containerNote = "these are the container's own addresses: other machines use the host's, and MAGPIE_PUBLIC_URL=http://<host>:<port> puts it here"
// containerLine is where other containers on this host reach the gateway
// while magpie runs in one, "" when that isn't known.
// while magpie runs in one, "" when that isn't known. In a LazyCat app on
// the box's bridge network it says how the box's LAN address gets the
// port, which LazyCat publishes only to its client's devices (mtoolstec
// on X).
func containerLine() string {
if gateway.LazyCatURL() != "" && !gateway.LazyCatBox() {
port := gateway.Port()
return muted.Render(" only devices with the LazyCat client reach " + gateway.LazyCatURL() + "; for the box's LAN IP on port " + port + ", forward port " + port + " to Magpie in LazyCat's LAN port forwarding app")
}
if u := gateway.ContainerHostURL(); u != "" {
return muted.Render(" other containers on this host ") + u
}
+29 -5
View File
@@ -223,8 +223,12 @@ var ifaceNames = func() []string {
// other containers on the NAS needed 172.17.0.1); host.docker.internal is
// not there on Linux unless a container is given it. "" when magpie is
// not in a container, is on the host's network, or has no default route.
//
// In a LazyCat app it is "" too: the bridge's gateway there is LazyCat's
// own, where no container port is published, and other LazyCat apps reach
// magpie at its domain.
func ContainerHostURL() string {
if !inThisContainer() || hostNetwork(ifaceNames()) {
if lazyCatURL() != "" || !inThisContainer() || hostNetwork(ifaceNames()) {
return ""
}
gw := defaultGateway(routeTable())
@@ -333,10 +337,27 @@ func overlayRoot(mountinfo string) bool {
// LANURLs are the addresses other machines on the network reach the
// gateway at: MAGPIE_PUBLIC_URL when set, else one per IPv4 address this
// computer has there.
// computer has there. In a LazyCat app on the box's network, the box's
// LAN addresses come first, before the app's domain, which only devices
// with LazyCat's client reach; a MAGPIE_PUBLIC_URL of the user's own
// (another domain, an address) stays first.
func LANURLs() []string {
if u := publicURL(); u != "" {
return []string{u}
lc := lazyCatURL()
if lc == "" || pinnedHost() != "" {
return []string{u}
}
var box []string
for _, h := range lazyCatBoxHosts() {
box = append(box, Scheme()+"://"+net.JoinHostPort(h, Port()))
}
if len(box) == 0 {
return []string{u}
}
if u == lc {
return append(box, lc)
}
return slices.Concat([]string{u}, box, []string{lc})
}
// a gateway MAGPIE_ADDR keeps on one host is reached there alone; on
// loopback, only through a proxy, whose address MAGPIE_PUBLIC_URL says
@@ -369,9 +390,12 @@ func LANURLs() []string {
// Settings offered http://198.18.0.1 instead of 192.168.110.x (coeo91 on
// Discord). It goes by the address, not the interface's name: Tailscale's
// is a utun too, and its address is reached.
func LANHosts() []string {
func LANHosts() []string { return lanHostsOf(hostIPs()) }
// lanHostsOf is LANHosts of the addresses ips.
func lanHostsOf(ips []net.IP) []string {
var home, near, far []string
for _, ip := range hostIPs() {
for _, ip := range ips {
if ip.To4() == nil || ip.IsLoopback() || ip.IsLinkLocalUnicast() || fakeIP(ip) {
continue
}
+3
View File
@@ -228,6 +228,9 @@ func TestInContainer(t *testing.T) {
// MAGPIE_PUBLIC_URL template a system didn't render is no address, and
// LazyCat's is used instead.
func TestLazyCatPublicURL(t *testing.T) {
// an app's container on the box's bridge (lazycat_test.go)
lazyCatNet(t, []string{"lo", "eth0"}, map[string][]string{"eth0": {"172.28.3.66"}}, bridgeRoutes, "172.28.3.65")
inThisContainer = func() bool { return inContainer("/") }
t.Setenv("MAGPIE_ADDR", "0.0.0.0:3425")
t.Setenv("MAGPIE_PUBLIC_URL", "")
t.Setenv("LAZYCAT_APP_DOMAIN", "")
+142
View File
@@ -0,0 +1,142 @@
package gateway
import (
"context"
"net"
"slices"
"strings"
"sync"
"time"
)
// A LazyCat (懒猫微服) app's container is on a bridge network of the box's
// own: its address (172.28.x.x) and the bridge's (the container's default
// route, 172.28.3.65) are reached from nothing outside the box. LazyCat
// serves the app at its domain (lazyCatURL), which only devices running
// LazyCat's client resolve, and publishes no container port on the box's
// LAN address. So "Share on local network" offered
// https://magpie.<box>.heiyu.space and http://172.28.3.65:3425, and neither
// was the http://192.168.0.100:3425 other devices on the home network use
// (mtoolstec on X, after v0.1.3432).
//
// A package whose service runs on the box's network (network_mode: host,
// as LazyCat's Emby, Lucky and LAN Sheriff do) has the box's interfaces,
// and the gateway listens on its LAN address itself: those addresses are
// offered first. On a bridge network they can't be known (LazyCat names
// the box's domain to a container, never its LAN address), and Settings
// says how the port gets there.
// LazyCatURL is a LazyCat app's own address, served to devices with
// LazyCat's client; "" outside LazyCat.
func LazyCatURL() string { return lazyCatURL() }
// LazyCatBox: magpie runs in a LazyCat app on the box's own network, so the
// addresses it finds are the box's, which other devices on its LAN reach.
func LazyCatBox() bool { return lazyCatURL() != "" && len(lazyCatBoxHosts()) > 0 }
// lazyCatBoxHosts are the box's LAN addresses while magpie runs on its
// network: the IPv4 addresses (as LANHosts takes them) of the interfaces
// the default route leaves by, which is the box's link to the router, not
// one of its container bridges or the virtual address other LazyCat apps
// reach it at (host.lzcapp). nil on a bridge network, where the default
// route is the container's own eth0.
func lazyCatBoxHosts() []string {
if !lazyCatHostNet() {
return nil
}
lzc := lzcHostIPs()
var ips []net.IP
for _, name := range defaultIfaces(routeTable()) {
for _, ip := range ifaceIPs(name) {
if !slices.ContainsFunc(lzc, ip.Equal) {
ips = append(ips, ip)
}
}
}
return lanHostsOf(ips)
}
// lazyCatHostNet: the network magpie is on is the box's: the box runs its
// apps in containers, so its own network has their bridges and veth pairs
// (hostNetwork), and host.lzcapp, which LazyCat gives apps for the box, is
// one of this network's own addresses (on a bridge network it is the
// bridge's, another machine's). A lookup that fails is asked again a
// minute on, as LazyCat's DNS may not answer while the app starts.
func lazyCatHostNet() bool {
if hostNetwork(ifaceNames()) {
return true
}
own := hostIPs()
return slices.ContainsFunc(lzcHostIPs(), func(ip net.IP) bool { return slices.ContainsFunc(own, ip.Equal) })
}
// lzcHostIPs are host.lzcapp's addresses; a variable for the tests.
var lzcHostIPs = func() []net.IP { return lzcLookup.get() }
// lzcLookup holds host.lzcapp's addresses: a found answer for the
// process's life (a box's network doesn't change under a running app), a
// failure for a minute.
var lzcLookup = &cachedLookup{name: "host.lzcapp", retry: time.Minute}
type cachedLookup struct {
name string
retry time.Duration
mu sync.Mutex
ips []net.IP
found bool
at time.Time
}
func (c *cachedLookup) get() []net.IP {
if lazyCatURL() == "" {
return nil
}
c.mu.Lock()
if c.found || !c.at.IsZero() && time.Since(c.at) < c.retry {
defer c.mu.Unlock()
return c.ips
}
c.mu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
addrs, err := net.DefaultResolver.LookupIPAddr(ctx, c.name)
var ips []net.IP
for _, a := range addrs {
ips = append(ips, a.IP)
}
c.mu.Lock()
defer c.mu.Unlock()
c.ips, c.found, c.at = ips, err == nil && len(ips) > 0, time.Now()
return c.ips
}
// defaultIfaces are the interfaces of /proc/net/route's default routes
// (defaultGateway's), in the table's order.
func defaultIfaces(table string) []string {
var out []string
for _, line := range strings.Split(table, "\n") {
f := strings.Fields(line)
if len(f) < 4 || f[1] != "00000000" || f[0] == "Iface" || slices.Contains(out, f[0]) {
continue
}
out = append(out, f[0])
}
return out
}
// ifaceIPs are the addresses on the interface named, when it is up; a
// variable for the tests.
var ifaceIPs = func(name string) []net.IP {
i, err := net.InterfaceByName(name)
if err != nil || i.Flags&net.FlagUp == 0 {
return nil
}
addrs, _ := i.Addrs()
var out []net.IP
for _, a := range addrs {
if n, ok := a.(*net.IPNet); ok {
out = append(out, n.IP)
}
}
return out
}
+161
View File
@@ -0,0 +1,161 @@
package gateway
import (
"net"
"slices"
"testing"
)
// lazyCatNet holds what a LazyCat box's network looks like to magpie for a
// test: the interfaces' names, their addresses, the route table and
// host.lzcapp's answer; nothing is looked up.
func lazyCatNet(t *testing.T, names []string, addrs map[string][]string, table string, lzc ...string) {
t.Helper()
t.Cleanup(func(ifn func() []string, ips func(string) []net.IP, rt func() string, lz func() []net.IP, hi func() []net.IP, in func() bool) func() {
return func() {
ifaceNames, ifaceIPs, routeTable, lzcHostIPs, hostIPs, inThisContainer = ifn, ips, rt, lz, hi, in
}
}(ifaceNames, ifaceIPs, routeTable, lzcHostIPs, hostIPs, inThisContainer))
parse := func(ss []string) []net.IP {
var out []net.IP
for _, s := range ss {
out = append(out, net.ParseIP(s))
}
return out
}
ifaceNames = func() []string { return names }
ifaceIPs = func(name string) []net.IP { return parse(addrs[name]) }
routeTable = func() string { return table }
lzcHostIPs = func() []net.IP { return parse(lzc) }
hostIPs = func() []net.IP {
var out []net.IP
for _, n := range names {
out = append(out, parse(addrs[n])...)
}
return out
}
inThisContainer = func() bool { return true }
}
const (
// the box: its LAN link enp2s0 holds the default route, beside the
// apps' bridges
boxRoutes = "Iface\tDestination\tGateway\tFlags\nenp2s0\t00000000\t0100A8C0\t0003\nenp2s0\t0000A8C0\t00000000\t0001\nlzc-br0\t00001CAC\t00000000\t0001\n"
// an app's container on the box's bridge: eth0 to 172.28.3.65
bridgeRoutes = "Iface\tDestination\tGateway\tFlags\neth0\t00000000\t41031CAC\t0003\neth0\t00001CAC\t00000000\t0001\n"
)
// mtoolstec on X: magpie in a LazyCat app offered the app's domain, which
// only devices with LazyCat's client reach, and the box's bridge
// (172.28.3.65), which nothing off the box reaches; other devices on the
// home network wanted http://192.168.0.100:3425/v1. On the box's network
// (network_mode: host) the box's LAN address is offered first, then the
// domain; a MAGPIE_PUBLIC_URL of the user's own stays first. On a bridge
// network the box's address can't be known: the domain alone, and no
// bridge address for other containers.
func TestLazyCatOffersTheBoxAddress(t *testing.T) {
t.Setenv("MAGPIE_ADDR", "0.0.0.0:3425")
t.Setenv("MAGPIE_PUBLIC_URL", "")
t.Setenv("LAZYCAT_APP_DOMAIN", "magpie.snyht3.heiyu.space")
const lc = "https://magpie.snyht3.heiyu.space"
box := Scheme() + "://192.168.0.100:3425"
// host network: the box's interfaces, docker-style bridges among them
lazyCatNet(t, []string{"lo", "enp2s0", "lzc-br0", "veth1a2b"}, map[string][]string{
"lo": {"127.0.0.1"}, "enp2s0": {"192.168.0.100", "fe80::1"}, "lzc-br0": {"172.28.0.1"},
}, boxRoutes, "172.28.0.1")
if got, want := LANURLs(), []string{box, lc}; !slices.Equal(got, want) {
t.Errorf("host network: %v, want %v", got, want)
}
if !LazyCatBox() {
t.Error("host network: not the box's")
}
if got := ContainerHostURL(); got != "" {
t.Errorf("host network: other containers offered %q", got)
}
// the box's network found by host.lzcapp alone, with no bridge named
// as Docker's
lazyCatNet(t, []string{"lo", "enp2s0", "lzc0"}, map[string][]string{
"enp2s0": {"192.168.0.100"}, "lzc0": {"198.18.0.1"},
}, boxRoutes, "198.18.0.1")
if got, want := LANURLs(), []string{box, lc}; !slices.Equal(got, want) {
t.Errorf("host.lzcapp on this network: %v, want %v", got, want)
}
// host.lzcapp on the default route's interface is not the LAN's
lazyCatNet(t, []string{"lo", "enp2s0", "veth0"}, map[string][]string{
"enp2s0": {"192.168.0.100", "172.28.0.1"},
}, boxRoutes, "172.28.0.1")
if got, want := LANURLs(), []string{box, lc}; !slices.Equal(got, want) {
t.Errorf("host.lzcapp on the LAN link: %v, want %v", got, want)
}
// the user's own address first
t.Setenv("MAGPIE_PUBLIC_URL", "https://ai.example.com")
if got, want := LANURLs(), []string{"https://ai.example.com", box, lc}; !slices.Equal(got, want) {
t.Errorf("MAGPIE_PUBLIC_URL: %v, want %v", got, want)
}
// the package's MAGPIE_PUBLIC_URL, the domain, is said once
t.Setenv("MAGPIE_PUBLIC_URL", lc+"/")
if got, want := LANURLs(), []string{box, lc}; !slices.Equal(got, want) {
t.Errorf("MAGPIE_PUBLIC_URL the domain: %v, want %v", got, want)
}
t.Setenv("MAGPIE_PUBLIC_URL", "")
// MAGPIE_ADDR pinned to one address: that one alone is served
t.Setenv("MAGPIE_ADDR", "192.168.0.100:3425")
if got, want := LANURLs(), []string{lc}; !slices.Equal(got, want) {
t.Errorf("pinned: %v, want %v", got, want)
}
t.Setenv("MAGPIE_ADDR", "0.0.0.0:3425")
// bridge network: the container's eth0 alone, host.lzcapp the bridge's
lazyCatNet(t, []string{"lo", "eth0"}, map[string][]string{
"eth0": {"172.28.3.66"},
}, bridgeRoutes, "172.28.3.65")
if got, want := LANURLs(), []string{lc}; !slices.Equal(got, want) {
t.Errorf("bridge network: %v, want %v", got, want)
}
if LazyCatBox() {
t.Error("bridge network: said to be the box's")
}
if got := ContainerHostURL(); got != "" {
t.Errorf("bridge network: other containers offered %q", got)
}
if LazyCatURL() != lc {
t.Errorf("LazyCatURL: %q", LazyCatURL())
}
// outside LazyCat nothing changes: a NAS's host network offers its own
t.Setenv("LAZYCAT_APP_DOMAIN", "")
lazyCatNet(t, []string{"lo", "enp2s0", "docker0"}, map[string][]string{
"enp2s0": {"192.168.0.100"},
}, boxRoutes)
if LazyCatBox() || LazyCatURL() != "" {
t.Error("outside LazyCat: said to be one")
}
}
func TestDefaultIfaces(t *testing.T) {
for _, c := range []struct {
table string
want []string
}{
{boxRoutes, []string{"enp2s0"}},
{bridgeRoutes, []string{"eth0"}},
{"Iface\tDestination\tGateway\tFlags\nwlan0\t00000000\t0101A8C0\t0003\neth0\t00000000\t0100A8C0\t0003\nwlan0\t00000000\t0101A8C0\t0003\n", []string{"wlan0", "eth0"}},
{"Iface\tDestination\tGateway\tFlags\neth0\t0000A8C0\t00000000\t0001\n", nil},
{"", nil},
} {
if got := defaultIfaces(c.table); !slices.Equal(got, c.want) {
t.Errorf("%q: %v, want %v", c.table, got, c.want)
}
}
}
// A lookup's answer is kept; a failure is asked again only after retry;
// outside LazyCat nothing is asked.
func TestCachedLookupOutsideLazyCat(t *testing.T) {
t.Setenv("LAZYCAT_APP_DOMAIN", "")
c := &cachedLookup{name: "host.lzcapp.invalid", retry: 0}
if got := c.get(); got != nil || !c.at.IsZero() {
t.Errorf("outside LazyCat: %v, asked at %v", got, c.at)
}
}
+9
View File
@@ -538,6 +538,11 @@ type settingsJSON struct {
// where other containers on this host reach the gateway while magpie
// runs in one (gateway.ContainerHostURL)
LANContainerHost string `json:"lanContainerHost,omitempty"`
// a LazyCat app's domain, which only devices with LazyCat's client
// reach (gateway.LazyCatURL), and whether the box's LAN addresses are
// listed too: when not, the page says how the port gets there
LANLazyCat string `json:"lanLazyCat,omitempty"`
LANLazyCatBox bool `json:"lanLazyCatBox,omitempty"`
// those of LANURLs at an internet address, which anyone online can
// reach, not only this network
LANPublic []string `json:"lanPublic,omitempty"`
@@ -846,6 +851,7 @@ func settingsState() settingsJSON {
if s.LAN {
s.LANURLs, s.LANContainer = gateway.LANURLs(), gateway.ContainerAddrs()
s.LANContainerHost = gateway.ContainerHostURL()
s.LANLazyCat, s.LANLazyCatBox = gateway.LazyCatURL(), gateway.LazyCatBox()
s.LANPublic = gateway.PublicURLs(s.LANURLs)
}
s.CodexWarmed, s.ClaudeWarmed = latest(provider.CodexWarmed()), latest(provider.ClaudeWarmed())
@@ -1131,6 +1137,9 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
if u := gateway.ContainerHostURL(); u != "" {
side["containerHost"] = u
}
if u := gateway.LazyCatURL(); u != "" {
side["lazyCat"], side["lazyCatBox"] = u, gateway.LazyCatBox()
}
if u := gateway.PublicURL(); u != "" {
side["publicURL"] = u
}
+12
View File
@@ -1235,6 +1235,9 @@ const I18N = {
"Other devices use the host’s address this page was opened at, and other containers on this host the host’s Docker bridge address, both on the gateway’s port; MAGPIE_PUBLIC_URL sets another": "其他设备用打开这个页面所用的宿主机地址,本机上的其他容器用宿主机的 Docker bridge 地址,端口都是网关的端口;MAGPIE_PUBLIC_URL 可另设",
"Other containers on this host use the host’s Docker bridge address, on the gateway’s port; other devices use the host’s own, which MAGPIE_PUBLIC_URL puts here": "本机上的其他容器用宿主机的 Docker bridge 地址,端口是网关的端口;其他设备用宿主机自己的地址,用 MAGPIE_PUBLIC_URL 把它设在这里",
"Other containers on this host": "同一主机上的其他容器",
"LazyCat client": "懒猫客户端",
"LazyCat": "懒猫微服",
"Only devices with the LazyCat client reach this address. For other devices to use the box’s LAN IP on port {port}, forward port {port} to Magpie in LazyCat’s LAN port forwarding app": "只有装了懒猫客户端的设备能访问这个地址。要让其他设备用微服的局域网 IP 加 {port} 端口访问,请在懒猫的「局域网端口转发工具」里把 {port} 端口转发到 Magpie",
"New key": "换新 Key",
"API keys, private keys, tokens and passwords go to vendors as placeholders, and come back as they were": "API Key、私钥、Token 和密码以占位符发给模型厂商,回复里再还原",
"Mask personal data": "脱敏个人信息",
@@ -6042,6 +6045,9 @@ const I18N = {
"Other devices use the host’s address this page was opened at, and other containers on this host the host’s Docker bridge address, both on the gateway’s port; MAGPIE_PUBLIC_URL sets another": "其他裝置使用開啟此頁面所用的主機位址,本機上的其他容器使用主機的 Docker bridge 位址,連接埠都是閘道的連接埠;MAGPIE_PUBLIC_URL 可另設",
"Other containers on this host use the host’s Docker bridge address, on the gateway’s port; other devices use the host’s own, which MAGPIE_PUBLIC_URL puts here": "本機上的其他容器使用主機的 Docker bridge 位址,連接埠是閘道的連接埠;其他裝置使用主機自己的位址,用 MAGPIE_PUBLIC_URL 把它設在這裡",
"Other containers on this host": "同一主機上的其他容器",
"LazyCat client": "懶貓用戶端",
"LazyCat": "懶貓微服",
"Only devices with the LazyCat client reach this address. For other devices to use the box’s LAN IP on port {port}, forward port {port} to Magpie in LazyCat’s LAN port forwarding app": "只有安裝了懶貓用戶端的裝置能存取這個位址。要讓其他裝置用微服的區域網 IP 加 {port} 連接埠存取,請在懶貓的「局域網端口轉發工具」裡把 {port} 連接埠轉發到 Magpie",
"New key": "換新 Key",
"API keys, private keys, tokens and passwords go to vendors as placeholders, and come back as they were": "API Key、私鑰、Token 和密碼以佔位符發給模型廠商,回覆裡再還原",
"Mask personal data": "脫敏個人資訊",
@@ -10820,6 +10826,9 @@ const I18N = {
"Other devices use the host’s address this page was opened at, and other containers on this host the host’s Docker bridge address, both on the gateway’s port; MAGPIE_PUBLIC_URL sets another": "ほかのデバイスはこのページを開いたホストのアドレスを、このホストのほかのコンテナはホストの Docker bridge アドレスを使います。どちらもゲートウェイのポートです。MAGPIE_PUBLIC_URL で別のものを設定できます",
"Other containers on this host use the host’s Docker bridge address, on the gateway’s port; other devices use the host’s own, which MAGPIE_PUBLIC_URL puts here": "このホストのほかのコンテナはホストの Docker bridge アドレスをゲートウェイのポートで使います。ほかのデバイスはホスト自身のアドレスを使います。MAGPIE_PUBLIC_URL でそれをここに表示できます",
"Other containers on this host": "同じホストのほかのコンテナ",
"LazyCat client": "LazyCat クライアント",
"LazyCat": "LazyCat",
"Only devices with the LazyCat client reach this address. For other devices to use the box’s LAN IP on port {port}, forward port {port} to Magpie in LazyCat’s LAN port forwarding app": "このアドレスには LazyCat クライアントのあるデバイスだけが届きます。ほかのデバイスでボックスの LAN IP のポート {port} を使うには、LazyCat の「LAN ポート転送」アプリでポート {port} を Magpie に転送してください",
"New key": "新しいキー",
"API keys, private keys, tokens and passwords go to vendors as placeholders, and come back as they were": "APIキー、秘密鍵、トークン、パスワードはプレースホルダーとしてベンダーに送られ、元どおりに戻されます",
"Mask personal data": "個人情報をマスク",
@@ -15613,6 +15622,9 @@ const I18N = {
"Other devices use the host’s address this page was opened at, and other containers on this host the host’s Docker bridge address, both on the gateway’s port; MAGPIE_PUBLIC_URL sets another": "Andere Geräte nutzen die Adresse des Hosts, unter der diese Seite geöffnet wurde, andere Container auf diesem Host die Docker-Bridge-Adresse des Hosts, beide auf dem Port des Gateways; MAGPIE_PUBLIC_URL legt eine andere fest",
"Other containers on this host use the host’s Docker bridge address, on the gateway’s port; other devices use the host’s own, which MAGPIE_PUBLIC_URL puts here": "Andere Container auf diesem Host nutzen die Docker-Bridge-Adresse des Hosts auf dem Port des Gateways; andere Geräte nutzen die eigene Adresse des Hosts, die MAGPIE_PUBLIC_URL hier einträgt",
"Other containers on this host": "Andere Container auf diesem Host",
"LazyCat client": "LazyCat-Client",
"LazyCat": "LazyCat",
"Only devices with the LazyCat client reach this address. For other devices to use the box’s LAN IP on port {port}, forward port {port} to Magpie in LazyCat’s LAN port forwarding app": "Nur Geräte mit dem LazyCat-Client erreichen diese Adresse. Damit andere Geräte die LAN-IP der Box auf Port {port} nutzen, leite Port {port} in LazyCats App „LAN-Portweiterleitung“ an Magpie weiter",
"New key": "Neuer Schlüssel",
"API keys, private keys, tokens and passwords go to vendors as placeholders, and come back as they were": "API-Schlüssel, private Schlüssel, Token und Passwörter gehen als Platzhalter an Anbieter und kommen unverändert zurück",
"Mask personal data": "Personenbezogene Daten maskieren",
@@ -325,7 +325,7 @@ function renderGatewayLan() {
// (the host's Docker bridge address), then one on the internet (an
// ISP's static one); a name said once for the lines it heads
const said = [addrWho(g, shown, others)], rest = urls.filter((u) => u !== shown);
const order = [t("Local network"), t("Public address"), t("Other containers on this host"), t("On the internet")];
const order = [t("Local network"), t("Public address"), t("LazyCat client"), t("Other containers on this host"), t("On the internet")];
rest.map((u) => [addrWho(g, u, others), u]).sort((a, b) => order.indexOf(a[0]) - order.indexOf(b[0]))
.forEach(([who, u]) => { line(said.at(-1) === who ? "" : who, u); said.push(who); });
if (!urls.length) list.append(el("div", "gw-url-none", t("This computer has no local network address right now")));
@@ -294,7 +294,19 @@ try { lanWant = localStorage.getItem("magpie.lanAddress") || ""; } catch {}
// on the host reach it at the host's Docker bridge address, the
// container's default route (jiezhengj on Discord: other containers on a
// NAS needed http://172.17.0.1:3425), which follows, said to be theirs.
function lanShown(urls, container, bridge) {
//
// In a LazyCat app (lazy: its domain, and whether the box's LAN addresses
// are listed), the domain serves only devices with LazyCat's client, and
// on a bridge network the box's LAN address isn't known, nor is the port
// there: the line says how to get it there (mtoolstec on X wanted
// http://192.168.0.100:3425/v1 and was offered the domain and the
// container bridge's 172.28.3.65).
function lanShown(urls, container, bridge, lazy = {}) {
if (lazy.url && !lazy.box) {
const port = lazyPort();
return { urls, others: [], head: t("LazyCat"),
sub: t("Only devices with the LazyCat client reach this address. For other devices to use the box’s LAN IP on port {port}, forward port {port} to Magpie in LazyCat’s LAN port forwarding app", { port }) };
}
const others = bridge ? [bridge] : [];
if (!container) return { urls: [...urls, ...others.filter((u) => !urls.includes(u))], others, sub: "" };
const host = location.hostname, at = urls[0] || bridge ? new URL(urls[0] || bridge) : null;
@@ -310,7 +322,14 @@ function lanShown(urls, container, bridge) {
// which says whether its addresses are a container's and where other
// containers reach it
function gwLAN(g) {
return lanShown(g?.lan && g.lanURLs || [], !!g?.container, g?.lan && g.containerHost || "");
return lanShown(g?.lan && g.lanURLs || [], !!g?.container, g?.lan && g.containerHost || "",
{ url: g?.lazyCat || "", box: !!g?.lazyCatBox });
}
// lazyPort: the gateway's port, for the LazyCat line: its listen address'
// (bootPrefs or Settings' gateway), 3425 when it names none
function lazyPort() {
const at = prefs?.gateway || sideGwAt?.url || "";
return /:(\d+)\/?$/.exec(at)?.[1] || "3425";
}
// addrWho: the words every list of the gateway's addresses names one by,
// for g (providers' gateway, or Settings' read as one): this computer's,
@@ -322,6 +341,7 @@ function gwLAN(g) {
function addrWho(g, u, others = []) {
if (u === g.url) return t("This computer");
if (others.includes(u)) return t("Other containers on this host");
if (u && u === g.lazyCat) return t("LazyCat client");
if ((g.lanPublic || []).includes(u) || u === g.publicURL && g.publicKind === "internet") return t("On the internet");
if (u === g.publicURL && g.publicKind !== "local") return t("Public address");
return t("Local network");
@@ -329,7 +349,7 @@ function addrWho(g, u, others = []) {
// pubWho: About's MAGPIE_PUBLIC_URL row, from /api/settings, by addrWho
// (a private address is the local network's; jiezhengj on Discord)
function pubWho(s) {
return addrWho({ url: s.gateway, publicURL: s.publicURL, publicKind: s.publicKind, lanPublic: s.lanPublic }, s.publicURL,
return addrWho({ url: s.gateway, publicURL: s.publicURL, publicKind: s.publicKind, lanPublic: s.lanPublic, lazyCat: s.lanLazyCat }, s.publicURL,
s.lanContainerHost ? [s.lanContainerHost] : []);
}
// gwFar: where other machines reach the gateway, for the sidebar and the
@@ -343,7 +363,10 @@ function gwFar(g) {
// address picked here, else the first
function sideLAN(g) {
const u = gwFar(g);
return u[0] && (g.publicURL || (u.includes(lanWant) ? lanWant : u[0]));
// a LazyCat app's domain is MAGPIE_PUBLIC_URL's too, and the box's LAN
// address before it is the one other devices use
const pub = g.publicURL && !(g.lazyCatBox && g.publicURL === g.lazyCat) ? g.publicURL : "";
return u[0] && (pub || (u.includes(lanWant) ? lanWant : u[0]));
}
// the line was drawn from boot.js before this script came
if (sideGwAt) renderSideGw();
@@ -372,7 +395,8 @@ function renderLAN(s) {
row(t("Share on local network"), t("Agents on other computers on this network, or through a tunnel to this one such as Cloudflare Tunnel, can use magpie’s models with a gateway key from Gateway"), "",
segs([["off", t("Off")], ["on", t("On")]], s.lan ? "on" : "off", (v) => set({ on: v === "on" })));
if (!s.lan) return;
const { urls, others, sub } = lanShown(s.lanURLs || [], s.lanContainer, s.lanContainerHost);
const { urls, others, sub, head } = lanShown(s.lanURLs || [], s.lanContainer, s.lanContainerHost,
{ url: s.lanLazyCat || "", box: !!s.lanLazyCatBox });
if (!urls.length) row(t("Address"), t("This computer has no local network address right now"), "");
else {
lanSelectedURL = urls.includes(lanWant) ? lanWant : urls[0];
@@ -389,7 +413,7 @@ function renderLAN(s) {
e.stopPropagation();
if (address.classList.contains("open")) return closeProtoMenu();
const suffix = lanProtocol === "openai" ? "/v1" : "";
openProtoMenu(address, urls.map((u) => ({ v: u, name: u + suffix, note: far.has(u) ? t("On the internet") : others.includes(u) ? t("Other containers on this host") : "" })), lanSelectedURL,
openProtoMenu(address, urls.map((u) => ({ v: u, name: u + suffix, note: far.has(u) ? t("On the internet") : others.includes(u) ? t("Other containers on this host") : u === s.lanLazyCat ? t("LazyCat client") : "" })), lanSelectedURL,
(v) => { lanSelectedURL = lanWant = v; keepPick("magpie.lanAddress", v); update(); renderSideGw(); }, "Address", "lan-address-menu");
};
}
@@ -417,7 +441,7 @@ function renderLAN(s) {
addressRow.classList.add("lan-address-row");
update();
}
if (sub) row(t("In a container"), sub, "").classList.add("lan-container");
if (sub) row(head || t("In a container"), sub, "").classList.add("lan-container");
}
// renderWebPage: Browser access, the app's own page served to a browser
+5
View File
@@ -605,6 +605,10 @@ type gatewayJSON struct {
// ContainerHost: where other containers on this host reach the
// gateway while magpie runs in one (gateway.ContainerHostURL)
ContainerHost string `json:"containerHost,omitempty"`
// LazyCat: a LazyCat app's domain, which only devices with LazyCat's
// client reach; LazyCatBox: the box's LAN addresses are listed too
LazyCat string `json:"lazyCat,omitempty"`
LazyCatBox bool `json:"lazyCatBox,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
@@ -1313,6 +1317,7 @@ func providersState() providersJSON {
s.Gateway.LANURLs = gateway.LANURLs()
s.Gateway.LANPublic = gateway.PublicURLs(s.Gateway.LANURLs)
s.Gateway.Container, s.Gateway.ContainerHost = gateway.ContainerAddrs(), gateway.ContainerHostURL()
s.Gateway.LazyCat, s.Gateway.LazyCatBox = gateway.LazyCatURL(), gateway.LazyCatBox()
if u := gateway.PublicURL(); slices.Contains(s.Gateway.LANURLs, u) {
s.Gateway.PublicURL, s.Gateway.PublicKind = u, gateway.URLKind(u)
}
+6 -2
View File
@@ -35,11 +35,15 @@ function fixture(lang, theme, events, options = {}) {
// options.container: magpie runs in a container, and lanURLs are its
// own; options.containerHost is where other containers on the host
// reach the gateway (the host's Docker bridge address)
// options.lazyCat: a LazyCat app's domain, and options.lazyCatBox that
// magpie is on the box's network, so lanURLs are the box's
const container = () => ({ ...(lan && options.container ? { container: true } : {}),
...(lan && options.containerHost ? { containerHost: options.containerHost } : {}) });
...(lan && options.containerHost ? { containerHost: options.containerHost } : {}),
...(options.lazyCat ? { lazyCat: options.lazyCat, ...(options.lazyCatBox ? { lazyCatBox: true } : {}) } : {}) });
const lanState = () => ({ lang, theme, lan,
lanURLs: lan ? lanURLs : [], ...lanPublic(), ...(container().container ? { lanContainer: true } : {}),
...(container().containerHost ? { lanContainerHost: container().containerHost } : {}), fx: { rate: 7.2, at: new Date().toISOString() },
...(container().containerHost ? { lanContainerHost: container().containerHost } : {}),
...(lan && options.lazyCat ? { lanLazyCat: options.lazyCat, ...(options.lazyCatBox ? { lanLazyCatBox: true } : {}) } : {}), 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 },
+112
View File
@@ -0,0 +1,112 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// mtoolstec on X ran magpie as a LazyCat (懒猫微服) app. Share on local
// network offered the app's domain, which only devices with LazyCat's
// client reach, and the box's container bridge (172.28.3.65), which
// nothing off the box reaches, named other containers'; other devices on
// the home network wanted http://192.168.0.100:3425/v1.
// - On the box's network (the package's network_mode: host) magpie finds
// the box's LAN address: it comes first, then the domain, named LazyCat
// client's, in Settings' menu, on the Gateway page and in the sidebar.
// - On a bridge network that address can't be known: the domain alone,
// named the same, and a line says how the port gets to the box's LAN
// address (LazyCat's LAN port forwarding app), in Settings and on the
// Gateway page. No bridge address is offered.
// No backend, the API is faked here.
const assert = require("node:assert/strict");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const { fixture } = require("./fixtures/caller-keys.cjs");
const { openPart, reach } = require("./reader.cjs");
const LC = "https://magpie.snyht3.heiyu.space", BOX = "http://192.168.0.100:3999", HERE = "http://127.0.0.1:3999";
const words = {
en: { client: "LazyCat client", head: "LazyCat", lan: "Local network", here: "This computer",
sub: "Only devices with the LazyCat client reach this address. For other devices to use the box’s LAN IP on port 3999, forward port 3999 to Magpie in LazyCat’s LAN port forwarding app" },
zh: { client: "懒猫客户端", head: "懒猫微服", lan: "局域网", here: "本机",
sub: "只有装了懒猫客户端的设备能访问这个地址。要让其他设备用微服的局域网 IP 加 3999 端口访问,请在懒猫的「局域网端口转发工具」里把 3999 端口转发到 Magpie" },
"zh-TW": { client: "懶貓用戶端", head: "懶貓微服", lan: "區域網", here: "本機", sub: /區域網 IP 加 3999 連接埠.*「局域網端口轉發工具」/ },
ja: { client: "LazyCat クライアント", head: "LazyCat", lan: "ローカルネットワーク", here: "このコンピュータ", sub: /LAN IP のポート 3999.*ポート 3999/ },
de: { client: "LazyCat-Client", head: "LazyCat", lan: "Lokales Netzwerk", here: "Dieser Computer", sub: /LAN-IP der Box auf Port 3999.*Port 3999/ },
};
const same = (got, want) => want instanceof RegExp ? assert.match(got, want) : assert.equal(got, want);
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
for (const width of [1100, 420]) {
test(`${engine} ${lang} ${width}: a LazyCat app offers the box's LAN address, or says how to get it`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const w = words[lang];
const open = async (view, box) => {
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(6000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", fixture(lang, "light", [], { lan: true, bootGateway: true, publicURL: LC, lazyCat: LC,
lazyCatBox: box, lanURLs: box ? [BOX, LC] : [LC] }));
await page.goto("http://magpie.test/?view=" + view);
return { page, errors };
};
const fits = async (page) => assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "wider than the window");
const list = async (page) => {
await page.locator("#gatewayLan .gw-url").first().waitFor();
const rows = page.locator("#gatewayLan .gw-url");
const out = [];
for (let i = 0; i < await rows.count(); i++)
out.push([(await rows.nth(i).locator(".gw-url-label").textContent()).trim(), (await rows.nth(i).locator("code").textContent()).trim()]);
return out;
};
const side = (page) => page.locator("#sideGw span").textContent();
// on the box's network: the box's address first, then the domain
{
const { page, errors } = await open("settings", true);
await page.locator("#sideGw").waitFor({ state: "attached" }); // folded away at 420px, and still drawn
assert.match(await side(page), /192\.168\.0\.100:3999/);
await openPart(page, "network");
await page.locator("#lanList .lan-address-row").waitFor();
assert.equal(await page.locator("#lanList .lan-container").count(), 0);
await reach(page, page.locator("#lanList .lan-interface"));
await page.locator("#lanList .lan-interface").click();
const items = page.locator(".proto-menu .pm-item");
await items.first().waitFor();
assert.deepEqual((await items.locator(".pm-name").allTextContents()).map((x) => x.trim()), [BOX + "/v1", LC + "/v1"]);
assert.deepEqual((await items.locator(".pm-note").allTextContents()).map((x) => x.trim()), ["", w.client]);
await fits(page);
assert.deepEqual(errors, []);
}
{
const { page, errors } = await open("gateway", true);
assert.deepEqual(await list(page), [[w.here, HERE], [w.lan, BOX], [w.client, LC]]);
assert.equal(await page.locator("#gatewayLan .gw-url-none").count(), 0);
await fits(page);
assert.deepEqual(errors, []);
}
// on a bridge network: the domain, and how to reach the box
{
const { page, errors } = await open("settings", false);
await openPart(page, "network");
await page.locator("#lanList .lan-address-row").waitFor();
assert.equal((await page.locator("#lanList .lan-address-text").textContent()).trim(), LC + "/v1");
const note = page.locator("#lanList .lan-container");
assert.equal((await note.locator(".name").textContent()).trim(), w.head);
same((await note.locator(".sub").textContent()).trim(), w.sub);
assert.doesNotMatch(await page.locator("#lanList").textContent(), /172\.28/);
const border = await note.evaluate((r) => getComputedStyle(r).borderLeftWidth);
assert(border === "0px" || border === "", "no left border accent: " + border);
await fits(page);
assert.deepEqual(errors, []);
}
{
const { page, errors } = await open("gateway", false);
assert.deepEqual(await list(page), [[w.here, HERE], [w.client, LC]]);
same((await page.locator("#gatewayLan .gw-url-none").textContent()).trim(), w.sub);
assert.match(await side(page), /magpie\.snyht3\.heiyu\.space/);
await fits(page);
assert.deepEqual(errors, []);
}
});
}
}
}