Files
Reims-Go/internal/app/appupdate_flow.go
T
Dnyo666 ceeec602be feat(i18n,plugin): implement end-to-end i18n & L10n v2 architecture and language pack protocol
- Build single-source-of-truth 7-domain locale catalog (`locales/{zh-CN,en-US}/*.json`, 1,100+ keys) and `cmd/i18ngen` generator emitting Go catalogs and eager/lazy-split TypeScript domain modules (`core`/`vm` eager; `wizard`/`settings`/`plugins` lazy)
- Add zero-dependency ICU MessageFormat subset (`{var}`, `{n, number}`, CLDR `plural`, `select`), 8-hop cycle-free regional fallback (`zh-HK/zh-MO -> zh-Hant -> zh-TW -> zh-CN`), `auto` OS display-language preference, and `en-XA` pseudo-localization across Go and TypeScript
- Introduce `CodedError` supportability with `[E_CODE]` badges, collapsible `[detail]` diagnostics, and automatic SMC OSK / SMBIOS serial / MAC / token redaction
- Add Host × Guest macOS dual-terminology annotation (`FormatGuestTerm`) across 6 official Apple guest UI locales and localize Win32 system tray, file pickers, and DPI-adaptive `installguide` overlays with CJK font fallback probing
- Upgrade L1–L4 plugin localization to dual-track v2: Track A full language packs (`files`, WOFF2 `fonts`, cross-plugin `pluginOverrides`), Track B plugin-scoped `l10n` bundles (`HasUIMessages` isolation), live `plugin/localeChanged` notifications, `< 2ms` static CLI pack loading, and `reims-go plugin locale init|check` translator toolchain with `zh-TW` and `ja-JP` reference packs
- Harden security, WCAG 2.1 AA token contrast, `< 768px` responsive drawer & form layouts, and RTL logical properties; add backend security/locale regression tests and frontend `node --test` static/runtime guard suite in CI

# Conflicts:
#	frontend/src/i18n.ts
#	internal/cli/cli.go
#	internal/i18n/i18n.go
2026-11-30 14:56:19 +08:00

213 lines
6.4 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/i18n"
"github.com/Nwflower/reims-go/internal/installer"
"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 progress.
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 stable release in the background and
// returns the task ID ("app-update", subject = the release tag). Canceling it
// keeps the partial file, and the next download continues from there. A
// download that already finished and still verifies completes at once.
func (a *App) DownloadAppUpdate() (string, error) {
if err := a.updateSupported(); err != nil {
return "", err
}
a.mu.Lock()
if a.needsSetup {
a.mu.Unlock()
return "", errors.New("choose a data folder first")
}
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, installer.Update{
Kind: installer.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.
target := selfupdate.Target(exe, filepath.Base(path))
if err := selfupdate.Swap(exe, target, path); 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: removes what an earlier swap left next to
// the executable and, after an update restart, the downloaded installer files.
func (a *App) finishAppUpdate() {
exe, err := selfupdate.Executable()
if err != nil {
return
}
selfupdate.Cleanup(exe)
if a.launch.WaitPID == 0 {
return
}
a.mu.Lock()
dataRoot := a.cfg.DataRoot
a.mu.Unlock()
if dataRoot != "" {
_ = os.RemoveAll(appUpdateDir(dataRoot))
}
a.emitLog("app", "Reims-Go updated to "+version.Version)
}