fix(update): let newer Windows clients take over the running instance

This commit is contained in:
YXC0915 committed 2026-12-04 22:56:37 +08:00
1 parent c5c5922acb
commit d41b29e345
12 files changed
+440 -21

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["yxc0915"],
"zh": "手动打开更高版本的 Windows 客户端时,自动退出正在运行的旧客户端并在原位置更新,原来的快捷方式仍可使用。",
"en": "Opening a newer Windows client now closes the running older client and updates its executable in place so existing shortcuts still work."
}
+4
View File
@@ -28,6 +28,10 @@ func (a *App) afterStartup() {
// onSecondInstance handles another `reims-go.exe` started while this one runs.
func (a *App) onSecondInstance(data options.SecondInstanceData) {
if len(data.Args) == 1 && data.Args[0] == cli.QuitForUpdateArg {
a.QuitApp()
return
}
w, ok := cli.ParseWindowArgs(data.Args)
if !ok {
// Command-line mode never gets here (it does not take the lock), so
+4
View File
@@ -11,6 +11,10 @@ func findWindow() uintptr { return 0 }
func ForwardVMClose(string) bool { return false }
func WindowForUpdate() (uint32, func()) { return 0, func() {} }
func DesktopWindowPID() uint32 { return 0 }
func sendToWindow(uintptr, []string, uint32) error { return errors.ErrUnsupported }
func spawnWindow([]string) error { return errors.ErrUnsupported }
+37 -2
View File
@@ -9,9 +9,11 @@ import (
"os/exec"
"runtime"
"syscall"
"time"
"unsafe"
"github.com/wailsapp/wails/v2/pkg/options"
"golang.org/x/sys/windows"
)
// Handing work to the desktop window speaks Wails v2's own single-instance
@@ -59,6 +61,40 @@ func findWindow() uintptr {
return h
}
// WindowForUpdate identifies the client with Wails' single-instance window.
// A missing window may mean the older client has just acquired its lock.
func WindowForUpdate() (uint32, func()) {
hwnd := findWindow()
if hwnd == 0 {
lockName := "wails-app-" + InstanceID + "sim"
h, err := windows.OpenMutex(windows.SYNCHRONIZE, false, windows.StringToUTF16Ptr(lockName))
if err == nil {
defer windows.CloseHandle(h)
for i := 0; i < 20 && hwnd == 0; i++ {
time.Sleep(25 * time.Millisecond)
hwnd = findWindow()
}
}
}
pid := windowPID(hwnd)
return pid, func() {
if pid != 0 && windowPID(hwnd) == pid {
_ = sendToWindow(hwnd, []string{QuitForUpdateArg}, 500)
}
}
}
// DesktopWindowPID returns the current Wails single-instance owner, if any.
func DesktopWindowPID() uint32 { return windowPID(findWindow()) }
func windowPID(hwnd uintptr) uint32 {
var pid uint32
if hwnd != 0 {
procGetWindowPID.Call(hwnd, uintptr(unsafe.Pointer(&pid)))
}
return pid
}
// ForwardVMClose delegates both the request and the foreground permission
// inherited from the VM window that launched this helper.
func ForwardVMClose(name string) bool {
@@ -66,8 +102,7 @@ func ForwardVMClose(name string) bool {
if hwnd == 0 {
return false
}
var pid uint32
if tid, _, _ := procGetWindowPID.Call(hwnd, uintptr(unsafe.Pointer(&pid))); tid != 0 {
if pid := windowPID(hwnd); pid != 0 {
procAllowSetForeground.Call(uintptr(pid))
}
return sendToWindow(hwnd, WindowArgs{CloseVM: name}.Args(), 500) == nil
+12
View File
@@ -5,6 +5,9 @@ import (
"strings"
)
// QuitForUpdateArg is an IPC-only request to exit without stopping VMs.
const QuitForUpdateArg = "--quit-for-update"
// The desktop window's own flags. `vm start` launches the window with them
// (or sends them to a window already running), so they are the whole
// protocol between command-line mode and the window. Each flag is one
@@ -19,6 +22,7 @@ const (
flagCloseVM = "--close-vm="
flagWaitPID = "--wait-pid="
flagDataRoot = "--data-root="
flagTakeover = "--takeover-relaunch"
)
// WindowArgs is what the desktop window was asked to do at launch, or by a
@@ -46,6 +50,9 @@ type WindowArgs struct {
// update: the new window waits for it to exit before taking the
// single-instance lock, which it would otherwise hand straight back to it.
WaitPID uint32
// TakeoverRelaunch opens the replacement while its parent still holds the
// desktop startup mutex. Wails still enforces the window's own lock.
TakeoverRelaunch bool
}
// ParseWindowArgs reads the window flags. ok is false when args hold
@@ -63,6 +70,8 @@ func ParseWindowArgs(args []string) (w WindowArgs, ok bool) {
w.Background = true
case a == flagSafeMode:
w.SafeMode = true
case a == flagTakeover:
w.TakeoverRelaunch = true
case strings.HasPrefix(a, flagStartVM):
w.StartVM = strings.TrimPrefix(a, flagStartVM)
case strings.HasPrefix(a, flagResumeVM):
@@ -122,6 +131,9 @@ func (w WindowArgs) Args() []string {
if w.WaitPID != 0 {
out = append(out, flagWaitPID+strconv.FormatUint(uint64(w.WaitPID), 10))
}
if w.TakeoverRelaunch {
out = append(out, flagTakeover)
}
return out
}
+2 -1
View File
@@ -28,6 +28,7 @@ func TestParseWindowArgs(t *testing.T) {
{[]string{"--close-vm="}, WindowArgs{}, false},
{[]string{"--wait-pid=4242"}, WindowArgs{WaitPID: 4242}, true},
{[]string{"--background", "--wait-pid=7"}, WindowArgs{Background: true, WaitPID: 7}, true},
{[]string{"--takeover-relaunch"}, WindowArgs{TakeoverRelaunch: true}, true},
{[]string{"--wait-pid=0"}, WindowArgs{}, false},
{[]string{"--wait-pid=abc"}, WindowArgs{}, false},
{[]string{"--background", "--resume-vm=m0", "--start-result=result.json"}, WindowArgs{Background: true, ResumeVM: "m0", StartResult: "result.json"}, true},
@@ -53,7 +54,7 @@ func TestCloseWindowArgsRoundTrip(t *testing.T) {
}
func TestWindowArgsRoundTrip(t *testing.T) {
w := WindowArgs{Background: true, StartVM: "mac os", StartDriver: "test.driver.linux", StartResult: `D:\Data\tmp\cli-start-9.json`, WaitPID: 31337}
w := WindowArgs{Background: true, StartVM: "mac os", StartDriver: "test.driver.linux", StartResult: `D:\Data\tmp\cli-start-9.json`, WaitPID: 31337, TakeoverRelaunch: true}
got, ok := ParseWindowArgs(w.Args())
if !ok || got != w {
t.Fatalf("round trip = %+v, %v", got, ok)
+11 -6
View File
@@ -3,7 +3,7 @@
package selfupdate
import (
"errors"
"os"
"os/exec"
"syscall"
)
@@ -13,13 +13,18 @@ const detachedProcess = 0x00000008
// Launch starts exe with args detached from this process, so it outlives the
// quit that follows.
func Launch(exe string, args []string) error {
process, err := startDetached(exe, args)
if err != nil {
return err
}
return process.Release()
}
func startDetached(exe string, args []string) (*os.Process, error) {
cmd := exec.Command(exe, args...)
cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: detachedProcess | syscall.CREATE_NEW_PROCESS_GROUP}
if err := cmd.Start(); err != nil {
return err
return nil, err
}
if cmd.Process == nil {
return errors.New("new Reims-Go did not start")
}
return cmd.Process.Release()
return cmd.Process, nil
}
+10 -10
View File
@@ -129,22 +129,22 @@ func Cleanup(exe string) {
}
func copyFile(src, dst string) error {
out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
if err != nil {
return err
}
err = writeExecutable(src, out)
return errors.Join(err, out.Close())
}
func writeExecutable(src string, out *os.File) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
if err != nil {
return err
}
if _, err := io.Copy(out, in); err != nil {
out.Close()
return err
}
if err := out.Sync(); err != nil {
out.Close()
return err
}
return out.Close()
return out.Sync()
}
+9
View File
@@ -0,0 +1,9 @@
//go:build !windows
package selfupdate
func LockDesktopStartup(string) (func(), error) { return func() {}, nil }
func Takeover(uint32, func(), []string, func() uint32) (bool, error) { return false, nil }
func ReportTakeoverError(error) {}
+281
View File
@@ -0,0 +1,281 @@
//go:build windows
package selfupdate
import (
"context"
"debug/buildinfo"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"runtime/debug"
"strings"
"sync"
"syscall"
"time"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/version"
"golang.org/x/sys/windows"
)
// LockDesktopStartup serializes replacement and Wails lock acquisition across
// launches. A dedicated OS thread owns the mutex until the window is ready.
func LockDesktopStartup(instanceID string) (func(), error) {
ready := make(chan error, 1)
released := make(chan struct{})
done := make(chan struct{})
go func() {
defer close(done)
runtime.LockOSThread()
defer runtime.UnlockOSThread()
h, err := windows.CreateMutex(nil, false, windows.StringToUTF16Ptr(instanceID+"-desktop-startup"))
if err != nil && !errors.Is(err, windows.ERROR_ALREADY_EXISTS) {
ready <- err
return
}
defer windows.CloseHandle(h)
event, err := windows.WaitForSingleObject(h, 30_000)
if err == nil && event != windows.WAIT_OBJECT_0 && event != windows.WAIT_ABANDONED {
err = fmt.Errorf("could not acquire the Reims-Go startup mutex (%#x)", event)
}
ready <- err
if err == nil {
<-released
_ = windows.ReleaseMutex(h)
}
}()
if err := <-ready; err != nil {
return nil, err
}
return sync.OnceFunc(func() {
close(released)
<-done
}), nil
}
// Takeover replaces the running client's executable at the exact path used by
// its shortcuts. The caller holds the desktop startup lock.
func Takeover(pid uint32, requestExit func(), relaunchArgs []string, windowPID func() uint32) (bool, error) {
// The compatibility probe runs the old client's version command. Never
// launch that executable with elevated privileges inherited from this one.
if pid == 0 || pid == uint32(os.Getpid()) || windows.GetCurrentProcessToken().IsElevated() {
return false, nil
}
process, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION|windows.PROCESS_TERMINATE|windows.SYNCHRONIZE, false, pid)
if err != nil {
return false, nil
}
defer windows.CloseHandle(process)
if !sameUser(process) {
return false, nil
}
buf := make([]uint16, 32768)
size := uint32(len(buf))
if err := windows.QueryFullProcessImageName(process, 0, &buf[0], &size); err != nil {
return false, nil
}
target := windows.UTF16ToString(buf[:size])
source, err := Executable()
if err != nil {
return false, err
}
oldFile, err := os.Stat(target)
if err != nil || !oldFile.Mode().IsRegular() {
return false, nil
}
if current, err := os.Stat(source); err != nil || os.SameFile(current, oldFile) {
return false, err
}
oldBuild, err := buildinfo.ReadFile(target)
newBuild, ok := debug.ReadBuildInfo()
if err != nil || !ok || oldBuild.Path != newBuild.Path || oldBuild.Main.Path != newBuild.Main.Path {
return false, nil
}
oldVersion, err := probeVersion(target)
if err != nil || !isNewerClient(version.Version, newBuild, oldVersion, oldBuild) {
return false, nil
}
// Stage the copy first so a read-only install folder leaves the old
// client running. The unique name also avoids the in-app updater's .new.
staged, err := stageExecutable(source, target, ".reims-go-takeover-*")
if err != nil {
return false, fmt.Errorf("stage update next to %s: %w", target, err)
}
defer os.Remove(staged)
if !fileMatches(target, oldFile) {
return false, nil
}
requestExit()
if err := stopClient(process); err != nil {
return false, fmt.Errorf("close old Reims-Go: %w", err)
}
if !fileMatches(target, oldFile) {
return false, nil // the old client may have completed an in-app update
}
backup, err := stageExecutable(target, target, filepath.Base(target)+".old-*")
if err != nil {
return false, fmt.Errorf("back up %s: %w", target, err)
}
if !fileMatches(target, oldFile) {
_ = os.Remove(backup)
return false, nil
}
if err := replaceExecutable(staged, target); err != nil {
_ = os.Remove(backup)
return false, fmt.Errorf("replace %s: %w", target, err)
}
if err := launchReplacement(target, relaunchArgs, windowPID); err != nil {
if restoreErr := replaceExecutable(backup, target); restoreErr != nil {
err = errors.Join(err, fmt.Errorf("restore the old client from %s: %w", backup, restoreErr))
}
return false, fmt.Errorf("reopen %s: %w", target, err)
}
return true, nil
}
// Keep the startup mutex until the replacement owns the Wails lock. Otherwise
// a concurrent launch can acquire the lock from its copy in Downloads first.
func launchReplacement(target string, args []string, windowPID func() uint32) error {
process, err := startDetached(target, args)
if err != nil {
return err
}
defer process.Release()
var startupErr error
err = process.WithHandle(func(handle uintptr) {
h := windows.Handle(handle)
deadline := time.Now().Add(12 * time.Second)
for time.Now().Before(deadline) {
if windowPID() == uint32(process.Pid) {
return
}
event, err := windows.WaitForSingleObject(h, 50)
if err != nil {
startupErr = errors.Join(err, terminateClient(h))
return
}
if event == windows.WAIT_OBJECT_0 {
startupErr = errors.New("the updated client exited before opening its window")
return
}
}
startupErr = errors.Join(errors.New("the updated client did not open its window"), terminateClient(h))
})
return errors.Join(err, startupErr)
}
func sameUser(process windows.Handle) bool {
var token windows.Token
if windows.OpenProcessToken(process, windows.TOKEN_QUERY, &token) != nil {
return false
}
defer token.Close()
user, err := token.GetTokenUser()
current, currentErr := windows.GetCurrentProcessToken().GetTokenUser()
return err == nil && currentErr == nil && !token.IsElevated() && user.User.Sid.Equals(current.User.Sid)
}
func probeVersion(exe string) (string, error) {
// Older releases expose their version through the CLI. Give the probe
// its own data directory since their CLI loads config before dispatch.
dir, err := os.MkdirTemp("", "reims-go-version-*")
if err != nil {
return "", err
}
defer os.RemoveAll(dir)
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, exe, "--data-root="+dir, "version")
cmd.Dir = dir
cmd.Env = append(os.Environ(), "REIMS_GO_LOCATION_FILE="+filepath.Join(dir, "location.json"))
cmd.WaitDelay = time.Second
cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: windows.CREATE_NO_WINDOW}
out, err := cmd.Output()
if err != nil {
return "", err
}
fields := strings.Fields(string(out))
if len(fields) != 2 || fields[0] != "reims-go" || version.Compare(fields[1], "") <= 0 {
return "", errors.New("could not identify the client version")
}
return fields[1], nil
}
func isNewerClient(newVersion string, newBuild *debug.BuildInfo, oldVersion string, oldBuild *debug.BuildInfo) bool {
newBase, _, newDev := strings.Cut(newVersion, "-dev-")
oldBase, _, oldDev := strings.Cut(oldVersion, "-dev-")
if newDev && oldDev && newBase == oldBase {
// Rolling release version suffixes are commit IDs, which have no
// meaningful order. Use the source commit timestamps when available.
previous := buildTime(oldBuild)
return newVersion != oldVersion && !previous.IsZero() && buildTime(newBuild).After(previous)
}
return version.Compare(newVersion, oldVersion) > 0
}
func buildTime(info *debug.BuildInfo) time.Time {
for _, setting := range info.Settings {
if setting.Key == "vcs.time" {
stamp, _ := time.Parse(time.RFC3339, setting.Value)
return stamp
}
}
return time.Time{}
}
func fileMatches(path string, expected os.FileInfo) bool {
current, err := os.Stat(path)
return err == nil && os.SameFile(current, expected)
}
func stopClient(process windows.Handle) error {
if event, err := windows.WaitForSingleObject(process, 3000); event == windows.WAIT_OBJECT_0 || err != nil {
return err
}
// Legacy clients do not know the quit request. Stop only the verified
// client process using the original handle, never a reused PID or tree.
return terminateClient(process)
}
func terminateClient(process windows.Handle) error {
terminateErr := windows.TerminateProcess(process, 0)
event, err := windows.WaitForSingleObject(process, 3000)
if event == windows.WAIT_OBJECT_0 {
return nil
}
return errors.Join(errors.New("the client process did not exit"), terminateErr, err)
}
func stageExecutable(src, target, pattern string) (string, error) {
file, err := os.CreateTemp(filepath.Dir(target), pattern)
if err != nil {
return "", err
}
if err := errors.Join(writeExecutable(src, file), file.Close()); err != nil {
_ = os.Remove(file.Name())
return "", err
}
return file.Name(), nil
}
func replaceExecutable(from, to string) error {
return windows.MoveFileEx(windows.StringToUTF16Ptr(from), windows.StringToUTF16Ptr(to),
windows.MOVEFILE_REPLACE_EXISTING|windows.MOVEFILE_WRITE_THROUGH)
}
func ReportTakeoverError(err error) {
fmt.Fprintln(os.Stderr, err)
message := "Reims-Go couldn't replace the older client."
if i18n.Detect() == i18n.ZhCN {
message = "Reims-Go 未能替换旧版客户端。"
}
_, _ = windows.MessageBox(0, windows.StringToUTF16Ptr(message+"\n\n"+err.Error()),
windows.StringToUTF16Ptr("Reims-Go"), windows.MB_OK|windows.MB_ICONWARNING)
}
@@ -0,0 +1,33 @@
//go:build windows
package selfupdate
import (
"runtime/debug"
"testing"
)
func TestTakeoverVersionOrdering(t *testing.T) {
build := func(stamp string) *debug.BuildInfo {
return &debug.BuildInfo{Settings: []debug.BuildSetting{{Key: "vcs.time", Value: stamp}}}
}
yesterday, today := build("2026-12-03T00:00:00Z"), build("2026-12-04T00:00:00Z")
for _, tc := range []struct {
new, old string
build *debug.BuildInfo
want bool
}{
{"v0.2.14", "v0.2.13", today, true},
{"v0.2.13", "v0.2.13", today, false},
{"v0.2.12", "v0.2.13", today, false},
{"v0.2.14-alpha.2", "v0.2.14-alpha.1", today, true},
{"v0.2.14-alpha.2", "v0.2.14", today, false},
{"v0.2.14-dev-111aaaa", "v0.2.14-dev-fff3333", today, true},
{"v0.2.14-dev-fff3333", "v0.2.14-dev-111aaaa", yesterday, false},
{"v0.2.14-dev-111aaaa", "v0.2.14-dev-fff3333", build(""), false},
} {
if got := isNewerClient(tc.new, tc.build, tc.old, yesterday); got != tc.want {
t.Errorf("take over with %s over %s = %t, want %t", tc.new, tc.old, got, tc.want)
}
}
}
+30 -2
View File
@@ -12,6 +12,7 @@ import (
"github.com/Nwflower/reims-go/internal/cli"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/selfupdate"
"github.com/wailsapp/wails/v2"
"github.com/wailsapp/wails/v2/pkg/options"
@@ -66,6 +67,30 @@ func main() {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
firstRun := os.Getenv("REIMS_GO_FIRST_RUN") == "1"
releaseStartup := func() {}
if !firstRun && !launch.TakeoverRelaunch && selfupdate.Supported() == nil {
release, err := selfupdate.LockDesktopStartup(cli.InstanceID)
if err != nil {
fmt.Fprintln(os.Stderr, err)
} else {
releaseStartup = release
defer release()
if !launch.Background && launch.WaitPID == 0 && launch.StartVM == "" && launch.ResumeVM == "" {
pid, requestExit := cli.WindowForUpdate()
relaunch := launch
relaunch.TakeoverRelaunch = true
restarted, err := selfupdate.Takeover(pid, requestExit, relaunch.Args(), cli.DesktopWindowPID)
if restarted {
return
}
if err != nil {
release()
selfupdate.ReportTakeoverError(err)
}
}
}
}
app.RegisterLicenseTexts(licenseText, noticeText)
desktopApp, hooks := app.New(trayIconPNG, launch)
// A simulated first launch must open its own window even when an installed
@@ -74,7 +99,7 @@ func main() {
UniqueId: cli.InstanceID,
OnSecondInstanceLaunch: hooks.OnSecondInstanceLaunch,
}
if os.Getenv("REIMS_GO_FIRST_RUN") == "1" {
if firstRun {
instanceLock = nil
}
err := wails.Run(&options.App{
@@ -113,7 +138,10 @@ func main() {
DarkModeBorder: windows.RGB(58, 58, 62),
},
},
OnStartup: hooks.OnStartup,
OnStartup: func(ctx context.Context) {
releaseStartup()
hooks.OnStartup(ctx)
},
OnBeforeClose: hooks.OnBeforeClose,
OnShutdown: hooks.OnShutdown,
Bind: []any{