update: a Mac update no longer leaves a second magpie in Spotlight (#3965)

Stage unpacked the new app to /Applications/.magpie-update/app/magpie.app
and Install moved the old one to .magpie-update/old.app. LaunchServices
registers a folder ending in .app in /Applications within seconds, and
Install only deleted the folder, so Spotlight kept listing the gone path
as another magpie.

- Stage ditto's the zip (one top folder, magpie.app, checked against the
  real v0.1.2119 zip: no FinderInfo bundle bit, no __MACOSX) into
  .magpie-update/unzip and renames magpie.app to .magpie-update/payload
  at once, then has lsregister -u forget the unzip path in case it was
  seen in that moment. codesign verifies a bundle named payload the same
  (checked on the real zip: verify ok, a tampered copy fails).
- Install and InstallAsAdmin move the old app to <stage>/old, and remove
  filepath.Dir(staged), which is still .magpie-update (or the cache's
  update folder on the admin path); renames stay on one volume.
- ForgetOldStaging runs once from the GUI's updater start, in a
  goroutine: lsregister -u on .magpie-update/app/magpie.app and
  .magpie-update/old.app beside the app and in ~/Library/Caches/magpie/
  update. lsregister is /System/Library/Frameworks/CoreServices.framework/
  Frameworks/LaunchServices.framework/Support/lsregister (present on
  macOS 27.2); failures are ignored, a 10s cap, marker in magpie's cache.
  /Volumes/magpie (an old DMG) is left alone.

Run at this head (base ffa07395e):
- mote (macOS 27.2): gofmt -l clean; go build, GOOS=windows go build,
  GOOS=linux go build -tags nogui; go vet, GOOS=windows go vet and
  GOOS=linux go vet -tags nogui on internal/update, internal/gui,
  internal/cli; go test internal/update internal/gui internal/proc
  internal/appdir: build and vet ok;
  update, proc, appdir ok; gui FAIL only in TestMainWindowCorners/
  macOS_26_SDK (the titlebar toolbar on macOS 27), already filed as
  #3949 and not in code this touches
- win-run (xiaomi-gpu, Windows 11): go test ./internal/update ok.
- wsl-run (magpie-desktop): go test ./internal/update ok.
- Real LaunchServices on mote, a fake bundle id (com.example...) in
  /Applications/lstest-3965, not magpie.app: the old flow by hand
  registered .magpie-update/app/magpie.app within 30s and kept it after
  the folder was deleted. A throwaway test running this Stage + Install
  with the real lsregister: after 45s staged and 15s installed,
  lsregister -dump shows only lstest-3965/magpie.app; with stagedName
  set back to magpie.app the same run shows .magpie-update/magpie.app
  registered (red). ForgetOldStaging with the real lsregister removed
  both registered .magpie-update paths after their folders were deleted.
  Everything registered was unregistered and the folder removed.

Broken by hand, each red: asideName "old.app" (TestInstallAsAdminAside-
IsNoApp), stagedName "magpie.app" (TestInstallStagesNoApp, TestStage-
UnpacksNoApp), RemoveAll two folders up as before (TestInstallStagesNoApp:
the Applications folder went with it), no unregister of the unzip path
(TestStageUnpacksNoApp), no marker (TestForgetOldStaging).

