Files
Reims-Go/internal/app/appupdate_flow.go
T
NwflowerandClaude Opus 5.5 c639682a88 refactor: remove unused functions and keep the codebase free of them
Delete functions that no product code calls, and fold "simple plus
WithOptions" pairs into the one signature callers actually use. Rename
the live macOS lifecycle functions that were labelled Legacy.

The architecture tests now share one source loader and reject functions
without a product caller and catalog messages nobody reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 20:55:03 -07:00

239 lines
7.1 KiB
Go

package app
// In-app update: download the new release's Windows executable as a tracked
// task, check it against the release's SHA256SUMS.txt, then swap it in and
// restart (internal/selfupdate). Running VMs are separate processes and keep
// running; Guest Tools reconnects once the new window is up.
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/Nwflower/reims-go/internal/cli"
"github.com/Nwflower/reims-go/internal/fetch"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/netproxy"
"github.com/Nwflower/reims-go/internal/selfupdate"
"github.com/Nwflower/reims-go/internal/version"
)
// appUpdateTaskKind is the task kind the frontend watches for update host.
const appUpdateTaskKind = "app-update"
// appUpdateReady is the verified download InstallAppUpdate swaps in.
var appUpdateReady struct {
sync.Mutex
version string
path string
sha256 string
}
func (a *App) locale() i18n.Locale {
a.mu.Lock()
raw := a.cfg.Locale
a.mu.Unlock()
return i18n.EffectiveLocale(raw)
}
func (a *App) updateErr(key string, args ...any) error {
return errors.New(i18n.T(a.locale(), key, args...))
}
func (a *App) updateSupported() error {
if err := selfupdate.Supported(); err != nil {
if errors.Is(err, selfupdate.ErrDevBuild) {
return a.updateErr("err.update_dev_build")
}
return err
}
return nil
}
func appUpdateDir(dataRoot string) string {
return filepath.Join(dataRoot, "downloads", "app")
}
// DownloadAppUpdate downloads the newest eligible release on the selected
// update channel in the background and returns the task ID ("app-update",
// subject = the release tag). Canceling keeps the partial file so the next
// download resumes from there.
func (a *App) DownloadAppUpdate() (string, error) {
if err := a.updateSupported(); err != nil {
return "", err
}
if err := a.requireWritableDataRoot(); err != nil {
return "", err
}
a.mu.Lock()
dataRoot := a.cfg.DataRoot
a.mu.Unlock()
info, err := a.CheckAppUpdate(false)
if err != nil {
return "", err
}
switch {
case !info.HasUpdate:
return "", a.updateErr("err.update_none")
case info.DownloadURL == "" || info.AssetName == "":
return "", a.updateErr("err.update_no_asset")
case info.SumsURL == "":
return "", a.updateErr("err.update_no_sums")
}
for _, t := range tasks.list() {
if t.Kind == appUpdateTaskKind && t.Status == TaskRunning {
return t.ID, nil
}
}
a.ensureTaskEmitter()
ctx, cancel := context.WithCancel(a.baseCtx())
id := tasks.start(appUpdateTaskKind, info.Latest, "", cancel)
go func() {
defer cancel()
path, sum, err := downloadAppUpdate(ctx, info, appUpdateDir(dataRoot), func(done, total int64) {
tasks.update(id, host.Update{
Kind: host.KindProgress, Step: "downloading " + info.AssetName,
Done: done, Total: total, Percent: percent(done, total),
})
})
switch {
case err == nil:
appUpdateReady.Lock()
appUpdateReady.version, appUpdateReady.path, appUpdateReady.sha256 = info.Latest, path, sum
appUpdateReady.Unlock()
a.emitLog("app", fmt.Sprintf("Update %s downloaded and verified (SHA-256 %s)", info.Latest, sum))
tasks.finish(id, info.Latest, nil)
case ctx.Err() != nil:
tasks.finish(id, "", context.Canceled)
default:
a.emitLog("app", "Update download error: "+err.Error())
tasks.finish(id, "", err)
}
}()
return id, nil
}
// downloadAppUpdate fetches info's executable into dir and checks it against
// the release's SHA256SUMS.txt. It returns the file and its hash.
func downloadAppUpdate(ctx context.Context, info version.UpdateInfo, dir string, onProgress fetch.Progress) (string, string, error) {
client := netproxy.NewClient()
want, err := fetch.ExpectedSum(ctx, client, info.SumsURL, info.AssetName)
if err != nil {
return "", "", err
}
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", "", err
}
path, err := fetch.Resume(ctx, client, info.DownloadURL, filepath.Join(dir, info.AssetName), info.AssetSize, want, onProgress)
if err != nil {
return "", "", err
}
return path, want, nil
}
// InstallAppUpdate swaps the downloaded update in for the running executable,
// starts it, and quits this window. The new window waits for this process to
// exit before it opens. Running VMs are not touched.
func (a *App) InstallAppUpdate() error {
if err := a.updateSupported(); err != nil {
return err
}
appUpdateReady.Lock()
ver, path, want := appUpdateReady.version, appUpdateReady.path, appUpdateReady.sha256
appUpdateReady.Unlock()
if path == "" {
return a.updateErr("err.update_not_ready")
}
// The file sat in the data folder since the download: check it again.
if got, err := fetch.FileSHA256(path); err != nil || !strings.EqualFold(got, want) {
appUpdateReady.Lock()
appUpdateReady.path = ""
appUpdateReady.Unlock()
return a.updateErr("err.update_changed")
}
exe, err := selfupdate.Executable()
if err != nil {
return err
}
if err := selfupdate.Writable(filepath.Dir(exe)); err != nil {
return a.updateErr("err.update_not_writable", filepath.Dir(exe))
}
// A file still named after a release takes the new release's name.
a.mu.Lock()
channel := version.ChannelStable
if a.cfg != nil {
channel = version.NormalizeChannel(a.cfg.AppUpdateChannel)
}
a.mu.Unlock()
target := selfupdate.Target(exe, filepath.Base(path))
if err := selfupdate.Swap(exe, target, path, version.KeepsPreviousInstall(channel)); err != nil {
return err
}
a.emitLog("app", fmt.Sprintf("Installed update %s at %s; restarting", ver, target))
a.uiHealth.mu.Lock()
hidden := a.uiHealth.windowHidden
a.uiHealth.mu.Unlock()
args := cli.WindowArgs{Background: hidden, WaitPID: uint32(os.Getpid())}.Args()
if err := selfupdate.Launch(target, args); err != nil {
a.emitLog("app", "Could not start the updated Reims-Go: "+err.Error())
return a.updateErr("err.update_relaunch")
}
// Return to the frontend first, then quit for real (not to the tray).
go func() {
time.Sleep(300 * time.Millisecond)
a.QuitApp()
}()
return nil
}
// finishAppUpdate runs at startup: on the stable channel it removes what an
// earlier swap left next to the executable and, after an update restart, the
// downloaded installer files. On alpha/dev channels those old executables and
// downloaded installers are preserved for safe manual rollback.
func (a *App) finishAppUpdate() {
exe, err := selfupdate.Executable()
if err != nil {
return
}
a.finishAppUpdateWithExe(exe)
}
func (a *App) finishAppUpdateWithExe(exe string) {
a.mu.Lock()
dataRoot := ""
channel := version.ChannelStable
if a.cfg != nil {
dataRoot = a.cfg.DataRoot
channel = version.NormalizeChannel(a.cfg.AppUpdateChannel)
}
a.mu.Unlock()
keepOld := version.KeepsPreviousInstall(channel)
if keepOld {
selfupdate.CleanupStaging(exe)
} else {
selfupdate.Cleanup(exe)
}
if a.launch.WaitPID == 0 {
return
}
if !keepOld && dataRoot != "" && a.dataRootUsable() {
_ = os.RemoveAll(appUpdateDir(dataRoot))
}
if keepOld {
a.emitLog("app", fmt.Sprintf("Reims-Go updated to %s (%s channel; previous executable and downloaded installers preserved)", version.Version, channel))
} else {
a.emitLog("app", "Reims-Go updated to "+version.Version)
}
}