update: a Windows magpie on the Desktop leaves no magpie.exe.new or magpie.com there

nianshou5 on Discord (#help, Windows): magpie.com and magpie.exe.new
showed on the Desktop and came back after being deleted. Both were
written beside magpie.exe:

- magpie.exe.new is the update the GUI downloads as soon as it is out
  and swaps in at the next restart. StageBinary put it beside the
  program whenever that folder was writable, so it sat on the Desktop
  until a restart, and a deleted one was downloaded again by the next
  check.
- magpie.com (#3737) is written at every start while the app's folder
  is on PATH, and Settings > Command line's Add puts that folder on
  PATH, so deleting it on the Desktop lasted until the next start.

Now:

- StageBinary downloads into magpie's cache, in a folder of this
  program's own (update/<hash of the exe path>), when a rename from
  there reaches the program's folder (renamesInto, a real probe: the
  swap must stay one rename on one volume). With the cache on another
  volume it goes into a hidden .magpie-update folder beside the program
  (FILE_ATTRIBUTE_HIDDEN on Windows). A folder magpie may not write is
  unchanged (cache, moved in as administrator). The stage folder is
  removed after the swap or a failed download.
- At start RemoveStaleNew looks in every place a download may be,
  magpie.exe.new beside the program included, and removes one no newer
  than the running version (same bytes, or an older file version); a
  newer one stays, as before.
- Settled (the installed copy opened from a Desktop/Downloads one)
  also removes the update downloaded for that one, which nothing will
  put in now.
- In a download folder (Desktop, Downloads, a temp folder, as
  isDownloadFolder already says) a start only keeps an existing
  magpie.com up to date and never writes a missing one; Add still
  writes it. Any other folder on PATH is as before. A Desktop
  magpie.exe that opens the installed one (Settle) already wrote none.

Run:
- Windows (win-run, xiaomi-gpu, sandbox HOME from testenv), a repro
  test with the running test binary standing for magpie.exe on a
  Desktop on PATH: at origin/main 72ed121fd StageBinary staged
  test.test.exe.new beside it, and magpie.com came back after delete +
  start; with this change the download was in
  AppData\Local\magpie\update\<hash>\ and magpie.com stayed gone.
- Windows: a real program (whoami.exe) staged into the cache passed the
  real trial start (canStart) and was swapped in for a Desktop
  magpie.exe with the real moveAside/moveIn; the stage folder was gone
  after.
- At the pushed head (rebased on d6beb9975): go test ./internal/update
  on mote and on Windows: ok. Before the rebase also on Linux (wsl-run). gofmt, go vet ./internal/update (darwin, linux, windows),
  GOOS=windows go vet ./internal/gui ./internal/cli: clean.
- go test ./internal/gui ./internal/cli on Windows: TestUpdateThatWontStart,
  TestLodyImportHandoff, TestImportStatusUnreadableIsUnknown,
  TestAionUiImportRow (#4115), TestGatewayHeldByAContainer (#2107,
  #3649) and TestLibraryMCPHub (#4140) red, the same 6 when run at
  origin/main 72ed121fd.
- Full suite on mote (-timeout 45m): started at the pre-rebase tree
  (same update changes, base 72ed121fd) and still running at push; its
  result and any red go in a follow-up.

Broken by hand: staging back beside the exe, the download-folder rule
in EnsureCompanion off, removeStaged out of Settled: the new tests
(TestUpdateStagedOutOfTheProgramsFolder, TestUpdateStagedHiddenWithoutTheCache,
TestStartClearsAnOlderDownloadBeside, TestNoCompanionPutBackOnTheDesktop,
TestSettledClearsOnlyMagpiesFiles, TestNoCompanionBesideAForwardingDownload)
went red.

Not tried: a real GUI self-update of a release build on the Windows
desktop, a cache and Desktop on separate real volumes (the hidden
fallback was tested with no cache), the reporter's own machine, and a
real terminal's `magpie` (unchanged code outside download folders).
This commit is contained in:
yetone
2026-10-31 00:21:26 +08:00
parent d6beb9975a
commit 482e883142
10 changed files with 402 additions and 25 deletions
+11 -2
View File
@@ -20,7 +20,8 @@ import (
//
// It is written wherever a terminal runs magpie from: when the app's
// folder is on PATH, where Settings › Command line puts it, or a magpie.com
// or magpie.cmd is there already. The app writes it again as it starts
// or magpie.cmd is there already. On the Desktop or in Downloads only Add
// writes it, and a start only keeps one there up to date. The app writes it again as it starts
// when its bytes differ, so an update brings it along. They differ only
// when the launcher does: it is built without the release's commit in it
// (the Makefile's -buildvcs=false), or every update wrote a new magpie.com
@@ -107,7 +108,15 @@ func EnsureCompanion(exe string) error {
return nil
}
dir := filepath.Dir(exe)
if !onPath(dir, os.Getenv("PATH")) && !exists(filepath.Join(dir, comName)) && !exists(filepath.Join(dir, shimName)) {
if downloadFolder(dir) {
// the Desktop or Downloads, which the user sees: one there is
// kept up to date, never put back once deleted (nianshou5 on
// Discord: it came back on every start, the Desktop being on
// PATH). Settings › Command line's Add still writes it.
if !exists(filepath.Join(dir, comName)) {
return nil
}
} else if !onPath(dir, os.Getenv("PATH")) && !exists(filepath.Join(dir, comName)) && !exists(filepath.Join(dir, shimName)) {
return nil
}
_, err := writeCom(comLauncher, exe)
+5 -2
View File
@@ -88,8 +88,11 @@ func TestComOwner(t *testing.T) {
// EnsureCompanion writes where a terminal runs magpie from, and nowhere
// else: a downloads folder off PATH gets nothing.
func TestEnsureCompanion(t *testing.T) {
old := comLauncher
t.Cleanup(func() { comLauncher = old })
old, wasDL := comLauncher, downloadFolder
t.Cleanup(func() { comLauncher, downloadFolder = old, wasDL })
// on Windows a temporary folder counts as a download folder, which
// gets one only from Add (TestNoCompanionPutBackOnTheDesktop)
downloadFolder = func(string) bool { return false }
sep := string(os.PathListSeparator)
comLauncher = nil
@@ -0,0 +1,10 @@
//go:build !windows
package update
import (
"path/filepath"
"strings"
)
func hiddenForTest(p string) bool { return strings.HasPrefix(filepath.Base(p), ".") }
+209
View File
@@ -0,0 +1,209 @@
package update
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"testing"
)
// desktopFixture is magpie.exe on a Desktop, with magpie's cache
// elsewhere and a release asset to download.
type desktopFixture struct {
desktop, exe, cache string
asset Asset
body []byte
}
func newDesktopFixture(t *testing.T) *desktopFixture {
t.Helper()
root := t.TempDir()
f := &desktopFixture{
desktop: filepath.Join(root, "Desktop"),
cache: filepath.Join(root, "Local", "magpie"),
body: []byte("MZ the next version"),
}
f.exe = filepath.Join(f.desktop, "magpie.exe")
if err := os.MkdirAll(f.desktop, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(f.exe, []byte("MZ this version"), 0o755); err != nil {
t.Fatal(err)
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write(f.body) }))
t.Cleanup(srv.Close)
sum := sha256.Sum256(f.body)
f.asset = Asset{URL: srv.URL, SHA256: hex.EncodeToString(sum[:])}
was, wasStart := stageCache, canStart
t.Cleanup(func() { stageCache, canStart = was, wasStart })
stageCache = func() (string, error) { return f.cache, nil }
canStart = func(string) error { return nil }
return f
}
// what is in the Desktop besides magpie.exe and what an update moved
// aside (removed at the next start, RemoveOld)
func (f *desktopFixture) beside(t *testing.T) []string {
t.Helper()
es, err := os.ReadDir(f.desktop)
if err != nil {
t.Fatal(err)
}
var out []string
for _, e := range es {
if n := e.Name(); n != "magpie.exe" && n != "magpie.exe.old" {
out = append(out, n)
}
}
return out
}
// An update waiting for the next restart is downloaded to magpie's cache,
// not beside the program as magpie.exe.new, which showed on a Desktop and
// came back after it was deleted (nianshou5 on Discord). The swap still
// puts it in, and leaves nothing of the download behind.
func TestUpdateStagedOutOfTheProgramsFolder(t *testing.T) {
f := newDesktopFixture(t)
staged, err := stageBinaryFor(context.Background(), f.asset, f.exe)
if err != nil {
t.Fatal(err)
}
if got := f.beside(t); len(got) != 0 {
t.Fatalf("beside magpie.exe while the update waits: %v", got)
}
if !inFolder(staged, f.cache) {
t.Fatalf("staged at %s, not in the cache %s", staged, f.cache)
}
if _, err := InstallBinaryAside(staged, f.exe); err != nil {
t.Fatal(err)
}
if b, _ := os.ReadFile(f.exe); string(b) != string(f.body) {
t.Fatalf("magpie.exe after the swap: %q", b)
}
if got := f.beside(t); len(got) != 0 {
t.Fatalf("beside magpie.exe after the swap: %v", got)
}
if es, _ := os.ReadDir(filepath.Join(f.cache, "update")); len(es) != 0 {
t.Fatalf("left in the cache: %v", es)
}
}
// With no cache a rename reaches (another volume), the download goes into
// a hidden folder beside the program, which the swap removes.
func TestUpdateStagedHiddenWithoutTheCache(t *testing.T) {
f := newDesktopFixture(t)
stageCache = func() (string, error) { return "", errors.New("no cache") }
staged, err := stageBinaryFor(context.Background(), f.asset, f.exe)
if err != nil {
t.Fatal(err)
}
if want := filepath.Join(f.desktop, besideStage, "magpie.exe.new"); staged != want {
t.Fatalf("staged at %s, want %s", staged, want)
}
if got := f.beside(t); !slices.Equal(got, []string{besideStage}) {
t.Fatalf("beside magpie.exe while the update waits: %v", got)
}
if !hiddenForTest(filepath.Join(f.desktop, besideStage)) {
t.Fatal(besideStage + " isn't hidden")
}
if _, err := InstallBinaryAside(staged, f.exe); err != nil {
t.Fatal(err)
}
if got := f.beside(t); len(got) != 0 {
t.Fatalf("beside magpie.exe after the swap: %v", got)
}
}
// A download a failed restart keeps for the next try stays where it was
// staged, out of sight; a failed download leaves nothing.
func TestFailedDownloadLeavesNothing(t *testing.T) {
f := newDesktopFixture(t)
quickRetries(t)
f.asset.SHA256 = "00"
if _, err := stageBinaryFor(context.Background(), f.asset, f.exe); err == nil {
t.Fatal("a download that doesn't match its checksum was staged")
}
if got := f.beside(t); len(got) != 0 {
t.Fatalf("beside magpie.exe: %v", got)
}
if es, _ := os.ReadDir(filepath.Join(f.cache, "update")); len(es) != 0 {
t.Fatalf("left in the cache: %v", es)
}
}
// What an earlier version downloaded beside the program (magpie.exe.new)
// goes at the next start once it is no newer than the program: an older
// version, or this one over again. A newer one, which a magpie still
// running may put in, stays.
func TestStartClearsAnOlderDownloadBeside(t *testing.T) {
f := newDesktopFixture(t)
saved := fileVersion
t.Cleanup(func() { fileVersion = saved })
versions := map[string]uint64{f.exe: 5}
fileVersion = func(p string) uint64 { return versions[p] }
left := f.exe + ".new"
os.WriteFile(left, []byte("MZ an older one"), 0o755)
versions[left] = 4
RemoveStaleNew(f.exe)
if exists(left) {
t.Fatal("an older magpie.exe.new was kept")
}
os.WriteFile(left, []byte("MZ a newer one"), 0o755)
versions[left] = 6
RemoveStaleNew(f.exe)
if !exists(left) {
t.Fatal("a newer magpie.exe.new was removed")
}
// the same in the cache
staged, err := stageBinaryFor(context.Background(), f.asset, f.exe)
if err != nil {
t.Fatal(err)
}
versions[staged] = 5
RemoveStaleNew(f.exe)
if exists(staged) || exists(filepath.Dir(staged)) {
t.Fatal("a download of this version was kept in the cache")
}
}
// A start of a magpie on the Desktop doesn't put magpie.com back there
// once deleted, though the Desktop is on PATH; one there is kept up to
// date, and Add (cliPlace's writeCom) still writes it.
func TestNoCompanionPutBackOnTheDesktop(t *testing.T) {
f := newDesktopFixture(t)
was, wasDL, wasTo := comLauncher, downloadFolder, installTarget
t.Cleanup(func() { comLauncher, downloadFolder, installTarget = was, wasDL, wasTo })
comLauncher = []byte("MZ launcher")
downloadFolder = func(dir string) bool { return samePath(dir, f.desktop) }
installTarget = func() string { return "" } // runs where it is (portable, MAGPIE_NO_INSTALL)
t.Setenv("PATH", f.desktop)
com := filepath.Join(f.desktop, comName)
if err := EnsureCompanion(f.exe); err != nil || exists(com) {
t.Fatalf("magpie.com written on the Desktop: %v", err)
}
if _, err := writeCom([]byte("MZ older launcher"), f.exe); err != nil {
t.Fatal(err)
}
if err := EnsureCompanion(f.exe); err != nil || !comRuns(com, f.exe) {
t.Fatalf("magpie.com there not kept: %v", err)
}
if b, _ := os.ReadFile(com); string(b) != string(comText(comLauncher, f.exe)) {
t.Fatal("magpie.com there not brought up to date")
}
os.Remove(com)
if err := EnsureCompanion(f.exe); err != nil || exists(com) {
t.Fatalf("a deleted magpie.com came back: %v", err)
}
// a folder of the user's own on PATH is as before
other := filepath.Join(t.TempDir(), "magpie.exe")
t.Setenv("PATH", filepath.Dir(other))
if err := EnsureCompanion(other); err != nil || !exists(filepath.Join(filepath.Dir(other), comName)) {
t.Fatalf("magpie.com not written in a folder of the user's on PATH: %v", err)
}
}
@@ -0,0 +1,12 @@
package update
import "golang.org/x/sys/windows"
func hiddenForTest(p string) bool {
u, err := windows.UTF16PtrFromString(p)
if err != nil {
return false
}
a, err := windows.GetFileAttributes(u)
return err == nil && a&windows.FILE_ATTRIBUTE_HIDDEN != 0
}
+4 -1
View File
@@ -210,7 +210,7 @@ func Forward(from, to string) error {
// Settled clears, in the installed magpie Forward opened, what magpie left
// beside the exe it was installed from: what updates moved aside there,
// and the magpie.com or magpie.cmd magpie wrote there to run it, which
// an update downloaded for it (magpie.exe.new), and the magpie.com or magpie.cmd magpie wrote there to run it, which
// the `magpie` on PATH is now. A file it didn't write, or wrote for
// another program, is left.
func Settled() {
@@ -224,6 +224,9 @@ func Settled() {
func clearBeside(from string) {
RemoveOld(from)
// an update the download had fetched is never put in now: the
// installed one updates itself
removeStaged(from)
dir := filepath.Dir(from)
if p := filepath.Join(dir, comName); comRuns(p, from) {
RemoveOld(p)
+3
View File
@@ -7,3 +7,6 @@ func installPath() string { return "" }
func isDownloadFolder(string) bool { return false }
func exeVersion(string) uint64 { return 0 }
func webViewDefault(string) string { return "" }
// hide does nothing: a name starting with a dot is hidden already.
func hide(string) {}
+9 -3
View File
@@ -249,9 +249,13 @@ func TestSettledClearsOnlyMagpiesFiles(t *testing.T) {
if err := os.WriteFile(f.exe+".old", []byte("MZ"), 0o755); err != nil {
t.Fatal(err)
}
// an update an older magpie downloaded beside it, never put in now
if err := os.WriteFile(f.exe+".new", []byte("MZ newer"), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv(installedFromEnv, f.exe)
Settled()
for _, p := range []string{com, filepath.Join(dir, shimName), f.exe + ".old"} {
for _, p := range []string{com, filepath.Join(dir, shimName), f.exe + ".old", f.exe + ".new"} {
if exists(p) {
t.Fatalf("%s left", filepath.Base(p))
}
@@ -356,8 +360,10 @@ func TestNoCompanionBesideAForwardingDownload(t *testing.T) {
if err := EnsureCompanion(f.exe); err != nil {
t.Fatal(err)
}
if got := exists(filepath.Join(f.downloads, comName)); got == forwards(f.exe) {
t.Fatalf("magpie.com beside the download: %v, forwarding: %v", got, forwards(f.exe))
// nor one that runs where it is: a download folder gets one only from
// Add (TestNoCompanionPutBackOnTheDesktop)
if exists(filepath.Join(f.downloads, comName)) {
t.Fatalf("magpie.com beside the download, forwarding: %v", forwards(f.exe))
}
}
+11
View File
@@ -80,3 +80,14 @@ func webViewDefault(exe string) string {
}
return filepath.Join(a, filepath.Base(exe))
}
// hide gives p the hidden attribute, which Explorer leaves out of view.
func hide(p string) {
u, err := windows.UTF16PtrFromString(p)
if err != nil {
return
}
if a, err := windows.GetFileAttributes(u); err == nil {
windows.SetFileAttributes(u, a|windows.FILE_ATTRIBUTE_HIDDEN)
}
}
+128 -17
View File
@@ -526,8 +526,8 @@ func ReplaceBinary(ctx context.Context, rel *Release) error {
return err
}
// StageBinary downloads the release's build for this binary next to it (or
// to the cache, where magpie may not write there), ready for InstallBinary.
// StageBinary downloads the release's build for this binary out of sight
// (binaryStage), ready for InstallBinary.
func StageBinary(ctx context.Context, rel *Release) (string, error) {
a, ok := rel.Assets[BinaryAsset()]
if !ok {
@@ -537,24 +537,119 @@ func StageBinary(ctx context.Context, rel *Release) (string, error) {
if err != nil {
return "", err
}
tmp := exe + ".new"
if !Writable(filepath.Dir(exe)) {
dir := stageDir(filepath.Dir(exe))
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", err
}
tmp = filepath.Join(dir, filepath.Base(exe)+".new")
return stageBinaryFor(ctx, a, exe)
}
func stageBinaryFor(ctx context.Context, a Asset, exe string) (string, error) {
tmp, err := binaryStage(exe)
if err != nil {
return "", err
}
if err := download(ctx, a, tmp); err != nil {
dropStage(tmp)
return "", err
}
if err := os.Chmod(tmp, 0o755); err != nil {
os.Remove(tmp)
dropStage(tmp)
return "", err
}
return tmp, nil
}
// The GUI downloads an update when it is out and swaps it in at the next
// restart, which may be days later. It was downloaded beside the program
// as magpie.exe.new, so a magpie kept on the Desktop showed the download
// there, and deleted, it came back with the next check (nianshou5 on
// Discord). It is downloaded to magpie's cache now, in a folder of this
// program's own, whenever a rename from there reaches the program's
// folder, which is what puts it in; else (the cache on another volume)
// into a hidden .magpie-update folder beside the program. Where magpie may
// not write beside the program, it goes to the cache as before, to be
// moved in with the administrator's password.
// besideStage is the hidden folder beside the program an update is
// downloaded into when no rename from the cache reaches the program.
const besideStage = ".magpie-update"
// stageCache is magpie's cache folder; tests set it.
var stageCache = appdir.SystemCache
// binaryStage is the file StageBinary downloads exe's new build to, its
// folder made.
func binaryStage(exe string) (string, error) {
dir, name := filepath.Dir(exe), filepath.Base(exe)+".new"
if !Writable(dir) {
d := stageDir(dir)
if err := os.MkdirAll(d, 0o755); err != nil {
return "", err
}
return filepath.Join(d, name), nil
}
if d := cacheStage(exe); d != "" && os.MkdirAll(d, 0o755) == nil {
if renamesInto(d, dir) {
return filepath.Join(d, name), nil
}
os.Remove(d)
}
d := filepath.Join(dir, besideStage)
if err := os.MkdirAll(d, 0o755); err != nil {
return "", err
}
hide(d)
return filepath.Join(d, name), nil
}
// cacheStage is exe's own folder in the cache for its downloads, "" with
// no cache: two copies of magpie (a portable one and the installed one)
// never share one.
func cacheStage(exe string) string {
cache, err := stageCache()
if err != nil || cache == "" {
return ""
}
sum := sha256.Sum256([]byte(strings.ToLower(filepath.Clean(exe))))
return filepath.Join(cache, "update", hex.EncodeToString(sum[:6]))
}
// renamesInto says whether a file in from can be renamed into dir: the
// same volume, which a move that can't fail half way needs.
func renamesInto(from, dir string) bool {
f, err := os.CreateTemp(from, ".magpie-update-*")
if err != nil {
return false
}
f.Close()
to := filepath.Join(dir, filepath.Base(f.Name()))
if err := os.Rename(f.Name(), to); err != nil {
os.Remove(f.Name())
return false
}
os.Remove(to)
return true
}
// dropStage removes the folder a staged download was in once it is empty,
// when it is one binaryStage made.
func dropStage(staged string) {
d := filepath.Dir(staged)
if filepath.Base(d) == besideStage || (len(filepath.Base(d)) == 12 && filepath.Base(filepath.Dir(d)) == "update") {
os.Remove(d)
}
}
// stagedFiles are the places a download of exe's next build may be: where
// binaryStage puts it, and beside exe as exe.new, where earlier versions
// put it.
func stagedFiles(exe string) []string {
name := filepath.Base(exe) + ".new"
out := []string{exe + ".new", filepath.Join(filepath.Dir(exe), besideStage, name)}
if d := cacheStage(exe); d != "" {
out = append(out, filepath.Join(d, name))
}
return out
}
// InstallBinary swaps a staged binary in for exe, the running one, which
// keeps going until it exits.
func InstallBinary(staged, exe string) error {
@@ -576,6 +671,7 @@ func InstallBinaryAside(staged, exe string) (string, error) {
if !trialled.passed(staged) {
if err := canStart(staged); err != nil {
os.Remove(staged)
dropStage(staged)
return "", &BlockedError{Err: err}
}
trialled.note(staged)
@@ -603,9 +699,11 @@ func InstallBinaryAside(staged, exe string) (string, error) {
}
} else if !NeedsAdmin(err) { // kept for InstallBinaryAsAdmin
os.Remove(staged)
dropStage(staged)
}
return "", err
}
dropStage(staged)
return old, nil
}
@@ -786,17 +884,30 @@ func Replaced(exe string, started os.FileInfo) bool {
return err == nil && started != nil && (now.Size() != started.Size() || !now.ModTime().Equal(started.ModTime()))
}
// RemoveStaleNew removes exe.new when it is exe over again: the update a
// magpie left running from before it downloaded once more.
// RemoveStaleNew removes a download of exe's next build (stagedFiles)
// that is no newer than exe: exe over again (the update a magpie left
// running from before it downloaded once more), or an older version a
// swap never put in. A newer one, which a magpie still running may yet
// put in, stays.
func RemoveStaleNew(exe string) {
staged := exe + ".new"
a, err1 := os.Stat(exe)
b, err2 := os.Stat(staged)
if err1 != nil || err2 != nil || a.Size() != b.Size() {
return
mine := fileVersion(exe)
for _, staged := range stagedFiles(exe) {
if !exists(staged) {
continue
}
if v := fileVersion(staged); sameBytes(exe, staged) || (mine != 0 && v != 0 && v <= mine) {
os.Remove(staged)
}
dropStage(staged)
}
if ha, hb := fileHash(exe), fileHash(staged); ha != "" && ha == hb {
}
// removeStaged removes every download of exe's next build: what nothing
// will put in.
func removeStaged(exe string) {
for _, staged := range stagedFiles(exe) {
os.Remove(staged)
dropStage(staged)
}
}