Not tried: a real magpie update of the installed /Applications/magpie.app
with Spotlight's UI (the fake bundle stood in), the administrator-password
path for real, the full go test ./... suite.
This commit is contained in:
yetone
2026-10-30 09:23:35 +08:00
parent ffa07395eb
commit eed140c4d9
5 changed files with 291 additions and 9 deletions
+3
View File
@@ -129,6 +129,9 @@ func updateDue(s settings.Settings, last, now time.Time) bool {
func (u *updater) start() {
u.place(runtime.GOOS, update.GUI)
if u.bundle != "" {
go update.ForgetOldStaging(u.bundle) // #3965
}
go func() {
time.Sleep(5 * time.Second) // let the app settle first
for {
+2 -2
View File
@@ -43,7 +43,7 @@ func TestInstallNeedsAdmin(t *testing.T) {
apps := filepath.Join(root, "Applications")
bundle := filepath.Join(apps, "magpie.app")
app(t, bundle, "old")
staged := filepath.Join(root, "cache", "app", "magpie.app")
staged := filepath.Join(root, "cache", "update", stagedName)
app(t, staged, "new")
os.Chmod(apps, 0o555)
defer os.Chmod(apps, 0o755)
@@ -67,7 +67,7 @@ func TestSwapScript(t *testing.T) {
t.Skip("the swap runs as root under /bin/sh, on a Mac or Linux")
}
dir := filepath.Join(t.TempDir(), `it's "a" \ $(dir) `)
bundle, staged, old := filepath.Join(dir, "magpie.app"), filepath.Join(dir, "s", "magpie.app"), filepath.Join(dir, "s", "old.app")
bundle, staged, old := filepath.Join(dir, "magpie.app"), filepath.Join(dir, "s", stagedName), filepath.Join(dir, "s", asideName)
app(t, bundle, "old")
app(t, staged, "new")
if b, err := exec.Command("/bin/sh", "-c", swapScript(staged, bundle, old)).CombinedOutput(); err != nil {
+57
View File
@@ -0,0 +1,57 @@
package update
import (
"context"
"os"
"path/filepath"
"runtime"
"time"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/proc"
)
// lsregister is the tool that edits LaunchServices' list of apps; -u on a
// path takes that path off the list, whether or not it still exists.
const lsregister = "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister"
// unregister has LaunchServices forget an app at path, as best it can: a
// missing tool or a failure leaves things as they were, and never holds
// an update up for long. Tests stand in for it.
var unregister = func(path string) {
if runtime.GOOS != "darwin" {
return
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
proc.CommandContext(ctx, lsregister, "-u", path).Run()
}
// forgotMarker, in magpie's cache, records that ForgetOldStaging has run.
const forgotMarker = "launchservices-forgot-staging"
// ForgetOldStaging has LaunchServices forget the apps updates before
// #3965 left on its list: the new version unpacked as
// .magpie-update/app/magpie.app and the old one moved aside to
// .magpie-update/old.app, beside bundle or in magpie's cache. Their
// folders are gone, but Spotlight listed each as another magpie. It runs
// once, and nothing waits on it.
func ForgetOldStaging(bundle string) {
if runtime.GOOS != "darwin" || bundle == "" {
return
}
marker := filepath.Join(appdir.Cache(), forgotMarker)
if _, err := os.Stat(marker); err == nil {
return
}
dirs := []string{filepath.Join(filepath.Dir(bundle), ".magpie-update")}
if cache, err := appdir.SystemCache(); err == nil {
dirs = append(dirs, filepath.Join(cache, "update"))
}
for _, d := range dirs {
unregister(filepath.Join(d, "app", "magpie.app"))
unregister(filepath.Join(d, "old.app"))
}
os.MkdirAll(filepath.Dir(marker), 0o755)
os.WriteFile(marker, nil, 0o644)
}
+202
View File
@@ -0,0 +1,202 @@
package update
import (
"context"
"crypto/sha256"
"encoding/hex"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/appdir"
)
// noApps fails when any path under dir is named like an app: LaunchServices
// registers such a folder as another magpie, and Spotlight lists it after
// it is deleted (#3965).
func noApps(t *testing.T, dir string) {
t.Helper()
filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error {
if err == nil && strings.HasSuffix(d.Name(), ".app") {
t.Errorf("%s is named like an app", p)
}
return nil
})
}
// stubUnregister records what LaunchServices is told to forget, instead of
// telling it.
func stubUnregister(t *testing.T) *[]string {
t.Helper()
var got []string
was := unregister
unregister = func(p string) { got = append(got, p) }
t.Cleanup(func() { unregister = was })
return &got
}
// Install moves the old app aside and the staged one in under names that
// aren't an app's, then removes the staging folder and nothing beside it.
func TestInstallStagesNoApp(t *testing.T) {
apps := filepath.Join(t.TempDir(), "Applications")
bundle := filepath.Join(apps, "magpie.app")
app(t, bundle, "old")
app(t, filepath.Join(apps, "Other.app"), "other")
staged := filepath.Join(stageDir(apps), stagedName)
app(t, staged, "new")
noApps(t, filepath.Join(apps, ".magpie-update"))
if err := Install(staged, bundle); err != nil {
t.Fatal(err)
}
if version(t, bundle) != "new" {
t.Error("the new app isn't in place")
}
if _, err := os.Stat(filepath.Join(apps, "Other.app")); err != nil {
t.Errorf("Install removed an app beside magpie: %v", err)
}
if _, err := os.Stat(filepath.Join(apps, ".magpie-update")); !os.IsNotExist(err) {
t.Errorf(".magpie-update is left: %v", err)
}
}
// InstallAsAdmin moves the old app aside to a name that isn't an app's.
func TestInstallAsAdminAsideIsNoApp(t *testing.T) {
if runtime.GOOS != "darwin" {
t.Skip("osascript")
}
defer func(r func(string, ...string) ([]byte, error)) { run = r }(run)
var script string
run = func(name string, args ...string) ([]byte, error) {
script = args[len(args)-1]
return nil, nil
}
cache := filepath.Join(t.TempDir(), "update")
if err := InstallAsAdmin(filepath.Join(cache, stagedName), "/Applications/magpie.app"); err != nil {
t.Fatal(err)
}
if !strings.Contains(script, appleString(shellQuote(filepath.Join(cache, asideName)))) {
t.Errorf("the swap doesn't move the app aside to %s: %s", asideName, script)
}
if strings.Count(script, ".app") != strings.Count(script, "/Applications/magpie.app") {
t.Errorf("the swap names another app: %s", script)
}
}
// fakeApp makes an ad-hoc signed app bundle at path, with a bundle id of
// its own so LaunchServices never mixes it up with magpie.
func fakeApp(t *testing.T, path, v string) {
t.Helper()
if err := os.MkdirAll(filepath.Join(path, "Contents", "MacOS"), 0o755); err != nil {
t.Fatal(err)
}
plist := `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>CFBundleIdentifier</key><string>com.example.magpie-update-test</string>
<key>CFBundleExecutable</key><string>magpie</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleShortVersionString</key><string>` + v + `</string>
</dict></plist>
`
if err := os.WriteFile(filepath.Join(path, "Contents", "Info.plist"), []byte(plist), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(path, "Contents", "MacOS", "magpie"), []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
t.Fatal(err)
}
if b, err := exec.Command("codesign", "-s", "-", "--force", path).CombinedOutput(); err != nil {
t.Fatalf("codesign: %v: %s", err, b)
}
}
// Stage unpacks the release's magpie.app (the zip's one top folder, as
// the release builds it) to a name that isn't an app's, tells
// LaunchServices to forget the name it was unpacked under, and Install
// puts it in place.
func TestStageUnpacksNoApp(t *testing.T) {
if runtime.GOOS != "darwin" {
t.Skip("ditto and codesign")
}
forgot := stubUnregister(t)
root := t.TempDir()
src := filepath.Join(root, "src")
fakeApp(t, filepath.Join(src, "magpie.app"), "2.0")
zip := filepath.Join(root, "a.zip")
cmd := exec.Command("ditto", "-c", "-k", "--keepParent", "magpie.app", zip)
cmd.Dir = src
if b, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("ditto: %v: %s", err, b)
}
body, err := os.ReadFile(zip)
if err != nil {
t.Fatal(err)
}
sum := sha256.Sum256(body)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write(body) }))
defer srv.Close()
apps := filepath.Join(root, "Applications")
bundle := filepath.Join(apps, "magpie.app")
fakeApp(t, bundle, "1.0")
rel := &Release{Version: "2.0", Assets: map[string]Asset{AppAsset(): {URL: srv.URL, SHA256: hex.EncodeToString(sum[:])}}}
staged, err := Stage(context.Background(), rel, bundle)
if err != nil {
t.Fatal(err)
}
stage := filepath.Join(apps, ".magpie-update")
if staged != filepath.Join(stage, stagedName) {
t.Errorf("staged at %s", staged)
}
noApps(t, stage)
if want := filepath.Join(stage, "unzip", "magpie.app"); !slices.Contains(*forgot, want) {
t.Errorf("LaunchServices was told to forget %q, want %s", *forgot, want)
}
if err := Install(staged, bundle); err != nil {
t.Fatal(err)
}
if b, _ := os.ReadFile(filepath.Join(bundle, "Contents", "Info.plist")); !strings.Contains(string(b), "<string>2.0</string>") {
t.Error("the new app isn't in place")
}
if _, err := os.Stat(stage); !os.IsNotExist(err) {
t.Errorf(".magpie-update is left: %v", err)
}
}
// ForgetOldStaging tells LaunchServices to forget where earlier updates
// unpacked the new app and moved the old one aside, beside the app and in
// the cache, once.
func TestForgetOldStaging(t *testing.T) {
if runtime.GOOS != "darwin" {
t.Skip("LaunchServices")
}
forgot := stubUnregister(t)
marker := filepath.Join(appdir.Cache(), forgotMarker)
os.Remove(marker)
t.Cleanup(func() { os.Remove(marker) })
cache, err := appdir.SystemCache()
if err != nil {
t.Fatal(err)
}
ForgetOldStaging("/Applications/magpie.app")
want := []string{
"/Applications/.magpie-update/app/magpie.app",
"/Applications/.magpie-update/old.app",
filepath.Join(cache, "update", "app", "magpie.app"),
filepath.Join(cache, "update", "old.app"),
}
if !slices.Equal(*forgot, want) {
t.Errorf("forgot %q, want %q", *forgot, want)
}
*forgot = nil
ForgetOldStaging("/Applications/magpie.app")
if len(*forgot) != 0 {
t.Errorf("forgot %q again", *forgot)
}
}
+27 -7
View File
@@ -258,7 +258,8 @@ func Writable(dir string) bool {
}
// Stage downloads the app in rel and unpacks it next to the installed
// bundle, ready for Install. It returns the unpacked app.
// bundle, ready for Install. It returns the unpacked app, a bundle whose
// folder is named stagedName.
func Stage(ctx context.Context, rel *Release, bundle string) (string, error) {
a, ok := rel.Assets[AppAsset()]
if !ok {
@@ -274,13 +275,23 @@ func Stage(ctx context.Context, rel *Release, bundle string) (string, error) {
os.RemoveAll(dir)
return "", err
}
out := filepath.Join(dir, "app")
out := filepath.Join(dir, "unzip")
if b, err := proc.CommandContext(ctx, "ditto", "-x", "-k", zip, out).CombinedOutput(); err != nil {
os.RemoveAll(dir)
return "", fmt.Errorf("unzip: %v: %s", err, b)
}
os.Remove(zip)
app := filepath.Join(out, "magpie.app")
// the zip holds magpie.app, which leaves that name at once: a folder
// ending in .app beside the installed one is taken by LaunchServices
// for a second magpie, and Spotlight lists it after it is gone (#3965)
unzipped := filepath.Join(out, "magpie.app")
app := filepath.Join(dir, stagedName)
if err := os.Rename(unzipped, app); err != nil {
os.RemoveAll(dir)
return "", err
}
os.Remove(out)
unregister(unzipped) // in case it looked in that moment
if err := sameSigner(ctx, bundle, app); err != nil {
os.RemoveAll(dir)
return "", err
@@ -311,6 +322,15 @@ func team(ctx context.Context, app string) string {
return ""
}
// stagedName is what the new app is unpacked as in stageDir, and asideName
// what the installed one is moved to while they are swapped. Neither ends
// in .app, so LaunchServices never registers either as a second magpie
// (#3965); the renames don't need the name, and stay on one volume.
const (
stagedName = "payload"
asideName = "old"
)
// stageDir is where an update is unpacked: beside what it replaces, so
// installing it is a rename on one volume, or, where magpie may not write,
// in its cache, to be moved in with the administrator's password.
@@ -328,7 +348,7 @@ func stageDir(dir string) string {
// magpie's to change the error is a permission one (NeedsAdmin), and
// InstallAsAdmin can do it instead.
func Install(staged, bundle string) error {
old := filepath.Join(filepath.Dir(staged), "old.app")
old := filepath.Join(filepath.Dir(staged), asideName)
os.RemoveAll(old)
if err := os.Rename(bundle, old); err != nil {
return err
@@ -337,17 +357,17 @@ func Install(staged, bundle string) error {
os.Rename(old, bundle) // put it back
return err
}
os.RemoveAll(filepath.Dir(filepath.Dir(staged))) // .magpie-update
os.RemoveAll(filepath.Dir(staged)) // .magpie-update
return nil
}
// InstallAsAdmin is Install with the administrator's password, asked for
// by the system.
func InstallAsAdmin(staged, bundle string) error {
old := filepath.Join(filepath.Dir(staged), "old.app")
old := filepath.Join(filepath.Dir(staged), asideName)
err := asAdmin(swapScript(staged, bundle, old))
if err == nil {
os.RemoveAll(filepath.Dir(filepath.Dir(staged)))
os.RemoveAll(filepath.Dir(staged))
}
return err
}