fix(windows): start a responsive tray immediately after installation

This commit is contained in:
cabbage committed 2026-10-27 07:43:37 +00:00
1 parent 14cb3570c1
commit d59b2d5463
13 files changed
+850 -106

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
package main
import "fmt"
// Keep the original (normally unelevated) interactive process alive while its
// UAC child installs. Only successful installation may start the user frontend.
func runInstallerSteps(install func() error, startTray func() error) error {
if err := install(); err != nil {
return fmt.Errorf("install RVBox: %w", err)
}
if err := startTray(); err != nil {
return fmt.Errorf("RVBox is installed, but its notification-area icon could not start: %w", err)
}
return nil
}
+39
View File
@@ -0,0 +1,39 @@
package main
import (
"errors"
"reflect"
"strings"
"testing"
)
func TestInstallerStartsTrayOnlyAfterSuccessfulElevation_HP_WINCLI_06(t *testing.T) {
for _, tc := range []struct {
name string
installErr error
trayErr error
wantCalls []string
}{
{"success", nil, nil, []string{"install", "tray"}},
{"UAC cancelled", errors.New("cancelled"), nil, []string{"install"}},
{"installation failed", errors.New("copy failed"), nil, []string{"install"}},
{"tray failed", nil, errors.New("no desktop"), []string{"install", "tray"}},
} {
t.Run(tc.name, func(t *testing.T) {
var calls []string
err := runInstallerSteps(func() error { calls = append(calls, "install"); return tc.installErr }, func() error { calls = append(calls, "tray"); return tc.trayErr })
if !reflect.DeepEqual(calls, tc.wantCalls) {
t.Fatalf("calls = %v, want %v", calls, tc.wantCalls)
}
if tc.installErr != nil && !errors.Is(err, tc.installErr) || tc.trayErr != nil && !errors.Is(err, tc.trayErr) {
t.Fatalf("error lost its cause: %v", err)
}
if tc.installErr == nil && tc.trayErr == nil && err != nil {
t.Fatal(err)
}
if tc.trayErr != nil && !strings.Contains(err.Error(), "RVBox is installed") {
t.Fatalf("partial success is not explicit: %v", err)
}
})
}
}
+104 -20
View File
@@ -3,16 +3,21 @@
package main
import (
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"syscall"
"time"
"unsafe"
"github.com/rvbox/rvbox/internal/client/windowsservice"
"github.com/rvbox/rvbox/internal/client/windowstray"
"golang.org/x/sys/windows"
)
@@ -22,8 +27,11 @@ const (
)
var (
installerUser32 = syscall.NewLazyDLL("user32.dll")
installerMessageBox = installerUser32.NewProc("MessageBoxW")
installerUser32 = syscall.NewLazyDLL("user32.dll")
installerMessageBox = installerUser32.NewProc("MessageBoxW")
installerShellExecute = windows.NewLazySystemDLL("shell32.dll").NewProc("ShellExecuteExW")
installerCOMInitialize = windows.NewLazySystemDLL("ole32.dll").NewProc("CoInitializeEx")
installerCOMUninitialize = windows.NewLazySystemDLL("ole32.dll").NewProc("CoUninitialize")
)
// runInteractiveInstaller is the double-click entry point. It does no
@@ -35,21 +43,101 @@ func runInteractiveInstaller(_ io.Writer, _ io.Writer) error {
showInstallerMessage("RVBox setup could not locate its executable.", installerErrorIcon)
return err
}
err = runInstallerSteps(func() error { return runElevatedInstaller(executable) }, startInstalledTray)
if err != nil {
showInstallerMessage(err.Error(), installerErrorIcon)
return err
}
showInstallerMessage("RVBox is installed and its Windows service has started.\n\nThe notification-area icon is available now; no sign-out or reboot is needed. Windows may place it under the hidden-icons arrow.", installerInfoIcon)
return nil
}
// shellExecuteInfo matches SHELLEXECUTEINFOW, including pointer-sized fields
// and native alignment on the supported Windows amd64 build.
type shellExecuteInfo struct {
Size uint32
Mask uint32
Window uintptr
Verb *uint16
File *uint16
Parameters *uint16
Directory *uint16
Show int32
Instance uintptr
IDList uintptr
Class *uint16
ClassKey uintptr
HotKey uint32
Icon uintptr
Process windows.Handle
}
func runElevatedInstaller(executable string) error {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
// Shell extensions may require COM. Balance both S_OK and S_FALSE, while
// allowing a caller whose thread is already initialized in another mode.
hr, _, _ := installerCOMInitialize.Call(0, 2|4) // STA, disable OLE1 DDE.
if int32(hr) >= 0 {
defer installerCOMUninitialize.Call()
} else if uint32(hr) != 0x80010106 { // RPC_E_CHANGED_MODE
return fmt.Errorf("initialize setup shell: HRESULT %#x", uint32(hr))
}
file, err := windows.UTF16PtrFromString(executable)
if err != nil {
return err
}
arguments, err := windows.UTF16PtrFromString("--install-default")
if err != nil {
return err
info := shellExecuteInfo{
Size: uint32(unsafe.Sizeof(shellExecuteInfo{})),
Mask: 0x40 | 0x100, // SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC.
Verb: installerUTF16("runas"), File: file,
Parameters: installerUTF16("--install-default"), Show: windows.SW_SHOWNORMAL,
}
if err := windows.ShellExecute(0, installerUTF16("runas"), file, arguments, nil, windows.SW_SHOWNORMAL); err != nil {
showInstallerMessage("RVBox setup was cancelled or could not obtain administrator approval.\n\nNo changes were made.", installerErrorIcon)
return fmt.Errorf("request installer elevation: %w", err)
result, _, callErr := installerShellExecute.Call(uintptr(unsafe.Pointer(&info)))
if result == 0 {
return fmt.Errorf("request installer elevation: %w", callErr)
}
if info.Process == 0 {
return errors.New("elevated setup did not return a process handle")
}
defer windows.CloseHandle(info.Process)
if _, err := windows.WaitForSingleObject(info.Process, windows.INFINITE); err != nil {
return fmt.Errorf("wait for elevated setup: %w", err)
}
var exitCode uint32
if err := windows.GetExitCodeProcess(info.Process, &exitCode); err != nil {
return fmt.Errorf("read elevated setup result: %w", err)
}
if exitCode != 0 {
return fmt.Errorf("elevated setup failed (exit code %d)", exitCode)
}
return nil
}
func packagedInstallPaths() (string, string) {
programFiles := os.Getenv("ProgramFiles")
if programFiles == "" {
programFiles = `C:\Program Files`
}
programData := os.Getenv("ProgramData")
if programData == "" {
programData = `C:\ProgramData`
}
return filepath.Join(programFiles, "RVBox", "rvbox.exe"), filepath.Join(programData, "RVBox", "client.toml")
}
func startInstalledTray() error {
executable, configPath := packagedInstallPaths()
command := exec.Command(executable, "--tray", "--config", configPath)
if err := command.Start(); err != nil {
return err
}
_ = command.Process.Release()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return windowstray.WaitReady(ctx)
}
// installPackagedDefault executes only in the UAC-elevated child. It preserves
// a pre-existing operator configuration, atomically updates the executable,
// installs/updates the SCM service, and starts it.
@@ -59,7 +147,8 @@ func installPackagedDefault(_ io.Writer) error {
showInstallerMessage("RVBox could not be installed.\n\n"+err.Error()+"\n\nNo existing configuration was replaced.", installerErrorIcon)
return err
}
showInstallerMessage("RVBox is installed and its Windows service is starting.\n\nThe notification-area icon starts automatically at the next sign-in.", installerInfoIcon)
// The original interactive process waits for this child to exit, starts the
// tray with its own user token, then shows the single success message.
return nil
}
@@ -71,18 +160,13 @@ func installPackagedDefaultFiles() error {
if err != nil {
return fmt.Errorf("locate installer executable: %w", err)
}
programFiles := os.Getenv("ProgramFiles")
if programFiles == "" {
programFiles = `C:\Program Files`
targetExecutable, configPath := packagedInstallPaths()
targetDirectory, configDirectory := filepath.Dir(targetExecutable), filepath.Dir(configPath)
trayCtx, cancelTray := context.WithTimeout(context.Background(), 3*time.Second)
defer cancelTray()
if err := windowstray.CloseCurrent(trayCtx); err != nil {
return fmt.Errorf("close existing notification-area frontend: %w", err)
}
programData := os.Getenv("ProgramData")
if programData == "" {
programData = `C:\ProgramData`
}
targetDirectory := filepath.Join(programFiles, "RVBox")
targetExecutable := filepath.Join(targetDirectory, "rvbox.exe")
configDirectory := filepath.Join(programData, "RVBox")
configPath := filepath.Join(configDirectory, "client.toml")
// A running service can keep the prior executable open. Stop it before the
// atomic replacement; a missing service is already a successful first run.
+19
View File
@@ -0,0 +1,19 @@
//go:build windows
package main
import (
"runtime"
"testing"
"unsafe"
)
func TestInstallerShellExecuteInfoLayout_HP_WINCLI_07(t *testing.T) {
if runtime.GOARCH != "amd64" {
t.Skip("v1 Windows executable is amd64")
}
var info shellExecuteInfo
if unsafe.Sizeof(info) != 112 || unsafe.Offsetof(info.Instance) != 56 || unsafe.Offsetof(info.Process) != 104 {
t.Fatalf("SHELLEXECUTEINFOW layout mismatch: size=%d instance=%d process=%d", unsafe.Sizeof(info), unsafe.Offsetof(info.Instance), unsafe.Offsetof(info.Process))
}
}