Files
magpie/internal/daemon/daemon.go
T
JoeyWu-tech ab25a2317b autostart: on Linux the switch follows a package's own entry (#3372)
mtul0729, packaging magpie for nixpkgs (#3372, COSMIC on Wayland,
v0.1.1334): a package that ships its own autostart entry
($XDG_CONFIG_DIRS/autostart/magpie.desktop, /etc/xdg when unset) has
magpie open at login, but enabled() read only
$XDG_CONFIG_HOME/autostart, so Open at login said off over it. Off
removed a user file that wasn't there, and the package's entry went on
starting magpie. On wrote this copy's own path over the package's entry:
under a package manager a versioned path, gone once the package is
upgraded and collected. The package doc says the switch "can't say one
thing while the system does another"; on such a system it did.

Now, as the XDG Autostart spec has it:
- The entry that counts is the user's, else the first of the
  $XDG_CONFIG_DIRS folders (/etc/xdg when unset or empty) that has one.
  A relative folder has none, as the spec says, and neither has a file
  listed there, a folder this user can't search or a name too long,
  which systemd's generator and GLib can't open either. The user's own
  folder listed there too, by any name (os.SameFile, so /home linked to
  /var/home too), is still the user's.
- An entry is read as GLib's key file and systemd's parser read it: the
  keys of its [Desktop Entry] group alone (a [Desktop Action]'s Exec is
  not the entry's), spaces around = and CRLF lines as any others, the
  last of a key given twice, true or 1 for Hidden. It opens magpie when
  it is an application (Type=Application) with an Exec other than true
  (below), not Hidden.
- X-GNOME-Autostart-enabled=false (or 0) reads off too, as the issue
  asks. GNOME's and Cinnamon's sessions read it; systemd's generator
  (KDE's and COSMIC's sessions under systemd) doesn't, so there such an
  entry reads off while it starts.
- Off, over a package's entry that some desktop starts, writes an entry
  of the user's that hides it; that includes one GNOME has off, which
  systemd's generator still starts. Otherwise off removes the user's
  entry, as before. On, over a package's entry that starts magpie,
  removes the user's entry and writes no path; otherwise (no package
  entry, a hidden one, or one GNOME has off) it writes this copy's
  entry, as before.

The hiding entry is "[Desktop Entry] Type=Application Name=magpie
Exec=true Hidden=true". A session holds back the entries of a name only
once it has read one, and each reads differently (from their source):
- gnome-session (main and 42.0) and cinnamon-session load an entry with
  g_desktop_app_info_new_from_filename. GLib (main,
  g_desktop_app_info_load_from_keyfile) refuses one with no Type or
  Name, or whose Exec names a program it can't find, and the session
  skips an entry it can't load, so the package's starts.
- mate-session's egg_desktop_file_new refuses an application entry with
  no Exec, and the entry then takes no app id.
- cosmic-session without systemd never reads Hidden: it starts what Exec
  names, and takes the name once that ran.
- systemd's generator (main, xdg-autostart-service.c) reads Hidden
  first, and hides an entry it can't parse, which still holds back the
  rest.
true is on every system by that name, so each session reads the entry,
and COSMIC's runs true where it would have run magpie. A copy of the
package's own Exec would stop holding the package's back on GNOME once
its store path is collected. With this box's GLib 2.72.4 (Ubuntu
22.04's) and 2.84.2 (anaconda's), through ctypes: Exec=true and no Exec
load, hidden; an Exec naming a store path that is gone, and a bare
"[Desktop Entry] Hidden=true", don't load. An entry that runs true opens
nothing, so it reads off: XFCE's Session and Startup lists the hiding
entry as magpie, unticked, and ticking it there writes Hidden=false into
it (xfae-model.c), which runs true, not magpie. On takes it away for the
package's.

What is no entry, and what can't be read: a path where no regular file
is (a folder, a link that leads nowhere or round in a loop) is no entry,
as systemd's generator and GLib pass over it, and on leaves a folder
there alone. A file that can't be read (EACCES, EPERM, EIO) counts and
starts nothing, as systemd's generator has it; GLib passes over it, so
where the first entry is unreadable GNOME starts the next folder's while
Open at login reads off. Any other failed read, magpie out of files or
memory, says nothing of what the desktop reads at login: Set returns it
and writes nothing, and Open at login reads on, as the package's doc has
it for a system that can't be asked (Windows' Run key that can't be read
is not a no either).

