Files
Reims-Go/internal/runtime/runtime.go
T
千川白浪andClaude Opus 5.5 4bea654736 feat: add Wails desktop GUI and stage-0 UI redesign
Wails shell over the existing Go core (app.go, main.go, wails.json,
build/), with a React frontend for the VM list, VM detail, host page,
create wizard and settings, plus process helpers for the driver and
runtime packages.

UI redesign stage 0 (docs/ui-redesign.md):
- VM actions live in the page header: one primary action per state,
  icon-only secondary actions with tooltips, the rest in a "..." menu
- install guide is a single card with the only "eject installer" button
- summary is an icon + value row; paths, ICD, CPU model and runtime hash
  moved to a collapsed "technical details" section
- logs no longer auto-open; a status bar shows merged download progress
  and an error count; the log view sticks to the bottom
- busy states on actions, toasts for results, custom delete dialog with
  "keep disk files"
- design tokens, Windows font stack, integer type scale, no inline styles
- keyboard: sidebar listbox navigation, focus rings, Ctrl+N / Ctrl+, / Ctrl+L
- copy rewritten per the restraint rules in §4.5
- Radix primitives and lucide icons replace hand-rolled widgets

Backend: OpenVMFolder binding to show a VM's directory in Explorer.
Docs: shell-design.md revised for decisions D1 and D4.
Vite dev server pinned to 127.0.0.1 so `wails dev` can reach it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 03:09:39 -07:00

387 lines
9.3 KiB
Go

