Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

tui: quitting hands the gateway to magpie's service on Linux

yetone75e78a5a040d
diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md
index 91c7405a3..9fab1f9b9 100644
--- a/docs/subsystems/gui-shell.md
+++ b/docs/subsystems/gui-shell.md
@@ -20,6 +20,7 @@ three.
| Settings › Privacy | The page opens on what masking kept from vendors (`drawMaskObs` in app.js, fed by `/api/masking/summary`): the values masked over 7 or 30 days with a chart of the days, the kinds, what only the local model found, agents to providers, and the values masked most, each shown only while pointed at (`maskTip`, `/api/masking/value`, which says it is gone after a restart). Its records (`drawMaskRecs`, `/api/masking/records` and `/api/masking/record`) take the page's place, filtered by kind, finder, agent or provider, a day at a time, each opening on the text the vendor saw with its placeholders marked. `maskedBadge`, on the Gateway page's recent calls and the Routing page's log, opens a request's own record (`openMaskRecord`), in amber with the count sent as written when every value found was on Warn. Below the card, *What to mask*, *How it's found* (the rules, always on while anything is masked, and the local model on top of them), *When a value is found* (Mask, Warn or Block per kind, the secret kinds first and the personal ones behind *Show all kinds*, and the *Never mask* list; `renderMaskActions`), *Try it* (`renderMaskTry`, the text as the vendor would get it from `/api/masking/preview`, kept in no storage) and *Sharing*. See [gateway routing](gateway-routing.md) for what is recorded. | [`assets/app.js`](../../internal/gui/assets/app.js), [`masking.go`](../../internal/gui/masking.go) |
| Built-in plugins | Plugins › Built-in, the page's first tab (`drawBuiltin` in `plugins.js`, rows by `renderBuiltins` in `app.js`), lists magpie's built-in plugins, each with a name, a line on what it is and a switch: Routing groups, Library, Observability, Sessions, Warm-up and check-in, and the Gateway and Routing pages (Essential). A plugin on with settings has their rows under its row, drawn from its schema by the kernel's `ui.form`, and a change posts `{id, config}`. The Gateway page is drawn by its plugin's own scripts through the window's kernel (`kernel.js`, `assets/plugins/gateway/`); see the [plugin runtime](plugin-runtime.md), "The window's kernel". They are `plugins/*` registered with the [plugin runtime](plugin-runtime.md); `GET /api/plugins/builtin` says each one (`builtinJSON`: on is active, the user's own choice, what of it is in use) and `POST {id, on}` (or `{id, config}`) writes plugins.yml. A page marks what goes with a plugin `data-feature="<id>"`. Off, `featureStyle` hides everything so marked (rows drawn later too), `navHides` leaves its page's tab out of the sidebar and the header, `show` opens Agents for an address kept for it, and `setSetTab`, `partShows` and `findSettings` leave its Settings tab and rows out, of the search too. One in use stays on: its switch is disabled and the row says what uses it, and the POST refuses it off. A plugins.yml that doesn't parse is said above the list and no switch moves. `boot.js` says which are off (`featuresOff`) and their settings (`pluginConfig`) before the first paint, and `settings.builtins` carries the list on every state read. The TUI doesn't follow them. See `builtins.test.cjs`, `builtins_test.go`. | [`builtins.go`](../../internal/gui/builtins.go), [`assets/plugins.js`](../../internal/gui/assets/plugins.js), [`assets/app.js`](../../internal/gui/assets/app.js) |
| No GUI build | `-tags nogui` builds magpie without the GUI: `hasGUI` is false and `runGUI` says to use `magpie tui`. The files of `internal/gui` that need Wails build under `!nogui`. | [`gui_off.go`](../../internal/cli/gui_off.go) |
+| The terminal quitting | `magpie tui` that served the gateway with an agent connected hands the gateway on as it quits, on Linux where nothing opens magpie at login (a WSL distro, a server over SSH; zaidu259434 on X): `keepGateway` starts magpie's service when it is installed, installs it (`daemon.Install`) when the user never removed it (`daemon.Removed`, a mark `magpie daemon uninstall` leaves), and otherwise starts `magpie serve` in its own session (`serveInBackground`, log in magpie's cache). Elsewhere, with nothing connected, or where magpie opens at login, it only says the gateway stopped. | [`keep.go`](../../internal/tui/keep.go) |
## Runtime path
diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go
index fd1613e00..db87e3bd8 100644
--- a/internal/daemon/daemon.go
+++ b/internal/daemon/daemon.go
@@ -19,6 +19,7 @@ import (
"strings"
"github.com/yetone/magpie/internal/agentenv"
+ "github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/autostart"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/proc"
@@ -103,7 +104,22 @@ func Install(o Options) error {
return err
}
widenPath()
- return m.install(exe, serveArgs(o), withKey(environ(), o))
+ if err := m.install(exe, serveArgs(o), withKey(environ(), o)); err != nil {
+ return err
+ }
+ os.Remove(removedMark())
+ return nil
+}
+
+// removedMark is there once the user removed the service (Uninstall): what
+// magpie puts in place by itself (the terminal's keepGateway, as it quits) is put there
+// no more.
+func removedMark() string { return filepath.Join(appdir.Config(), "daemon-removed") }
+
+// Removed says the user removed the service, and hasn't installed it since.
+func Removed() bool {
+ _, err := os.Stat(removedMark())
+ return err == nil
}
// serveArgs is what the service runs magpie with.
@@ -231,7 +247,14 @@ func Node() string {
// Uninstall stops the service and removes it. One not installed is left
// as it is.
-func Uninstall() error { return with(manager.uninstall) }
+func Uninstall() error {
+ err := with(manager.uninstall)
+ if err == nil {
+ os.MkdirAll(filepath.Dir(removedMark()), 0o700)
+ os.WriteFile(removedMark(), nil, 0o600)
+ }
+ return err
+}
// Start starts the installed service.
func Start() error { return installed(manager.start) }
diff --git a/internal/daemon/daemon_test.go b/internal/daemon/daemon_test.go
index 0c2fdcafc..79f1a637e 100644
--- a/internal/daemon/daemon_test.go
+++ b/internal/daemon/daemon_test.go
@@ -539,3 +539,28 @@ func TestInstallCarriesTLS(t *testing.T) {
})
}
}
+
+// A service the user removed is recorded, so the terminal's hand-over of
+// the gateway (tui.keepGateway) never installs it again by itself; an
+// install by the user clears that.
+func TestUninstallRecordsTheUsersNo(t *testing.T) {
+ fakes(t, "linux")
+ if Removed() {
+ t.Fatal("removed before anything")
+ }
+ if err := Install(Options{}); err != nil {
+ t.Fatal(err)
+ }
+ if err := Uninstall(); err != nil {
+ t.Fatal(err)
+ }
+ if !Removed() {
+ t.Fatal("the user's uninstall not recorded")
+ }
+ if err := Install(Options{}); err != nil {
+ t.Fatal(err)
+ }
+ if Removed() {
+ t.Fatal("still recorded after the user installed it")
+ }
+}
diff --git a/internal/tui/detach_unix.go b/internal/tui/detach_unix.go
new file mode 100644
index 000000000..c3d620345
--- /dev/null
+++ b/internal/tui/detach_unix.go
@@ -0,0 +1,17 @@
+//go:build !windows
+
+package tui
+
+import (
+ "os/exec"
+ "syscall"
+)
+
+// detach keeps a started magpie out of this one's session, so it outlives
+// it and its terminal.
+func detach(cmd *exec.Cmd) {
+ if cmd.SysProcAttr == nil {
+ cmd.SysProcAttr = &syscall.SysProcAttr{}
+ }
+ cmd.SysProcAttr.Setsid = true
+}
diff --git a/internal/tui/detach_windows.go b/internal/tui/detach_windows.go
new file mode 100644
index 000000000..a26dc0d1d
--- /dev/null
+++ b/internal/tui/detach_windows.go
@@ -0,0 +1,7 @@
+package tui
+
+import "os/exec"
+
+// detach: magpie on Windows never starts a serve of its own here
+// (keepGateway is for Linux).
+func detach(*exec.Cmd) {}
diff --git a/internal/tui/keep.go b/internal/tui/keep.go
new file mode 100644
index 000000000..ae35c97e2
--- /dev/null
+++ b/internal/tui/keep.go
@@ -0,0 +1,127 @@
+package tui
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+
+ "github.com/yetone/magpie/internal/agent"
+ "github.com/yetone/magpie/internal/appdir"
+ "github.com/yetone/magpie/internal/autostart"
+ "github.com/yetone/magpie/internal/daemon"
+)
+
+// On Linux with no desktop session (a WSL distro, a server over SSH)
+// nothing opens magpie at login, so once magpie tui quit, the agents it had
+// connected asked a gateway that was gone: Codex in WSL "连接会失败,没自动
+// 启动magpie的网关" (zaidu259434 on X, with magpie installed in WSL and
+// pointed at Windows' magpie as a remote one). As it quits having served
+// the gateway with an agent connected, the terminal hands the gateway on:
+// to magpie's service (magpie daemon), installed now where systemd runs it
+// and the user never removed it, which starts it with the system or the
+// user's login from then on; else to a `magpie serve` of its own, in the
+// background until the system stops.
+
+// keeper is what keepGateway asks and does; a var for the tests.
+type keeper struct {
+ goos string
+ autostartOn func() bool
+ status func() (daemon.Status, error)
+ removed func() bool
+ start func() error
+ install func() error
+ linger func() string
+ background func() (pid int, log string, err error)
+}
+
+var keep = keeper{
+ goos: runtime.GOOS,
+ autostartOn: func() bool { return autostart.Enabled() != autostart.Off },
+ status: daemon.Get,
+ removed: daemon.Removed,
+ start: daemon.Start,
+ install: func() error { return daemon.Install(daemon.Options{}) },
+ linger: daemon.Linger,
+ background: serveInBackground,
+}
+
+// keepGateway hands the gateway on as the terminal quits having served it
+// (see above), and is what to say of it.
+func keepGateway(connected bool) string {
+ k := keep
+ if k.goos != "linux" || !connected || k.autostartOn() {
+ return gatewayGoneNote()
+ }
+ st, err := k.status()
+ switch {
+ case err == nil && st.Installed:
+ if err := k.start(); err == nil {
+ return "magpie: the gateway goes on in magpie's service (magpie daemon status)"
+ }
+ case err == nil && !k.removed():
+ if err := k.install(); err == nil {
+ msg := "magpie: the gateway goes on in magpie's service, which now starts with this system or your login, so agents connected to magpie reach it with magpie tui closed; magpie daemon uninstall removes it"
+ if l := k.linger(); l != "" {
+ msg += " (" + l + ")"
+ }
+ return msg
+ }
+ }
+ pid, log, err := k.background()
+ if err != nil {
+ return gatewayGoneNote() + " (couldn't start magpie serve in the background: " + err.Error() + ")"
+ }
+ msg := fmt.Sprintf("magpie: the gateway goes on in the background (magpie serve, pid %d, log %s) until this system stops", pid, log)
+ if wslHere() {
+ msg += "; for it to start with WSL, turn systemd on with [boot] systemd=true in /etc/wsl.conf and run magpie daemon install"
+ } else {
+ msg += "; magpie daemon install starts it with the system"
+ }
+ return msg
+}
+
+// serveInBackground starts `magpie serve` on its own, outliving this
+// process and its terminal, its output in a log in magpie's cache.
+func serveInBackground() (int, string, error) {
+ exe, err := os.Executable()
+ if err != nil {
+ return 0, "", err
+ }
+ log := filepath.Join(appdir.Cache(), "serve.log")
+ if err := os.MkdirAll(filepath.Dir(log), 0o700); err != nil {
+ return 0, "", err
+ }
+ f, err := os.OpenFile(log, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
+ if err != nil {
+ return 0, "", err
+ }
+ defer f.Close()
+ cmd := exec.Command(exe, "serve")
+ cmd.Stdout, cmd.Stderr = f, f
+ detach(cmd)
+ if err := cmd.Start(); err != nil {
+ return 0, "", err
+ }
+ pid := cmd.Process.Pid
+ cmd.Process.Release()
+ return pid, log, nil
+}
+
+// wslHere: this Linux is a WSL distro.
+func wslHere() bool {
+ b, _ := os.ReadFile("/proc/version")
+ return strings.Contains(strings.ToLower(string(b)), "microsoft")
+}
+
+// connected says one of agents is connected to magpie.
+func connected(agents []*agent.Agent) bool {
+ for _, a := range agents {
+ if a.Routed != nil && a.Routed() {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/tui/keep_test.go b/internal/tui/keep_test.go
new file mode 100644
index 000000000..27b6a83f9
--- /dev/null
+++ b/internal/tui/keep_test.go
@@ -0,0 +1,67 @@
+package tui
+
+import (
+ "errors"
+ "strings"
+ "testing"
+
+ "github.com/yetone/magpie/internal/daemon"
+)
+
+// zaidu259434 on X: magpie in WSL, its agents failed once magpie tui was
+// closed, nothing serving the gateway. The terminal quitting with an agent
+// connected hands the gateway to magpie's service, installing it where
+// systemd runs it and the user never removed it, starting it where it is
+// installed, else to a magpie serve in the background. Off Linux, with
+// nothing connected, or where the app opens at login, it only says the
+// gateway stopped.
+func TestKeepGatewayAsTheTerminalQuits(t *testing.T) {
+ was := keep
+ t.Cleanup(func() { keep = was })
+ type did struct{ installed, started, bg bool }
+ setup := func(goos string, auto, installed, removed bool, installErr error) *did {
+ d := &did{}
+ keep = keeper{
+ goos: goos,
+ autostartOn: func() bool { return auto },
+ status: func() (daemon.Status, error) { return daemon.Status{Installed: installed}, nil },
+ removed: func() bool { return removed },
+ start: func() error { d.started = true; return nil },
+ install: func() error { d.installed = true; return installErr },
+ linger: func() string { return "" },
+ background: func() (int, string, error) { d.bg = true; return 42, "/x/serve.log", nil },
+ }
+ return d
+ }
+ gone := gatewayGoneNote()
+
+ d := setup("linux", false, false, false, nil)
+ if msg := keepGateway(true); !d.installed || d.bg || !strings.Contains(msg, "magpie daemon uninstall") {
+ t.Errorf("no service: %+v %q", *d, msg)
+ }
+ d = setup("linux", false, true, false, nil)
+ if msg := keepGateway(true); !d.started || d.installed || d.bg || msg == gone {
+ t.Errorf("installed: %+v %q", *d, msg)
+ }
+ d = setup("linux", false, false, true, nil)
+ if msg := keepGateway(true); d.installed || !d.bg || !strings.Contains(msg, "pid 42") {
+ t.Errorf("removed by the user: %+v %q", *d, msg)
+ }
+ d = setup("linux", false, false, false, errors.New("this system has no systemd"))
+ if msg := keepGateway(true); !d.bg || !strings.Contains(msg, "background") {
+ t.Errorf("no systemd: %+v %q", *d, msg)
+ }
+ for name, c := range map[string]struct {
+ goos string
+ auto, con bool
+ }{
+ "mac": {"darwin", false, true},
+ "nothing on": {"linux", false, false},
+ "app at login": {"linux", true, true},
+ } {
+ d = setup(c.goos, c.auto, false, false, nil)
+ if msg := keepGateway(c.con); msg != gone || d.installed || d.bg || d.started {
+ t.Errorf("%s: %+v %q", name, *d, msg)
+ }
+ }
+}
diff --git a/internal/tui/tui.go b/internal/tui/tui.go
index 3b21faac3..fc934e00b 100644
--- a/internal/tui/tui.go
+++ b/internal/tui/tui.go
@@ -168,7 +168,7 @@ func Run(ready func()) error {
stop()
wait()
if served {
- fmt.Fprintln(os.Stderr, gatewayGoneNote())
+ fmt.Fprintln(os.Stderr, keepGateway(connected(m.agents)))
}
return err
}