* 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
516 lines
19 KiB
Go
516 lines
19 KiB
Go
package app
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/config"
|
|
"github.com/Nwflower/reims-go/internal/driver"
|
|
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
|
|
"github.com/Nwflower/reims-go/internal/macos/macosdriver"
|
|
"github.com/Nwflower/reims-go/internal/macos/reims"
|
|
"github.com/Nwflower/reims-go/internal/plugin"
|
|
rt "github.com/Nwflower/reims-go/internal/runtime"
|
|
"github.com/Nwflower/reims-go/internal/tray"
|
|
"github.com/Nwflower/reims-go/internal/vmstart"
|
|
)
|
|
|
|
func TestMacOSLaunchUsesLatestRuntimeSelection(t *testing.T) {
|
|
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "current", QEMUASLR: true}
|
|
for _, version := range []string{"current", "backup"} {
|
|
dir := folderTestDir(t, cfg.RuntimesDir(), version)
|
|
if err := os.WriteFile(filepath.Join(dir, "manifest.json"), []byte("{}"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
a := &App{cfg: &cfg}
|
|
d := macosdriver.NewReimsMacOSDriver(a.runtimeConfig, macosdriver.Options{OwnerID: "test.macos"})
|
|
ref := driver.NewVMRef(d.ID(), "test")
|
|
for _, version := range []string{"current", "backup", "current"} {
|
|
saved := cfg
|
|
saved.ActiveRuntime = version
|
|
if err := config.Save("", &saved); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
want := rt.Installed{Dir: filepath.Join(cfg.RuntimesDir(), version)}
|
|
prep, err := a.prep(ref.Name)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
c, err := a.client()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if c.Binary != want.ControlPath() || prep.Client.Binary != c.Binary || a.activeQemuPath() != want.QemuPath() {
|
|
t.Fatalf("%s: native clients or bridge selected the wrong runtime", version)
|
|
}
|
|
// Only manifests are installed. The attempted control executable
|
|
// identifies which runtime the same driver used for each new request.
|
|
_, startErr := d.Start(t.Context(), driver.StartRequest{Ref: ref})
|
|
_, resumeErr := d.Resume(t.Context(), driver.ResumeRequest{Ref: ref})
|
|
for _, err := range []error{startErr, resumeErr} {
|
|
if err == nil || !strings.Contains(err.Error(), want.ControlPath()) {
|
|
t.Fatalf("expected a launch attempt with %q, got %v", want.ControlPath(), err)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
type appSecondDriver struct {
|
|
id string
|
|
vms []driver.VMInfo
|
|
listErr error
|
|
starts, stops, deletes, sets int
|
|
actions []string
|
|
actionResults map[string]any
|
|
}
|
|
|
|
func (d *appSecondDriver) ID() string { return d.id }
|
|
func (d *appSecondDriver) DisplayName() plugin.LocalizedText { return plugin.LocalizedText{EnUS: d.id} }
|
|
func (d *appSecondDriver) RuntimeKind() string { return "test-runtime" }
|
|
func (d *appSecondDriver) RuntimeAPIRange() string { return "^1.0.0" }
|
|
func (d *appSecondDriver) Capabilities() []string { return nil }
|
|
func (d *appSecondDriver) CreateSchema() *plugin.SettingsSchema { return nil }
|
|
func (d *appSecondDriver) SettingsSchema() *plugin.SettingsSchema { return nil }
|
|
func (d *appSecondDriver) List(context.Context) ([]driver.VMInfo, error) { return d.vms, d.listErr }
|
|
func (d *appSecondDriver) Show(_ context.Context, name string) (driver.VMInfo, error) {
|
|
for _, vm := range d.vms {
|
|
if vm.Name == name {
|
|
return vm, nil
|
|
}
|
|
}
|
|
return driver.VMInfo{}, os.ErrNotExist
|
|
}
|
|
func (d *appSecondDriver) ValidateCreate(context.Context, driver.CreateRequest) []driver.ValidationIssue {
|
|
return nil
|
|
}
|
|
func (d *appSecondDriver) Create(context.Context, driver.CreateRequest, io.Writer, io.Writer) error {
|
|
return nil
|
|
}
|
|
func (d *appSecondDriver) ValidateSet(context.Context, driver.SetRequest) []driver.ValidationIssue {
|
|
return nil
|
|
}
|
|
func (d *appSecondDriver) Set(context.Context, driver.SetRequest, io.Writer, io.Writer) error {
|
|
d.sets++
|
|
return nil
|
|
}
|
|
func (d *appSecondDriver) Start(context.Context, driver.StartRequest) (driver.StartResult, error) {
|
|
d.starts++
|
|
return driver.StartResult{}, nil
|
|
}
|
|
func (d *appSecondDriver) Stop(context.Context, string, bool, io.Writer, io.Writer) error {
|
|
d.stops++
|
|
return nil
|
|
}
|
|
func (d *appSecondDriver) Delete(context.Context, string, bool, io.Writer, io.Writer) error {
|
|
d.deletes++
|
|
return nil
|
|
}
|
|
func (d *appSecondDriver) InvokeAction(_ context.Context, _ string, action string, _ map[string]any) (any, error) {
|
|
d.actions = append(d.actions, action)
|
|
return d.actionResults[action], nil
|
|
}
|
|
|
|
type nativeViewerDriver struct {
|
|
*appSecondDriver
|
|
shown string
|
|
}
|
|
|
|
func (d *nativeViewerDriver) ShowWindow(_ context.Context, name string) error {
|
|
d.shown = name
|
|
return nil
|
|
}
|
|
|
|
func TestHostedViewerIsOpenedThroughTheOwningDriver(t *testing.T) {
|
|
const id = "test.driver.viewer"
|
|
drv := &nativeViewerDriver{appSecondDriver: &appSecondDriver{id: id, vms: []driver.VMInfo{{
|
|
Name: "desktop", State: "running", Capabilities: []string{driver.CapHosted, driver.CapWindow},
|
|
}}}}
|
|
reg := plugin.NewRegistry(nil)
|
|
if err := reg.Register(plugin.PluginDef{Manifest: plugin.Manifest{ID: id, Version: "1.0.0"},
|
|
Source: plugin.SourceBuiltin, Desired: true, Activate: func(_ context.Context, sc *plugin.Scope) error {
|
|
reg.RegisterGuestDriver(sc, id, drv)
|
|
return nil
|
|
}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
reg.Reconcile(t.Context())
|
|
router := driver.NewRouter(reg, nil)
|
|
a := &App{driverRouter: router, lifecycleSvc: vmlifecycle.New(reg, router, nil)}
|
|
if err := a.FocusVMWindow(id, "desktop"); err != nil || drv.shown != "desktop" {
|
|
t.Fatalf("focus hosted viewer: shown=%q, err=%v", drv.shown, err)
|
|
}
|
|
drv.shown, drv.vms[0].State = "", "stopped"
|
|
if err := a.FocusVMWindow(id, "desktop"); err == nil || drv.shown != "" {
|
|
t.Fatalf("focus stopped VM: shown=%q, err=%v", drv.shown, err)
|
|
}
|
|
}
|
|
|
|
func TestAppSecondDriverUserEntry(t *testing.T) {
|
|
const driverID = "test.driver.linux"
|
|
drv := &appSecondDriver{id: driverID, vms: []driver.VMInfo{{Name: "ubuntu", DriverID: driverID, Directory: t.TempDir(), State: "stopped"}}}
|
|
reg := plugin.NewRegistry(nil)
|
|
if err := reg.Register(plugin.PluginDef{Manifest: plugin.Manifest{ID: "test.linux", Version: "1.0.0"},
|
|
Source: plugin.SourceBuiltin, Desired: true, Activate: func(_ context.Context, sc *plugin.Scope) error {
|
|
reg.RegisterGuestDriver(sc, driverID, drv)
|
|
return nil
|
|
}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
reg.Reconcile(context.Background())
|
|
router := driver.NewRouter(reg, nil)
|
|
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}, lifecycleSvc: vmlifecycle.New(reg, router, nil),
|
|
transitions: map[string]string{}, pendingChanges: map[string][]PendingChange{}}
|
|
info, err := a.GetVMInfo(driverID, "ubuntu")
|
|
if err != nil || info.DriverID != driverID {
|
|
t.Fatalf("GetVMInfo = %+v, %v", info, err)
|
|
}
|
|
vms, err := a.listVMsInternal(context.Background())
|
|
if err != nil || len(vms) != 1 || vms[0].DriverID != driverID {
|
|
t.Fatalf("list = %+v, %v", vms, err)
|
|
}
|
|
if err := a.StartVM(driverID, "ubuntu"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := a.StopVM(driverID, "ubuntu", false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := a.startHandedVM(driverID, "ubuntu"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := a.lifecycleSvc.Set(context.Background(), driver.NewVMRef(driverID, "ubuntu"), map[string]any{"memory": "8G"}, io.Discard, io.Discard); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := a.RestartVM(driverID, "ubuntu"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := a.DeleteVM(driverID, "ubuntu", false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if drv.starts != 3 || drv.stops != 2 || drv.deletes != 1 || drv.sets != 1 {
|
|
t.Fatalf("starts=%d stops=%d deletes=%d", drv.starts, drv.stops, drv.deletes)
|
|
}
|
|
}
|
|
|
|
func TestForceQuitWithUnreachableVMDriver(t *testing.T) {
|
|
const driverID = "test.driver.unreachable"
|
|
listErr := errors.New("runtime unavailable")
|
|
drv := &appSecondDriver{id: driverID, listErr: listErr}
|
|
reg := plugin.NewRegistry(nil)
|
|
if err := reg.Register(plugin.PluginDef{
|
|
Manifest: plugin.Manifest{ID: "test.unreachable", Version: "1.0.0"},
|
|
Source: plugin.SourceBuiltin, Desired: true,
|
|
Activate: func(_ context.Context, sc *plugin.Scope) error {
|
|
reg.RegisterGuestDriver(sc, driverID, drv)
|
|
return nil
|
|
},
|
|
}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
reg.Reconcile(t.Context())
|
|
a := &App{
|
|
cfg: &config.Config{DataRoot: t.TempDir()},
|
|
lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil),
|
|
}
|
|
if err := a.ForceQuitApp(); !errors.Is(err, listErr) || a.allowQuit {
|
|
t.Fatalf("force quit: err=%v, allowQuit=%v", err, a.allowQuit)
|
|
}
|
|
}
|
|
|
|
func TestAppRecoveryActionsUseLifecycle(t *testing.T) {
|
|
const driverID = driver.BuiltinReimsMacOSDriverID
|
|
drv := &appSecondDriver{id: driverID, vms: []driver.VMInfo{{Name: "ubuntu", DriverID: driverID, Directory: t.TempDir(), State: "running"}}, actionResults: map[string]any{
|
|
"enter_recovery": map[string]any{"running": true, "scheduled": true},
|
|
"finish_install": map[string]any{"running": true, "installer_ejected": true, "network_enabled": true, "upgraded_nvme": true, "disk_controller_from": "ahci", "recovery_pending": true},
|
|
}}
|
|
reg := plugin.NewRegistry(nil)
|
|
if err := reg.Register(plugin.PluginDef{Manifest: plugin.Manifest{ID: "test.recovery", Version: "1.0.0"}, Source: plugin.SourceBuiltin, Desired: true, Activate: func(_ context.Context, sc *plugin.Scope) error {
|
|
reg.RegisterGuestDriver(sc, driverID, drv)
|
|
return nil
|
|
}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
reg.Reconcile(context.Background())
|
|
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}, lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil), transitions: map[string]string{}, pendingChanges: map[string][]PendingChange{}}
|
|
if err := a.EnterRecovery("ubuntu"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := a.pendingChanges[vmKey("ubuntu")]; len(got) != 1 || got[0].Field != "recovery" {
|
|
t.Fatalf("enter pending = %+v", got)
|
|
}
|
|
a.pendingChanges = map[string][]PendingChange{}
|
|
if err := a.FinishInstall("ubuntu"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := a.pendingChanges[vmKey("ubuntu")]; len(got) != 4 {
|
|
t.Fatalf("finish pending = %+v", got)
|
|
}
|
|
if len(drv.actions) != 2 || drv.actions[0] != "enter_recovery" || drv.actions[1] != "finish_install" {
|
|
t.Fatalf("actions = %v", drv.actions)
|
|
}
|
|
}
|
|
|
|
// A same-named VM in another driver must not make macOS-native flows or tray
|
|
// actions ambiguous once the owning driver is known.
|
|
func TestSameNameVMsAcrossDriversStayIndependent(t *testing.T) {
|
|
mac := &appSecondDriver{id: driver.BuiltinReimsMacOSDriverID, vms: []driver.VMInfo{{Name: "dup", DriverID: driver.BuiltinReimsMacOSDriverID, Directory: t.TempDir(), State: "running"}}}
|
|
lin := &appSecondDriver{id: "test.driver.linux", vms: []driver.VMInfo{{Name: "dup", DriverID: "test.driver.linux", Directory: t.TempDir(), State: "running"}}}
|
|
reg := plugin.NewRegistry(nil)
|
|
for _, d := range []*appSecondDriver{mac, lin} {
|
|
d := d
|
|
if err := reg.Register(plugin.PluginDef{Manifest: plugin.Manifest{ID: "test." + d.id, Version: "1.0.0"}, Source: plugin.SourceBuiltin, Desired: true,
|
|
Activate: func(_ context.Context, sc *plugin.Scope) error { reg.RegisterGuestDriver(sc, d.id, d); return nil }}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
reg.Reconcile(context.Background())
|
|
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}, lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil),
|
|
transitions: map[string]string{}, pendingChanges: map[string][]PendingChange{}}
|
|
|
|
if err := a.StopVM("", "dup", false); err == nil {
|
|
t.Fatal("bare-name stop must stay ambiguous")
|
|
}
|
|
d, err := a.GetVMDetail("dup")
|
|
if err != nil || d.Directory != mac.vms[0].Directory {
|
|
t.Fatalf("GetVMDetail = %+v, %v", d, err)
|
|
}
|
|
if err := a.RestartVM(driver.BuiltinReimsMacOSDriverID, "dup"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if mac.stops != 1 || mac.starts != 1 || lin.stops != 0 || lin.starts != 0 {
|
|
t.Fatalf("macOS restart: mac stops=%d starts=%d, linux stops=%d starts=%d", mac.stops, mac.starts, lin.stops, lin.starts)
|
|
}
|
|
a.trayVMAction(lin.id, "dup", tray.ActRestart)
|
|
if lin.stops != 1 || lin.starts != 1 || mac.stops != 1 || mac.starts != 1 {
|
|
t.Fatalf("tray restart: mac stops=%d starts=%d, linux stops=%d starts=%d", mac.stops, mac.starts, lin.stops, lin.starts)
|
|
}
|
|
}
|
|
|
|
func TestDeleteVMClearsTelemetryAndAgentSession(t *testing.T) {
|
|
const driverID = "test.driver.cleanup"
|
|
drv := &appSecondDriver{
|
|
id: driverID,
|
|
vms: []driver.VMInfo{{Name: "dev", DriverID: driverID, Directory: t.TempDir(), State: "stopped"}},
|
|
}
|
|
reg := plugin.NewRegistry(nil)
|
|
if err := reg.Register(plugin.PluginDef{
|
|
Manifest: plugin.Manifest{ID: "test.cleanup", Version: "1.0.0"},
|
|
Source: plugin.SourceBuiltin, Desired: true,
|
|
Activate: func(_ context.Context, sc *plugin.Scope) error {
|
|
reg.RegisterGuestDriver(sc, driverID, drv)
|
|
return nil
|
|
},
|
|
}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
reg.Reconcile(context.Background())
|
|
a := &App{
|
|
cfg: &config.Config{DataRoot: t.TempDir()},
|
|
lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil),
|
|
transitions: map[string]string{},
|
|
pendingChanges: map[string][]PendingChange{},
|
|
}
|
|
key := drv.vms[0].Ref().Key()
|
|
a.recordTelemetryMilestone(key, "boot")
|
|
a.beginAgentSession(nil, "test.plugin", drv.vms[0], "Auto", "stage1", "manual", true)
|
|
|
|
if err := a.DeleteVM(driverID, "dev", false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if a.hasActiveAgentSession(key) {
|
|
t.Fatal("agent session remained active after deleting VM")
|
|
}
|
|
a.telemetryMu.Lock()
|
|
_, hasTelemetry := a.vmTelemetry[key]
|
|
a.telemetryMu.Unlock()
|
|
if hasTelemetry {
|
|
t.Fatal("telemetry state remained after deleting VM")
|
|
}
|
|
}
|
|
|
|
func TestStopVMMonitorWaitsForExitAndAllowsDirRemoval(t *testing.T) {
|
|
vmDir := t.TempDir()
|
|
logDir := filepath.Join(vmDir, "logs")
|
|
if err := os.MkdirAll(logDir, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(logDir, "qemu.log"), []byte("boot\n"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}}
|
|
if _, err := vmstart.SaveVMDisplay(vmDir, vmstart.VMDisplayConfig{TargetDisplay: "DISPLAY2"}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
const vmName = "monitor-wait-test"
|
|
a.startVMMonitor(vmName, driver.VMInfo{
|
|
Name: vmName,
|
|
DriverID: driver.BuiltinReimsMacOSDriverID,
|
|
Directory: vmDir,
|
|
}, time.Now())
|
|
stopVMMonitor(vmName)
|
|
|
|
vmMonitors.mu.Lock()
|
|
_, stillRegistered := vmMonitors.entries[vmName]
|
|
vmMonitors.mu.Unlock()
|
|
if stillRegistered {
|
|
t.Fatal("monitor entry still registered after stopVMMonitor")
|
|
}
|
|
if err := os.RemoveAll(vmDir); err != nil {
|
|
t.Fatalf("removing VM dir after stopVMMonitor failed: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestStoppingVMMonitorStaysRegisteredUntilExit(t *testing.T) {
|
|
const name = "monitor-concurrent-stop-test"
|
|
ctx, cancel := context.WithCancel(t.Context())
|
|
done := make(chan struct{})
|
|
vmMonitors.mu.Lock()
|
|
vmMonitors.entries[name] = vmMonitorEntry{cancel: cancel, done: done}
|
|
vmMonitors.mu.Unlock()
|
|
t.Cleanup(func() {
|
|
vmMonitors.mu.Lock()
|
|
delete(vmMonitors.entries, name)
|
|
vmMonitors.mu.Unlock()
|
|
})
|
|
|
|
stopped := make(chan struct{})
|
|
go func() {
|
|
stopVMMonitor(name)
|
|
close(stopped)
|
|
}()
|
|
defer func() {
|
|
close(done)
|
|
<-stopped
|
|
}()
|
|
select {
|
|
case <-ctx.Done():
|
|
case <-time.After(time.Second):
|
|
t.Fatal("stop did not cancel the monitor")
|
|
}
|
|
vmMonitors.mu.Lock()
|
|
entry, ok := vmMonitors.entries[name]
|
|
vmMonitors.mu.Unlock()
|
|
if !ok || entry.done != done {
|
|
t.Fatal("concurrent callers lost the monitor completion channel before exit")
|
|
}
|
|
}
|
|
|
|
func TestStopVMMonitorRespectsTimeoutWhenStuck(t *testing.T) {
|
|
origTimeout := vmMonitorStopTimeout
|
|
vmMonitorStopTimeout = 30 * time.Millisecond
|
|
t.Cleanup(func() { vmMonitorStopTimeout = origTimeout })
|
|
|
|
const name = "monitor-stuck-timeout-test"
|
|
ctx, cancel := context.WithCancel(t.Context())
|
|
done := make(chan struct{})
|
|
vmMonitors.mu.Lock()
|
|
vmMonitors.entries[name] = vmMonitorEntry{cancel: cancel, done: done}
|
|
vmMonitors.mu.Unlock()
|
|
t.Cleanup(func() {
|
|
vmMonitors.mu.Lock()
|
|
delete(vmMonitors.entries, name)
|
|
vmMonitors.mu.Unlock()
|
|
close(done)
|
|
})
|
|
|
|
finished := make(chan struct{})
|
|
go func() {
|
|
stopVMMonitor(name)
|
|
close(finished)
|
|
}()
|
|
select {
|
|
case <-finished:
|
|
case <-time.After(time.Second):
|
|
t.Fatal("stopVMMonitor hung indefinitely when monitor goroutine did not exit")
|
|
}
|
|
if ctx.Err() == nil {
|
|
t.Fatal("stopVMMonitor did not cancel the monitor context")
|
|
}
|
|
|
|
allFinished := make(chan struct{})
|
|
go func() {
|
|
stopAllVMMonitors()
|
|
close(allFinished)
|
|
}()
|
|
select {
|
|
case <-allFinished:
|
|
case <-time.After(time.Second):
|
|
t.Fatal("stopAllVMMonitors hung indefinitely when monitor goroutine did not exit")
|
|
}
|
|
}
|
|
|
|
func TestValidateCreateProtectsDirectoryOfAnotherDriver(t *testing.T) {
|
|
const driverID = "test.driver.linux"
|
|
target := t.TempDir()
|
|
child := filepath.Join(target, "ubuntu")
|
|
if err := os.Mkdir(child, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(target, ".reims-ctl-creating"), nil, 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
drv := &appSecondDriver{id: driverID, vms: []driver.VMInfo{{Name: "ubuntu", DriverID: driverID, Directory: child}}}
|
|
reg := plugin.NewRegistry(nil)
|
|
if err := reg.Register(plugin.PluginDef{Manifest: plugin.Manifest{ID: "test.linux", Version: "1.0.0"},
|
|
Source: plugin.SourceBuiltin, Desired: true, Activate: func(_ context.Context, sc *plugin.Scope) error {
|
|
reg.RegisterGuestDriver(sc, driverID, drv)
|
|
return nil
|
|
}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
reg.Reconcile(t.Context())
|
|
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}, lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil)}
|
|
issues := a.ValidateCreate(reims.CreateOpts{Name: "new-mac", Dir: target})
|
|
for _, issue := range issues {
|
|
if issue.Field == "dir" && issue.Code == "dir_not_empty" {
|
|
return
|
|
}
|
|
}
|
|
t.Fatalf("expected directory conflict for VM registered by another driver, got %+v", issues)
|
|
}
|
|
|
|
func TestValidateCreateRejectsLeftoverNonEmptyVMDir(t *testing.T) {
|
|
dataRoot := t.TempDir()
|
|
a := &App{cfg: &config.Config{DataRoot: dataRoot}}
|
|
leftoverDir := filepath.Join(a.cfg.XDGDataDir(), "reims-ctl", "vms", "macos-tahoe2")
|
|
if err := os.MkdirAll(leftoverDir, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(leftoverDir, "vm.toml"), []byte("name = \"macos-tahoe2\"\n"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
opts := reims.CreateOpts{
|
|
Name: "macos-tahoe2",
|
|
SourceMode: "apple",
|
|
MacOS: "tahoe",
|
|
CPUs: 2,
|
|
Memory: "4G",
|
|
DiskSize: "64G",
|
|
}
|
|
hasDirIssue := func(issues []reims.ValidationIssue) bool {
|
|
for _, is := range issues {
|
|
if is.Field == "dir" && is.Code == "dir_not_empty" {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
if issues := a.ValidateCreate(opts); !hasDirIssue(issues) {
|
|
t.Fatalf("expected dir_not_empty issue for leftover directory, got %+v", issues)
|
|
}
|
|
|
|
if err := os.RemoveAll(leftoverDir); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if issues := a.ValidateCreate(opts); hasDirIssue(issues) {
|
|
t.Fatalf("unexpected dir_not_empty issue after clearing directory: %+v", issues)
|
|
}
|
|
}
|