package runtime
import (
"archive/zip"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strings"
"github.com/Nwflower/reims-go/internal/config"
)
type Manifest struct {
SchemaVersion int `json:"schema_version"`
Name string `json:"name"`
Platform string `json:"platform"`
UpstreamRepo string `json:"upstream_repo"`
Commit string `json:"commit"`
FullCommit string `json:"full_commit"`
QemuVersion string `json:"qemu_version"`
UtilVersion string `json:"util_version"`
BuiltAt string `json:"built_at"`
FileCount int `json:"file_count"`
DLLCount int `json:"dll_count"`
RawBytes int64 `json:"raw_bytes"`
SHA256 map[string]string `json:"sha256"`
}
type Installed struct {
Commit string `json:"commit"`
Dir string `json:"dir"`
Active bool `json:"active"`
Manifest Manifest `json:"manifest"`
}
func (r Installed) ReimsCtlPath() string {
name := "reims-ctl"
if runtime.GOOS == "windows" {
name += ".exe"
}
return filepath.Join(r.Dir, "bin", name)
}
func (r Installed) ReimsUtilPath() string {
name := "reims-util"
if runtime.GOOS == "windows" {
name += ".exe"
}
return filepath.Join(r.Dir, "bin", name)
}
func (r Installed) QemuPath() string {
name := "qemu-system-x86_64"
if runtime.GOOS == "windows" {
name += ".exe"
}
return filepath.Join(r.Dir, "qemu", "bin", name)
}
func (r Installed) QemuImgPath() string {
name := "qemu-img"
if runtime.GOOS == "windows" {
name += ".exe"
}
return filepath.Join(r.Dir, "qemu", "bin", name)
}
// List returns all valid portable runtimes installed under cfg.RuntimesDir().
func List(cfg *config.Config) ([]Installed, error) {
entries, err := os.ReadDir(cfg.RuntimesDir())
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
return nil, err
}
var out []Installed
for _, e := range entries {
if !e.IsDir() || strings.HasSuffix(e.Name(), ".tmp") {
continue
}
dir := filepath.Join(cfg.RuntimesDir(), e.Name())
m, err := readManifest(filepath.Join(dir, "manifest.json"))
if err != nil {
continue
}
commit := m.Commit
if commit == "" {
commit = e.Name()
}
out = append(out, Installed{
Commit: commit,
Dir: dir,
Active: commit == cfg.ActiveRuntime,
Manifest: m,
})
}
sort.Slice(out, func(i, j int) bool {
return out[i].Manifest.BuiltAt > out[j].Manifest.BuiltAt
})
return out, nil
}
// ResolveActive returns the currently active installed runtime.
func ResolveActive(cfg *config.Config) (*Installed, error) {
list, err := List(cfg)
if err != nil {
return nil, err
}
for i := range list {
if list[i].Commit == cfg.ActiveRuntime {
return &list[i], nil
}
}
if len(list) == 1 {
return &list[0], nil
}
return nil, errors.New("no active runtime installed")
}
// BuildChildEnv returns a clean, D-drive-isolated environment for invoking reims-ctl.
func BuildChildEnv(cfg *config.Config, rt Installed) []string {
binDir := filepath.Join(rt.Dir, "bin")
overrides := map[string]string{
"XDG_CONFIG_HOME": cfg.XDGConfigDir(),
"XDG_DATA_HOME": cfg.XDGDataDir(),
"XDG_CACHE_HOME": cfg.XDGCacheDir(),
"REIMS_CTL_QEMU": rt.QemuPath(),
}
env := os.Environ()
out := make([]string, 0, len(env)+len(overrides))
seenPath := false
for _, kv := range env {
idx := strings.IndexByte(kv, '=')
if idx <= 0 {
continue
}
k := kv[:idx]
v := kv[idx+1:]
if strings.EqualFold(k, "PATH") {
out = append(out, k+"="+binDir+string(os.PathListSeparator)+v)
seenPath = true
continue
}
skip := false
for ok := range overrides {
if strings.EqualFold(k, ok) {
skip = true
break
}
}
if !skip {
out = append(out, kv)
}
}
if !seenPath {
out = append(out, "PATH="+binDir)
}
for k, v := range overrides {
out = append(out, k+"="+v)
}
return out
}
// InstallFromArchive verifies and atomically extracts a .tar.zst or .zip runtime archive.
func InstallFromArchive(cfg *config.Config, archivePath string) (*Installed, error) {
if err := cfg.EnsureDirs(); err != nil {
return nil, err
}
if err := verifySidecarSHA256(archivePath); err != nil {
return nil, err
}
tmpDir, err := os.MkdirTemp(cfg.RuntimesDir(), "install-*.tmp")
if err != nil {
return nil, err
}
defer os.RemoveAll(tmpDir)
low := strings.ToLower(archivePath)
switch {
case strings.HasSuffix(low, ".tar.zst"):
if err := extractTarZst(archivePath, tmpDir); err != nil {
return nil, err
}
case strings.HasSuffix(low, ".zip"):
if err := extractZip(archivePath, tmpDir); err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("unsupported archive format: %s (expected .tar.zst or .zip)", archivePath)
}
bundleDir, err := findBundleRoot(tmpDir)
if err != nil {
return nil, err
}
m, err := readManifest(filepath.Join(bundleDir, "manifest.json"))
if err != nil {
return nil, fmt.Errorf("read manifest.json: %w", err)
}
if m.Commit == "" {
return nil, errors.New("manifest.json missing commit")
}
for rel, expected := range m.SHA256 {
fp := filepath.Join(bundleDir, filepath.FromSlash(rel))
got, err := fileSHA256(fp)
if err != nil {
return nil, fmt.Errorf("hash %s: %w", rel, err)
}
if !strings.EqualFold(got, expected) {
return nil, fmt.Errorf("SHA256 mismatch for %s: expected %s, got %s", rel, expected, got)
}
}
finalDir := filepath.Join(cfg.RuntimesDir(), m.Commit)
_ = os.RemoveAll(finalDir)
if err := os.Rename(bundleDir, finalDir); err != nil {
return nil, fmt.Errorf("activate runtime dir: %w", err)
}
return &Installed{
Commit: m.Commit,
Dir: finalDir,
Active: true,
Manifest: m,
}, nil
}
func readManifest(path string) (Manifest, error) {
var m Manifest
raw, err := os.ReadFile(path)
if err != nil {
return m, err
}
// Strip UTF-8 BOM if written by Windows PowerShell Set-Content -Encoding utf8.
raw = []byte(strings.TrimPrefix(string(raw), "\uFEFF"))
err = json.Unmarshal(raw, &m)
return m, err
}
func findBundleRoot(dir string) (string, error) {
if _, err := os.Stat(filepath.Join(dir, "manifest.json")); err == nil {
return dir, nil
}
entries, err := os.ReadDir(dir)
if err != nil {
return "", err
}
for _, e := range entries {
if e.IsDir() {
sub := filepath.Join(dir, e.Name())
if _, err := os.Stat(filepath.Join(sub, "manifest.json")); err == nil {
return sub, nil
}
}
}
return "", errors.New("manifest.json not found in extracted runtime archive")
}
func verifySidecarSHA256(archivePath string) error {
sidecar := archivePath + ".sha256"
raw, err := os.ReadFile(sidecar)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil
}
return err
}
fields := strings.Fields(string(raw))
if len(fields) == 0 {
return nil
}
got, err := fileSHA256(archivePath)
if err != nil {
return err
}
if !strings.EqualFold(got, fields[0]) {
return fmt.Errorf("archive SHA256 mismatch: expected %s, got %s", fields[0], got)
}
return nil
}
func fileSHA256(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
func extractTarZst(archivePath, destDir string) error {
// Windows 10/11 built-in bsdtar supports .tar.zst natively on modern builds;
// fall back to zstd -dc | tar -xf if needed.
cmd := exec.Command("tar", "-xf", archivePath, "-C", destDir)
configureCmd(cmd)
if out, err := cmd.CombinedOutput(); err == nil {
return nil
} else {
zstdBin := findZstd()
if zstdBin == "" {
return fmt.Errorf("tar -xf failed (%v: %s) and zstd was not found", err, strings.TrimSpace(string(out)))
}
z := exec.Command(zstdBin, "-dc", archivePath)
t := exec.Command("tar", "-xf", "-", "-C", destDir)
configureCmd(z)
configureCmd(t)
pipe, err := z.StdoutPipe()
if err != nil {
return err
}
t.Stdin = pipe
if err := z.Start(); err != nil {
return err
}
tOut, tErr := t.CombinedOutput()
zErr := z.Wait()
if tErr != nil {
return fmt.Errorf("tar extract failed: %v (%s)", tErr, strings.TrimSpace(string(tOut)))
}
return zErr
}
}
func findZstd() string {
for _, c := range []string{"zstd", `D:\DevTools\msys64\usr\bin\zstd.exe`, `D:\DevTools\msys64\clang64\bin\zstd.exe`} {
if p, err := exec.LookPath(c); err == nil {
return p
}
}
return ""
}
func extractZip(archivePath, destDir string) error {
r, err := zip.OpenReader(archivePath)
if err != nil {
return err
}
defer r.Close()
for _, f := range r.File {
target := filepath.Join(destDir, f.Name)
if !strings.HasPrefix(filepath.Clean(target), filepath.Clean(destDir)+string(os.PathSeparator)) {
return fmt.Errorf("illegal zip path: %s", f.Name)
}
if f.FileInfo().IsDir() {
if err := os.MkdirAll(target, 0o755); err != nil {
return err
}
continue
}
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
return err
}
rc, err := f.Open()
if err != nil {
return err
}
out, err := os.Create(target)
if err != nil {
rc.Close()
return err
}
_, copyErr := io.Copy(out, rc)
rc.Close()
closeErr := out.Close()
if copyErr != nil {
return copyErr
}
if closeErr != nil {
return closeErr
}
}
return nil
}