Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
windows: the app opened from Downloads installs itself in Programs\magpie
yetonea3b9dd1127df
diff --git a/internal/appdir/appdir.go b/internal/appdir/appdir.goindex ab0361400..76588e95c 100644--- a/internal/appdir/appdir.go+++ b/internal/appdir/appdir.go@@ -270,10 +270,37 @@ func Cache() string {// default. Installed, that default is %APPDATA%\<exe name>, as it always// was, so nothing kept there is lost; portable, it is data\webview2, so a// portable magpie leaves no magpie.exe folder in the user's AppData (#508).+// A Windows magpie installed from a download under another name+// (update.Settle) keeps the profile it had there: the WebViewNote beside+// it names that folder.func WebView() string {if p := Portable(); p != "" {return filepath.Join(p, "webview2")}+ if runtime.GOOS != "windows" {+ return ""+ }+ exe, err := os.Executable()+ if err != nil {+ return ""+ }+ return noted(filepath.Join(filepath.Dir(exe), WebViewNote))+}++// WebViewNote is the file beside an installed Windows magpie naming the+// webview profile it keeps, the one it had where it was downloaded.+const WebViewNote = "webview-profile"++// noted is the absolute folder the note at path names, "" when there is+// no such note.+func noted(path string) string {+ b, err := os.ReadFile(path)+ if err != nil {+ return ""+ }+ if p := strings.TrimSpace(string(b)); filepath.IsAbs(p) {+ return p+ }return ""}diff --git a/internal/appdir/webview_note_test.go b/internal/appdir/webview_note_test.gonew file mode 100644index 000000000..1a182dfa0--- /dev/null+++ b/internal/appdir/webview_note_test.go@@ -0,0 +1,31 @@+package appdir++import (+ "os"+ "path/filepath"+ "testing"+)++// The note beside a Windows magpie installed from a download names the+// webview profile it keeps (update.Settle); a missing note, or one that+// doesn't name an absolute folder, leaves WebView2's own default.+func TestWebViewNote(t *testing.T) {+ dir := t.TempDir()+ note := filepath.Join(dir, WebViewNote)+ if got := noted(note); got != "" {+ t.Fatalf("no note read as %q", got)+ }+ want := filepath.Join(dir, "Roaming", "magpie-windows-amd64.exe")+ if err := os.WriteFile(note, []byte(want+"\r\n"), 0o644); err != nil {+ t.Fatal(err)+ }+ if got := noted(note); got != want {+ t.Fatalf("note read as %q, want %q", got, want)+ }+ if err := os.WriteFile(note, []byte("magpie-windows-amd64.exe\n"), 0o644); err != nil {+ t.Fatal(err)+ }+ if got := noted(note); got != "" {+ t.Fatalf("a relative note read as %q", got)+ }+}diff --git a/internal/autostart/autostart.go b/internal/autostart/autostart.goindex 2ca573d95..9ee699cf2 100644--- a/internal/autostart/autostart.go+++ b/internal/autostart/autostart.go@@ -85,3 +85,33 @@ func self() (string, error) {}return exe, nil}++// Repoint has the record that opens magpie at login open to instead, when+// it opens from: the Windows app installed itself from where it was+// downloaded (update.Settle). Nothing else in it changes, so a record the+// user switched off in Task Manager stays off, and none is made when there+// was none.+func Repoint(from, to string) error { return repoint(from, to) }++// repointed is the Windows Run value v opening to in place of from, with+// its arguments kept; ok is false when v doesn't open from.+func repointed(v, from, to string) (string, bool) {+ v = strings.TrimSpace(v)+ var exe, rest string+ if strings.HasPrefix(v, `"`) {+ i := strings.Index(v[1:], `"`)+ if i < 0 {+ return "", false+ }+ exe, rest = v[1:1+i], v[2+i:]+ } else {+ exe, rest, _ = strings.Cut(v, " ")+ if rest != "" {+ rest = " " + rest+ }+ }+ if exe == "" || !strings.EqualFold(filepath.Clean(exe), filepath.Clean(from)) {+ return "", false+ }+ return `"` + to + `"` + rest, true+}diff --git a/internal/autostart/repoint_other.go b/internal/autostart/repoint_other.gonew file mode 100644index 000000000..0a1056e89--- /dev/null+++ b/internal/autostart/repoint_other.go@@ -0,0 +1,6 @@+//go:build !windows++package autostart++// repoint: only the Windows app moves itself (update.Settle)+func repoint(string, string) error { return nil }diff --git a/internal/autostart/repoint_test.go b/internal/autostart/repoint_test.gonew file mode 100644index 000000000..c0c8c8bca--- /dev/null+++ b/internal/autostart/repoint_test.go@@ -0,0 +1,29 @@+package autostart++import "testing"++// The Windows app installed itself from Downloads (update.Settle): the Run+// value opening the download opens the installed copy, with its arguments;+// one opening anything else, or written by hand without a path magpie+// knows, is left.+func TestRepointed(t *testing.T) {+ from := `C:\Users\u\Downloads\magpie-windows-amd64.exe`+ to := `C:\Users\u\AppData\Local\Programs\magpie\magpie.exe`+ for _, c := range []struct {+ v, want string+ ok bool+ }{+ {`"` + from + `" tray`, `"` + to + `" tray`, true},+ {`"C:\USERS\U\DOWNLOADS\MAGPIE-WINDOWS-AMD64.EXE" tray`, `"` + to + `" tray`, true},+ {`"` + from + `"`, `"` + to + `"`, true},+ {from + ` tray --x`, `"` + to + `" tray --x`, true},+ {`"C:\Tools\magpie.exe" tray`, "", false},+ {`"` + from, "", false},+ {``, "", false},+ } {+ got, ok := repointed(c.v, from, to)+ if got != c.want || ok != c.ok {+ t.Errorf("repointed(%q) = %q, %v; want %q, %v", c.v, got, ok, c.want, c.ok)+ }+ }+}diff --git a/internal/autostart/repoint_windows.go b/internal/autostart/repoint_windows.gonew file mode 100644index 000000000..60cf74a05--- /dev/null+++ b/internal/autostart/repoint_windows.go@@ -0,0 +1,32 @@+package autostart++import (+ "errors"++ "golang.org/x/sys/windows/registry"+)++// repoint rewrites the magpie Run value when it opens from. Task Manager's+// switch for it is kept by the value's name, which stays.+func repoint(from, to string) error {+ k, err := openRunKey(registry.CURRENT_USER, runKey, registry.QUERY_VALUE|registry.SET_VALUE)+ if err != nil {+ if errors.Is(err, registry.ErrNotExist) {+ return nil+ }+ return err+ }+ defer k.Close()+ v, err := readRunValue(k)+ if err != nil {+ if errors.Is(err, registry.ErrNotExist) {+ return nil+ }+ return err+ }+ nv, ok := repointed(v, from, to)+ if !ok {+ return nil+ }+ return k.SetStringValue(name, nv)+}diff --git a/internal/gui/app.go b/internal/gui/app.goindex 0c84e70c8..d4ef6023b 100644--- a/internal/gui/app.go+++ b/internal/gui/app.go@@ -312,6 +312,19 @@ func Run(version string, showMain bool, link string) error {if devRole() == "backend" {return devBackend(func(w Windows) http.Handler { return Handler(w, startBackend()) })}+ // Windows: the app opened from Downloads (or the Desktop, or a zip)+ // opens the copy installed in the user's programs folder, putting+ // itself there first, and Open at login opens that one from now on+ if from, to := update.Settle(); to != "" {+ err := update.Forward(from, to)+ if err == nil {+ if err := autostart.Repoint(from, to); err != nil {+ log.Println("open at login:", err)+ }+ return nil+ }+ log.Println("install:", err)+ }// A restart to update on a Mac or Linux started this one beside the// magpie before, which hands it the gateway (handover.go).startExe, _ = update.Executable()@@ -323,6 +336,8 @@ func Run(version string, showMain bool, link string) error {// After an update off the Mac, the old process starts this one and then// quits; let it go before looking for the gateway.update.AwaitPredecessor()+ // installed from a download just now: what magpie left beside it goes+ update.Settled()// the Mac's second launch hands over to the magpie already runningif runningAlready(showMain || OpenPanel, link) {return nildiff --git a/internal/uninstall/profiles_windows_test.go b/internal/uninstall/profiles_windows_test.gonew file mode 100644index 000000000..e32e64e3a--- /dev/null+++ b/internal/uninstall/profiles_windows_test.go@@ -0,0 +1,37 @@+package uninstall++import (+ "os"+ "path/filepath"+ "testing"+)++// A magpie installed from a download keeps the profile it had there;+// uninstalling it removes that one too, and never a folder a note names+// outside %APPDATA%.+func TestProfilesTakeTheNotedOne(t *testing.T) {+ appData := t.TempDir()+ own := filepath.Join(appData, "magpie.exe")+ kept := filepath.Join(appData, "magpie-windows-amd64.exe")+ other := filepath.Join(t.TempDir(), "elsewhere")+ for _, p := range []string{own, kept, other} {+ if err := os.MkdirAll(filepath.Join(p, "EBWebView"), 0o755); err != nil {+ t.Fatal(err)+ }+ }+ got := profiles(appData, "magpie.exe", kept)+ if len(got) != 2 || got[0] != own || got[1] != kept {+ t.Fatalf("profiles = %q, want %q and %q", got, own, kept)+ }+ if got := profiles(appData, "magpie.exe", other); len(got) != 1 || got[0] != own {+ t.Fatalf("a note outside AppData: profiles = %q, want only %q", got, own)+ }+ if got := profiles(appData, "magpie.exe", own); len(got) != 1 {+ t.Fatalf("the note naming the exe's own: profiles = %q, want it once", got)+ }+ plain := filepath.Join(appData, "plain")+ os.MkdirAll(plain, 0o755)+ if got := profiles(appData, "nothing.exe", plain); len(got) != 0 {+ t.Fatalf("folders WebView2 didn't make: profiles = %q, want none", got)+ }+}diff --git a/internal/uninstall/system_windows.go b/internal/uninstall/system_windows.goindex 1beaf148b..b20bea032 100644--- a/internal/uninstall/system_windows.go+++ b/internal/uninstall/system_windows.go@@ -35,20 +35,39 @@ func unregisterScheme(exe string) error {}// webData is WebView2's profile of an installed magpie: %APPDATA%\<exe-// name> (portable, it is in the data folder already).+// name>, and the one a magpie installed from a download keeps under the+// download's name (appdir.WebView, update.Settle). Portable, it is in the+// data folder already.func webData() []string {if appdir.Portable() != "" {return nil}exe, err := os.Executable()- a := appdir.Getenv("APPDATA")- if err != nil || a == "" {+ if err != nil {return nil}- p := filepath.Join(a, filepath.Base(exe))- // only a folder WebView2 made: its EBWebView inside- if _, err := os.Stat(filepath.Join(p, "EBWebView")); err != nil {+ return profiles(appdir.Getenv("APPDATA"), filepath.Base(exe), appdir.WebView())+}++// profiles is webData's folders in appData: the exe's own and the noted+// one, each only where WebView2 made it (its EBWebView inside). A note+// naming a folder anywhere else is not followed.+func profiles(appData, exeName, noted string) []string {+ if appData == "" {return nil}- return []string{p}+ var out []string+ for _, p := range []string{filepath.Join(appData, exeName), noted} {+ if p == "" || !strings.EqualFold(filepath.Clean(filepath.Dir(p)), filepath.Clean(appData)) {+ continue+ }+ if len(out) > 0 && strings.EqualFold(filepath.Clean(out[0]), filepath.Clean(p)) {+ continue+ }+ if _, err := os.Stat(filepath.Join(p, "EBWebView")); err != nil {+ continue+ }+ out = append(out, p)+ }+ return out}diff --git a/internal/update/com.go b/internal/update/com.goindex 410602ec4..44779b372 100644--- a/internal/update/com.go+++ b/internal/update/com.go@@ -101,7 +101,9 @@ func comOwner(exe string) bool {// magpie.cmd there), or brings one there up to this version. Nothing in// a build without the launcher, or when it is as it should be already.func EnsureCompanion(exe string) error {- if comLauncher == nil || !comOwner(exe) {+ // a download that opens the installed magpie (Settle) leaves the+ // command to that one, in its folder on PATH+ if comLauncher == nil || !comOwner(exe) || forwards(exe) {return nil}dir := filepath.Dir(exe)diff --git a/internal/update/install.go b/internal/update/install.gonew file mode 100644index 000000000..ea3ebf474--- /dev/null+++ b/internal/update/install.go@@ -0,0 +1,276 @@+package update++import (+ "fmt"+ "io"+ "log"+ "os"+ "path/filepath"+ "runtime"+ "strings"++ "github.com/yetone/magpie/internal/appdir"+)++// The Windows app is one exe with no installer, and the site's download+// lands it in Downloads as magpie-windows-amd64.exe. Left there, the Start+// menu shortcut, Open at login and the `magpie` command all name a file+// the user tidies away, and the command came from a magpie.com written+// beside it in Downloads (lucky_eagle_38410 on Discord). So the desktop+// app, opened from a folder downloads land in, installs itself the way a+// Mac app is moved into Applications: it copies itself to+// %LOCALAPPDATA%\Programs\magpie\magpie.exe — the user's own programs+// folder, no administrator — puts that folder on the user's PATH, and+// opens the copy there, which makes the shortcut, Open at login and its+// updates name it. The download is left where it is: it is the user's+// file. Opened again, it opens the installed copy, or puts itself there+// first when it is the newer version.+//+// It is left alone, and runs where it is as before, when it runs from+// anywhere else (a folder the user chose: D:\Tools, a USB drive), when it+// is portable (a data folder or .portable file beside it, appdir), or+// with MAGPIE_NO_INSTALL=1.++// NoInstallEnv, set to 1, keeps a magpie run from Downloads there.+const NoInstallEnv = "MAGPIE_NO_INSTALL"++// installedFromEnv names, for the installed copy started in its place,+// the exe it was installed from, whose leftovers it clears (Settled).+const installedFromEnv = "MAGPIE_INSTALLED_FROM"++// What Settle asks of the system; tests set them.+var (+ // installTarget is %LOCALAPPDATA%\Programs\magpie\magpie.exe, "" off+ // Windows+ installTarget = installPath+ // downloadFolder says whether dir is one downloads land in:+ // Downloads, the Desktop or a temporary folder (an exe opened from+ // inside a zip); not a folder inside them, the home folder or+ // Documents+ downloadFolder = isDownloadFolder+ // fileVersion is the version in an exe's resources, 0 when unknown+ fileVersion = exeVersion+ // portableData is a portable magpie's data folder, "" installed+ portableData = appdir.Portable+ // webViewHome is the folder WebView2 keeps an installed magpie's+ // profile in by default, %APPDATA%\<exe name>; "" off Windows+ webViewHome = webViewDefault+ // installCLI puts the installed folder on the user's PATH with the+ // command a terminal runs there+ installCLI = cliPlace+)++// Settle installs the desktop app run from a download folder (see+// above), and says what to open instead of running on here: from is this+// exe and to the installed one, both "" when this one runs on. Anything+// that goes wrong leaves this one running, as before.+func Settle() (from, to string) {+ if os.Getenv(NoInstallEnv) == "1" {+ return "", ""+ }+ exe, err := Executable()+ if err != nil {+ return "", ""+ }+ to, err = settle(exe)+ if err != nil {+ log.Println("install:", err)+ return "", ""+ }+ if to == "" {+ return "", ""+ }+ return exe, to+}++// settle is Settle for exe: the installed exe to open instead, "" to run+// exe where it is.+func settle(exe string) (string, error) {+ to := installTarget()+ if to == "" || samePath(exe, to) || !downloadFolder(filepath.Dir(exe)) || portableData() != "" {+ return "", nil+ }+ if !exists(to) {+ if err := installFresh(exe, to); err != nil {+ return "", err+ }+ return to, nil+ }+ if sameFile(exe, to) || sameBytes(exe, to) {+ return to, nil+ }+ mine, theirs := fileVersion(exe), fileVersion(to)+ if mine == 0 || theirs == 0 || mine <= theirs {+ // the installed copy is as new or newer, or it can't be told:+ // that one is kept, and updates itself+ return to, nil+ }+ // a newer version, downloaded again: it goes in place of the+ // installed one, as an update would+ staged, err := copyBeside(exe, to)+ if err != nil {+ return "", err+ }+ if _, err := InstallBinaryAside(staged, to); err != nil {+ os.Remove(staged)+ return "", fmt.Errorf("putting %s in place of %s: %w", filepath.Base(exe), to, err)+ }+ return to, nil+}++// installFresh puts a copy of exe at to, puts its folder on the user's+// PATH with the `magpie` command a terminal runs there (cliPlace), and+// points the installed copy at the webview profile exe had, which is kept+// by its file name.+func installFresh(exe, to string) error {+ dir := filepath.Dir(to)+ if err := os.MkdirAll(dir, 0o755); err != nil {+ return err+ }+ staged, err := copyBeside(exe, to)+ if err != nil {+ return err+ }+ if err := moveIn(staged, to); err != nil {+ os.Remove(staged)+ return fmt.Errorf("installing to %s: %w", to, err)+ }+ keepWebView(exe, to)+ if err := installCLI(to, dir); err != nil {+ // the app runs the same without the command; Settings' Command+ // line says it isn't there and offers it again+ log.Println("install: the magpie command:", err)+ }+ return nil+}++// keepWebView has the copy at to keep the webview profile exe had: the+// pages' storage there would be lost to a new profile under magpie.exe's+// name. Nothing when that one has a profile already.+func keepWebView(exe, to string) {+ home := webViewHome+ old, now := home(exe), home(to)+ if old == "" || now == "" || samePath(old, now) || exists(now) || !exists(old) {+ return+ }+ if err := os.WriteFile(filepath.Join(filepath.Dir(to), appdir.WebViewNote), []byte(old+"\n"), 0o644); err != nil {+ log.Println("install: the webview profile:", err)+ }+}++// copyBeside copies exe into a new file in to's folder, ready to be moved+// in at to; the file is its path.+func copyBeside(exe, to string) (string, error) {+ src, err := os.Open(exe)+ if err != nil {+ return "", err+ }+ defer src.Close()+ f, err := os.CreateTemp(filepath.Dir(to), ".magpie-install-*")+ if err != nil {+ return "", err+ }+ _, err = io.Copy(f, src)+ if cerr := f.Close(); err == nil {+ err = cerr+ }+ if err != nil {+ os.Remove(f.Name())+ return "", fmt.Errorf("copying %s to %s: %w", filepath.Base(exe), filepath.Dir(to), err)+ }+ return f.Name(), nil+}++// Forward opens the installed magpie at to with this one's arguments, and+// waits for it to say it is up; the caller then quits. A restart to+// update waits on this one for that word (MAGPIE_STARTED): it is passed on+// once the installed one has said it. When to can't be started, this one+// runs on.+func Forward(from, to string) error {+ marker := filepath.Join(os.TempDir(), fmt.Sprintf("magpie-installed-%d", os.Getpid()))+ os.Remove(marker)+ defer os.Remove(marker)+ var env []string+ for _, e := range os.Environ() {+ if !strings.HasPrefix(e, startedEnv+"=") && !strings.HasPrefix(e, installedFromEnv+"=") {+ env = append(env, e)+ }+ }+ env = append(env, startedEnv+"="+marker, installedFromEnv+"="+from)+ exited, kill, err := launch(to, os.Args[1:], env)+ if err == nil {+ err = awaitStarted(marker, exited, kill)+ }+ if err != nil {+ return fmt.Errorf("opening %s: %w", to, err)+ }+ reportStarted()+ return nil+}++// 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+// the `magpie` on PATH is now. A file it didn't write, or wrote for+// another program, is left.+func Settled() {+ from := os.Getenv(installedFromEnv)+ os.Unsetenv(installedFromEnv)+ if from == "" || !filepath.IsAbs(from) {+ return+ }+ clearBeside(from)+}++func clearBeside(from string) {+ RemoveOld(from)+ dir := filepath.Dir(from)+ if p := filepath.Join(dir, comName); comRuns(p, from) {+ RemoveOld(p)+ if err := os.Remove(p); err != nil && !os.IsNotExist(err) {+ log.Println("install: removing", p+":", err)+ }+ }+ if p := filepath.Join(dir, shimName); shimRuns(p, from) {+ if err := os.Remove(p); err != nil && !os.IsNotExist(err) {+ log.Println("install: removing", p+":", err)+ }+ }+}++// forwards says whether exe is a download Settle opens the installed+// magpie in place of: nothing is written beside it for a terminal, which+// runs the installed one.+func forwards(exe string) bool {+ if runtime.GOOS != "windows" || os.Getenv(NoInstallEnv) == "1" {+ return false+ }+ to := installTarget()+ return to != "" && !samePath(exe, to) && downloadFolder(filepath.Dir(exe)) && portableData() == "" && exists(to)+}++// samePath says whether two paths name the same file, Windows' way: in+// any case.+func samePath(a, b string) bool {+ return strings.EqualFold(filepath.Clean(a), filepath.Clean(b))+}++// sameBytes says whether the files at a and b hold the same bytes.+func sameBytes(a, b string) bool {+ sa, err1 := os.Stat(a)+ sb, err2 := os.Stat(b)+ if err1 != nil || err2 != nil || sa.Size() != sb.Size() {+ return false+ }+ ha, hb := fileHash(a), fileHash(b)+ return ha != "" && ha == hb+}++// inFolder says whether path is dir or lies in it, in any case.+func inFolder(path, dir string) bool {+ if dir == "" || !filepath.IsAbs(dir) {+ return false+ }+ rel, err := filepath.Rel(strings.ToLower(filepath.Clean(dir)), strings.ToLower(filepath.Clean(path)))+ return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))+}diff --git a/internal/update/install_other.go b/internal/update/install_other.gonew file mode 100644index 000000000..f4c1fbbf5--- /dev/null+++ b/internal/update/install_other.go@@ -0,0 +1,9 @@+//go:build !windows++package update++// Only the Windows app installs itself; elsewhere there is nothing to do.+func installPath() string { return "" }+func isDownloadFolder(string) bool { return false }+func exeVersion(string) uint64 { return 0 }+func webViewDefault(string) string { return "" }diff --git a/internal/update/install_test.go b/internal/update/install_test.gonew file mode 100644index 000000000..b19cef28f--- /dev/null+++ b/internal/update/install_test.go@@ -0,0 +1,383 @@+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")+ }+}diff --git a/internal/update/install_windows.go b/internal/update/install_windows.gonew file mode 100644index 000000000..01c17c445--- /dev/null+++ b/internal/update/install_windows.go@@ -0,0 +1,82 @@+package update++import (+ "os"+ "path/filepath"+ ptr "unsafe"++ "golang.org/x/sys/windows"++ "github.com/yetone/magpie/internal/appdir"+)++// installPath is %LOCALAPPDATA%\Programs\magpie\magpie.exe: the user's own+// programs folder (FOLDERID_UserProgramFiles), where per-user installers+// put their apps, which needs no administrator.+func installPath() string {+ local := appdir.Getenv("LOCALAPPDATA")+ if local == "" {+ if p, err := windows.KnownFolderPath(windows.FOLDERID_UserProgramFiles, 0); err == nil && p != "" {+ return filepath.Join(p, "magpie", "magpie.exe")+ }+ return ""+ }+ return filepath.Join(local, "Programs", "magpie", "magpie.exe")+}++// isDownloadFolder: Downloads and Desktop, where they are kept (the+// known folders, which OneDrive or the user may have moved) and under the+// home folder, and any temporary folder, where Explorer opens an exe from+// inside a zip. A folder of the user's own, even one inside these, isn't.+func isDownloadFolder(dir string) bool {+ var dirs []string+ if h, err := appdir.Home(); err == nil {+ dirs = append(dirs, filepath.Join(h, "Downloads"), filepath.Join(h, "Desktop"))+ }+ for _, id := range []*windows.KNOWNFOLDERID{windows.FOLDERID_Downloads, windows.FOLDERID_Desktop} {+ if p, err := windows.KnownFolderPath(id, 0); err == nil && p != "" {+ dirs = append(dirs, p)+ }+ }+ for _, d := range dirs {+ if samePath(dir, d) {+ return true+ }+ }+ for _, t := range []string{os.TempDir(), appdir.Getenv("TEMP"), appdir.Getenv("TMP")} {+ if inFolder(dir, t) {+ return true+ }+ }+ return false+}++// exeVersion is the file version in the exe's resources (make+// release-windows writes the release's there), as one number to compare:+// 0 when it has none, as a build of one's own.+func exeVersion(path string) uint64 {+ n, err := windows.GetFileVersionInfoSize(path, nil)+ if err != nil || n == 0 {+ return 0+ }+ buf := make([]byte, n)+ if err := windows.GetFileVersionInfo(path, 0, n, ptr.Pointer(&buf[0])); err != nil {+ return 0+ }+ var fixed *windows.VS_FIXEDFILEINFO+ var size uint32+ if err := windows.VerQueryValue(ptr.Pointer(&buf[0]), `\`, ptr.Pointer(&fixed), &size); err != nil || fixed == nil || size == 0 {+ return 0+ }+ return uint64(fixed.FileVersionMS)<<32 | uint64(fixed.FileVersionLS)+}++// webViewDefault is where WebView2 keeps the profile of the program at+// exe when magpie names none: %APPDATA%\<exe name> (Wails' default).+func webViewDefault(exe string) string {+ a := os.Getenv("AppData")+ if a == "" {+ return ""+ }+ return filepath.Join(a, filepath.Base(exe))+}