Files
Reims-Go/internal/driver/reims/reims.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

594 lines
20 KiB
Go

package reims
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
// Client wraps reims-ctl invocations using an isolated portable runtime.
type Client struct {
Binary string
Env []string
}
func NewClient(cfg *config.Config, installed rt.Installed) *Client {
return &Client{
Binary: installed.ReimsCtlPath(),
Env: rt.BuildChildEnv(cfg, installed),
}
}
type VMListItem struct {
Name string `json:"name"`
Dir string `json:"dir"`
PID *int `json:"pid"`
State string `json:"state"`
}
type VMDetail struct {
Name string `json:"name"`
State string `json:"state"`
Kind string `json:"kind"`
Directory string `json:"directory"`
CPUs int `json:"cpus"`
Memory string `json:"memory"`
Disk string `json:"disk"`
DiskController string `json:"disk_controller"`
Graphics string `json:"graphics"`
Display string `json:"display"`
Displays int `json:"displays"`
Resolution string `json:"resolution"`
GPU string `json:"gpu"`
HasOpenCore bool `json:"has_opencore"`
HasInstaller bool `json:"has_installer"`
InstallerPath string `json:"installer_path,omitempty"`
CPUModel string `json:"cpu_model"`
Audio bool `json:"audio"`
AudioRaw string `json:"audio_raw"`
Network bool `json:"network"`
NetworkSummary string `json:"network_summary"`
SSHPort int `json:"ssh_port"`
Logs bool `json:"logs"`
LogLevel string `json:"log_level"`
StopTimeout int `json:"stop_timeout"`
Capture bool `json:"capture"`
Borderless bool `json:"borderless"`
ExtraArgs string `json:"extra_args"`
}
type ValidationIssue struct {
Field string `json:"field"`
Code string `json:"code"`
Message string `json:"message"`
}
type CreateOpts struct {
Name string `json:"name"`
Dir string `json:"dir,omitempty"`
SourceMode string `json:"source_mode,omitempty"` // "apple" | "installer" | "disk"
MacOS string `json:"macos,omitempty"`
Installer string `json:"installer,omitempty"`
CPUs int `json:"cpus,omitempty"`
Memory string `json:"memory,omitempty"`
DiskSize string `json:"disk_size,omitempty"`
Disk string `json:"disk,omitempty"`
DiskMode string `json:"disk_mode,omitempty"`
Graphics string `json:"graphics,omitempty"`
GPU string `json:"gpu,omitempty"`
Resolution string `json:"resolution,omitempty"`
Displays int `json:"displays,omitempty"`
Borderless *bool `json:"borderless,omitempty"`
Audio *bool `json:"audio,omitempty"`
Network *bool `json:"network,omitempty"`
SSHPort int `json:"ssh_port,omitempty"`
Logs *bool `json:"logs,omitempty"`
Start bool `json:"start,omitempty"`
}
type SetOpts struct {
Name string `json:"name"`
CPUs int `json:"cpus,omitempty"`
Memory string `json:"memory,omitempty"`
Graphics string `json:"graphics,omitempty"`
Displays int `json:"displays,omitempty"`
DiskController string `json:"disk_controller,omitempty"`
Resolution string `json:"resolution,omitempty"`
Borderless *bool `json:"borderless,omitempty"`
Capture *bool `json:"capture,omitempty"`
GPU string `json:"gpu,omitempty"`
Logs *bool `json:"logs,omitempty"`
LogLevel string `json:"log_level,omitempty"`
Audio *bool `json:"audio,omitempty"`
AudioBackend string `json:"audio_backend,omitempty"`
Network *bool `json:"network,omitempty"`
SSHPort *int `json:"ssh_port,omitempty"`
StopTimeout *int `json:"stop_timeout,omitempty"`
ExtraArgs *string `json:"extra_args,omitempty"`
Env []string `json:"env,omitempty"`
}
var (
reVMName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`)
reSizeG = regexp.MustCompile(`(?i)^(\d+)\s*([GM])$`)
reRes = regexp.MustCompile(`^(\d{3,5})x(\d{3,5})$`)
reMac = regexp.MustCompile(`(?i),?\s*mac\s+[0-9a-f]{2}(:[0-9a-f]{2}){5}`)
)
// ParseSizeGB parses "16G" or "4096M" into gigabytes.
func ParseSizeGB(raw string) (float64, bool) {
m := reSizeG.FindStringSubmatch(strings.TrimSpace(raw))
if len(m) != 3 {
return 0, false
}
v, err := strconv.ParseFloat(m[1], 64)
if err != nil || v <= 0 {
return 0, false
}
if strings.EqualFold(m[2], "M") {
return v / 1024.0, true
}
return v, true
}
// ValidateCreate performs pre-save validation aligned with VZVirtualMachineConfiguration.validate().
func ValidateCreate(o CreateOpts, rep host.Report) []ValidationIssue {
var issues []ValidationIssue
name := strings.TrimSpace(o.Name)
if !reVMName.MatchString(name) {
issues = append(issues, ValidationIssue{Field: "name", Code: "invalid_name", Message: "VM name must start with a letter/digit and use only A-Z, 0-9, ., _, -"})
}
if o.CPUs < 1 || (rep.LogicalCPUs > 0 && o.CPUs > rep.LogicalCPUs) {
issues = append(issues, ValidationIssue{Field: "cpus", Code: "invalid_cpus", Message: fmt.Sprintf("vCPUs must be between 1 and %d", max(rep.LogicalCPUs, 1))})
}
if o.Memory != "" {
memGB, ok := ParseSizeGB(o.Memory)
if !ok || memGB < 2 {
issues = append(issues, ValidationIssue{Field: "memory", Code: "invalid_memory", Message: "Memory must be at least 2G (e.g. 8G, 16G)"})
} else if rep.TotalRAMGB > 0 && memGB > rep.TotalRAMGB*0.85 {
issues = append(issues, ValidationIssue{Field: "memory", Code: "memory_exceeds_host", Message: fmt.Sprintf("Memory %.0fG exceeds safe host limit (host total %.1f GB)", memGB, rep.TotalRAMGB)})
}
}
if o.Disk == "" && o.DiskSize != "" {
diskGB, ok := ParseSizeGB(o.DiskSize)
if !ok || diskGB < 32 {
issues = append(issues, ValidationIssue{Field: "disk_size", Code: "invalid_disk_size", Message: "New disk size must be at least 32G (recommended 128G)"})
}
}
if o.Disk != "" {
if _, err := os.Stat(o.Disk); err != nil {
issues = append(issues, ValidationIssue{Field: "disk", Code: "disk_not_found", Message: "Selected disk image file does not exist"})
}
}
if o.Installer != "" {
if _, err := os.Stat(o.Installer); err != nil {
issues = append(issues, ValidationIssue{Field: "installer", Code: "installer_not_found", Message: "Selected installer image file does not exist"})
}
}
if o.GPU != "" && o.GPU != "auto" && strings.HasSuffix(strings.ToLower(o.GPU), ".json") {
if _, err := os.Stat(o.GPU); err != nil {
issues = append(issues, ValidationIssue{Field: "gpu", Code: "gpu_icd_not_found", Message: "Selected Vulkan ICD JSON file does not exist"})
}
}
if o.Resolution != "" && !reRes.MatchString(strings.TrimSpace(o.Resolution)) {
issues = append(issues, ValidationIssue{Field: "resolution", Code: "invalid_resolution", Message: "Resolution must match WIDTHxHEIGHT (e.g. 1920x1080)"})
}
if o.Displays != 0 && (o.Displays < 1 || o.Displays > 4) {
issues = append(issues, ValidationIssue{Field: "displays", Code: "invalid_displays", Message: "Displays must be between 1 and 4"})
}
if o.SSHPort < 0 || o.SSHPort > 65535 {
issues = append(issues, ValidationIssue{Field: "ssh_port", Code: "invalid_ssh_port", Message: "SSH port must be 0..65535"})
}
return issues
}
// ValidateSet validates configuration edits before invoking `reims-ctl set`.
func ValidateSet(o SetOpts, current VMDetail, rep host.Report) []ValidationIssue {
var issues []ValidationIssue
if strings.TrimSpace(o.Name) == "" {
issues = append(issues, ValidationIssue{Field: "name", Code: "missing_name", Message: "VM name is required"})
}
if o.CPUs != 0 && (o.CPUs < 1 || (rep.LogicalCPUs > 0 && o.CPUs > rep.LogicalCPUs)) {
issues = append(issues, ValidationIssue{Field: "cpus", Code: "invalid_cpus", Message: fmt.Sprintf("vCPUs must be between 1 and %d", max(rep.LogicalCPUs, 1))})
}
if o.Memory != "" {
memGB, ok := ParseSizeGB(o.Memory)
if !ok || memGB < 2 {
issues = append(issues, ValidationIssue{Field: "memory", Code: "invalid_memory", Message: "Memory must be at least 2G"})
} else if rep.TotalRAMGB > 0 && memGB > rep.TotalRAMGB*0.85 {
issues = append(issues, ValidationIssue{Field: "memory", Code: "memory_exceeds_host", Message: fmt.Sprintf("Memory %.0fG exceeds safe host limit (%.1f GB total)", memGB, rep.TotalRAMGB)})
}
}
if o.Graphics != "" && current.Graphics != "" && o.Graphics != current.Graphics && current.State == "running" {
issues = append(issues, ValidationIssue{Field: "graphics", Code: "graphics_requires_stop", Message: "Stop the VM before switching graphics type (OpenCore must be rebuilt)"})
}
if o.DiskController != "" && current.HasInstaller {
issues = append(issues, ValidationIssue{Field: "disk_controller", Code: "eject_before_controller_change", Message: "Eject the macOS installer before changing disk controller"})
}
if o.GPU != "" && o.GPU != "auto" && strings.HasSuffix(strings.ToLower(o.GPU), ".json") {
if _, err := os.Stat(o.GPU); err != nil {
issues = append(issues, ValidationIssue{Field: "gpu", Code: "gpu_icd_not_found", Message: "Selected Vulkan ICD JSON file does not exist"})
}
}
if o.Resolution != "" && !reRes.MatchString(strings.TrimSpace(o.Resolution)) {
issues = append(issues, ValidationIssue{Field: "resolution", Code: "invalid_resolution", Message: "Resolution must match WIDTHxHEIGHT"})
}
if o.Displays != 0 && (o.Displays < 1 || o.Displays > 4) {
issues = append(issues, ValidationIssue{Field: "displays", Code: "invalid_displays", Message: "Displays must be between 1 and 4"})
}
if o.SSHPort != nil && (*o.SSHPort < 0 || *o.SSHPort > 65535) {
issues = append(issues, ValidationIssue{Field: "ssh_port", Code: "invalid_ssh_port", Message: "SSH port must be 0..65535"})
}
return issues
}
// BuildCreateArgs converts CreateOpts into deterministic reims-ctl CLI arguments.
func BuildCreateArgs(o CreateOpts) ([]string, error) {
if strings.TrimSpace(o.Name) == "" {
return nil, fmt.Errorf("vm name is required")
}
args := []string{"create", o.Name}
if o.Dir != "" {
args = append(args, "--dir", o.Dir)
}
if o.MacOS != "" {
args = append(args, "--macos", o.MacOS)
}
if o.Installer != "" {
args = append(args, "--installer", o.Installer)
}
if o.CPUs > 0 {
args = append(args, "--cpus", strconv.Itoa(o.CPUs))
}
if o.Memory != "" {
args = append(args, "--memory", o.Memory)
}
if o.DiskSize != "" && o.Disk == "" {
args = append(args, "--disk-size", o.DiskSize)
}
if o.Disk != "" {
args = append(args, "--disk", o.Disk)
if o.DiskMode != "" {
args = append(args, "--disk-mode", o.DiskMode)
}
}
if o.Graphics != "" {
args = append(args, "--graphics", o.Graphics)
}
if o.GPU != "" {
args = append(args, "--gpu", o.GPU)
}
if o.Resolution != "" {
args = append(args, "--resolution", o.Resolution)
}
if o.Displays > 0 {
args = append(args, "--displays", strconv.Itoa(o.Displays))
}
if o.Borderless != nil {
args = append(args, "--borderless", strconv.FormatBool(*o.Borderless))
}
if o.Audio != nil {
args = append(args, "--audio", strconv.FormatBool(*o.Audio))
}
if o.Network != nil {
args = append(args, "--network", strconv.FormatBool(*o.Network))
}
if o.SSHPort > 0 {
args = append(args, "--ssh-port", strconv.Itoa(o.SSHPort))
}
if o.Logs != nil {
args = append(args, "--logs", strconv.FormatBool(*o.Logs))
}
if o.Start {
args = append(args, "--start")
}
return args, nil
}
// PreviewCreateCommand formats the exact CLI command shown on Step 5 of the wizard.
func PreviewCreateCommand(o CreateOpts) (string, error) {
args, err := BuildCreateArgs(o)
if err != nil {
return "", err
}
quoted := make([]string, 0, len(args)+1)
quoted = append(quoted, "reims-ctl")
for _, a := range args {
if strings.ContainsAny(a, " \t\"") {
quoted = append(quoted, strconv.Quote(a))
} else {
quoted = append(quoted, a)
}
}
return strings.Join(quoted, " "), nil
}
// BuildSetArgs converts SetOpts into reims-ctl set CLI arguments.
func BuildSetArgs(o SetOpts) ([]string, error) {
if strings.TrimSpace(o.Name) == "" {
return nil, fmt.Errorf("vm name is required")
}
args := []string{"set", o.Name}
if o.CPUs > 0 {
args = append(args, "--cpus", strconv.Itoa(o.CPUs))
}
if o.Memory != "" {
args = append(args, "--memory", o.Memory)
}
if o.Graphics != "" {
args = append(args, "--graphics", o.Graphics)
}
if o.Displays > 0 {
args = append(args, "--displays", strconv.Itoa(o.Displays))
}
if o.DiskController != "" {
args = append(args, "--disk-controller", o.DiskController)
}
if o.Resolution != "" {
args = append(args, "--resolution", o.Resolution)
}
if o.Borderless != nil {
args = append(args, "--borderless", strconv.FormatBool(*o.Borderless))
}
if o.Capture != nil {
args = append(args, "--capture", strconv.FormatBool(*o.Capture))
}
if o.GPU != "" {
args = append(args, "--gpu", o.GPU)
}
if o.Logs != nil {
args = append(args, "--logs", strconv.FormatBool(*o.Logs))
}
if o.LogLevel != "" {
args = append(args, "--log-level", o.LogLevel)
}
if o.Audio != nil {
args = append(args, "--audio", strconv.FormatBool(*o.Audio))
}
if o.AudioBackend != "" {
args = append(args, "--audio-backend", o.AudioBackend)
}
if o.Network != nil {
args = append(args, "--network", strconv.FormatBool(*o.Network))
}
if o.SSHPort != nil {
args = append(args, "--ssh-port", strconv.Itoa(*o.SSHPort))
}
if o.StopTimeout != nil {
args = append(args, "--stop-timeout", strconv.Itoa(*o.StopTimeout))
}
if o.ExtraArgs != nil {
args = append(args, "--extra-args", *o.ExtraArgs)
}
for _, kv := range o.Env {
if strings.TrimSpace(kv) != "" {
args = append(args, "--env", kv)
}
}
return args, nil
}
// ParseShow parses the text output of `reims-ctl show <name>` while redacting MAC addresses.
func ParseShow(name, text string) VMDetail {
d := VMDetail{
Name: name,
Displays: 1,
Resolution: "1920x1080",
DiskController: "ahci",
Graphics: "reims-vgpu",
GPU: "auto",
Capture: true,
StopTimeout: 90,
}
for _, rawLine := range strings.Split(text, "\n") {
line := strings.TrimSpace(rawLine)
if line == "" || line == name {
continue
}
// Keys are separated from values by 2+ spaces in `reims-ctl show`.
parts := regexp.MustCompile(`\s{2,}`).Split(line, 2)
if len(parts) != 2 {
continue
}
k := strings.ToLower(strings.TrimSpace(parts[0]))
v := strings.TrimSpace(parts[1])
switch k {
case "state":
d.State = v
case "kind":
d.Kind = v
case "directory":
d.Directory = v
case "cpus":
d.CPUs, _ = strconv.Atoi(v)
case "memory":
d.Memory = v
case "disk":
d.Disk = v
low := strings.ToLower(v)
switch {
case strings.Contains(low, "nvme"):
d.DiskController = "nvme"
case strings.Contains(low, "virtio"):
d.DiskController = "virtio"
default:
d.DiskController = "ahci"
}
case "graphics":
if strings.HasPrefix(v, "vmware-svga") {
d.Graphics = "vmware-svga"
} else {
d.Graphics = "reims-vgpu"
}
case "display":
d.Display = v
if m := reRes.FindString(v); m != "" {
d.Resolution = m
}
if strings.Contains(strings.ToLower(v), "borderless") {
d.Borderless = true
}
switch {
case strings.HasPrefix(v, "two"):
d.Displays = 2
case strings.HasPrefix(v, "three"):
d.Displays = 3
case strings.HasPrefix(v, "four"):
d.Displays = 4
default:
d.Displays = 1
}
case "gpu":
if strings.HasPrefix(strings.ToLower(v), "automatic") {
d.GPU = "auto"
} else {
d.GPU = v
}
case "opencore":
d.HasOpenCore = v != ""
case "installer":
d.HasInstaller = v != "" && !strings.EqualFold(v, "none")
d.InstallerPath = v
case "cpu model":
d.CPUModel = v
case "audio":
d.AudioRaw = v
d.Audio = strings.HasPrefix(strings.ToLower(v), "on")
case "network":
// Redact MAC per docs/shell-design.md §3.
d.NetworkSummary = strings.TrimSpace(reMac.ReplaceAllString(v, " (MAC configured)"))
d.Network = !strings.EqualFold(v, "off") && !strings.EqualFold(v, "none")
case "ssh":
if m := regexp.MustCompile(`(\d+)`).FindString(v); m != "" {
d.SSHPort, _ = strconv.Atoi(m)
}
case "logs":
d.Logs = strings.HasPrefix(strings.ToLower(v), "on")
if m := regexp.MustCompile(`\(([^)]+)\)`).FindStringSubmatch(v); len(m) == 2 {
d.LogLevel = m[1]
}
case "stop timeout":
if m := regexp.MustCompile(`(\d+)`).FindString(v); m != "" {
d.StopTimeout, _ = strconv.Atoi(m)
}
case "capture":
d.Capture = !strings.EqualFold(v, "off") && !strings.EqualFold(v, "false")
case "extra args":
d.ExtraArgs = v
}
}
return d
}
func (c *Client) run(ctx context.Context, stdout, stderr io.Writer, args ...string) error {
cmd := exec.CommandContext(ctx, c.Binary, args...)
configureCmd(cmd)
cmd.Env = c.Env
if stdout != nil {
cmd.Stdout = stdout
}
if stderr != nil {
cmd.Stderr = stderr
}
return cmd.Run()
}
func (c *Client) List(ctx context.Context) ([]VMListItem, error) {
var out, errBuf bytes.Buffer
if err := c.run(ctx, &out, &errBuf, "list", "--json"); err != nil {
return nil, fmt.Errorf("reims-ctl list: %w (%s)", err, strings.TrimSpace(errBuf.String()))
}
var list []VMListItem
if err := json.Unmarshal(bytes.TrimSpace(out.Bytes()), &list); err != nil {
return nil, fmt.Errorf("parse list --json: %w", err)
}
return list, nil
}
func (c *Client) ListRaw(ctx context.Context) ([]map[string]any, error) {
var out, errBuf bytes.Buffer
if err := c.run(ctx, &out, &errBuf, "list", "--json"); err != nil {
return nil, fmt.Errorf("reims-ctl list: %w (%s)", err, strings.TrimSpace(errBuf.String()))
}
var list []map[string]any
if err := json.Unmarshal(bytes.TrimSpace(out.Bytes()), &list); err != nil {
return nil, fmt.Errorf("parse list --json: %w", err)
}
return list, nil
}
func (c *Client) Show(ctx context.Context, name string) (VMDetail, error) {
var out, errBuf bytes.Buffer
if err := c.run(ctx, &out, &errBuf, "show", name); err != nil {
return VMDetail{}, fmt.Errorf("reims-ctl show %s: %w (%s)", name, err, strings.TrimSpace(errBuf.String()))
}
return ParseShow(name, out.String()), nil
}
func (c *Client) ReadLogs(ctx context.Context, name string, serial bool) (string, error) {
args := []string{"logs", name}
if serial {
args = append(args, "--serial")
}
var out, errBuf bytes.Buffer
if err := c.run(ctx, &out, &errBuf, args...); err != nil {
msg := strings.TrimSpace(errBuf.String())
if msg == "" {
msg = err.Error()
}
return out.String(), fmt.Errorf("%s", msg)
}
return out.String(), nil
}
func (c *Client) Create(ctx context.Context, o CreateOpts, stdout, stderr io.Writer) error {
args, err := BuildCreateArgs(o)
if err != nil {
return err
}
return c.run(ctx, stdout, stderr, args...)
}
func (c *Client) Set(ctx context.Context, o SetOpts, stdout, stderr io.Writer) error {
args, err := BuildSetArgs(o)
if err != nil {
return err
}
return c.run(ctx, stdout, stderr, args...)
}
func (c *Client) Start(ctx context.Context, name string, stdout, stderr io.Writer) error {
return c.run(ctx, stdout, stderr, "start", name)
}
func (c *Client) Stop(ctx context.Context, name string, stdout, stderr io.Writer) error {
return c.run(ctx, stdout, stderr, "stop", name)
}
func (c *Client) StopForce(ctx context.Context, name string, stdout, stderr io.Writer) error {
return c.run(ctx, stdout, stderr, "stop", "--force", name)
}
func (c *Client) Eject(ctx context.Context, name string, stdout, stderr io.Writer) error {
return c.run(ctx, stdout, stderr, "eject", name)
}
func (c *Client) Delete(ctx context.Context, name string, keepFiles bool, stdout, stderr io.Writer) error {
args := []string{"delete", name}
if keepFiles {
args = append(args, "--keep-files")
}
return c.run(ctx, stdout, stderr, args...)
}