Files
Reims-Go/internal/app/install_guide_test.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

1116 lines
43 KiB
Go

package app
import (
"context"
"encoding/json"
"io"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/macos/guest"
"github.com/Nwflower/reims-go/internal/macos/installguide"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/macos/startprep"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
func syncGuidesForTest(
ctx context.Context,
a *App,
gm *installguide.Manager,
vms []driver.VMListItem,
shown map[string]driver.VMInfo,
checked map[int]bool,
loc i18n.Locale,
) bool {
return (&guideTracker{a: a, mgr: gm, checked: checked}).startMissing(ctx, vms, shown, loc)
}
func TestInstallGuideFollowsBootMedia(t *testing.T) {
d := reims.VMDetail{Directory: t.TempDir()}
for _, test := range []struct {
marker, path string
want installguide.Kind
show bool
}{
{"", "", installguide.BuiltIn, false}, {"want", "", installguide.BuiltIn, false},
{"on", "", installguide.BuiltIn, true}, {"restore", "", installguide.BuiltIn, false},
{"", "BaseSystem.img", installguide.Online, true}, {"", "offline-installer-tahoe.img", installguide.Offline, true},
} {
startprep.WriteRecoveryMarker(d.Directory, test.marker)
d.HasInstaller, d.InstallerPath = test.path != "", test.path
if kind, show := installGuideKind(d); kind != test.want || show != test.show {
t.Errorf("%+v: got (%d,%t)", test, kind, show)
}
}
}
func TestInstallGuideFollowsPluginSwitch(t *testing.T) {
dataRoot := t.TempDir()
mgr, err := plugin.NewManager(plugin.ManagerOptions{DataRoot: dataRoot, HostVersion: "0.0.0"})
if err != nil {
t.Fatal(err)
}
defer mgr.Close()
cfg := config.Default()
cfg.DataRoot = dataRoot
cfg.Locale = i18n.ZhCN
a := &App{
cfg: cfg,
pluginMgr: mgr,
themeMode: "dark",
pollWake: make(chan struct{}, 1),
}
if loc, th := a.guidePreferences(); loc != i18n.ZhCN || th != installguide.ThemeDark {
t.Fatalf("guidePreferences = (%q, %q)", loc, th)
}
cb := builtin.HostCallbacks{
GetConfig: func() config.Config { return *cfg },
SyncInstallGuides: a.wakePoll,
}
if err := builtin.RegisterAll(mgr.Registry(), cb, nil); err != nil {
t.Fatal(err)
}
if err := guest.Register(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
t.Fatal(err)
}
mgr.Registry().Reconcile(context.Background())
if !a.installGuideEnabled() {
t.Fatal("expected install guide enabled when plugin is active")
}
// Drain initial SyncInstallGuides wakeup.
select {
case <-a.pollWake:
default:
t.Fatal("expected initial SyncInstallGuides to wake poll")
}
// Disabling the plugin removes the service and closes the guide manager.
if err := mgr.Registry().SetDesired(context.Background(), guest.ID, false); err != nil {
t.Fatal(err)
}
if a.installGuideEnabled() || a.getInstallGuideManager() != nil {
t.Fatal("expected install guide disabled after plugin toggle off")
}
// Re-enabling restores the service and wakes pollVMs to attach running VMs.
if err := mgr.Registry().SetDesired(context.Background(), guest.ID, true); err != nil {
t.Fatal(err)
}
if !a.installGuideEnabled() {
t.Fatal("expected install guide enabled after plugin toggle on")
}
select {
case <-a.pollWake:
default:
t.Fatal("expected re-enabling builtin.install-guide to wake poll")
}
}
func newInstallGuideTestApp(t *testing.T) (*App, *plugin.Manager) {
t.Helper()
dataRoot := t.TempDir()
cfg := config.Default()
cfg.DataRoot = dataRoot
cfg.Locale = i18n.ZhCN
a := &App{
cfg: cfg,
themeMode: "dark",
pollWake: make(chan struct{}, 1),
}
var mgr *plugin.Manager
var err error
mgr, err = plugin.NewManager(plugin.ManagerOptions{
DataRoot: dataRoot,
HostVersion: "0.3.0",
HostHandlers: func(pluginID string) map[string]plugin.RPCRequestHandler {
return a.hostAPISvc().Handlers(mgr, pluginID)
},
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { mgr.Close() })
a.pluginMgr = mgr
cb := builtin.HostCallbacks{
GetConfig: func() config.Config { return *cfg },
SyncInstallGuides: a.wakePoll,
GetSetting: func(pluginID, vmName, key string) (any, bool) {
v, ok := mgr.GetSettings(pluginID, vmName, false)[key]
return v, ok
},
PluginDataDir: mgr.Layout().DataDir,
PluginLogPath: mgr.Layout().LogPath,
CallHostAPI: mgr.CallHostAPI,
}
if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
t.Fatal(err)
}
if err := guest.Register(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
t.Fatal(err)
}
mgr.Registry().OnChange(func() {
a.stopAgentSessionsForInactivePlugins(mgr)
})
mgr.Registry().Reconcile(context.Background())
// Drain initial SyncInstallGuides wakeup.
select {
case <-a.pollWake:
default:
}
return a, mgr
}
func drainWake(ch chan struct{}) bool {
select {
case <-ch:
return true
default:
return false
}
}
func macOSRecoveryVM(name, dir string, pid int, installerPath string) (driver.VMListItem, driver.VMInfo) {
p := pid
item := driver.VMListItem{
Name: name,
DriverID: driver.BuiltinReimsMacOSDriverID,
Dir: dir,
PID: &p,
State: "running",
Capabilities: []string{driver.CapOpenCore},
}
det := vmInfoFromMacOSDetail(reims.VMDetail{
Name: name,
Directory: dir,
State: "running",
HasInstaller: installerPath != "",
InstallerPath: installerPath,
})
return item, det
}
func TestAutoInstallManualExitRestoresInstallGuide(t *testing.T) {
a, mgr := newInstallGuideTestApp(t)
gm := a.getInstallGuideManager()
if gm == nil {
t.Fatal("expected install guide manager active by default")
}
defer gm.Close()
vmDir := t.TempDir()
const vmName = "tahoe-stop"
const pid = 41001
item, det := macOSRecoveryVM(vmName, vmDir, pid, "offline-installer-tahoe.img")
vmKey := det.Ref().Key()
checked := map[int]bool{}
shown := map[string]driver.VMInfo{vmKey: det}
// 1. Initial boot starts the manual install guide and marks PID checked.
if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) {
t.Fatal("expected initial poll to start manual install guide")
}
if !gm.HasActive(vmName, pid) || !checked[pid] {
t.Fatalf("expected active guide and checked PID, active=%v checked=%v", gm.HasActive(vmName, pid), checked[pid])
}
// 2. Starting auto-install suppresses the manual guide.
a.beginAgentSession(mgr, guest.IDAutoInstall, det, "macOS 自动装机助手", "stage1_boot_recovery", "lock", true)
a.setAgentSessionAutoInstallConfig(vmKey, guest.IDAutoInstall, "recovery_only", "", false)
drainWake(a.pollWake)
if gm.HasActive(vmName, pid) {
t.Fatal("auto-install session must suppress active manual install guide")
}
// Polling while session is active must NOT start the guide or keep PID poisoned as checked.
if syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) {
t.Fatal("poll must not start manual install guide while auto-install is active")
}
if gm.HasActive(vmName, pid) {
t.Fatal("manual guide must stay suppressed while auto-install is active")
}
// 3. User manually exits auto-install -> wakes poll and restores manual guide on the SAME PID.
if err := a.StopAgentSession(det.DriverID, vmName); err != nil {
t.Fatalf("StopAgentSession: %v", err)
}
if !drainWake(a.pollWake) {
t.Fatal("StopAgentSession must wake pollVMs to restore manual install guide")
}
// Even if checked[pid] had remained true (e.g. session began & stopped between two polls),
// the recheck flag must clear checked[pid] and restore the manual guide.
checked[pid] = true
if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) {
t.Fatal("expected manual install guide to be restored after user stops auto-install")
}
if !gm.HasActive(vmName, pid) {
t.Fatal("expected manual install guide active again after StopAgentSession")
}
// 4. Starting auto-install again and failing mid-run (non-completed EndSession) also restores manual guide.
a.beginAgentSession(mgr, guest.IDAutoInstall, det, "macOS 自动装机助手", "stage2a_offline_terminal", "lock", true)
a.setAgentSessionAutoInstallConfig(vmKey, guest.IDAutoInstall, "recovery_only", "", false)
drainWake(a.pollWake)
if gm.HasActive(vmName, pid) {
t.Fatal("second auto-install run must suppress manual guide")
}
a.sessionMu.Lock()
a.agentSessions[vmKey].status = "failed"
a.sessionMu.Unlock()
a.endAgentSession(mgr, guest.IDAutoInstall, vmKey, "session_ended")
if !drainWake(a.pollWake) {
t.Fatal("failed endAgentSession must wake pollVMs to restore manual install guide")
}
if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) {
t.Fatal("expected manual install guide restored after failed auto-install session")
}
// 5. Disabling the auto-install plugin mid-run also restores the manual guide.
a.beginAgentSession(mgr, guest.IDAutoInstall, det, "macOS 自动装机助手", "stage1_boot_recovery", "lock", true)
a.setAgentSessionAutoInstallConfig(vmKey, guest.IDAutoInstall, "recovery_only", "", false)
drainWake(a.pollWake)
if gm.HasActive(vmName, pid) {
t.Fatal("expected manual guide suppressed before plugin disable")
}
if err := mgr.Disable(t.Context(), guest.IDAutoInstall); err != nil {
t.Fatalf("Disable auto-install plugin: %v", err)
}
if !drainWake(a.pollWake) {
t.Fatal("disabling auto-install plugin must wake pollVMs to restore manual guide")
}
if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) {
t.Fatal("expected manual install guide restored after disabling auto-install plugin")
}
}
func TestAutoInstallCompletionRestoresManualGuideAcrossModes(t *testing.T) {
t.Run("recovery_only completes to setup guide without completed overlay overlap", func(t *testing.T) {
a, mgr := newInstallGuideTestApp(t)
gm := a.getInstallGuideManager()
defer gm.Close()
vmDir := t.TempDir()
const vmName = "tahoe-rec-only"
oldPID, newPID := 51001, 51002
recItem, recDet := macOSRecoveryVM(vmName, vmDir, oldPID, "offline-installer-tahoe.img")
vmKey := recDet.Ref().Key()
checked := map[int]bool{}
// Start auto-install before first poll (as CreateWizard does).
a.beginAgentSession(mgr, guest.IDAutoInstall, recDet, "macOS 自动装机助手", "stage0_preflight", "lock", true)
a.setAgentSessionAutoInstallConfig(vmKey, guest.IDAutoInstall, "recovery_only", "", false)
drainWake(a.pollWake)
syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{recItem}, map[string]driver.VMInfo{vmKey: recDet}, checked, i18n.ZhCN)
if gm.HasActive(vmName, oldPID) {
t.Fatal("guide must stay suppressed during recovery_only auto-install")
}
// Stage 4: finish_install commits post-install handoff pinned to oldPID.
commitHandoff := a.prepareInstallGuideFinishHandoff(recDet)
if !commitHandoff(true, oldPID) {
t.Fatal("expected prepareInstallGuideFinishHandoff commit to succeed")
}
a.markAgentSessionFinishInstallDone(vmKey)
// VM restarts with newPID and installer ejected (HasInstaller=false).
postItem, postDet := macOSRecoveryVM(vmName, vmDir, newPID, "")
syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{postItem}, map[string]driver.VMInfo{vmKey: postDet}, checked, i18n.ZhCN)
if gm.HasActive(vmName, newPID) {
t.Fatal("guide must stay suppressed until recovery_only completes")
}
// Stage 5: recovery_only completes and ends session.
a.sessionMu.Lock()
a.agentSessions[vmKey].stage = "stage6_desktop_ready"
a.agentSessions[vmKey].status = "completed"
a.agentSessions[vmKey].message = "已完成恢复模式安装并进入 macOS,画面输入已解锁"
a.sessionMu.Unlock()
a.endAgentSession(mgr, guest.IDAutoInstall, vmKey, "session_ended")
if a.isCompletedOverlay(vmKey) {
t.Fatal("must not retain overlapping completed session overlay when manual install guide takes over")
}
if !drainWake(a.pollWake) {
t.Fatal("completed auto-install session must wake pollVMs to show manual guide")
}
if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{postItem}, map[string]driver.VMInfo{vmKey: postDet}, checked, i18n.ZhCN) {
t.Fatal("expected manual install guide to start after recovery_only completion")
}
if !gm.HasActive(vmName, newPID) {
t.Fatal("expected manual install guide active on post-restart PID")
}
// Verify checkpoint hands off to Setup Assistant (step="setup", not desktop).
raw, err := os.ReadFile(filepath.Join(vmDir, ".reims-go-install-guide.json"))
if err != nil {
t.Fatalf("read guide checkpoint: %v", err)
}
var cp struct {
Step string `json:"step"`
RestartFrom uint32 `json:"restart_from"`
}
if err := json.Unmarshal(raw, &cp); err != nil {
t.Fatalf("parse guide checkpoint: %v", err)
}
if cp.Step != string(installguide.StepSetup) || cp.RestartFrom != uint32(oldPID) {
t.Fatalf("recovery_only checkpoint = %+v, want step=%s restart_from=%d", cp, installguide.StepSetup, oldPID)
}
})
t.Run("full mode completes to desktop guide without completed overlay overlap", func(t *testing.T) {
a, mgr := newInstallGuideTestApp(t)
gm := a.getInstallGuideManager()
defer gm.Close()
vmDir := t.TempDir()
const vmName = "tahoe-full"
oldPID, newPID := 52001, 52002
_, recDet := macOSRecoveryVM(vmName, vmDir, oldPID, "offline-installer-tahoe.img")
vmKey := recDet.Ref().Key()
checked := map[int]bool{}
a.beginAgentSession(mgr, guest.IDAutoInstall, recDet, "macOS 自动装机助手", "stage0_preflight", "lock", true)
a.setAgentSessionAutoInstallConfig(vmKey, guest.IDAutoInstall, "full", "", false)
commitHandoff := a.prepareInstallGuideFinishHandoff(recDet)
if !commitHandoff(true, oldPID) {
t.Fatal("expected finish_install handoff commit")
}
a.markAgentSessionFinishInstallDone(vmKey)
postItem, postDet := macOSRecoveryVM(vmName, vmDir, newPID, "")
a.sessionMu.Lock()
a.agentSessions[vmKey].stage = "stage6_desktop_ready"
a.agentSessions[vmKey].status = "completed"
a.agentSessions[vmKey].sawSetupAssistant = true
a.sessionMu.Unlock()
drainWake(a.pollWake)
a.endAgentSession(mgr, guest.IDAutoInstall, vmKey, "session_ended")
if a.isCompletedOverlay(vmKey) {
t.Fatal("must not retain overlapping completed session overlay when manual install guide takes over")
}
if !drainWake(a.pollWake) {
t.Fatal("full mode completion must wake pollVMs")
}
if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{postItem}, map[string]driver.VMInfo{vmKey: postDet}, checked, i18n.ZhCN) || !gm.HasActive(vmName, newPID) {
t.Fatal("expected manual install guide active on desktop after full mode completion")
}
// Verify checkpoint advanced to desktop (step="desktop", restart_from=0).
raw, err := os.ReadFile(filepath.Join(vmDir, ".reims-go-install-guide.json"))
if err != nil {
t.Fatalf("read guide checkpoint: %v", err)
}
var cp struct {
Step string `json:"step"`
RestartFrom uint32 `json:"restart_from"`
}
if err := json.Unmarshal(raw, &cp); err != nil {
t.Fatalf("parse guide checkpoint: %v", err)
}
if cp.Step != string(installguide.StepDesktop) || cp.RestartFrom != 0 {
t.Fatalf("full mode checkpoint = %+v, want step=%s restart_from=0", cp, installguide.StepDesktop)
}
})
t.Run("stopping after finish_install before restart restores manual guide at restartPending", func(t *testing.T) {
a, mgr := newInstallGuideTestApp(t)
gm := a.getInstallGuideManager()
defer gm.Close()
vmDir := t.TempDir()
const vmName = "tahoe-pre-restart-stop"
const oldPID = 53001
_, recDet := macOSRecoveryVM(vmName, vmDir, oldPID, "offline-installer-tahoe.img")
vmKey := recDet.Ref().Key()
checked := map[int]bool{oldPID: true}
a.beginAgentSession(mgr, guest.IDAutoInstall, recDet, "macOS 自动装机助手", "stage4_finish_install", "lock", true)
a.setAgentSessionAutoInstallConfig(vmKey, guest.IDAutoInstall, "recovery_only", "", false)
commitHandoff := a.prepareInstallGuideFinishHandoff(recDet)
if !commitHandoff(true, oldPID) {
t.Fatal("expected finish_install handoff commit")
}
a.markAgentSessionFinishInstallDone(vmKey)
drainWake(a.pollWake)
// User exits before VM restarts (installer already ejected on disk, same PID still running).
if err := a.StopAgentSession(recDet.DriverID, vmName); err != nil {
t.Fatalf("StopAgentSession: %v", err)
}
if !drainWake(a.pollWake) {
t.Fatal("expected StopAgentSession to wake pollVMs")
}
postItem, postDet := macOSRecoveryVM(vmName, vmDir, oldPID, "")
if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{postItem}, map[string]driver.VMInfo{vmKey: postDet}, checked, i18n.ZhCN) || !gm.HasActive(vmName, oldPID) {
t.Fatal("expected manual guide to reappear after pre-restart stop")
}
})
t.Run("non-autoinstall session on already-installed VM does not pop spurious guide", func(t *testing.T) {
a, mgr := newInstallGuideTestApp(t)
gm := a.getInstallGuideManager()
defer gm.Close()
vmDir := t.TempDir()
const vmName = "tahoe-normal"
const pid = 54001
item, det := macOSRecoveryVM(vmName, vmDir, pid, "")
vmKey := det.Ref().Key()
checked := map[int]bool{}
a.beginAgentSession(mgr, "reims.agent", det, "MCP Agent", "working", "auto", false)
a.sessionMu.Lock()
a.agentSessions[vmKey].status = "completed"
a.sessionMu.Unlock()
a.endAgentSession(mgr, "reims.agent", vmKey, "session_ended")
if !a.isCompletedOverlay(vmKey) {
t.Fatal("expected completed overlay retained when no manual guide applies")
}
if syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, map[string]driver.VMInfo{vmKey: det}, checked, i18n.ZhCN) || gm.HasActive(vmName, pid) {
t.Fatal("must not start manual install guide for normal installed VM with non-autoinstall session")
}
})
t.Run("disabled install_guide retains completed overlay as fallback", func(t *testing.T) {
a, mgr := newInstallGuideTestApp(t)
if err := mgr.Registry().SetDesired(t.Context(), guest.ID, false); err != nil {
t.Fatal(err)
}
if a.installGuideEnabled() {
t.Fatal("expected install guide disabled")
}
vmDir := t.TempDir()
const vmName = "tahoe-no-guide"
_, det := macOSRecoveryVM(vmName, vmDir, 55001, "")
vmKey := det.Ref().Key()
a.beginAgentSession(mgr, guest.IDAutoInstall, det, "macOS 自动装机助手", "stage6_desktop_ready", "lock", true)
a.setAgentSessionAutoInstallConfig(vmKey, guest.IDAutoInstall, "recovery_only", "", false)
a.sessionMu.Lock()
a.agentSessions[vmKey].status = "completed"
a.sessionMu.Unlock()
a.endAgentSession(mgr, guest.IDAutoInstall, vmKey, "session_ended")
if !a.isCompletedOverlay(vmKey) {
t.Fatal("expected completed overlay retained when VM-window manual install guide is disabled")
}
})
t.Run("pending handoff restores manual guide when vmDir becomes known on poll", func(t *testing.T) {
a, mgr := newInstallGuideTestApp(t)
gm := a.getInstallGuideManager()
defer gm.Close()
vmDir := t.TempDir()
const vmName = "tahoe-lazy-dir"
const pid = 56001
// Start session with empty Directory so handoff queues in pendingGuideHandoffs.
noDirDet := driver.VMInfo{DriverID: driver.BuiltinReimsMacOSDriverID, Name: vmName, State: "running"}
vmKey := noDirDet.Ref().Key()
a.beginAgentSession(mgr, guest.IDAutoInstall, noDirDet, "macOS 自动装机助手", "stage5_wait_reboot", "lock", true)
a.setAgentSessionAutoInstallConfig(vmKey, guest.IDAutoInstall, "recovery_only", "", false)
a.sessionMu.Lock()
a.agentSessions[vmKey].status = "completed"
a.sessionMu.Unlock()
a.endAgentSession(mgr, guest.IDAutoInstall, vmKey, "session_ended")
if a.isCompletedOverlay(vmKey) {
t.Fatal("must hand off to manual guide even when vmDir is resolved on poll")
}
postItem, postDet := macOSRecoveryVM(vmName, vmDir, pid, "")
checked := map[int]bool{}
if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{postItem}, map[string]driver.VMInfo{vmKey: postDet}, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) {
t.Fatal("expected pending handoff applied on poll to start manual guide")
}
if !installguide.HasPostInstallCheckpoint(vmDir, vmName) {
t.Fatal("expected pending handoff persisted to vmDir on poll")
}
})
}
type stubMacOSRecoveryDriver struct {
vm driver.VMInfo
}
func (d *stubMacOSRecoveryDriver) ID() string { return driver.BuiltinReimsMacOSDriverID }
func (d *stubMacOSRecoveryDriver) DisplayName() plugin.LocalizedText { return plugin.LocalizedText{EnUS: "macOS Stub"} }
func (d *stubMacOSRecoveryDriver) RuntimeKind() string { return "reims-vgpu" }
func (d *stubMacOSRecoveryDriver) RuntimeAPIRange() string { return ">=1.0.0" }
func (d *stubMacOSRecoveryDriver) Capabilities() []string { return []string{driver.CapOpenCore, driver.CapQMP} }
func (d *stubMacOSRecoveryDriver) CreateSchema() *plugin.SettingsSchema { return nil }
func (d *stubMacOSRecoveryDriver) SettingsSchema() *plugin.SettingsSchema { return nil }
func (d *stubMacOSRecoveryDriver) List(context.Context) ([]driver.VMInfo, error) {
return []driver.VMInfo{d.vm}, nil
}
func (d *stubMacOSRecoveryDriver) Show(_ context.Context, name string) (driver.VMInfo, error) {
if name != d.vm.Name {
return driver.VMInfo{}, os.ErrNotExist
}
return d.vm, nil
}
func (d *stubMacOSRecoveryDriver) ValidateCreate(context.Context, driver.CreateRequest) []driver.ValidationIssue {
return nil
}
func (d *stubMacOSRecoveryDriver) Create(context.Context, driver.CreateRequest, io.Writer, io.Writer) error {
return nil
}
func (d *stubMacOSRecoveryDriver) ValidateSet(context.Context, driver.SetRequest) []driver.ValidationIssue {
return nil
}
func (d *stubMacOSRecoveryDriver) Set(context.Context, driver.SetRequest, io.Writer, io.Writer) error {
return nil
}
func (d *stubMacOSRecoveryDriver) Start(context.Context, driver.StartRequest) (driver.StartResult, error) {
return driver.StartResult{}, nil
}
func (d *stubMacOSRecoveryDriver) Stop(context.Context, string, bool, io.Writer, io.Writer) error {
return nil
}
func (d *stubMacOSRecoveryDriver) Delete(context.Context, string, bool, io.Writer, io.Writer) error {
return nil
}
type stubFailingAutoInstallEndpoint struct {
status string
msg string
}
func (e *stubFailingAutoInstallEndpoint) Call(_ context.Context, method string, _ any, out any) error {
if method == "autoinstall/status" && out != nil {
b, _ := json.Marshal(map[string]any{
"status": e.status,
"message": e.msg,
})
return json.Unmarshal(b, out)
}
return nil
}
func (e *stubFailingAutoInstallEndpoint) Notify(string, any) {}
func newPermissionDenialGuideTestEnv(t *testing.T, vmName string, pid int, installerPath string) (*App, *plugin.Manager, *installguide.Manager, driver.VMListItem, driver.VMInfo, string) {
t.Helper()
dataRoot := t.TempDir()
vmDir := t.TempDir()
cfg := config.Default()
cfg.DataRoot = dataRoot
cfg.Locale = i18n.ZhCN
a := &App{
cfg: cfg,
themeMode: "dark",
pollWake: make(chan struct{}, 1),
}
var mgr *plugin.Manager
var err error
mgr, err = plugin.NewManager(plugin.ManagerOptions{
DataRoot: dataRoot,
HostVersion: "0.3.0",
HostHandlers: func(pluginID string) map[string]plugin.RPCRequestHandler {
return a.hostAPISvc().Handlers(mgr, pluginID)
},
OnSettingsChanged: func(pluginID, vmName string) {
a.onPluginSettingsChanged(pluginID, vmName)
},
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { mgr.Close() })
a.pluginMgr = mgr
cb := builtin.HostCallbacks{
GetConfig: func() config.Config { return *cfg },
SyncInstallGuides: a.wakePoll,
GetSetting: func(pluginID, vmName, key string) (any, bool) {
v, ok := mgr.GetSettings(pluginID, vmName, false)[key]
return v, ok
},
PluginDataDir: mgr.Layout().DataDir,
PluginLogPath: mgr.Layout().LogPath,
CallHostAPI: mgr.CallHostAPI,
}
if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
t.Fatal(err)
}
if err := guest.Register(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
t.Fatal(err)
}
mgr.Registry().OnChange(func() {
a.stopAgentSessionsForInactivePlugins(mgr)
})
mgr.Registry().Reconcile(context.Background())
item, det := macOSRecoveryVM(vmName, vmDir, pid, installerPath)
p := pid
det.PID = &p
det.Phase = driver.PhaseInstaller
det.Capabilities = []string{driver.CapOpenCore, driver.CapQMP}
det.GuestOS = &driver.GuestOSInfo{Family: "macos"}
drvReg := plugin.NewRegistry(nil)
stubDrv := &stubMacOSRecoveryDriver{vm: det}
if err := drvReg.Register(plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: "test.macos.driver",
Version: "1.0.0",
Name: plugin.LocalizedText{EnUS: "macOS Stub"},
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: true,
Activate: func(_ context.Context, sc *plugin.Scope) error {
sc.Registry().RegisterGuestDriver(sc, driver.BuiltinReimsMacOSDriverID, stubDrv)
return nil
},
}); err != nil {
t.Fatal(err)
}
drvReg.Reconcile(context.Background())
router := driver.NewRouter(drvReg, func() string { return dataRoot })
stateTable := driver.NewStateTable()
router.SetStateTable(stateTable)
a.driverRouter = router
a.vmStateTable = stateTable
a.lifecycleSvc = vmlifecycle.New(drvReg, router, nil)
a.lastVMs = []driver.VMListItem{item}
gm := a.getInstallGuideManager()
if gm == nil {
t.Fatal("expected install guide manager active")
}
t.Cleanup(func() { gm.Close() })
drainWake(a.pollWake)
return a, mgr, gm, item, det, vmDir
}
func TestPermissionDenialRestoresOriginalManualInstallGuide(t *testing.T) {
t.Run("blocking session.begin protected_phase denial restores guide and clears secret without session.end", func(t *testing.T) {
const vmName = "tahoe-deny-begin"
const pid = 61001
a, mgr, gm, item, det, vmDir := newPermissionDenialGuideTestEnv(t, vmName, pid, "offline-installer-tahoe.img")
vmKey := det.Ref().Key()
checked := map[int]bool{pid: true}
shown := map[string]driver.VMInfo{vmKey: det}
// Simulate StartAutoInstall opening a session with DPAPI secret & ephemeral grant.
if err := mgr.SetSettings(guest.IDAutoInstall, vmKey, map[string]any{"account_password": "TempPass123!"}); err != nil {
t.Fatalf("store temp secret: %v", err)
}
a.grantEphemeralVMAccess(guest.IDAutoInstall, vmKey)
a.beginAgentSession(mgr, guest.IDAutoInstall, det, "macOS 自动装机助手", "stage0_preflight", "lock", true)
a.setAgentSessionAutoInstallConfig(vmKey, guest.IDAutoInstall, "full", "account_password", false)
drainWake(a.pollWake)
promptCount := 0
a.confirmEmit = func(p ConfirmPrompt) {
promptCount++
go func() { _ = a.ResolveConfirmRequest(p.ID, false, 0, false) }()
}
// Plugin requests blocking protected-phase confirmation and NEVER calls host/session.end.
rawReq, _ := json.Marshal(map[string]any{
"vm": vmKey,
"label": "macOS Auto-Install",
"stage": "stage0_preflight",
"takeover_policy": "lock",
"request_protected_phase_auth": true,
"prefer_until_phase_exit": true,
})
handlers := a.hostAPISvc().Handlers(mgr, guest.IDAutoInstall)
_, err := handlers["host/session.begin"](context.Background(), rawReq)
if err == nil || !strings.Contains(err.Error(), "confirmation_denied") {
t.Fatalf("session.begin err = %v, want confirmation_denied", err)
}
if promptCount != 1 {
t.Fatalf("expected 1 confirmation prompt, got %d", promptCount)
}
if a.hasActiveAgentSession(vmKey) {
t.Fatal("active agent session must be torn down immediately on permission denial")
}
if a.hasEphemeralVMAccess(guest.IDAutoInstall, vmKey) {
t.Fatal("ephemeral VM access must be revoked when denied session is torn down")
}
if sec, sErr := mgr.SecretSetting(guest.IDAutoInstall, vmKey, "account_password"); sErr == nil && sec != "" {
t.Fatalf("temporary DPAPI secret must be wiped on denial, got non-empty secret")
}
if !drainWake(a.pollWake) {
t.Fatal("permission denial must wake pollVMs to restore original manual guide")
}
// Denial record must be preserved so a follow-up non-blocking check returns confirmation_denied without re-prompting.
if err := a.authorizeProtectedPhase(context.Background(), mgr, guest.IDAutoInstall, det, driver.PhaseInstaller, false, false); err == nil || !strings.Contains(err.Error(), "confirmation_denied") {
t.Fatalf("subsequent protected phase check err = %v, want confirmation_denied", err)
}
if promptCount != 1 {
t.Fatalf("subsequent check must not re-prompt after denial, got %d prompts", promptCount)
}
// Even with checked[pid]=true, poll restores the original offline manual install guide.
if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) {
t.Fatal("expected original manual install guide restored after blocking permission denial")
}
// Ensure no spurious post-install checkpoint was persisted (installer never ran).
if _, err := os.Stat(filepath.Join(vmDir, ".reims-go-install-guide.json")); err == nil {
t.Fatal("must not write post-install checkpoint when script never ran due to permission denial")
}
})
t.Run("async protected_phase denial during console call aborts session and restores guide", func(t *testing.T) {
const vmName = "tahoe-deny-async"
const pid = 61002
a, mgr, gm, item, det, _ := newPermissionDenialGuideTestEnv(t, vmName, pid, "offline-installer-tahoe.img")
vmKey := det.Ref().Key()
checked := map[int]bool{pid: true}
shown := map[string]driver.VMInfo{vmKey: det}
const extPlugin = "test.external.agent"
a.grantEphemeralVMAccess(extPlugin, vmKey)
a.beginAgentSession(mgr, extPlugin, det, "External Agent", "working", "auto", true)
drainWake(a.pollWake)
prompts := make(chan ConfirmPrompt, 2)
a.confirmEmit = func(p ConfirmPrompt) { prompts <- p }
_, _, err := a.resolveComputerUseVM(context.Background(), mgr, extPlugin, vmKey, false)
if err == nil || !strings.Contains(err.Error(), "confirmation_required") {
t.Fatalf("first console call err = %v, want confirmation_required", err)
}
var p ConfirmPrompt
select {
case p = <-prompts:
case <-time.After(2 * time.Second):
t.Fatal("expected async confirmation prompt")
}
if err := a.ResolveConfirmRequest(p.ID, false, 0, false); err != nil {
t.Fatal(err)
}
waitFor(t, "active session aborted on async denial", func() bool {
return !a.hasActiveAgentSession(vmKey)
})
if !drainWake(a.pollWake) {
t.Fatal("async permission denial must wake pollVMs")
}
if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) {
t.Fatal("expected manual install guide restored after async denial")
}
// Subsequent non-blocking check returns confirmation_denied without re-prompting or spamming pollWake.
drainWake(a.pollWake)
if err := a.authorizeProtectedPhase(context.Background(), mgr, extPlugin, det, driver.PhaseInstaller, false, false); err == nil || !strings.Contains(err.Error(), "confirmation_denied") {
t.Fatalf("repeat check err = %v, want confirmation_denied", err)
}
if len(prompts) != 0 {
t.Fatal("repeat check must not open a second confirmation dialog")
}
if drainWake(a.pollWake) {
t.Fatal("repeat denied call without active session must not spam pollWake")
}
})
t.Run("host/ui.confirm protected_phase denial without prior session restores manual guide", func(t *testing.T) {
const vmName = "tahoe-deny-confirm"
const pid = 61003
a, mgr, gm, item, det, _ := newPermissionDenialGuideTestEnv(t, vmName, pid, "offline-installer-tahoe.img")
vmKey := det.Ref().Key()
checked := map[int]bool{pid: true}
shown := map[string]driver.VMInfo{vmKey: det}
a.confirmEmit = func(p ConfirmPrompt) {
go func() { _ = a.ResolveConfirmRequest(p.ID, false, 0, false) }()
}
rawReq, _ := json.Marshal(map[string]any{
"vm": vmKey,
"protected_phase": driver.PhaseInstaller,
"title": "Allow installer automation",
"message": "Plugin wants to run install.sh",
})
handlers := a.hostAPISvc().Handlers(mgr, guest.IDAutoInstall)
res, err := handlers["host/ui.confirm"](context.Background(), rawReq)
if err != nil {
t.Fatalf("host/ui.confirm returned unexpected error: %v", err)
}
if cr, ok := res.(pluginproto.ConfirmResult); !ok || cr.Approved {
t.Fatalf("host/ui.confirm result = %#v, want Approved=false", res)
}
if !drainWake(a.pollWake) {
t.Fatal("host/ui.confirm protected_phase denial must wake pollVMs")
}
if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) {
t.Fatal("expected manual install guide restored after host/ui.confirm denial")
}
})
}
func TestBrokerAndHeadlessPermissionDenialRestoresOriginalManualInstallGuide(t *testing.T) {
t.Run("broker permission denial in StartAutoInstall, ResumeAutoInstall, and session.begin restores manual guide", func(t *testing.T) {
const vmName = "tahoe-deny-broker"
const pid = 61004
a, mgr, gm, item, det, _ := newPermissionDenialGuideTestEnv(t, vmName, pid, "offline-installer-tahoe.img")
vmKey := det.Ref().Key()
shown := map[string]driver.VMInfo{vmKey: det}
// Register an external auto-installer plugin missing qmp:write permission.
const lackingPlugin = "community.lacking.autoinstall"
if err := mgr.Registry().Register(plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: lackingPlugin,
Version: "1.0.0",
Name: plugin.LocalizedText{EnUS: "Lacking Perms AutoInstaller"},
Permissions: []string{"vm:read"},
Contributes: plugin.Contributes{
AutoInstallers: []plugin.AutoInstallerContribution{{
ID: "lacking-macos",
Title: plugin.LocalizedText{EnUS: "Lacking AutoInstall"},
GuestFamilies: []string{"macos"},
}},
},
},
Source: plugin.SourceLocal,
Trust: plugin.TrustCommunity,
Desired: true,
}); err != nil {
t.Fatal(err)
}
// Register an external plugin awaiting high-risk approval (NeedsApproval=true).
const unapprovedPlugin = "community.unapproved.agent"
if err := mgr.Registry().Register(plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: unapprovedPlugin,
Version: "1.0.0",
Name: plugin.LocalizedText{EnUS: "Unapproved Agent"},
Permissions: []string{"vm:read", "vm:screen", "qmp:write", "vm:control"},
},
Source: plugin.SourceLocal,
Trust: plugin.TrustCommunity,
NeedsApproval: true,
}); err != nil {
t.Fatal(err)
}
mgr.Registry().Reconcile(context.Background())
drainWake(a.pollWake)
// Part A: StartAutoInstall fails broker precheck and restores manual guide.
checked := map[int]bool{pid: true}
if _, err := a.StartAutoInstall(AutoInstallStartRequest{
PluginID: lackingPlugin,
DriverID: det.DriverID,
VMName: vmName,
Mode: "recovery_only",
SLAAccepted: true,
}); err == nil {
t.Fatal("StartAutoInstall must fail when plugin lacks required permissions")
}
if a.hasActiveAgentSession(vmKey) {
t.Fatal("StartAutoInstall must not leave an active session when broker denies permissions")
}
if !drainWake(a.pollWake) {
t.Fatal("StartAutoInstall permission denial must wake pollVMs")
}
if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) {
t.Fatal("expected manual install guide restored after StartAutoInstall broker denial")
}
// Part B: ResumeAutoInstall also fails broker precheck and restores manual guide.
gm.Cancel(vmName)
checked[pid] = true
drainWake(a.pollWake)
if _, err := a.ResumeAutoInstall(lackingPlugin, det.DriverID, vmName); err == nil {
t.Fatal("ResumeAutoInstall must fail when plugin lacks required permissions")
}
if !drainWake(a.pollWake) {
t.Fatal("ResumeAutoInstall permission denial must wake pollVMs")
}
if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) {
t.Fatal("expected manual install guide restored after ResumeAutoInstall broker denial")
}
// Part C: Unapproved plugin calling host/session.begin aborts any active session and restores guide.
a.beginAgentSession(mgr, unapprovedPlugin, det, "Unapproved Agent", "working", "lock", true)
checked[pid] = true
drainWake(a.pollWake)
rawBegin, _ := json.Marshal(map[string]any{"vm": vmKey, "label": "Unapproved"})
if _, err := a.hostAPISvc().Handlers(mgr, unapprovedPlugin)["host/session.begin"](context.Background(), rawBegin); err == nil {
t.Fatal("unapproved plugin host/session.begin must fail broker check")
}
if a.hasActiveAgentSession(vmKey) {
t.Fatal("unapproved plugin broker denial must abort active session")
}
if !drainWake(a.pollWake) {
t.Fatal("unapproved plugin broker denial must wake pollVMs")
}
if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) {
t.Fatal("expected manual install guide restored after unapproved plugin broker denial")
}
})
t.Run("headless confirmation_unavailable aborts session and restores manual guide", func(t *testing.T) {
const vmName = "tahoe-deny-headless"
const pid = 61005
a, mgr, gm, item, det, _ := newPermissionDenialGuideTestEnv(t, vmName, pid, "offline-installer-tahoe.img")
vmKey := det.Ref().Key()
checked := map[int]bool{pid: true}
shown := map[string]driver.VMInfo{vmKey: det}
a.confirmEmit = nil
a.ctx = nil
a.grantEphemeralVMAccess(guest.IDAutoInstall, vmKey)
a.beginAgentSession(mgr, guest.IDAutoInstall, det, "macOS 自动装机助手", "stage0_preflight", "lock", true)
drainWake(a.pollWake)
rawBegin, _ := json.Marshal(map[string]any{
"vm": vmKey,
"request_protected_phase_auth": true,
})
_, err := a.hostAPISvc().Handlers(mgr, guest.IDAutoInstall)["host/session.begin"](context.Background(), rawBegin)
if err == nil || !strings.Contains(err.Error(), "confirmation_unavailable") {
t.Fatalf("headless session.begin err = %v, want confirmation_unavailable", err)
}
if a.hasActiveAgentSession(vmKey) {
t.Fatal("headless confirmation_unavailable must abort active session")
}
if !drainWake(a.pollWake) {
t.Fatal("headless confirmation_unavailable must wake pollVMs")
}
if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) {
t.Fatal("expected manual install guide restored on headless confirmation_unavailable")
}
})
t.Run("revoking per-VM allow_ai_access immediately aborts session and restores manual guide", func(t *testing.T) {
const vmName = "tahoe-revoke-access"
const pid = 61006
a, mgr, gm, item, det, _ := newPermissionDenialGuideTestEnv(t, vmName, pid, "offline-installer-tahoe.img")
vmKey := det.Ref().Key()
checked := map[int]bool{pid: true}
shown := map[string]driver.VMInfo{vmKey: det}
const agentPlugin = "community.remote.agent"
if err := mgr.Registry().Register(plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: agentPlugin,
Version: "1.0.0",
Name: plugin.LocalizedText{EnUS: "Remote Agent"},
Permissions: []string{"vm:read", "vm:screen", "qmp:write"},
Settings: &plugin.SettingsSchema{
Scope: "vm",
Properties: map[string]plugin.SettingProperty{
computerUseAccessSetting: {Type: "boolean"},
},
},
},
Source: plugin.SourceLocal,
Trust: plugin.TrustCommunity,
Desired: true,
}); err != nil {
t.Fatal(err)
}
mgr.Registry().Reconcile(context.Background())
if err := mgr.SetSettings(agentPlugin, vmKey, map[string]any{computerUseAccessSetting: true}); err != nil {
t.Fatal(err)
}
a.beginAgentSession(mgr, agentPlugin, det, "Remote Agent", "working", "auto", false)
drainWake(a.pollWake)
// User turns off per-VM allow_ai_access while plugin session is active.
if err := mgr.SetSettings(agentPlugin, vmKey, map[string]any{computerUseAccessSetting: false}); err != nil {
t.Fatal(err)
}
if a.hasActiveAgentSession(vmKey) {
t.Fatal("disabling per-VM allow_ai_access must immediately abort active plugin session")
}
if !drainWake(a.pollWake) {
t.Fatal("revoking per-VM allow_ai_access must wake pollVMs")
}
if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) {
t.Fatal("expected manual install guide restored after revoking allow_ai_access")
}
})
t.Run("watchAutoInstallSession ends lingering session when plugin fails without calling session.end", func(t *testing.T) {
const vmName = "tahoe-watch-fallback"
const pid = 61007
a, mgr, gm, item, det, _ := newPermissionDenialGuideTestEnv(t, vmName, pid, "offline-installer-tahoe.img")
vmKey := det.Ref().Key()
checked := map[int]bool{pid: true}
shown := map[string]driver.VMInfo{vmKey: det}
prevInterval := autoInstallWatchInterval
autoInstallWatchInterval = 15 * time.Millisecond
t.Cleanup(func() { autoInstallWatchInterval = prevInterval })
const extAuto = "community.failing.autoinstall"
ep := &stubFailingAutoInstallEndpoint{status: "failed", msg: "permission denied"}
if err := mgr.Registry().Register(plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: extAuto,
Version: "1.0.0",
Name: plugin.LocalizedText{EnUS: "Failing AutoInstaller"},
Permissions: []string{"vm:read", "vm:screen", "qmp:write", "vm:control"},
Contributes: plugin.Contributes{
AutoInstallers: []plugin.AutoInstallerContribution{{
ID: "failing-macos",
Title: plugin.LocalizedText{EnUS: "Failing AutoInstall"},
GuestFamilies: []string{"macos"},
}},
},
},
Source: plugin.SourceLocal,
Trust: plugin.TrustCommunity,
Desired: true,
Activate: func(_ context.Context, sc *plugin.Scope) error {
sc.Registry().RegisterInProcessEndpoint(sc, ep)
return nil
},
}); err != nil {
t.Fatal(err)
}
mgr.Registry().Reconcile(context.Background())
a.grantEphemeralVMAccess(extAuto, vmKey)
a.beginAgentSession(mgr, extAuto, det, "Failing AutoInstall", "stage0_preflight", "lock", true)
a.setAgentSessionAutoInstallConfig(vmKey, extAuto, "recovery_only", "", false)
watchCtx, watchGen, ok := a.startAutoInstallSessionWatch(vmKey, extAuto)
if !ok {
t.Fatal("startAutoInstallSessionWatch returned ok=false")
}
drainWake(a.pollWake)
done := make(chan struct{})
go func() {
defer close(done)
a.watchAutoInstallSession(watchCtx, watchGen, mgr, extAuto, vmKey, "", false)
}()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("watchAutoInstallSession did not exit after plugin reported failed status")
}
if a.hasActiveAgentSession(vmKey) {
t.Fatal("watchAutoInstallSession must end lingering session when plugin fails without calling host/session.end")
}
if !drainWake(a.pollWake) {
t.Fatal("watchAutoInstallSession cleanup must wake pollVMs")
}
if !syncGuidesForTest(t.Context(), a, gm, []driver.VMListItem{item}, shown, checked, i18n.ZhCN) || !gm.HasActive(vmName, pid) {
t.Fatal("expected manual install guide restored after watchAutoInstallSession cleanup")
}
})
}