Files
Reims-Go/internal/macos/macosdriver/driver.go
T
球球 7fd1947bef feat(plugin,host,macos,ui): 实现 Agent 受控接管、受保护阶段确认、离线预配置与自动装机基础 (#103, #105, #129) (#134)
* feat(plugin,host,ui): add agent session takeover, protected-phase confirmation, and autoinstall host foundation

* feat(macos,ui,cli): add offline REIMSPROV first-boot provisioning to skip Setup Assistant (#129)

Builds a per-VM read-only REIMSPROV disk image containing a pure-Go XAR Distribution flat package (provision.pkg) and an offline Recovery fallback script (provision-offline.sh). Passwords are hashed in memory to Apple SALTED-SHA512-PBKDF2 bplist00 ShadowHashData (never persisted in plaintext, no auto-login or NOPASSWD sudo). Uses native OpenDirectory.framework (JXA NSData) + dseditgroup under SIP-enabled live bootinstalld and dslocal plist + PlistBuddy under offline Recovery, skips Setup Assistant and Keyboard Setup Assistant, pre-stages Guest Tools, integrates with CreateWizard / VMPage / vm provision CLI / StartAutoInstall, and zero-wipes on finish_install, normal cold start, or DeleteVM.

* feat(autoinstall,host,ui): add input-locked session shield, recovery-only mode, and restart grace cap

Adds the real-machine end-to-end verified baseline for automatic macOS installation: (1) takeover_policy 'lock' with transparent Win32 VM client-area input shield, low-level key/mouse lock preserving host escape shortcuts (Alt+Tab/Alt+Esc/Win), HUD & UI Pause/Resume controls, and write guards while paused; (2) decoupled recovery_only vs full (REIMSPROV) modes in StartAutoInstall, CreateWizard, and VMAutoInstallPanel; (3) graceful_timeout_sec cap (default 10s) on automated built-in macOS host/vm.restart so Setup Assistant/Login Window restarts do not stall 90s on ACPI; (4) additional modifier aliases in console manager and agent-session/telemetry cleanup on VM deletion.

* feat(autoinstall,overlay,plugin): add built-in macOS auto-install plugin, dynamic island overlay, and review fixes

* fix(app,host,macos,ui): address PR #134 automated review findings

- Frontend & i18n:
  - Fix UTF-8/GBK mojibake in VMPage.tsx.
  - Emit reims:confirm-resolved on timeout/cancel/resolve so frontend modals auto-close and surface errors cleanly; stop submitCreate from continuing after PrepareVMProvision failure.
  - Gate AutoInstallPanel RapidOCR download button on preflight can_download_ocr when pinned default assets are unavailable.
- App / Sessions / Confirm / Lifecycle:
  - Add 30s denial cooldown for protected-phase confirmation prompts and revoke (pluginID, vmKey) grants on non-completed session exits.
  - Fix sessionOverlay / activeAgentSessions data race, remove duplicate permission-denied invocation, guard against clobbering other sessions or completed overlays, and unify VM key normalization.
  - Grant protected-phase confirmation and attach lock-mode session + watcher when resuming auto-install without an active session.
  - Unify FinishInstall and host/vm.finishInstall result handling and persist .reims-go-provision-ready across restarts.
  - Preserve non-timeout stop errors in restartMacOSVMLocked instead of force-killing.
- Host Takeover Hooks:
  - Require both keyboard and mouse WH_*_LL hooks (rolling back partial installs), initialize thread message queue before ready, reset started state on error/exit for retry, and report hook failures.
- macOS Provisioning & Autoinstall Engine:
  - Track REIMSPROV staged/wipe-pending/ready lifecycle markers, exclude "restore" recovery marker from re-attaching REIMSPROV, fail explicitly on offline admin plist creation failure, and report wipe failures.
  - Serialize per-VM Start/Stop/Resume with stop generation tokens, guard ROI fast-path against maxDim overflow, switch hostclient early-event buffer to FIFO eviction, fix untyped nil Engine return, tighten negation & high-risk fuzzy matching, preserve ackedQemuErrors across RebootWindow resets, and re-orient/expire stale inherited running checkpoints.
  - Document verified Windows SDK IDL vtable slots for WinOCR (live-tested on Windows) and add regression tests across app, host, macosdriver, startprep, installer, and autoinstall packages.

* fix(app,cli,host,macos,ui): address PR #134 second automated review findings

- CLI & Desktop Control Channel:
  - Add __reims_host__ / autoinstall desktop control channel with data_root verification so CLI status, resume, and stop talk directly to the live desktop runner instead of splitting checkpoint state or launching doomed short-lived CLI runners.
  - Merge live runners with on-disk checkpoints when listing status without a VM argument.
- App Sessions, Confirmations, Downloads & Telemetry:
  - Scope single-VM not_authorized errors to the target VM in handleSessionBegin and resolveComputerUseVM so active sessions on other VMs are not aborted.
  - Exclude stopped and suspended VMs from hasUnboundAgentSession fast-polling.
  - Revoke protected-phase grants when a VM disappears from poll results.
  - Require manifest Secret:true validation before storing auto-install passwords and remove the unsafe default account_password fallback.
  - Reject userinfo URLs in allow_custom_mirror, gate custom-mirror exemption strictly on plugin.ErrNetOriginNotDeclared, and keep redirect SSRF checks enabled on loopback custom mirrors.
  - Preserve VM telemetry milestones across suspend-resume and Win10 cold-reboot restarts while still resetting on fresh cold boots.
  - Log a warning when Guest Tools bridge is unavailable while preparing REIMSPROV.
  - Clarify CallHostAPI authorization/audit contract and add regression test proving built-in plugins enforce catalog permissions and audit logging.
- Host Takeover & Guest Tools:
  - Track locked mouse button presses via a 5-button bitmask so ButtonUp events from drags started outside the VM window are never swallowed.
  - Align active-window-reporter.js permissions to 0o100755 across ToolsDiskFiles, ToolsProvisionFiles, and postinstall.
- macOS Provisioning & Autoinstall Engine (OCR / Vision / Rules / Runner):
  - Never delete an unwiped REIMSPROV image on OpenFile/Write/Sync failure; persist wipe-pending marker and return error for retry.
  - Harden live postinstall preference writes with chmod 600, plutil -lint, chown, and cfprefsd flush.
  - Rewrite Windows RapidOCR C ABI structs and result extraction to match RapidAI/RapidOcrOnnx@675e73fe4c include/OcrLiteCApi.h:27-70 and src/OcrLiteCApi.cpp:12-160 (5-arg OcrInit verified).
  - Inspect PE32/PE32+ IMAGE_DIRECTORY_ENTRY_IMPORT directly to require onnxruntime.dll only for dynamically linked RapidOcrOnnx.dll builds.
  - Validate cfg.VM and use collision-free SHA-256-suffixed checkpoint paths with read fallback; redact PII/paths/UUIDs/MACs/IPs/tokens in diagnostic summaries; snapshot checkpoints before releasing r.mu for serialized disk I/O.
  - Add contrast/border/focus-ring ok return to DetectInputFieldNearLabel, enforce mask-dots verification in fillAccountForm and login screens, refuse blind password typing on clock-only lock screens, confirm shell readiness before typing install.sh, and prefer isolated button lines over modal prose in FindHit.
- Frontend:
  - Require explicit Apple SLA confirmation in both recovery_only and full modes across AutoInstallPanel and CreateWizard, with unit tests in frontend/scripts/test-autoinstall.mjs.

* fix(app,cli,host,macos,ui): address PR #134 third automated review findings

Addresses all confirmed findings from Review #6204465334 (commit d516350)
with targeted regression tests and hardens verified COM vtable bindings:

- App & Session Lifecycle:
  - Track hostPaused separately in agentSession so plugin host/session.update
    (paused_for_user=false) cannot clear physical user takeover or explicit
    PauseAgentSession holds; only host ResumeAgentSession or timed takeover
    expiry clears them.
  - Give each auto-install session watcher a monotonic watchGen + cancelable
    child context so restarting/resuming auto-install on the same VM cancels
    any superseded watcher and prevents stale timeout or secret cleanup.
  - Bound fast 500ms unbound-PID discovery for running VMs to
    sessionDiscoverGraceWindow via unboundSince (refreshed on restart/rebind).
  - Keep non-blocking buffered confirm resolution send inside confirmMu for
    clear mutual exclusion with cancelPendingConfirmations.
  - Clear cold-reboot telemetry preserveNextBoot via defer on all early-return
    and StartVM-failure paths in watchColdReboot.
  - Rebuild REIMSPROV with current StartAutoInstall credentials (preserving
    install_guest_tools) whenever VM is stopped instead of reusing stale images.
- CLI & macOS Provisioning / StartPrep:
  - Refuse `vm provision --clear` and overwriting existing REIMSPROV while the
    VM is running or paused.
  - Guard live "/" root in postinstall against macOS Recovery/Installer
    (/System/Installation/CDIS), forbid "/" in provision-offline.sh, and scope
    chmod 644 strictly to com.apple.keyboardtype.plist.
  - Reject unknown -* options in REIMSHELP/install.sh (including after --erase).
  - Defer clearing the one-shot REIMSPROV staged marker until after
    setExtraArgs (startprep) and StartWithCompat (macosdriver) succeed.
  - Preserve pending RestartFrom guards in AdvancePostInstallHandoff when
    checkpoint is already at StepDesktop.
- Host Input & Session Overlay:
  - Filter injected keyboard events (LLKHF_INJECTED / LLKHF_LOWER_IL_INJECTED)
    in locked-input mode consistently with the mouse hook.
  - Clean up exited overlay entries in entry.run() and recreate dead entries on
    Manager.Upsert when CreateWindowExW fails or exits early.
  - Cache the static island base surface (shell + icons + DirectWrite text) and
    measured text metrics across breathing frames, raising timerBreathMs to 100ms.
  - Replace magic Direct2D/DirectWrite vtable indices with named d2d1.h /
    dwrite.h constants, check EndDraw HRESULT, and add a live Windows DirectWrite
    rendering smoke test.
- Autoinstall OCR, Rules, Watchdog & Runner:
  - Persist and verify a per-file SHA-256 manifest.json in <dataDir>/ocr/
    before loading RapidOcrOnnx.dll / onnxruntime.dll; reject duplicate
    whitelisted basenames in offline zip imports.
  - Signal WinOCREngine.Close() before acquiring e.mu and add bounded wait +
    channel wakeup in Recognize so Close() immediately cancels in-flight OCR.
  - Fall back to installed RapidOCR when WinOCR initialization fails in Open(),
    and distinguish needs_rapidocr_import from needs_rapidocr_download in Probe.
  - Pause instead of pressing Return when post-TypeSecret login screenshot fails.
  - Re-baseline ColdRebootCount in Watchdog.ResetRebootWindow / ResetAfterResume.
  - Tighten recovery.main specificity (drop bare "Disk Utility"), guard 4-5 char
    pure-ASCII needles from sliding-window fuzzy collisions, use Unicode word
    boundaries for short names (<4 runes) in RedactDiagnosticText, and honor
    rule verify.wait_change_ms with early exit on visual frame diff.

* fix(autoinstall): handle CJK short-name redaction, sh-3.2 prompt bound, and OCR re-import pruning
2026-12-06 15:46:39 +08:00

639 lines
20 KiB
Go

package macosdriver
import (
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/installer"
"github.com/Nwflower/reims-go/internal/macos/opencore"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/macos/startprep"
"github.com/Nwflower/reims-go/internal/plugin"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/vmstart"
)
// ReimsMacOSCapabilities lists all capabilities supported by builtin.driver.reims-macos.
var ReimsMacOSCapabilities = []string{
driver.CapSnapshot,
driver.CapCowClone,
driver.CapResize,
driver.CapQMP,
driver.CapSSH,
driver.CapGuestTools,
driver.CapAffinity,
driver.CapOpenCore,
driver.CapRecovery,
}
// ReimsMacOSDriver adapts internal/macos/reims into the generic driver.Driver interface
// as the compiled-in `builtin.driver.reims-macos` extension (§3.2, §5.3).
type Options struct {
OwnerID string
ManagedByDesktop bool
WHPXFallbackEnabled func() bool
ColdRebootEnabled func() bool
MigrateLedger func(*plugin.ArgLedger)
PrepareGuestToolsImage func(string, string) error
PrepareNetwork func(context.Context, string, bool) (func(), error)
}
type ReimsMacOSDriver struct {
getConfig func() config.Config
opts Options
}
var _ driver.Driver = (*ReimsMacOSDriver)(nil)
// NewReimsMacOSDriver creates the built-in macOS driver adapter.
func NewReimsMacOSDriver(getConfig func() config.Config, options ...Options) *ReimsMacOSDriver {
var opts Options
if len(options) > 0 {
opts = options[0]
}
return &ReimsMacOSDriver{getConfig: getConfig, opts: opts}
}
func (d *ReimsMacOSDriver) ID() string { return driver.BuiltinReimsMacOSDriverID }
func (d *ReimsMacOSDriver) DisplayName() plugin.LocalizedText {
return plugin.LocalizedText{ZhCN: "macOS (Reims vGPU)", EnUS: "macOS (Reims vGPU)"}
}
func (d *ReimsMacOSDriver) RuntimeKind() string { return rt.DefaultKind }
func (d *ReimsMacOSDriver) RuntimeAPIRange() string { return "^1.0.0" }
func (d *ReimsMacOSDriver) Capabilities() []string {
return append([]string(nil), ReimsMacOSCapabilities...)
}
func (d *ReimsMacOSDriver) CreateSchema() *plugin.SettingsSchema {
return nil // Uses the native macOS CreateWizard UI
}
func (d *ReimsMacOSDriver) SettingsSchema() *plugin.SettingsSchema {
return nil // Uses the native macOS SettingsModal UI
}
func (d *ReimsMacOSDriver) client() (*reims.Client, error) {
c, _, err := d.startClient()
return c, err
}
func (d *ReimsMacOSDriver) startClient() (*reims.Client, rt.Installed, error) {
cfg := d.getConfig()
active, err := rt.ResolveForKind(&cfg, d.RuntimeKind())
if err != nil {
return nil, rt.Installed{}, err
}
if err := rt.CheckCompatibility(d.RuntimeKind(), d.RuntimeAPIRange(), *active); err != nil {
return nil, rt.Installed{}, err
}
return reims.NewClient(&cfg, *active), *active, nil
}
func (d *ReimsMacOSDriver) List(ctx context.Context) ([]driver.VMInfo, error) {
c, active, err := d.startClient()
if err != nil {
if errors.Is(err, rt.ErrNoActiveRuntime) {
registered, registryErr := reims.ListRegisteredVMs(d.getConfig().DataRoot)
if registryErr == nil && len(registered) == 0 {
return nil, nil
}
return nil, errors.Join(err, registryErr)
}
return nil, err
}
items, err := c.List(ctx)
if err != nil {
return nil, err
}
caps := d.vmCapabilities(active, "")
out := make([]driver.VMInfo, 0, len(items))
for _, it := range items {
state := it.State
if state == "stopped" && reims.HasSuspendState(it.Dir) {
state = "suspended"
}
out = append(out, driver.VMInfo{
Name: it.Name,
DriverID: d.ID(),
Directory: it.Dir,
DriverName: "macOS (Reims vGPU)",
State: state,
PID: it.PID,
Capabilities: append([]string(nil), caps...),
GuestOS: macOSGuestOS(),
})
}
return out, nil
}
func macOSGuestOS() *driver.GuestOSInfo {
return &driver.GuestOSInfo{Family: driver.GuestFamilyMacOS, Arch: "x86_64"}
}
// PasteCombo is the key combination that pastes inside a macOS guest.
func (d *ReimsMacOSDriver) PasteCombo() string { return "meta_l+v" }
// ConsoleEndpoint tells the host to reach the console through its QMP proxy.
func (d *ReimsMacOSDriver) ConsoleEndpoint() string { return "qmp" }
// Keymap is empty: the macOS guest uses the host's default US layout mapping.
func (d *ReimsMacOSDriver) Keymap() string { return "" }
var (
_ driver.PhaseReporter = (*ReimsMacOSDriver)(nil)
_ driver.DriverMetadata = (*ReimsMacOSDriver)(nil)
)
// Phase reports recovery or installer when the VM boots from them.
func (d *ReimsMacOSDriver) Phase(ctx context.Context, name string) (string, error) {
c, err := d.client()
if err != nil {
return "", err
}
det, err := c.Show(ctx, name)
if err != nil {
return "", err
}
return macOSPhase(det), nil
}
func macOSPhase(det reims.VMDetail) string {
marker := startprep.ReadRecoveryMarker(det.Directory)
switch {
case det.RecoveryMode || marker == "on" || marker == "want":
return driver.PhaseRecovery
case det.HasInstaller:
return driver.PhaseInstaller
default:
return driver.PhaseNormal
}
}
func (d *ReimsMacOSDriver) Show(ctx context.Context, name string) (driver.VMInfo, error) {
c, active, err := d.startClient()
if err != nil {
return driver.VMInfo{}, err
}
det, err := c.Show(ctx, name)
if err != nil {
return driver.VMInfo{}, err
}
enrichSuspendDetail(&det)
det.AutoResolution = vmstart.SupportsAutoResolution(det.Graphics) && vmstart.ReadVMDisplay(det.Directory).AutoResolution
marker := startprep.ReadRecoveryMarker(det.Directory)
det.RecoveryMode = marker == "on" || marker == "want"
rawBytes, err := json.Marshal(det)
if err != nil {
return driver.VMInfo{}, fmt.Errorf("encode macOS VM detail: %w", err)
}
var data map[string]any
if err := json.Unmarshal(rawBytes, &data); err != nil {
return driver.VMInfo{}, fmt.Errorf("decode macOS VM detail: %w", err)
}
info := driver.VMInfo{
Name: det.Name,
DriverID: d.ID(),
DriverName: "macOS (Reims vGPU)",
State: det.State,
CPUs: det.CPUs,
Memory: det.Memory,
DiskSummary: det.Disk,
DiskPath: det.DiskPath(),
Directory: det.Directory,
Network: det.Network,
SSHPort: det.SSHPort,
Capabilities: d.vmCapabilities(active, det.Kind),
DriverData: data,
GuestOS: macOSGuestOS(),
Phase: macOSPhase(det),
}
driver.SyncSSHEndpoint(&info)
return info, nil
}
func (d *ReimsMacOSDriver) ValidateCreate(_ context.Context, req driver.CreateRequest) []driver.ValidationIssue {
var opts reims.CreateOpts
if err := decodeMap(req.Options, &opts); err != nil {
return []driver.ValidationIssue{{Field: "options", Message: err.Error()}}
}
if opts.Name == "" {
opts.Name = req.Name
}
if opts.Dir == "" {
opts.Dir = req.Dir
}
cfg := d.getConfig()
rep := host.Inspect(cfg.DataRoot)
issues := reims.ValidateCreate(opts, rep, cfg.Locale)
var registered []reims.VMListItem
xdgDataDir := ""
if strings.TrimSpace(cfg.DataRoot) != "" {
xdgDataDir = cfg.XDGDataDir()
if regVMs, err := reims.ListRegisteredVMs(cfg.DataRoot); err == nil {
for _, vm := range regVMs {
registered = append(registered, reims.VMListItem{Name: vm.Name, Dir: vm.Directory})
}
}
}
if issue := reims.ValidateCreateTargetDir(xdgDataDir, opts, registered, cfg.Locale); issue != nil {
issues = append(issues, *issue)
}
out := make([]driver.ValidationIssue, 0, len(issues))
for _, is := range issues {
out = append(out, driver.ValidationIssue{Field: is.Field, Message: is.Message})
}
return out
}
func (d *ReimsMacOSDriver) Create(ctx context.Context, req driver.CreateRequest, stdout, stderr io.Writer) error {
c, active, err := d.startClient()
if err != nil {
return err
}
var opts reims.CreateOpts
if err := decodeMap(req.Options, &opts); err != nil {
return err
}
loc := i18n.EffectiveLocale(d.getConfig().Locale)
if !active.Manifest.HasCapability("win32-native-aio") {
if dcache := strings.TrimSpace(opts.DiskCache); dcache != "" && !strings.EqualFold(dcache, "default") {
return errors.New(i18n.T(loc, "validate.disk_cache_requires_runtime"))
}
if reims.IsWindowsRawDevicePath(opts.Disk) {
return errors.New(i18n.T(loc, "validate.raw_disk_requires_runtime"))
}
}
if opts.Name == "" {
opts.Name = req.Name
}
if opts.Dir == "" {
opts.Dir = req.Dir
}
applyAutoResolution := opts.AutoResolution != nil && *opts.AutoResolution && vmstart.SupportsAutoResolution(opts.Graphics)
if applyAutoResolution {
opts.Resolution, _ = host.RecommendAutoResolution(host.PrimaryDisplayOf(host.ConnectedDisplays()), opts.Borderless != nil && *opts.Borderless, c.DisplayFixedMode)
}
startAfterCreate := applyAutoResolution && opts.Start
if startAfterCreate {
opts.Start = false
}
if err := c.Create(ctx, opts, stdout, stderr); err != nil {
return err
}
vmDir := opts.Dir
if det, err := c.Show(ctx, opts.Name); err == nil && det.Directory != "" {
vmDir = det.Directory
}
if vmDir == "" {
cfg := d.getConfig()
vmDir = filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms", opts.Name)
}
if err := driver.WriteOwnerDriver(vmDir, d.ID()); err != nil {
return err
}
if applyAutoResolution {
if _, err := vmstart.SaveVMAutoResolution(vmDir, true); err != nil {
return err
}
}
if startAfterCreate {
_, err := d.Start(ctx, driver.StartRequest{Ref: driver.NewVMRef(d.ID(), opts.Name), Stdout: stdout, Stderr: stderr})
return err
}
return nil
}
func (d *ReimsMacOSDriver) ValidateSet(ctx context.Context, req driver.SetRequest) []driver.ValidationIssue {
var opts reims.SetOpts
if err := decodeMap(req.Changes, &opts); err != nil {
return []driver.ValidationIssue{{Field: "changes", Message: err.Error()}}
}
opts.Name = req.Name
var cur reims.VMDetail
if c, err := d.client(); err == nil {
if det, err := c.Show(ctx, req.Name); err == nil {
cur = det
}
}
cfg := d.getConfig()
rep := host.Inspect(cfg.DataRoot)
issues := reims.ValidateSet(opts, cur, rep, cfg.Locale)
out := make([]driver.ValidationIssue, 0, len(issues))
for _, is := range issues {
out = append(out, driver.ValidationIssue{Field: is.Field, Message: is.Message})
}
return out
}
func (d *ReimsMacOSDriver) Set(ctx context.Context, req driver.SetRequest, stdout, stderr io.Writer) error {
c, active, err := d.startClient()
if err != nil {
return err
}
var opts reims.SetOpts
if err := decodeMap(req.Changes, &opts); err != nil {
return err
}
if strings.TrimSpace(opts.DiskCache) != "" && !active.Manifest.HasCapability("win32-native-aio") {
return errors.New(i18n.T(i18n.EffectiveLocale(d.getConfig().Locale), "validate.disk_cache_requires_runtime"))
}
opts.Name = req.Name
cur, release, err := startprep.LockMutableVM(ctx, c, req.Name)
if err != nil {
return err
}
defer release()
return ApplyVMOptions(ctx, c, cur, opts, stdout, stderr, func(cur reims.VMDetail) error {
live := cur.State == "running" || cur.State == "paused"
if opts.GuestLang == "" && (live || opts.Graphics == "" || opts.Graphics == cur.Graphics) {
return nil
}
prep, err := startprep.New(d.getConfig(), func(line string) {
if stdout != nil {
_, _ = fmt.Fprintln(stdout, line)
}
})
if err != nil {
return err
}
if opts.GuestLang != "" {
return prep.ApplyGuestLang(ctx, cur.Directory, opts.GuestLang, live)
}
prep.ReplayGuestLang(ctx, cur.Directory)
return nil
})
}
func autoResolutionAfterSet(cur reims.VMDetail, opts reims.SetOpts) bool {
if !vmstart.SupportsAutoResolution(cmp.Or(opts.Graphics, cur.Graphics)) {
return false
}
if opts.AutoResolution != nil {
return *opts.AutoResolution
}
return cur.AutoResolution && vmstart.SupportsAutoResolution(cur.Graphics) && strings.TrimSpace(opts.Resolution) == ""
}
type SettingsState struct {
CPUs, Displays int
Memory, Resolution, GPU, DiskController, DiskCache, AudioBackend, GuestLang string
AutoResolution, Borderless, NestedVirt, Audio bool
}
type SettingsOutcome struct {
Valid, Running bool
Before, After SettingsState
}
type settingsOutcomeKey struct{}
func WithSettingsOutcome(ctx context.Context, outcome *SettingsOutcome) context.Context {
return context.WithValue(ctx, settingsOutcomeKey{}, outcome)
}
func configuredResolution(cur reims.VMDetail) string {
if raw, ok := reims.ReadConfiguredResolution(cur.Directory); ok {
return raw
}
return cur.Resolution
}
func needsAutoResolutionSync(cur reims.VMDetail, configured, resolution string) bool {
return !vmstart.SupportsAutoResolution(cur.Graphics) || !strings.EqualFold(strings.TrimSpace(configured), resolution)
}
// ApplyVMOptions saves the settings batch while the caller holds the VM operation lock.
func ApplyVMOptions(ctx context.Context, c *reims.Client, cur reims.VMDetail, opts reims.SetOpts, stdout, stderr io.Writer, applyGuestLang func(reims.VMDetail) error) (err error) {
live := cur.State == "running" || cur.State == "paused"
prevDisplay := vmstart.ReadVMDisplay(cur.Directory)
cur.AutoResolution = prevDisplay.AutoResolution
nextDisplay := prevDisplay
nextDisplay.AutoResolution = autoResolutionAfterSet(cur, opts)
cur.Resolution = configuredResolution(cur)
syncAutoResolution := nextDisplay.AutoResolution && opts.AutoResolution != nil
if syncAutoResolution {
opts.Resolution = ""
if !live {
borderless := cur.Borderless
if opts.Borderless != nil {
borderless = *opts.Borderless
}
target, _ := vmstart.ResolveTargetDisplay(prevDisplay, host.ConnectedDisplays())
resolution, _ := host.RecommendAutoResolution(target, borderless, c.DisplayFixedMode)
if needsAutoResolutionSync(cur, cur.Resolution, resolution) {
opts.Resolution = resolution
}
}
}
outcome, _ := ctx.Value(settingsOutcomeKey{}).(*SettingsOutcome)
if strings.TrimSpace(opts.GuestLang) != "" {
cur.GuestLang = opencore.ReadSavedGuestLang(cur.Directory)
if cur.GuestLang == "" {
if path := opencore.ResolveOpenCorePath(cur.Directory); path != "" {
cur.GuestLang, _ = opencore.ReadImagePrevLang(path)
}
}
}
ctlCommitted := false
if nextDisplay != prevDisplay {
if _, err := vmstart.SaveVMDisplay(cur.Directory, nextDisplay); err != nil {
return err
}
defer func() {
if err != nil && !ctlCommitted {
if _, rollbackErr := vmstart.SaveVMDisplay(cur.Directory, prevDisplay); rollbackErr != nil {
err = errors.Join(err, rollbackErr)
}
}
}()
}
if opts.NestedVirt != nil {
prevNestedVirt, readErr := vmstart.ReadVMNestedVirt(cur.Directory)
if readErr != nil {
return readErr
}
cur.NestedVirt = prevNestedVirt.Enabled
if err := vmstart.SaveVMNestedVirt(cur.Directory, vmstart.VMNestedVirtConfig{Enabled: *opts.NestedVirt}); err != nil {
return err
}
defer func() {
if err != nil && !ctlCommitted {
if rollbackErr := vmstart.SaveVMNestedVirt(cur.Directory, prevNestedVirt); rollbackErr != nil {
err = errors.Join(err, rollbackErr)
}
}
}()
}
guestLangAfterSet := !live && opts.Graphics != "" && opts.Graphics != cur.Graphics
if !guestLangAfterSet {
if err := applyGuestLang(cur); err != nil {
return err
}
}
if reims.HasCtlSetChanges(opts) {
if err := c.Set(ctx, opts, stdout, stderr); err != nil {
return err
}
ctlCommitted = true
}
if guestLangAfterSet {
if err := applyGuestLang(cur); err != nil {
if outcome != nil {
*outcome = settingsOutcome(cur, opts, nextDisplay.AutoResolution, live)
}
return err
}
}
if outcome != nil {
*outcome = settingsOutcome(cur, opts, nextDisplay.AutoResolution, live)
}
return nil
}
func settingsOutcome(cur reims.VMDetail, applied reims.SetOpts, autoResolution, live bool) SettingsOutcome {
before := SettingsState{
CPUs: cur.CPUs, Displays: cur.Displays, Memory: cur.Memory, Resolution: cur.Resolution,
GPU: cur.GPU, DiskController: cur.DiskController, DiskCache: cmp.Or(cur.DiskCache, "default"),
AudioBackend: cmp.Or(cur.AudioBackend, "auto"), GuestLang: cmp.Or(cur.GuestLang, "en-US:0"),
AutoResolution: vmstart.SupportsAutoResolution(cur.Graphics) && cur.AutoResolution,
Borderless: cur.Borderless, NestedVirt: cur.NestedVirt, Audio: cur.Audio,
}
after := before
after.AutoResolution = autoResolution
after.Memory = cmp.Or(applied.Memory, before.Memory)
after.GPU = cmp.Or(applied.GPU, before.GPU)
if dc := strings.ToLower(strings.TrimSpace(applied.DiskController)); dc != "" {
after.DiskController = dc
}
if dcache := strings.ToLower(strings.TrimSpace(applied.DiskCache)); dcache != "" {
after.DiskCache = dcache
}
after.AudioBackend = cmp.Or(applied.AudioBackend, before.AudioBackend)
if applied.Resolution != "" {
after.Resolution = applied.Resolution
if raw, found := reims.ReadConfiguredResolution(cur.Directory); found {
after.Resolution = raw
}
}
if applied.CPUs > 0 {
after.CPUs = applied.CPUs
}
if applied.Displays > 0 {
after.Displays = applied.Displays
}
if applied.Borderless != nil {
after.Borderless = *applied.Borderless
}
if applied.NestedVirt != nil {
after.NestedVirt = *applied.NestedVirt
}
if applied.Audio != nil {
after.Audio = *applied.Audio
}
if strings.TrimSpace(applied.GuestLang) != "" {
after.GuestLang = cmp.Or(opencore.ReadSavedGuestLang(cur.Directory), before.GuestLang)
}
return SettingsOutcome{Valid: true, Running: live, Before: before, After: after}
}
func (d *ReimsMacOSDriver) Stop(ctx context.Context, name string, force bool, stdout, stderr io.Writer) error {
c, err := d.client()
if err != nil {
return err
}
release, err := startprep.LockVMForStop(ctx, c, name, force)
if err != nil {
return err
}
defer release()
if force {
return c.StopForce(ctx, name, stdout, stderr)
}
return c.Stop(ctx, name, stdout, stderr)
}
func (d *ReimsMacOSDriver) Delete(ctx context.Context, name string, keepFiles bool, stdout, stderr io.Writer) error {
c, err := d.client()
if err != nil {
return err
}
if det, serr := c.Show(ctx, name); serr == nil && det.Directory != "" {
_ = installer.SecureRemoveProvisionImage(det.Directory)
}
return c.Delete(ctx, name, keepFiles, stdout, stderr)
}
func (d *ReimsMacOSDriver) InvokeAction(ctx context.Context, vmName, action string, params map[string]any) (any, error) {
c, err := d.client()
if err != nil {
return nil, err
}
switch action {
case "eject":
_, release, err := startprep.LockMutableVM(ctx, c, vmName)
if err != nil {
return nil, err
}
defer release()
return nil, c.Eject(ctx, vmName, io.Discard, io.Discard)
case "insert":
path, _ := params["path"].(string)
if path == "" {
return nil, fmt.Errorf("insert requires a non-empty path")
}
_, release, err := startprep.LockMutableVM(ctx, c, vmName)
if err != nil {
return nil, err
}
defer release()
return nil, c.Insert(ctx, vmName, path, io.Discard, io.Discard)
case "enter_recovery":
return d.enterRecovery(ctx, vmName)
case "finish_install":
return d.finishInstall(ctx, vmName)
case "upgrade_nvme":
det, release, err := startprep.LockMutableVM(ctx, c, vmName)
if err != nil {
return nil, err
}
defer release()
if det.HasInstaller {
return nil, fmt.Errorf("exit recovery mode before switching disk controller")
}
return nil, c.Set(ctx, reims.SetOpts{Name: vmName, DiskController: "nvme"}, io.Discard, io.Discard)
default:
return nil, fmt.Errorf("unknown macOS action %q", action)
}
}
func (d *ReimsMacOSDriver) ReadLogs(ctx context.Context, name string, serial bool) (string, error) {
c, err := d.client()
if err != nil {
return "", err
}
return c.ReadLogs(ctx, name, serial)
}
func decodeMap(m map[string]any, dst any) error {
if len(m) == 0 {
return nil
}
raw, err := json.Marshal(m)
if err != nil {
return fmt.Errorf("marshal options: %w", err)
}
return json.Unmarshal(raw, dst)
}