The user's entry is written where the desktop reads it. A link there (to
magpie's launcher, which install.sh writes, the usual way to have an app
open at login; or into a read-only store), or a hard link, is replaced
by the entry, not written through: edit.WriteAtomic writes a link's
target, and a hard-linked file in place, so off over a package's entry
would have left the launcher running true, and failed over a read-only
target with the switch still on. Main's enable() wrote through such a
link too, when on was asked over one (a linked launcher already reads
on); it goes through the same write now.

Old entries: a user entry an older magpie wrote stays and still counts
over a package's, as before. The switch reads on over it, so in the app
taking it away is off, then on; `magpie autostart on` does it in one
step. One whose store path was collected reads on as well, though
systemd's generator starts nothing for it and still holds the package's
back, so on COSMIC or KDE magpie doesn't open while the switch says on;
GLib passes over it, and GNOME starts the package's.

The daemon and the terminal: `magpie daemon install` refuses while
magpie opens at login, so the app and the service don't both serve the
gateway, and `magpie tui` quitting hands the gateway on (keepGateway,
75e78a5a) only where nothing opens magpie at login. Both read
autostart.Enabled, code unchanged, so a package's entry counts for both
now. Where a desktop session runs XDG autostart that is the point:
install says to run `magpie autostart off` first, which now hides the
entry, where before the service went in beside an app the package's
entry went on opening. On a box no desktop logs into (NixOS-WSL, a NixOS
server over SSH) nothing runs the entry, yet install refuses and
keepGateway only says the gateway stopped; `magpie autostart off` gets
both going. That is #3756, filed with this, for yetone to say what they
should count on Linux; a session check wouldn't settle it, since install
over SSH into a desktop box has no DISPLAY either.

An entry the desktop's own settings switched off reads off for the guard
as well: XFCE writes Hidden=true into the user's entry, which main still
counted (it read Type and Exec alone), so install refused; now it goes
in. I kept that reading, and daemon.go's comment now says so, rather
than have the guard count such an entry. The switch and `magpie
autostart` read it off, and a guard counting it would refuse with
"magpie already opens at login" where `magpie autostart` says it
doesn't. The Mac has a state for that case (NeedsAllowing, which the CLI
and the app explain in System Settings' words), and Linux has none to
show it; Windows reads a Run value Task Manager switched off as off, and
on switches it back, as Set(true) does here. What it costs: ticking
magpie again in the desktop's settings after the install opens the app
beside the service, in #3756 too. For an AppImage or a tarball, with no
package entry, on and off write and remove as before, and what changes
is how an entry reads (Hidden, the GNOME key, a failed read, as above)
and that a link at the entry is replaced, not written through.

