Files
magpie/internal/update/install_test.go
T
yetone a3b9dd1127 windows: the app opened from Downloads installs itself in Programs\magpie
lucky_eagle_38 on Discord: Windows magpie is one exe that lands in
Downloads, the user moves it around, and the `magpie` command came from
a magpie.com ("ms-dos" file) magpie wrote beside it there. They asked
for a fixed install folder, with the command coming from PATH.

Before: wherever the exe ran, the Start menu Magpie.lnk, App Paths,
Open at login (HKCU Run "magpie") and updates named it there. Settings >
Command line put that folder on the user PATH and wrote magpie.com (or
magpie.cmd) beside it, and EnsureCompanion kept writing magpie.com there.

Now (update.Settle, first thing in gui.Run): the desktop app run from
Downloads, the Desktop or a temp folder (an exe opened inside a zip)
copies itself to %LOCALAPPDATA%\Programs\magpie\magpie.exe, per-user and
with no admin. It puts that folder first on the HKCU PATH with its
magpie.com (cliPlace, with WM_SETTINGCHANGE as before) and opens the
copy (Forward waits for its MAGPIE_STARTED, then passes that on, so an
update restart waiting on the download isn't rolled back). The copy's
shortcut.Ensure re-points the Start menu lnk and App Paths. Its updates
replace the installed exe in place. The download quits.
- Run again: the download opens the installed copy. If its RT_VERSION
  is newer than the installed one, it first goes in place of that copy
  (InstallBinaryAside, as an update does). An older or unversioned
  download never replaces it.
- Open at login: the Run value is re-pointed only when it named the
  download (autostart.Repoint). Task Manager's StartupApproved off flag
  is kept.
- Leftovers beside the download (update.Settled, in the installed copy):
  - Removed: what updates moved aside (.old). Also magpie.com and
    magpie.cmd, but only when magpie wrote them for that exe (comRuns
    and shimRuns check the marker and target).
  - Never removed: the download itself and any other file.
  - EnsureCompanion writes no magpie.com beside a download that forwards.
- WebView2's profile is keyed by exe name. The old profile
  (%APPDATA%\magpie-windows-amd64.exe) is kept through a webview-profile
  note beside the install, which appdir.WebView reads. magpie uninstall
  removes that noted profile too (only a folder directly in %APPDATA%
  with an EBWebView in it).

Not moved:
- an exe in a folder the user chose (D:\Tools, a USB drive, the home
  folder, Documents, a subfolder of Downloads);
- a portable copy (a data folder or .portable beside it);
- any copy run with MAGPIE_NO_INSTALL=1;
- CLI runs (only the desktop app installs).

Left for old users: the Downloads entry an earlier Command line put on
the HKCU PATH stays. The user may have added it themselves, and it now
comes after the install folder. Taskbar pins still name the download,
which opens the installed copy.

Run:
- Real run on xiaomi-gpu (Windows 11) as a throwaway local user,
  through a scheduled task (the user is deleted now; its profile hive
  was still held at cleanup and is removed on the next unload):
  - Seeded with the real v0.1.2124 in Downloads, its folder on PATH, its
    magpie.com, a Run value with the off flag, the lnk and App Paths on
    it, a .old, a user's own magpie.cmd and notes.txt.
  - Then ran release-built (make release-windows) v0.1.2000 from
    Downloads with `tray`:
    - Programs\magpie got magpie.exe 0.1.2000, magpie.com and the note.
    - PATH is that folder first.
    - Run, lnk and App Paths now name it. The off flag is kept.
    - Downloads lost magpie.com and the .old and kept the exe, the
      user's magpie.cmd and notes.txt.
    - The download exited 0, and the installed copy ran.
  - Again: forwarded, nothing changed.
  - v0.1.2001 from Downloads: it replaced the installed 0.1.2000.
  - The registry PATH's `magpie` is Programs\magpie\magpie.com, and
    `magpie version` gives v0.1.2001.
  - Ran a copy at ~\Tools\magpie.exe: it ran there and the install was
    not touched.
  - The installed copy's `magpie update` went to the real v0.1.2126
    in place (magpie.exe.old aside).
- win-run (Windows): go test ./internal/update ./internal/autostart
  ./internal/appdir ./internal/shortcut ok. ./internal/gui has 5 reds:
  TestGatewayHeldByAContainer, TestLodyImportHandoff,
  TestImportStatusUnreadableIsUnknown, TestAionUiImportRow and
  TestUpdateThatWontStart. They fail the same alone on origin/main
  4a4a90c23 and are filed in #4115.
- mote: go vet ./..., GOOS=windows go vet ./..., GOOS=linux go vet
  -tags nogui ./... and GOOS=windows go build all OK. go test -tags
  nogui -timeout 45m ./... gives 80 ok, no FAIL, at 9e8c22dad + this.
  After rebasing onto fce294c5a (gui assets, pii, sessions, WorkBuddy
  min), the vets and the gui, uninstall, update and sessions packages
  ran again on mote: all ok. On Windows, uninstall, update, autostart
  and appdir ran ok at that head. TestCoreScriptBudget was red at
  6db21d869, the upstream head then, and fce294c5a fixed it.
- Broken by hand on Windows, each one red:
  - no forwards check in EnsureCompanion:
    TestNoCompanionBesideAForwardingDownload;
  - always replace: TestSettleKeepsTheInstalledVersion;
  - the shim always removed: TestSettledClearsOnlyMagpiesFiles;
  - no download-folder check: TestSettleLeavesAChosenPlace;
  - the original marker passed on: TestForwardWaitsForTheInstalledOne;
  - no keepWebView: TestSettleKeepsTheWebViewProfile;
  - a case-sensitive Run path: TestRepointed;
  - uninstall without the noted profile: TestProfilesTakeTheNotedOne.

Not tried:
- the GUI on an interactive desktop: the real run was in a batch logon,
  where WebView2 did start;
- a OneDrive-moved Downloads (it is read from the known folder);
- an exe opened from inside a zip;
- taskbar pins.
Not changed: magpie uninstall still leaves the exe, magpie.com and the
PATH entry, now in Programs\magpie. #2663 is open for the uninstall
flow that cleans them.
2026-10-30 11:28:32 +08:00

384 lines
12 KiB
Go

package update
import (
"bytes"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
)
// installFixture is a download folder holding exe (magpie-windows-amd64.exe,
// as the site names it) and the place it installs to, each with its
// version; what Settle asks of the system answers from them.
type installFixture struct {
downloads, exe, to, profiles string
versions map[string]uint64
placed []string // folders installCLI was asked to put on PATH
portable string
}
func newInstallFixture(t *testing.T) *installFixture {
t.Helper()
root := t.TempDir()
f := &installFixture{
downloads: filepath.Join(root, "Downloads"),
to: filepath.Join(root, "Local", "Programs", "magpie", "magpie.exe"),
profiles: filepath.Join(root, "Roaming"),
versions: map[string]uint64{},
}
f.exe = filepath.Join(f.downloads, "magpie-windows-amd64.exe")
if err := os.MkdirAll(f.downloads, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(f.exe, []byte("MZ new download"), 0o755); err != nil {
t.Fatal(err)
}
saved := []any{installTarget, downloadFolder, fileVersion, portableData, webViewHome, installCLI}
t.Cleanup(func() {
installTarget = saved[0].(func() string)
downloadFolder = saved[1].(func(string) bool)
fileVersion = saved[2].(func(string) uint64)
portableData = saved[3].(func() string)
webViewHome = saved[4].(func(string) string)
installCLI = saved[5].(func(string, string) error)
})
installTarget = func() string { return f.to }
downloadFolder = func(dir string) bool { return samePath(dir, f.downloads) }
fileVersion = func(p string) uint64 {
for k, v := range f.versions {
if samePath(k, p) {
return v
}
}
return 0
}
portableData = func() string { return f.portable }
webViewHome = func(exe string) string { return filepath.Join(f.profiles, filepath.Base(exe)) }
installCLI = func(exe, dir string) error {
f.placed = append(f.placed, dir)
return nil
}
return f
}
func (f *installFixture) installed(t *testing.T, b string, version uint64) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(f.to), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(f.to, []byte(b), 0o755); err != nil {
t.Fatal(err)
}
f.versions[f.to] = version
}
func readString(t *testing.T, p string) string {
t.Helper()
b, err := os.ReadFile(p)
if err != nil {
t.Fatal(err)
}
return string(b)
}
// Opened from Downloads with nothing installed, the app is copied to the
// user's programs folder as magpie.exe, that folder goes on the PATH, and
// the installed one is what opens. The download itself stays: it is the
// user's file.
func TestSettleInstallsADownload(t *testing.T) {
f := newInstallFixture(t)
to, err := settle(f.exe)
if err != nil {
t.Fatal(err)
}
if to != f.to {
t.Fatalf("settle opens %q, want the installed %q", to, f.to)
}
if got := readString(t, f.to); got != "MZ new download" {
t.Fatalf("installed copy holds %q", got)
}
if got := readString(t, f.exe); got != "MZ new download" {
t.Fatalf("the download was changed or removed: %q", got)
}
if len(f.placed) != 1 || !samePath(f.placed[0], filepath.Dir(f.to)) {
t.Fatalf("PATH given %v, want the install folder once", f.placed)
}
left, _ := filepath.Glob(filepath.Join(filepath.Dir(f.to), ".magpie-install-*"))
if len(left) != 0 {
t.Fatalf("staging files left: %v", left)
}
}
// A copy kept anywhere the user chose, or a portable one, runs where it
// is and installs nothing; so does one run with MAGPIE_NO_INSTALL=1.
func TestSettleLeavesAChosenPlace(t *testing.T) {
f := newInstallFixture(t)
tools := filepath.Join(filepath.Dir(f.downloads), "Tools", "magpie-windows-amd64.exe")
if err := os.MkdirAll(filepath.Dir(tools), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(tools, []byte("MZ"), 0o755); err != nil {
t.Fatal(err)
}
if to, err := settle(tools); to != "" || err != nil {
t.Fatalf("a copy in a folder of the user's own opens %q (%v)", to, err)
}
f.portable = filepath.Join(f.downloads, "data")
if to, err := settle(f.exe); to != "" || err != nil {
t.Fatalf("a portable copy opens %q (%v)", to, err)
}
f.portable = ""
if to, err := settle(f.to); to != "" || err != nil {
t.Fatalf("the installed copy opens %q (%v)", to, err)
}
if exists(f.to) {
t.Fatal("installed though it shouldn't have been")
}
t.Setenv(NoInstallEnv, "1")
if from, to := Settle(); from != "" || to != "" {
t.Fatalf("MAGPIE_NO_INSTALL=1 still opens %q", to)
}
if forwards(f.exe) {
t.Fatal("MAGPIE_NO_INSTALL=1 still counts as forwarding")
}
}
// Installed already: the download opens it, and only a newer version goes
// in its place. An older or unknown one leaves the installed copy, which
// updates itself.
func TestSettleKeepsTheInstalledVersion(t *testing.T) {
for _, c := range []struct {
name string
mine, theirs uint64
want string
placedOnPath bool
}{
{"older download", 1<<32 | 100<<16, 1<<32 | 200<<16, "MZ installed", false},
{"same version", 1<<32 | 200<<16, 1<<32 | 200<<16, "MZ installed", false},
{"no version in the download", 0, 1<<32 | 200<<16, "MZ installed", false},
{"no version installed", 1<<32 | 300<<16, 0, "MZ installed", false},
{"newer download", 1<<32 | 300<<16, 1<<32 | 200<<16, "MZ new download", false},
} {
t.Run(c.name, func(t *testing.T) {
f := newInstallFixture(t)
f.installed(t, "MZ installed", c.theirs)
f.versions[f.exe] = c.mine
to, err := settle(f.exe)
if err != nil || to != f.to {
t.Fatalf("settle = %q, %v; want %q", to, err, f.to)
}
if got := readString(t, f.to); got != c.want {
t.Fatalf("installed holds %q, want %q", got, c.want)
}
if len(f.placed) != 0 {
t.Fatalf("PATH written again for an installed magpie: %v", f.placed)
}
if got := readString(t, f.exe); got != "MZ new download" {
t.Fatalf("the download was changed: %q", got)
}
})
}
}
// A failure to install leaves the download running where it is.
func TestSettleFailingRunsOn(t *testing.T) {
f := newInstallFixture(t)
// a file where the install folder should be
if err := os.MkdirAll(filepath.Dir(filepath.Dir(f.to)), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Dir(f.to), []byte("in the way"), 0o644); err != nil {
t.Fatal(err)
}
to, err := settle(f.exe)
if to != "" || err == nil {
t.Fatalf("settle = %q, %v; want this one to run on, with the reason", to, err)
}
if len(f.placed) != 0 {
t.Fatal("PATH written for an install that failed")
}
}
// WebView2 keeps a profile per exe name, so magpie.exe would start with
// none: the installed copy is pointed at the download's, unless it has
// one of its own.
func TestSettleKeepsTheWebViewProfile(t *testing.T) {
f := newInstallFixture(t)
old := filepath.Join(f.profiles, "magpie-windows-amd64.exe")
if err := os.MkdirAll(old, 0o755); err != nil {
t.Fatal(err)
}
if _, err := settle(f.exe); err != nil {
t.Fatal(err)
}
note := filepath.Join(filepath.Dir(f.to), "webview-profile")
if got := strings.TrimSpace(readString(t, note)); !samePath(got, old) {
t.Fatalf("webview note names %q, want %q", got, old)
}
g := newInstallFixture(t)
for _, d := range []string{"magpie-windows-amd64.exe", "magpie.exe"} {
if err := os.MkdirAll(filepath.Join(g.profiles, d), 0o755); err != nil {
t.Fatal(err)
}
}
if _, err := settle(g.exe); err != nil {
t.Fatal(err)
}
if exists(filepath.Join(filepath.Dir(g.to), "webview-profile")) {
t.Fatal("pointed away from magpie.exe's own profile")
}
}
// The installed copy clears what magpie wrote beside the download: the
// magpie.com and magpie.cmd that ran it, and what updates moved aside.
// A magpie.cmd of the user's own, or one magpie wrote for another
// program there, stays.
func TestSettledClearsOnlyMagpiesFiles(t *testing.T) {
f := newInstallFixture(t)
dir := f.downloads
com := filepath.Join(dir, comName)
if err := os.WriteFile(com, comText([]byte("MZ launcher"), f.exe), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, shimName), []byte(shimText(f.exe)), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(f.exe+".old", []byte("MZ"), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv(installedFromEnv, f.exe)
Settled()
for _, p := range []string{com, filepath.Join(dir, shimName), f.exe + ".old"} {
if exists(p) {
t.Fatalf("%s left", filepath.Base(p))
}
}
if !exists(f.exe) {
t.Fatal("the download itself was removed")
}
if os.Getenv(installedFromEnv) != "" {
t.Fatal("passed on to what the installed magpie starts")
}
// the user's own, and magpie's for another program
own := []byte("@echo off\r\nrem mine\r\n\"%~dp0magpie-windows-amd64.exe\" %*\r\n")
if err := os.WriteFile(filepath.Join(dir, shimName), own, 0o755); err != nil {
t.Fatal(err)
}
other := comText([]byte("MZ launcher"), filepath.Join(dir, "magpie-windows-amd64 (1).exe"))
if err := os.WriteFile(com, other, 0o755); err != nil {
t.Fatal(err)
}
t.Setenv(installedFromEnv, f.exe)
Settled()
if b, err := os.ReadFile(filepath.Join(dir, shimName)); err != nil || !bytes.Equal(b, own) {
t.Fatalf("the user's magpie.cmd: %q, %v", b, err)
}
if b, err := os.ReadFile(com); err != nil || !bytes.Equal(b, other) {
t.Fatalf("another program's magpie.com: %v", err)
}
}
// Forward opens the installed one with this one's arguments, waits for
// its word, and passes that word on to a restart to update waiting on
// this one.
func TestForwardWaitsForTheInstalledOne(t *testing.T) {
waiting := filepath.Join(t.TempDir(), "started")
t.Setenv(startedEnv, waiting)
was := launch
t.Cleanup(func() { launch = was })
var gotExe string
var gotArgs, gotEnv []string
launch = func(exe string, args, env []string) (<-chan struct{}, func(), error) {
gotExe, gotArgs, gotEnv = exe, args, env
for _, e := range env {
if m, ok := strings.CutPrefix(e, startedEnv+"="); ok {
os.WriteFile(m, []byte("1"), 0o644)
}
}
return make(chan struct{}), func() {}, nil
}
if err := Forward(`C:\Users\u\Downloads\magpie-windows-amd64.exe`, `C:\Users\u\AppData\Local\Programs\magpie\magpie.exe`); err != nil {
t.Fatal(err)
}
if !strings.HasSuffix(gotExe, `magpie.exe`) {
t.Fatalf("opened %q", gotExe)
}
if strings.Join(gotArgs, " ") != strings.Join(os.Args[1:], " ") {
t.Fatalf("args %v, want %v", gotArgs, os.Args[1:])
}
var from, marks int
for _, e := range gotEnv {
if strings.HasPrefix(e, installedFromEnv+`=C:\Users\u\Downloads\magpie-windows-amd64.exe`) {
from++
}
if strings.HasPrefix(e, startedEnv+"=") {
marks++
if strings.HasSuffix(e, "="+waiting) {
t.Fatal("the restart's own marker handed on, which it removes as it reads it")
}
}
}
if from != 1 || marks != 1 {
t.Fatalf("env: %d %s, %d %s", from, installedFromEnv, marks, startedEnv)
}
if !exists(waiting) {
t.Fatal("the restart waiting on this one was never told")
}
// one that quits without a word: this one runs on
launch = func(string, []string, []string) (<-chan struct{}, func(), error) {
c := make(chan struct{})
close(c)
return c, func() {}, nil
}
if err := Forward("a", "b"); err == nil {
t.Fatal("a magpie that quit unstarted taken as opened")
}
}
// A download that opens the installed magpie writes no magpie.com beside
// it: the terminal's magpie is the installed one's.
func TestNoCompanionBesideAForwardingDownload(t *testing.T) {
f := newInstallFixture(t)
f.installed(t, "MZ installed", 0)
if forwards(f.exe) != (runtime.GOOS == "windows") {
// forwards is Windows' alone
t.Fatalf("forwards(%s) = %v", f.exe, forwards(f.exe))
}
was := comLauncher
t.Cleanup(func() { comLauncher = was })
comLauncher = []byte("MZ launcher")
t.Setenv("PATH", f.downloads)
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))
}
}
func TestInFolder(t *testing.T) {
root := t.TempDir()
for _, c := range []struct {
path string
want bool
}{
{root, true},
{filepath.Join(root, "Temp1_magpie.zip"), true},
{strings.ToUpper(filepath.Join(root, "x")), true},
{filepath.Dir(root), false},
{root + "-other", false},
} {
if got := inFolder(c.path, root); got != c.want {
t.Errorf("inFolder(%q) = %v, want %v", c.path, got, c.want)
}
}
if inFolder(root, "") || inFolder(root, "relative") {
t.Error("a folder that isn't absolute holds things")
}
}