update: the Mac relaunch starts the bundle's program when open never works (molvqingtai on Discord)

molvqingtai (Discord, 10-24): on macOS, magpie's restart after a
self-update still leaves it closed on versions after fb23bca5c, and only
while the screen is locked. Their 10-22 log (v0.1.1314) had the old
process exit 0 and `open` of the bundle fail ~160ms later with -600
(procNotFound), LaunchServices still sending to the gone process.
fb23bca5c tried that open again for ~13.5s (8 tries), and the report
says that isn't enough: LaunchServices can go on refusing for as long as
the session is locked, and the relaunch had nothing but LaunchServices
to start magpie with. With magpie closed, Prevent sleep is off too: the
Mac sleeps and the agents lose their connection.

Cause, as far as it could be checked: every route back went through
LaunchServices. A locked session was not reproduced here (the screen was
never locked), so "refuses for as long as it is locked" is the report's
shape, not something observed.

Fix (internal/update/update.go): relaunchCommand is now relaunchScript
over openWaits. The same open with the same pauses runs first; once the
last try has failed, the bundle's own program (Contents/MacOS/<the
CFBundleExecutable its Info.plist names, else this one's name, else
magpie>) is exec'd by the helper shell with RelaunchArgs: `tray` when no
window was up, `gui` when one was. That is what the Open at login launch
agent runs (ProgramArguments: Contents/MacOS/magpie tray), so it needs
nothing from LaunchServices. The shell is runAfterExit's, in a session of
its own (#2362); `exec` makes it the new magpie, so there is no shell
left to exit and take it with it. The instance lock is a flock on a file
keyed by the program's path, the same for open and for this start, so a
late open from LaunchServices hands over to the one already running.

Each try is written to relaunch.log in magpie's own folder
(appdir.Config(), ~/.config/magpie on the Mac): "magpie has exited;
opening <bundle>", then per try "open try N: exit S <open's stderr on
one line>", then "open gave up after N tries; starting <program> <args>"
or "no executable at <path>". The file is moved to relaunch.log.old past
64KB. A missing log folder writes nothing and changes nothing else.

Tests (internal/update/relaunch_fallback_test.go), with fakeOpen from
relaunch_retry_test.go first on PATH answering with the -600 text and a
fake bundle whose program writes the arguments it got:
- TestRelaunchStartsTheBundleWhenOpenNeverWorks: through runAfterExit
  after a gone pid, open refused every time; the program runs with tray
  (no window) and gui (window), after len(waits)+1 opens.
- TestRelaunchLogsEachTry: the log has the opening line, each try's exit
  status with open's -600 text, and the fallback's program and args.
- TestRelaunchOpenedStartsNothingElse: open working on try 2 is the
  whole relaunch; the program isn't also run; the log says exit 0.
- TestRelaunchNoProgramIsLogged: a bundle without its program is
  logged and the shell exits non-zero.
- TestRelaunchRunsTheProgramInfoPlistNames: "magpie dev" from
  Info.plist, in a bundle path with a quote in it.
- TestRelaunchLogInMagpiesFolder: the log is under XDG_CONFIG_HOME's
  magpie, and is moved to .old past 64KB.
Red by hand: with the fallback replaced by the old `|| exit 1`,
StartsTheBundle timed out at 30s ("the new version starting never
happened"), and LogsEachTry, NoProgramIsLogged and
RunsTheProgramInfoPlistNames failed; with note() a no-op, LogsEachTry, OpenedStartsNothingElse
and NoProgramIsLogged failed. All green with the fix.

Real run: a relauncher built from this tree calling update.Relaunch on
a scratch Scratch.app (CFBundleExecutable scratch, a script writing a
marker), under env -i with a sandbox HOME and an `open` first on PATH
that always fails with the -600 text. The relauncher exited at once;
relaunch.log under the sandbox's ~/.config/magpie had 8 tries 02:02:45
to 02:02:59, each "exit 1 _LSOpenURLsWithCompletionHandler() ... -600.",
then "open gave up after 8 tries; starting '.../scratch' 'tray'". The
marker: args=tray ppid=1 pgid=pid (own group), no tty, and still alive
3s later, after the relauncher and its shell were gone.

Run at 843417957 plus this change: gofmt -l internal/ (clean);
go vet ./... (darwin); GOOS=linux go vet -tags nogui ./...;
GOOS=windows go vet ./...; go test -count=1 ./internal/update (ok).
The full suite (-timeout 45m) was started on this tree before the push
and had not finished; per the owner's ship-at-once rule this didn't wait
for it.

Not tried: a real update with the screen locked (the screen here was
never locked), so whether the program started by path comes up under a
locked session is not seen, only that the login agent starts it the
same way. Not tried with the real magpie binary in the scratch bundle
(it would read the Keychain): the tray and the instance lock under this
start are the login agent's path, not observed here. An open that exits
0 while magpie doesn't come up isn't covered; relaunch.log will show it.
This commit is contained in:
yetone
2026-10-24 02:05:05 +08:00
parent 843417957c
commit f3eb92924e
3 changed files with 287 additions and 5 deletions
+206
View File
@@ -0,0 +1,206 @@
//go:build !windows
package update
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
)
// fakeBundle makes an app at dir/magpie.app whose Info.plist names exe as
// its program, a script that writes the arguments it was run with to
// dir/started: the new version, started.
func fakeBundle(t *testing.T, exe string) (bundle, started string) {
t.Helper()
dir := t.TempDir()
bundle = filepath.Join(dir, "magpie.app")
started = filepath.Join(dir, "started")
macos := filepath.Join(bundle, "Contents", "MacOS")
if err := os.MkdirAll(macos, 0o755); err != nil {
t.Fatal(err)
}
plist := `<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0"><dict>
<key>CFBundleExecutable</key>
<string>` + exe + `</string>
<key>CFBundleIdentifier</key><string>com.yetone.magpie</string>
</dict></plist>
`
if err := os.WriteFile(filepath.Join(bundle, "Contents", "Info.plist"), []byte(plist), 0o644); err != nil {
t.Fatal(err)
}
script := "#!/bin/sh\necho \"$@\" > '" + started + "'\n"
if err := os.WriteFile(filepath.Join(macos, exe), []byte(script), 0o755); err != nil {
t.Fatal(err)
}
return bundle, started
}
// waitFor waits for path to have something in it, and says what.
func waitFor(t *testing.T, path, what string) string {
t.Helper()
for end := time.Now().Add(30 * time.Second); time.Now().Before(end); time.Sleep(50 * time.Millisecond) {
if b, err := os.ReadFile(path); err == nil && len(b) > 0 {
return strings.TrimSpace(string(b))
}
}
t.Fatalf("after 30s, %s never happened", what)
return ""
}
var shortWaits = []string{"0.1", "0.1", "0.1"}
// The report after fb23bca5c (molvqingtai): with the screen locked, magpie
// updated itself and still never came back, though open was tried for
// 13s. Every open is refused here, as LaunchServices refused them; once
// the tries are spent the bundle's own program is run, by its path, with
// tray when no window was up, and the window's gui when one was.
func TestRelaunchStartsTheBundleWhenOpenNeverWorks(t *testing.T) {
for _, c := range []struct {
window bool
args string
}{{false, "tray"}, {true, "gui"}} {
dir := fakeOpen(t, 1000)
bundle, started := fakeBundle(t, "magpie")
log := filepath.Join(t.TempDir(), relaunchLogName)
if err := runAfterExit(gonePid(t), relaunchScript(bundle, c.window, log, shortWaits)); err != nil {
t.Fatal(err)
}
if got := waitFor(t, started, "the new version starting"); got != c.args {
t.Errorf("window %v: started with %q, want %q", c.window, got, c.args)
}
if n := tries(dir); n != len(shortWaits)+1 {
t.Errorf("window %v: open tried %d times before the fallback, want %d", c.window, n, len(shortWaits)+1)
}
if _, err := os.Stat(filepath.Join(dir, "opened")); err == nil {
t.Errorf("window %v: the fake open says it opened", c.window)
}
}
}
// runScript runs the relaunch's shell to its end, as runAfterExit's shell
// would once magpie is gone, and says how it exited.
func runScript(t *testing.T, script string) error {
t.Helper()
c := exec.Command("/bin/sh", "-c", script)
if err := c.Start(); err != nil {
t.Fatal(err)
}
done := make(chan error, 1)
go func() { done <- c.Wait() }()
select {
case err := <-done:
return err
case <-time.After(30 * time.Second):
c.Process.Kill()
<-done
t.Fatal("the relaunch shell was still running after 30s")
}
return nil
}
// Each try is written down, open's exit status and what it said with it,
// and the start it fell back to: the next report says what happened.
func TestRelaunchLogsEachTry(t *testing.T) {
fakeOpen(t, 1000)
bundle, started := fakeBundle(t, "magpie")
log := filepath.Join(t.TempDir(), relaunchLogName)
if err := runScript(t, relaunchScript(bundle, false, log, shortWaits)); err != nil {
t.Fatalf("the shell: %v", err)
}
waitFor(t, started, "the new version starting")
b, err := os.ReadFile(log)
if err != nil {
t.Fatal(err)
}
got := string(b)
for _, want := range []string{
"opening " + bundle,
"open try 1: exit 1 _LSOpenURLsWithCompletionHandler() failed for the application " + bundle + " with error -600.",
"open try 4: exit 1 ",
"open gave up after 4 tries; starting '" + filepath.Join(bundle, "Contents", "MacOS", "magpie") + "' 'tray'",
} {
if !strings.Contains(got, want) {
t.Errorf("the log has no %q:\n%s", want, got)
}
}
}
// An open that works is the whole relaunch: the program isn't run beside
// it as well, and the log says the open went through.
func TestRelaunchOpenedStartsNothingElse(t *testing.T) {
dir := fakeOpen(t, 1)
bundle, started := fakeBundle(t, "magpie")
log := filepath.Join(t.TempDir(), relaunchLogName)
if err := runScript(t, relaunchScript(bundle, false, log, shortWaits)); err != nil {
t.Fatalf("opened on the second try, and the shell said %v", err)
}
if _, err := os.Stat(started); err == nil {
t.Error("open worked and the bundle's program was run as well")
}
if n := tries(dir); n != 2 {
t.Errorf("open tried %d times, want 2", n)
}
if b, _ := os.ReadFile(log); !strings.Contains(string(b), "open try 2: exit 0") {
t.Errorf("the log doesn't say the second open worked:\n%s", b)
}
}
// A bundle with no program where it should be is written down, not a
// shell that says nothing.
func TestRelaunchNoProgramIsLogged(t *testing.T) {
fakeOpen(t, 1000)
bundle, _ := fakeBundle(t, "magpie")
exe := filepath.Join(bundle, "Contents", "MacOS", "magpie")
os.Remove(exe)
log := filepath.Join(t.TempDir(), relaunchLogName)
if err := runScript(t, relaunchScript(bundle, false, log, shortWaits)); err == nil {
t.Error("nothing started, and the shell said it did")
}
if b, _ := os.ReadFile(log); !strings.Contains(string(b), "no executable at "+exe) {
t.Errorf("the log doesn't name the missing program:\n%s", b)
}
}
// The program is the one the bundle's Info.plist names, even where it
// isn't magpie, and a quote in the bundle's path stays in it.
func TestRelaunchRunsTheProgramInfoPlistNames(t *testing.T) {
fakeOpen(t, 1000)
bundle, started := fakeBundle(t, "magpie dev")
moved := filepath.Join(filepath.Dir(bundle), "it's magpie.app")
if err := os.Rename(bundle, moved); err != nil {
t.Fatal(err)
}
log := filepath.Join(t.TempDir(), relaunchLogName)
if err := runScript(t, relaunchScript(moved, true, log, shortWaits)); err != nil {
t.Fatalf("the shell: %v", err)
}
if got := waitFor(t, started, "the program Info.plist names starting"); got != "gui" {
t.Errorf("started with %q, want gui", got)
}
}
// The log is in magpie's own folder, where the rest of its state is, and
// is kept small: past 64KB the last one is moved aside, not added to.
func TestRelaunchLogInMagpiesFolder(t *testing.T) {
cfg := t.TempDir()
t.Setenv("XDG_CONFIG_HOME", cfg)
want := filepath.Join(cfg, "magpie", relaunchLogName)
if got := relaunchLog(); got != want {
t.Fatalf("log at %q, want %q", got, want)
}
if err := os.WriteFile(want, make([]byte, 65<<10), 0o600); err != nil {
t.Fatal(err)
}
relaunchLog()
if _, err := os.Stat(want); err == nil {
t.Error("a log past 64KB is still there to be added to")
}
if fi, err := os.Stat(want + ".old"); err != nil || fi.Size() != 65<<10 {
t.Errorf("the last log wasn't kept as .old: %v", err)
}
}
+1 -1
View File
@@ -60,7 +60,7 @@ func tries(dir string) int {
func TestRelaunchOpenTriedAgain(t *testing.T) {
dir := fakeOpen(t, 2)
bundle := filepath.Join(t.TempDir(), "magpie.app")
if err := runAfterExit(gonePid(t), relaunchCommand(bundle, false)); err != nil {
if err := runAfterExit(gonePid(t), relaunchCommand(bundle, false, filepath.Join(t.TempDir(), relaunchLogName))); err != nil {
t.Fatal(err)
}
opened := filepath.Join(dir, "opened")
+80 -4
View File
@@ -17,6 +17,7 @@ import (
"encoding/json"
"errors"
"fmt"
"html"
"io"
"io/fs"
"net/http"
@@ -352,8 +353,10 @@ func InstallAsAdmin(staged, bundle string) error {
// Relaunch opens bundle again once this process (pid) has exited: with its
// window when window is set, else only its menu bar icon (`tray`, as a
// login launch), which a restart by itself uses while no window was up.
// Each try, and what it came to, is written to relaunch.log in magpie's
// own folder.
func Relaunch(bundle string, window bool) error {
return runAfterExit(os.Getpid(), relaunchCommand(bundle, window))
return runAfterExit(os.Getpid(), relaunchCommand(bundle, window, relaunchLog()))
}
// openWaits are the pauses, in seconds, between tries of the relaunch's
@@ -363,10 +366,83 @@ func Relaunch(bundle string, window bool) error {
// once, nothing started magpie again until the user did, nine hours later.
var openWaits = []string{"0.5", "1", "1", "2", "2", "3", "4"}
// relaunchLogName is the file in magpie's folder the relaunch writes each
// try of its open to, and the start it falls back to: the shell that runs
// them has no output anyone sees, and a magpie that never came back left
// only the system log to say why.
const relaunchLogName = "relaunch.log"
// relaunchLog is the relaunch's log file, made ready to append to; once it
// is past 64KB the last one is kept as relaunch.log.old. "" when magpie's
// folder can't be made: the tries then go unwritten.
func relaunchLog() string {
h, err := appdir.Home()
if err != nil || h == "" {
return ""
}
dir := appdir.Config()
if err := os.MkdirAll(dir, 0o700); err != nil {
return ""
}
p := filepath.Join(dir, relaunchLogName)
if fi, err := os.Stat(p); err == nil && fi.Size() > 64<<10 {
os.Rename(p, p+".old")
}
return p
}
// relaunchCommand is the shell command Relaunch runs once magpie has
// exited: open, tried again while it fails.
func relaunchCommand(bundle string, window bool) string {
return retried(relaunchOpen(bundle, window), openWaits)
// exited: open, tried again while it fails, and, when it never worked,
// the bundle's own executable run straight, as the login launch agent
// runs it. With the screen locked, magpie stayed closed after an update
// even with the 13s of tries (molvqingtai, after fb23bca5c): LaunchServices
// can go on refusing the open for as long as the session is locked, and a
// program run by its path needs nothing from it to start.
func relaunchCommand(bundle string, window bool, log string) string {
return relaunchScript(bundle, window, log, openWaits)
}
// relaunchScript is relaunchCommand with the pauses between opens.
func relaunchScript(bundle string, window bool, log string, waits []string) string {
if log == "" {
log = os.DevNull
}
exe := filepath.Join(bundle, "Contents", "MacOS", bundleExecutable(bundle))
run := shellQuote(exe)
for _, a := range RelaunchArgs(window, "") {
run += " " + shellQuote(a)
}
var b strings.Builder
b.WriteString("log=" + shellQuote(log) + "; ")
b.WriteString(`note() { echo "$(date '+%Y-%m-%d %H:%M:%S %z') $*" >> "$log" 2>/dev/null; }; `)
// open's own exit status and what it said, on one line
b.WriteString(`try() { n=$((n+1)); e=$(` + relaunchOpen(bundle, window) + ` 2>&1 >/dev/null); s=$?; note "open try $n: exit $s $(printf '%s' "$e" | tr '\n' ' ')"; return $s; }; `)
b.WriteString("n=0; note " + shellQuote("magpie has exited; opening "+bundle) + "; ")
b.WriteString(retried("try", waits))
b.WriteString(" || { note \"open gave up after $n tries; starting \"" + shellQuote(run) + "; ")
b.WriteString("[ -x " + shellQuote(exe) + " ] || { note \"no executable at \"" + shellQuote(exe) + "; exit 1; }; ")
b.WriteString("exec " + run + " </dev/null >/dev/null 2>&1; }")
return b.String()
}
// bundleExecutableKey finds the program an app's Info.plist names.
var bundleExecutableKey = regexp.MustCompile(`<key>CFBundleExecutable</key>\s*<string>([^<]+)</string>`)
// bundleExecutable is the name of the program in bundle's Contents/MacOS:
// the one its Info.plist names, else this one's own when it runs from
// that bundle, else magpie.
func bundleExecutable(bundle string) string {
if b, err := os.ReadFile(filepath.Join(bundle, "Contents", "Info.plist")); err == nil {
if m := bundleExecutableKey.FindSubmatch(b); m != nil {
if name := strings.TrimSpace(html.UnescapeString(string(m[1]))); name != "" && !strings.ContainsRune(name, '/') {
return name
}
}
}
if exe, err := Executable(); err == nil && filepath.Dir(exe) == filepath.Join(bundle, "Contents", "MacOS") {
return filepath.Base(exe)
}
return "magpie"
}
// retried is a shell command that runs command until it succeeds, sleeping