docs/subsystems/gui-shell.md says how Open at login reads on Linux, and
that the terminal's hand-off counts a package's entry (#3756).

Rebased onto origin/main 58fb3a77: 824100f3 added a line to
gui-shell.md next to the one this patch changes, so 7e9003aa no longer
applied. The code and the docs line are as they were (the same patch
for internal/).

What was run (tree 59fb33a8, on origin/main 58fb3a77, go1.26.8,
linux/amd64, Linux 5.15), outside graftcp, umask 077:
- go test -tags nogui ./internal/autostart ./internal/testenv -v:
  autostart ok, its new tests among them; testenv ok but TestProgram,
  red under this box's umask 077 (#3640), as on main.
- gofmt -l clean. go vet -tags nogui for linux, windows and darwin, go
  vet for windows without the tag, go build -tags nogui for linux and
  darwin, and go build for windows: exit 0 each; untagged linux vet and
  build stop at pkg-config (no GTK headers here). GOOS=freebsd vet: not
  run at this tree.
- go test -tags nogui -count=1 -timeout 45m ./... (log kept), Bun
  1.4.2, 8m35s, load 19 at its start: 70 packages ok, autostart,
  daemon, cli and tui among them; reds in 6, each known: agent
  TestInstalledVersion, TestCursorFolderFromTheEditorIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI, TestOmpDetectedWithPiDir
  and TestZedAppPath (#3141), TestCodexDriftReached (#3398) and the two
  Reasonix tests (#3641); davsync TestSyncTeraCloudStillSeesOtherWrites
  (#3420);
  edit TestWriteAtomicReadOnlyHardLink and testenv TestProgram
  (umask 077, #3640); gateway TestPluginToldWhereTheAgentWorks (#3675),
  the package ran to its end; gui TestGatewayHeldByAContainer and
  TestGatewayFixQuitsOnlyAMagpie (#3649).

The rest is what was run for 7e9003aa, at tree 719db0e7 on origin/main
6e6aba51, the same code (not this tree):
- Real use (real.log): the built magpie (-tags nogui) and origin/main's,
  each in a sandbox HOME under env -i, with a package entry (Exec=magpie
  tray, magpie on PATH) in XDG_CONFIG_DIRS, and systemd 249's
  systemd-xdg-autostart-generator after each step:
  - the package's entry alone: main says magpie doesn't open at login
    while the generator starts magpie tray; this says on.
  - off, twice: main writes nothing and it still starts; this writes the
    hiding entry, and the generator starts nothing.
  - on: main writes its own path, which it starts; this takes the hiding
    entry away, and the generator starts the package's magpie tray.
  - no package entry, on then off: both write their own path, which
    starts, then remove it, and nothing starts. The package's entry put
    back, off again: as the first off.
  - the package's entry with X-GNOME-Autostart-enabled=false: both say
    off while the generator starts it. Off: main writes nothing and it
    still starts; this writes the hiding entry, and nothing starts. On:
    both write their own path.
  - the hiding entry ticked again as XFCE does (Exec=true, Hidden=false)
    over the package's: the generator runs /usr/bin/true; main says on,
    this says off. On: this takes it away and the package's magpie tray
    starts; main writes its own path.
  - the user's entry a link to magpie's launcher, off over the
    package's: main takes the link away and the package's entry still
    starts; this writes the hiding entry in the link's place, and
    nothing starts. The launcher is unchanged in both.
  - an old entry of magpie's naming a store path that is gone, over the
    package's: both say on, and the generator starts nothing. On: this
    takes it away and the package's starts; main writes its own path.
- The new tests over origin/main's autostart_other.go, with a nil
  systemRecords and readEntry added so they build (red-on-main.log): all
  9 new ones red, and TestSet and TestSetThenTruncatedRecordReadsAsOff,
  which main has, pass. The first red of each: :101 "the package's entry
  opens magpie at login, and Open at login reads off"; :226 "the second
  system folder's alone: off, want on" (and 5 more rows: three more
  where a system folder alone has the entry, the user's own entry
  Hidden, and the user's own off by the GNOME key); :241
  "XDG_CONFIG_DIRS unset: [], want
  ["/etc/xdg/autostart/magpie.desktop"]"; :311 and :373, no hiding entry
  written; :440, off over a link to the launcher left no entry of the
  user's, and :437, on over it with no package's entry wrote through to
  the launcher (main's own enable(), the sibling above); :491 "a folder
  at the user's entry, the package's entry there: true: off, want on";
  :534, on over an unreadable user entry leaves it; :568, no hiding
  entry to read.
- Broken by hand (breaks.log), each one part of the fix undone, all 36
  red, the fix put back ok after. The first red of each:
  - where entries come from: no system folders :101; the system's
    folders over the user's :108; unset XDG_CONFIG_DIRS with no /etc/xdg
    :241; a relative folder kept :266; the user's folder, by any name,
    taken for a system's :290.
  - how an entry reads: Hidden ignored, Hidden=false read as hidden,
    Hidden=1 not read, all :226; the GNOME key ignored, and its 0 not
    read, :226; the system's entry starting whatever its Type :226;
    spaces around = kept, a line's CR kept, every group's keys read as
    the entry's, all :226; an entry that runs true read as opening
    magpie :120.
  - what off and on write: off always removing :108; off writing the
    hiding entry with no package entry :173; off deciding by GNOME's
    reading :373; on always writing this copy's path :131; on over a
    package's entry keeping the hiding entry :127; on taking away a
    folder of the entry's name :495.
  - the hiding entry: with no Exec :323, no Type :318, a store path for
    Exec :326, true named by a path :326.
  - what can't be read: a file in XDG_CONFIG_DIRS, a folder this user
    can't search and a name too long, each read as a failed read, :269;
    a folder at the entry's path, and a link loop, read as one :491; an
    unreadable entry read as no entry :528; every failed read an entry
    that starts nothing :576; magpie's own failed read read as no entry
    :576, and taken for a no :580.
  - links: a symlinked entry written through :437, and a hard-linked one
    :437.
- internal/autostart, daemon, cli and tui (pkgs.log): ok.
  internal/autostart with -race -count=3 (race.log): ok; nothing in it
  runs in a goroutine of its own.
- Probes at this tree, thrown away after (probes-3756.log): keepGateway
  with the real reading and all else stubbed, and Install behind
  daemon_test's fakes (fake systemctl, launchctl and loginctl alone on
  PATH). With the package's entry, keepGateway only says the gateway
  stopped and Install refuses before any systemctl call. Under the
  hiding entry off writes, and with no package entry but the user's own
  entry Hidden=true as XFCE writes it, keepGateway installs the service
  and Install goes through (the fake's daemon-reload, enable and
  restart).
- Full suite, -tags nogui (CI's Linux job tags gtk3), outside graftcp
  (systemd-run, umask 077, Bun 1.4.2 first on PATH as on CI, -timeout
  45m, log kept): 64 packages ok, autostart, daemon, cli and tui among
  them, and 8 packages red, each filed:
  - agent TestCodexDriftReached: #3398; TestInstalledVersion,
    TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
    TestQoderSettingsFromAnIDEPluginIsNotTheCLI,
    TestOmpDetectedWithPiDir and TestZedAppPath: #3141;
    TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout: this box's /tmp/.git,
    #3641.
  - davsync TestSyncTeraCloudStillSeesOtherWrites: #3420.
  - edit TestWriteAtomicReadOnlyHardLink: this box's umask 077, #3640.
  - gateway TestPluginToldWhereTheAgentWorks: this box's /tmp/.git,
    #3675.
  - gui TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie:
    this box's millions of open fds, #3649.
  - #3741.
  - provider: "fatal error: close of synctest channel from outside
    bubble" in TestUnreadLoginsWriteErrorsKeepCredentials, main's CI
    red, #3632; the package's tests after it didn't run.
  - testenv TestProgram: this box's umask 077, #3640, red so at
    origin/main 6e6aba51 alone too (testprogram-main.log).
- gofmt -l: clean. go vet -tags nogui for linux, windows and darwin,
  GOOS=windows go vet ./..., GOOS=freebsd go vet ./internal/autostart/
  ./internal/daemon/, go build -tags nogui for linux and darwin and
  GOOS=windows go build ./...: all clean. Untagged linux vet and build
  stop at pkg-config here (no GTK headers on this box).

Not changed: gnome-session also reads $XDG_DATA_DIRS/gnome/autostart,
between the user's folder and $XDG_CONFIG_DIRS; it isn't in the spec,
and this doesn't read it. systemd reads an XDG_CONFIG_DIRS that is set
but empty as no folders, and opens a relative folder from its working
directory; this follows the spec: /etc/xdg for an empty one, and no
relative folder. Whether the program an entry's Exec or TryExec names is
there isn't checked, and an entry with any Exec (Exec=magpie serve,
another program's magpie.desktop) reads as magpie opening at login. With
no package entry that starts magpie (none, a hidden one, or one GNOME
has off), on still writes the path self() gives, a versioned one under a
package manager (#3621, where skygunner has a branch, 0aac5452, which
git apply --check takes over this one); a Linux refresh() that took away
an old entry of magpie's whose Exec is gone, where a package's entry
starts magpie, belongs there too.

Not tried: a real login into GNOME, KDE, MATE, Cinnamon, XFCE or COSMIC
(what each session does is read from its source, GLib's loading tried
with the two GLibs above); NixOS itself, and home-manager's links; a
real `magpie daemon install` or keepGateway over a package's entry,
which would reach this box's own systemd and gateway
(TestRefusedBesideAutostart and TestKeepGatewayAsTheTerminalQuits stub
what they read, and the probes above use the real reading).

Batch run, at tree 104d75f0a (the twelve coffemon ports together, on
origin/main 7d022bdb6), mote, macOS, go1.26.8:
- go test -tags nogui -count=1 -timeout 45m on the packages the batch
  changes (agent, autostart, daemon, gateway, library, proc, provider,
  sessions, testenv, tui, gui): ok each.
- GUI, node --test with Playwright 1.62.0, Chromium and WebKit:
  library-*.test.cjs and i18n-keys.test.cjs, 1044 of 1044 pass.
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... and go build ./...: ok at cdd7c8e46, the same
  batch on origin/main 00098f12b one rebase before.
- The whole go test ./... at cdd7c8e46: 86 packages ok, one red,
  internal/cli TestEveryRouteHasACommandOrIsNamed (GET
  /api/context/reply has no command), red on main too (#5026).
- Linux (wsl-run, Ubuntu 24.04, at 339055896, the batch on f4c664a09):
  proc, autostart, testenv, tui ok; agent: only TestGrokInstalled red
  (#3548); #4033's proc.Look reds (Zed, Copilot, Qoder, Cursor, Omp)
  pass.
- Windows (win-run, Windows 11, at 339055896): proc, autostart, testenv,
  tui ok; library and agent red in the same tests as on origin/main
  f4c664a09 (#4115, #1827, #4786; #5068, #5069, #5070 filed now).
- Rebased onto origin/main fb1f4856a (three commits, no file in
  common with the batch) and run again at the pushed tree: gofmt -l
  nothing, go build ./... and go vet ./... ok; go test -tags nogui
  sessions, agent, autostart, tui, proc, testenv ok; i18n-keys and
  library-* 1044 of 1044 pass.
- Not run before the push: the whole GUI suite (a run at cdd7c8e46 was
  cut off at 1170 of ~1174 tests when mote rebooted; it runs again after
  the tag and any red is filed).
2026-11-03 20:38:11 +08:00

425 lines
13 KiB
Go

// Package daemon runs `magpie serve` as a service of the user's own: a
// systemd user unit on Linux, a launch agent on the Mac. The system starts
// it at boot or login and starts it again when it stops, with no window
// and no desktop session, for a server or a machine reached over SSH.
// Whether it is installed and running is the system's own record, read
// each time, never a setting of magpie's.
package daemon
import (
"errors"
"fmt"
"html"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"slices"
"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"
)
// Name is the service's name: magpie.service, com.yetone.magpie.serve.
const Name = "magpie"
// Status is what the system says of the service.
type Status struct {
Installed bool // the unit or launch agent is on disk
Enabled bool // started at boot or login
Running bool // its process is up
PID int // that process, when the system says
State string // the system's own word for it: active, failed, running…
LastExit string // how its last run ended, when the system says
File string // the unit or launch agent's file
Logs string // how to read what it printed
Advice []string
}
// manager is one system's way of running a service.
type manager interface {
file() string
logs() string
install(exe string, args, env []string) error
uninstall() error
start() error
stop() error
restart() error
status() (Status, error)
}
// goos picks the manager; a var so that the tests run both on any unix.
var goos = runtime.GOOS
// ErrUnsupported is for a system with no service manager magpie writes for.
var ErrUnsupported = errors.New("unsupported")
func current() (manager, error) {
switch goos {
case "linux":
return systemd{}, nil
case "darwin":
return launchd{}, nil
case "windows":
return nil, fmt.Errorf("%w on Windows: `magpie autostart on` opens magpie, with its gateway, when you log in; or run `magpie daemon install` inside WSL", ErrUnsupported)
case "android":
return nil, fmt.Errorf("%w on Android: `magpie autostart on` starts the gateway at boot through Termux:Boot", ErrUnsupported)
}
return nil, fmt.Errorf("%w on %s: run `magpie serve` under the system's own service manager", ErrUnsupported, goos)
}
// Options are what the service serves besides the gateway.
type Options struct {
// Web is the address the app's page is served on (`magpie serve
// --web=…`), "" for none.
Web string
// Key is the page's MAGPIE_WEB_KEY, written into the service so its
// link stays the same across restarts; needed with Web.
Key string
}
// Install writes the service for this copy of magpie, with the
// environment it was installed from, and starts it; again, it writes the
// service anew (a moved magpie, a new PATH or proxy) and restarts it.
func Install(o Options) error {
m, err := current()
if err != nil {
return err
}
// the app opened at login serves the gateway too: the two would take
// turns failing on the port
if autostartEnabled() {
return errors.New("magpie already opens at login and serves the gateway: run `magpie autostart off` first, or keep that instead")
}
if o.Web != "" && o.Key == "" {
return errors.New("the page needs a key")
}
exe, err := self()
if err != nil {
return err
}
widenPath()
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.
func serveArgs(o Options) []string {
if o.Web == "" {
return []string{"serve"}
}
return []string{"serve", webFlag + o.Web}
}
// webFlag is `magpie serve`'s, naming the page's address.
const webFlag = "--web="
// webKeyVar is the page's key in the service's environment.
const webKeyVar = "MAGPIE_WEB_KEY"
// withKey is env with the page's key, when it has a page: a key in the
// shell's environment is never carried otherwise.
func withKey(env []string, o Options) []string {
if o.Web == "" {
return env
}
return append(env, webKeyVar+"="+o.Key)
}
// Web is the page the installed service serves: its address and key, ""
// when it serves none or isn't installed. Read from the service's own
// file, which is the user's alone.
func Web() (addr, key string) {
m, err := current()
if err != nil {
return "", ""
}
b, err := os.ReadFile(m.file())
if err != nil {
return "", ""
}
return webOf(string(b))
}
var (
webArgRe = regexp.MustCompile(`(?:"|<string>)` + regexp.QuoteMeta(webFlag) + `([^"<\s]+)(?:"|</string>)`)
// a unit's Environment="MAGPIE_WEB_KEY=…", a plist's
// <key>MAGPIE_WEB_KEY</key><string>…</string>
webKeyRe = regexp.MustCompile(webKeyVar + `(?:=|</key><string>)([A-Za-z0-9._~-]+)`)
)
// TLS is the certificate and key files the installed service serves
// HTTPS with (`magpie daemon install --tls-cert … --tls-key …`), "" when
// it has none or isn't installed.
func TLS() (cert, key string) {
m, err := current()
if err != nil {
return "", ""
}
b, err := os.ReadFile(m.file())
if err != nil {
return "", ""
}
return tlsOf(string(b))
}
// tlsOf is TLS from a unit's or a launch agent's text: both files or
// neither.
func tlsOf(text string) (cert, key string) {
val := func(name string) string {
// a unit's Environment="NAME=…", quoted by unitQuote
if m := regexp.MustCompile(`Environment="` + name + `=((?:[^"\\]|\\.)*)"`).FindStringSubmatch(text); m != nil {
return strings.NewReplacer(`\\`, `\`, `\"`, `"`, "%%", "%").Replace(m[1])
}
// a plist's <key>NAME</key><string>…</string>
if m := regexp.MustCompile(`<key>` + name + `</key><string>([^<]*)</string>`).FindStringSubmatch(text); m != nil {
return html.UnescapeString(m[1])
}
return ""
}
cert, key = val("MAGPIE_TLS_CERT"), val("MAGPIE_TLS_KEY")
if cert == "" || key == "" {
return "", ""
}
return cert, key
}
// webOf is Web from a unit's or a launch agent's text.
func webOf(text string) (addr, key string) {
m := webArgRe.FindStringSubmatch(text)
if m == nil {
return "", ""
}
k := webKeyRe.FindStringSubmatch(text)
if k == nil {
return "", ""
}
return html.UnescapeString(m[1]), k[1]
}
// widenPath gives PATH, before it is written into the service, the
// folders a terminal of the user's has: nvm's default Node and the other
// managers' folders, then the login shell's own PATH — what the app does
// when it is opened from the Dock. The shell install is run from can lack
// them (nvm loaded lazily, a script, ssh without a login shell), and the
// service has only what is written: plugins and the MCP servers and agent
// CLIs they start need node, which wasn't found (bookyue on Discord). A
// var for the tests.
var widenPath = func() {
proc.UserPath()
cur := filepath.SplitList(os.Getenv("PATH"))
for _, d := range proc.LoginPath() {
if d != "" && filepath.IsAbs(d) && !slices.Contains(cur, d) {
cur = append(cur, d)
}
}
os.Setenv("PATH", strings.Join(cur, string(os.PathListSeparator)))
}
// Node is the node the service finds on its PATH, "" for none: what the
// CLI warns of after an install.
func Node() string {
p, err := exec.LookPath("node")
if err != nil {
return ""
}
return p
}
// Uninstall stops the service and removes it. One not installed is left
// as it is.
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) }
// Stop stops it, until the next boot or login, or Start.
func Stop() error { return installed(manager.stop) }
// Restart stops it and starts it again: a magpie updated in place serves
// as the new version.
func Restart() error { return installed(manager.restart) }
// Get is what the system says of the service.
func Get() (Status, error) {
m, err := current()
if err != nil {
return Status{}, err
}
st := Status{File: m.file(), Logs: m.logs()}
if _, err := os.Stat(st.File); err != nil {
return st, nil
}
got, err := m.status()
got.Installed, got.File, got.Logs = true, st.File, st.Logs
return got, err
}
// ErrNotInstalled is Start, Stop or Restart before Install.
var ErrNotInstalled = errors.New("the magpie service isn't installed: `magpie daemon install`")
func with(f func(manager) error) error {
m, err := current()
if err != nil {
return err
}
return f(m)
}
func installed(f func(manager) error) error {
return with(func(m manager) error {
if _, err := os.Stat(m.file()); err != nil {
return ErrNotInstalled
}
return f(m)
})
}
// autostartEnabled: magpie opens at login, by its own record or, on
// Linux, by a package's entry (#3372). On the Mac a record the user has
// switched off in System Settings for now counts all the same, since
// switching it back on there opens the app with the service still
// installed. On Linux an entry the desktop's own settings switched off
// (Hidden, X-GNOME-Autostart-enabled=false) reads off, as Open at login
// reads it, so the install goes in; and a package's entry counts on a box
// no desktop logs into too (#3756). A var for the tests.
var autostartEnabled = func() bool { return autostart.Enabled() != autostart.Off }
// self is the program the service runs: this one, by the name on PATH
// when that is this same file, so a package manager's link (Homebrew's
// /opt/homebrew/bin/magpie) still leads to the version it updates to. A
// var for the tests, whose binary is a build Go deletes.
var self = func() (string, error) {
if p := os.Getenv("APPIMAGE"); p != "" {
return p, nil
}
exe, err := os.Executable()
if err != nil {
return "", err
}
real := exe
if p, err := filepath.EvalSymlinks(exe); err == nil {
real = p
}
return pick(real, exe)
}
// pick is self past os.Executable: real is the running file, exe the
// name it was started by.
func pick(real, exe string) (string, error) {
if strings.Contains(real, "/AppTranslocation/") {
return "", errors.New("move magpie to Applications first, then install the service")
}
if strings.Contains(real, string(filepath.Separator)+"go-build") {
return "", errors.New("this magpie is a build `go run` deletes when it ends: install magpie, then run `magpie daemon install` from it")
}
if p, err := exec.LookPath(Name); err == nil {
if abs, err := filepath.Abs(p); err == nil {
if r, err := filepath.EvalSymlinks(abs); err == nil && sameFile(r, real) {
return abs, nil
}
}
}
if filepath.IsAbs(exe) && sameFile(exe, real) {
return exe, nil
}
return real, nil
}
func sameFile(a, b string) bool {
x, err := os.Stat(a)
if err != nil {
return false
}
y, err := os.Stat(b)
return err == nil && os.SameFile(x, y)
}
// carried are the variables the service gets from the shell it was
// installed from: the PATH that finds the agents' CLIs and bun, the proxy,
// magpie's own settings, and where each agent keeps its files. A service
// starts with the system's bare environment otherwise.
var carried = []string{
"PATH",
"HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",
"http_proxy", "https_proxy", "all_proxy", "no_proxy",
"XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME",
"MAGPIE_ADDR", "MAGPIE_TRUST_PROXY", "MAGPIE_BUN", "MAGPIE_WEB_URL",
// `magpie daemon install --tls-cert … --tls-key …` sets them
"MAGPIE_TLS_CERT", "MAGPIE_TLS_KEY",
}
// environ is carried's variables that are set, as KEY=value, in order.
func environ() []string {
var out []string
seen := map[string]bool{}
for _, k := range append(append([]string{}, carried...), agentenv.Vars...) {
if seen[k] {
continue
}
seen[k] = true
if v, ok := os.LookupEnv(k); ok && v != "" {
out = append(out, k+"="+v)
}
}
return out
}
// run runs a service manager's tool, from PATH, and gives what it printed.
// A failure carries that text, which is what the user needs to read.
func run(name string, args ...string) (string, error) {
out, err := proc.Command(name, args...).CombinedOutput()
text := strings.TrimSpace(string(out))
if err != nil {
if errors.Is(err, exec.ErrNotFound) {
return text, err
}
if text != "" {
return text, fmt.Errorf("%s %s: %s", name, strings.Join(args, " "), text)
}
return text, fmt.Errorf("%s %s: %w", name, strings.Join(args, " "), err)
}
return text, nil
}
// private writes a service's file, readable by the user alone from its
// first byte: it holds the environment, and a proxy's can carry a
// password.
func private(path string, data []byte) error {
if _, err := os.Lstat(path); os.IsNotExist(err) {
if err := os.WriteFile(path, nil, 0o600); err != nil {
return err
}
}
if err := edit.WriteAtomic(path, data); err != nil {
return err
}
return os.Chmod(path, 0o600)
}