Files
Reims-Go/internal/macos/autoinstall/runner/runner_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

2112 lines
73 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package runner
import (
"context"
"encoding/json"
"errors"
"image"
"image/color"
_ "image/jpeg"
_ "image/png"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
"time"
"unicode/utf8"
"github.com/Nwflower/reims-go/internal/macos/autoinstall/hostclient"
"github.com/Nwflower/reims-go/internal/macos/autoinstall/ocr"
"github.com/Nwflower/reims-go/internal/macos/autoinstall/rules"
"github.com/Nwflower/reims-go/internal/macos/autoinstall/vision"
"github.com/Nwflower/reims-go/pkg/pluginsdk"
)
type mockScreen struct {
blank bool
vmStopped bool
appleProg bool
advanceOnlyAtBottom bool
advanceOnScan bool
drawInputFields []image.Rectangle
rois map[string]vision.ROIScan
buttons map[string][]vision.ButtonBox
}
type mockHost struct {
mu sync.Mutex
screens []mockScreen
idx int
telemetry pluginsdk.VMTelemetry
sessionUpdates []pluginsdk.SessionUpdateRequest
sessionBegan bool
sessionEnded bool
beginErr error
beginPolicy string
ignoreHotkey bool
keyPressErr error
screenshotErrAt int
screenshotCalls int
screenshotErr error
screenshotImgs []image.Image
typedTexts []string
typedSecrets []string
keys []string
clicks []image.Point
finishInstall int
finishResp map[string]any
restarts int
takeoverOnce bool
lastPointer image.Point
secretDotPoints []image.Point
suppressMaskDots bool
}
func (m *mockHost) advance() {
m.mu.Lock()
defer m.mu.Unlock()
if m.idx < len(m.screens)-1 {
m.idx++
}
}
func (m *mockHost) current() mockScreen {
m.mu.Lock()
defer m.mu.Unlock()
if len(m.screens) == 0 {
return mockScreen{}
}
return m.screens[m.idx]
}
func (m *mockHost) BeginSession(_ context.Context, req pluginsdk.SessionBeginRequest) error {
m.mu.Lock()
m.sessionBegan = true
m.beginPolicy = req.TakeoverPolicy
err := m.beginErr
m.mu.Unlock()
return err
}
func (m *mockHost) UpdateSession(_ context.Context, req pluginsdk.SessionUpdateRequest) error {
m.mu.Lock()
m.sessionUpdates = append(m.sessionUpdates, req)
m.mu.Unlock()
return nil
}
func (m *mockHost) EndSession(_ context.Context, _ string) error {
m.mu.Lock()
m.sessionEnded = true
m.mu.Unlock()
return nil
}
func (m *mockHost) Confirm(_ context.Context, _ pluginsdk.ConfirmRequest) (pluginsdk.ConfirmResult, error) {
return pluginsdk.ConfirmResult{Approved: true, UntilPhaseExit: true}, nil
}
func (m *mockHost) Notify(_ context.Context, _, _ string) error { return nil }
func (m *mockHost) Screenshot(_ context.Context, _ pluginsdk.ScreenshotRequest) (image.Image, hostclient.ScreenshotMeta, error) {
m.mu.Lock()
m.screenshotCalls++
sErrAt := m.screenshotErrAt
sCalls := m.screenshotCalls
sErr := m.screenshotErr
m.mu.Unlock()
if sErr != nil && sErrAt > 0 && sCalls >= sErrAt {
return nil, hostclient.ScreenshotMeta{}, sErr
}
m.mu.Lock()
var customImg image.Image
if len(m.screenshotImgs) > 0 {
idx := sCalls - 1
if idx >= len(m.screenshotImgs) {
idx = len(m.screenshotImgs) - 1
}
customImg = m.screenshotImgs[idx]
}
m.mu.Unlock()
if customImg != nil {
return customImg, hostclient.ScreenshotMeta{Width: customImg.Bounds().Dx(), Height: customImg.Bounds().Dy()}, nil
}
sc := m.current()
if sc.vmStopped {
m.advance()
return nil, hostclient.ScreenshotMeta{}, errors.New("vm_not_running: VM rebooting")
}
img := image.NewRGBA(image.Rect(0, 0, 1280, 720))
if len(sc.drawInputFields) > 0 {
// Light-mode macOS window background (#ECECEC) with white bordered input boxes.
for y := 0; y < 720; y++ {
for x := 0; x < 1280; x++ {
img.SetRGBA(x, y, color.RGBA{236, 236, 236, 255})
}
}
for _, r := range sc.drawInputFields {
clamped := r.Intersect(img.Bounds())
for y := clamped.Min.Y; y < clamped.Max.Y; y++ {
for x := clamped.Min.X; x < clamped.Max.X; x++ {
if y == clamped.Min.Y || y == clamped.Max.Y-1 || x == clamped.Min.X || x == clamped.Max.X-1 {
img.SetRGBA(x, y, color.RGBA{180, 180, 180, 255})
} else {
img.SetRGBA(x, y, color.RGBA{255, 255, 255, 255})
}
}
}
}
}
m.mu.Lock()
dots := append([]image.Point(nil), m.secretDotPoints...)
m.mu.Unlock()
for _, pt := range dots {
// Paint 4 dark bullet dots centered around pt to simulate macOS NSSecureTextField bullets.
for i := 0; i < 4; i++ {
cx := pt.X - 24 + i*14
for dy := -3; dy <= 3; dy++ {
for dx := -3; dx <= 3; dx++ {
px, py := cx+dx, pt.Y+dy
if image.Pt(px, py).In(img.Bounds()) {
img.SetRGBA(px, py, color.RGBA{20, 20, 20, 255})
}
}
}
}
}
if sc.appleProg {
for y := 0; y < 720; y++ {
for x := 0; x < 1280; x++ {
img.SetRGBA(x, y, color.RGBA{4, 4, 4, 255})
}
}
for y := 260; y < 350; y++ {
for x := 600; x < 680; x++ {
img.SetRGBA(x, y, color.RGBA{245, 245, 245, 255})
}
}
for y := 460; y < 468; y++ {
for x := 460; x < 820; x++ {
img.SetRGBA(x, y, color.RGBA{180, 180, 180, 255})
}
}
m.advance()
}
if sc.blank {
m.advance()
}
return img, hostclient.ScreenshotMeta{Width: 1280, Height: 720, SourceWidth: 1280, SourceHeight: 720, Blank: sc.blank}, nil
}
func (m *mockHost) PointerMove(_ context.Context, _ string, x, y, _, _ int) error {
m.mu.Lock()
if m.takeoverOnce {
m.takeoverOnce = false
m.mu.Unlock()
return errors.New("user_takeover: user touched mouse")
}
m.lastPointer = image.Pt(x, y)
m.mu.Unlock()
return nil
}
func (m *mockHost) PointerClick(_ context.Context, _, _ string) error {
m.mu.Lock()
pt := m.lastPointer
m.clicks = append(m.clicks, pt)
sc := m.screens[m.idx]
m.mu.Unlock()
if !sc.advanceOnlyAtBottom || pt.Y >= 580 {
m.advance()
}
return nil
}
func (m *mockHost) KeyPress(_ context.Context, _, key string, mods ...string) error {
m.mu.Lock()
combo := key
if len(mods) > 0 {
combo = strings.Join(mods, "+") + "+" + key
}
m.keys = append(m.keys, combo)
ignoreHotkey := m.ignoreHotkey
kErr := m.keyPressErr
m.mu.Unlock()
if kErr != nil {
return kErr
}
if combo != "meta_l+a" && !(ignoreHotkey && combo == "shift+meta_l+t") {
m.advance()
}
return nil
}
func (m *mockHost) TypeText(_ context.Context, _, text string) (int, error) {
m.mu.Lock()
m.typedTexts = append(m.typedTexts, text)
m.mu.Unlock()
if strings.Contains(text, "install.sh") {
m.advance()
}
return len(text), nil
}
func (m *mockHost) TypeSecret(_ context.Context, _, setting string) (int, error) {
m.mu.Lock()
m.typedSecrets = append(m.typedSecrets, setting)
if !m.suppressMaskDots {
pt := m.lastPointer
if pt == (image.Point{}) {
pt = image.Pt(640, 620)
}
m.secretDotPoints = append(m.secretDotPoints, pt)
}
m.mu.Unlock()
return 12, nil
}
func (m *mockHost) FinishInstall(_ context.Context, _ string) (map[string]any, error) {
m.mu.Lock()
m.finishInstall++
resp := m.finishResp
m.mu.Unlock()
if resp != nil {
return resp, nil
}
return map[string]any{"ok": true}, nil
}
func (m *mockHost) RestartVM(_ context.Context, _ string) (map[string]any, error) {
m.mu.Lock()
m.restarts++
m.mu.Unlock()
m.advance()
return map[string]any{"ok": true}, nil
}
func (m *mockHost) Telemetry(_ context.Context, _ string) (pluginsdk.VMTelemetry, error) {
m.mu.Lock()
defer m.mu.Unlock()
return m.telemetry, nil
}
func (m *mockHost) DownloadAndWait(_ context.Context, _ ocr.DownloadOptions) (string, error) {
return "", errors.New("unused")
}
type mockLocator struct {
host *mockHost
}
func (l *mockLocator) ScanROI(_ context.Context, _ image.Image, roiName string, _ *image.Point) (vision.ROIScan, error) {
sc := l.host.current()
if s, ok := sc.rois[roiName]; ok {
if sc.advanceOnScan && roiName == "terminal" {
l.host.advance()
}
return s, nil
}
return vision.ROIScan{}, nil
}
func (l *mockLocator) ScanButtons(_ context.Context, _ image.Image, roiName string) ([]vision.ButtonBox, error) {
sc := l.host.current()
if btns, ok := sc.buttons[roiName]; ok {
return btns, nil
}
return nil, nil
}
func scanText(text string, rect image.Rectangle) vision.ROIScan {
return vision.ROIScan{
ROI: rect,
Text: text,
Lines: []ocr.Line{{Text: text, Rect: rect, Words: []ocr.Word{{Text: text, Rect: rect}}}},
}
}
func TestStage0To6OfflineEndToEndFlow(t *testing.T) {
dataDir := t.TempDir()
eng, err := rules.LoadEngine(dataDir)
if err != nil {
t.Fatal(err)
}
continueBtn := []vision.ButtonBox{{Rect: image.Rect(920, 620, 1080, 660), Center: image.Pt(1000, 640), Enabled: true, Text: "Continue"}}
agreeBtn := []vision.ButtonBox{{Rect: image.Rect(920, 620, 1080, 660), Center: image.Pt(1000, 640), Enabled: true, Text: "Agree"}}
mh := &mockHost{
telemetry: pluginsdk.VMTelemetry{State: "running", Phase: "installer", DiskBytes: 4 << 30, DiskDeltaBytes: 10 << 20, CPUPercent: 45},
screens: []mockScreen{
// 0: Boot blank
{blank: true},
// 1: Recovery language selector
{rois: map[string]vision.ROIScan{"body": scanText("以简体中文作为主要语言", image.Rect(300, 200, 900, 260))}},
// 2: Recovery main (opens Terminal via Shift+Cmd+T hotkey)
{rois: map[string]vision.ROIScan{
"menu_bar": scanText("实用工具", image.Rect(200, 4, 280, 28)),
"body": scanText("重新安装 macOS", image.Rect(400, 250, 800, 310)),
}},
// 3: Terminal open -> runner types install.sh
{rois: map[string]vision.ROIScan{
"menu_bar": scanText("终端 Shell 编辑", image.Rect(40, 4, 260, 28)),
"terminal": scanText("-bash-3.2#", image.Rect(100, 100, 400, 140)),
}},
// 4: Terminal output shows startosinstall -> transitions to Stage 3
{advanceOnScan: true, rois: map[string]vision.ROIScan{"terminal": scanText("Formatting Macintosh HD... Extracting... startosinstall", image.Rect(100, 100, 900, 240))}},
// 5: Stage 3 Win10 cold reboot transient stopped state
{vmStopped: true},
// 6: Stage 3 Apple progress bar
{appleProg: true},
// 7: Stage 3 first Setup Assistant detection -> triggers Stage 4 finish_install + restart!
{rois: map[string]vision.ROIScan{"title_band": scanText("选择国家或地区", image.Rect(300, 120, 900, 180))}},
// 8: Post-restart Setup Assistant: Region
{
rois: map[string]vision.ROIScan{"title_band": scanText("Select Your Country or Region", image.Rect(300, 120, 900, 180))},
buttons: map[string][]vision.ButtonBox{"action_bar": continueBtn},
},
// 9: Create Computer Account (clicks Continue after FullName, AccountName, TypeSecret x2)
{
advanceOnlyAtBottom: true,
drawInputFields: []image.Rectangle{
image.Rect(460, 262, 700, 288),
image.Rect(460, 312, 700, 338),
image.Rect(460, 362, 700, 388),
image.Rect(460, 412, 700, 438),
},
rois: map[string]vision.ROIScan{
"title_band": scanText("Create a Computer Account", image.Rect(300, 120, 900, 180)),
"body": {
Text: "Full Name\nAccount Name\nPassword\nVerify",
Lines: []ocr.Line{
{Text: "Full Name", Rect: image.Rect(320, 260, 440, 290)},
{Text: "Account Name", Rect: image.Rect(320, 310, 440, 340)},
{Text: "Password", Rect: image.Rect(320, 360, 440, 390)},
{Text: "Verify", Rect: image.Rect(320, 410, 440, 440)},
},
},
},
buttons: map[string][]vision.ButtonBox{"action_bar": continueBtn},
},
// 10: Online Apple Account -> Set Up Later
{
rois: map[string]vision.ROIScan{
"title_band": scanText("Sign In with Your Apple Account", image.Rect(300, 120, 900, 180)),
"action_bar": scanText("Set Up Later", image.Rect(320, 620, 480, 650)),
},
},
// 11: Skip Apple Account confirmation modal -> Skip
{
rois: map[string]vision.ROIScan{
"modal": {
Text: "Are you sure you want to skip?\nSkip",
Lines: []ocr.Line{
{Text: "Are you sure you want to skip?", Rect: image.Rect(420, 260, 860, 300)},
{Text: "Skip", Rect: image.Rect(740, 420, 820, 455)},
},
},
},
},
// 12: Terms and Conditions (requires SLA accepted!)
{
rois: map[string]vision.ROIScan{"title_band": scanText("Terms and Conditions", image.Rect(300, 120, 900, 180))},
buttons: map[string][]vision.ButtonBox{"action_bar": agreeBtn},
},
// 13: FileVault (explicitly skipped!)
{
rois: map[string]vision.ROIScan{
"title_band": scanText("Your Mac is Ready for FileVault", image.Rect(300, 120, 900, 180)),
"action_bar": scanText("Not Now", image.Rect(320, 620, 460, 650)),
},
},
// 14: Keyboard Setup Assistant on first desktop -> Cmd+Q
{
rois: map[string]vision.ROIScan{
"modal": scanText("Keyboard Setup Assistant", image.Rect(400, 220, 860, 280)),
},
},
// 15: Usable Desktop (2 consecutive stable frames)
{
rois: map[string]vision.ROIScan{
"menu_bar": scanText("Finder File Edit View Go Window Help 14:25", image.Rect(10, 4, 1260, 28)),
},
},
},
}
r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, RunConfig{
VM: "builtin.guest.macos:sequoia-auto",
GuestLang: "zh-Hans:0",
FullName: "Reims User",
AccountName: "reimsuser",
SLAAccepted: true,
Appearance: "auto",
}, Options{DisableSleep: true})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
r.Start(ctx)
r.Wait()
st := r.Status()
if st.Status != StatusCompleted || st.Stage != StageDesktopReady {
t.Fatalf("expected completed desktop stage, got status=%s stage=%s idx=%d rules=%v msg=%q pause=%q", st.Status, st.Stage, mh.idx, st.MatchedRules, st.Message, st.PauseReason)
}
if !mh.sessionBegan || !mh.sessionEnded {
t.Fatalf("expected session begin/end, got began=%v ended=%v", mh.sessionBegan, mh.sessionEnded)
}
if mh.finishInstall != 1 || mh.restarts != 1 {
t.Fatalf("expected exactly 1 finish_install and 1 restart, got finish=%d restart=%d", mh.finishInstall, mh.restarts)
}
if len(mh.typedSecrets) != 2 {
t.Fatalf("expected Password + Verify typed via typeSecret (2 calls), got %v", mh.typedSecrets)
}
// Verify checkpoint contains zero plaintext passwords.
cpBytes, err := os.ReadFile(checkpointPath(dataDir, "builtin.guest.macos:sequoia-auto"))
if err != nil {
t.Fatalf("missing checkpoint: %v", err)
}
if strings.Contains(strings.ToLower(string(cpBytes)), "password_plain") {
t.Fatal("checkpoint must never store plaintext password")
}
// Verify Keyboard Setup Assistant closed with Cmd+Q.
foundCmdQ := false
for _, k := range mh.keys {
if k == "meta_l+q" {
foundCmdQ = true
}
}
if !foundCmdQ {
t.Fatalf("expected meta_l+q for Keyboard Setup Assistant, got keys=%v", mh.keys)
}
}
func TestNonEmptyDiskRefusalPausesForUser(t *testing.T) {
dataDir := t.TempDir()
eng, err := rules.LoadEngine(dataDir)
if err != nil {
t.Fatal(err)
}
mh := &mockHost{
screens: []mockScreen{
{rois: map[string]vision.ROIScan{
"menu_bar": scanText("Utilities", image.Rect(200, 4, 280, 28)),
"body": scanText("Reinstall macOS", image.Rect(400, 250, 800, 310)),
}},
{rois: map[string]vision.ROIScan{
"menu_bar": scanText("Terminal Shell Edit", image.Rect(40, 4, 260, 28)),
"terminal": scanText("-bash-3.2#", image.Rect(100, 100, 400, 140)),
}},
{rois: map[string]vision.ROIScan{"terminal": scanText("Refusing to erase non-empty disk /dev/disk0", image.Rect(100, 100, 900, 240))}},
},
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, RunConfig{
VM: "builtin.guest.macos:nonempty", GuestLang: "en-US:0", FullName: "Test", AccountName: "test", SLAAccepted: true,
}, Options{DisableSleep: true})
if err != nil {
t.Fatal(err)
}
r.Start(ctx)
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if r.Status().Status == StatusPausedForUser {
break
}
time.Sleep(5 * time.Millisecond)
}
st := r.Status()
if st.Status != StatusPausedForUser || !strings.Contains(st.PauseReason, "terminal_safety_stop") {
t.Fatalf("expected terminal safety pause on non-empty disk, got %+v", st)
}
r.Stop()
r.Wait()
}
func TestUnknownPagePauseRedactsUserAndResumes(t *testing.T) {
dataDir := t.TempDir()
eng, err := rules.LoadEngine(dataDir)
if err != nil {
t.Fatal(err)
}
// Pre-seed checkpoint at Stage 5 so test jumps straight to Setup Assistant.
_ = saveCheckpoint(dataDir, Checkpoint{
VM: "builtin.guest.macos:unknown",
Stage: StageSetupAssistant,
Status: StatusPausedForUser,
FinishInstallDone: true,
Config: RunConfig{VM: "builtin.guest.macos:unknown", GuestLang: "en-US:0", FullName: "Alice SecretName", AccountName: "alice", SLAAccepted: true},
})
mh := &mockHost{
screens: []mockScreen{
{rois: map[string]vision.ROIScan{"title_band": scanText("Brand New macOS 27 Feature for Alice SecretName", image.Rect(200, 120, 900, 180))}},
{rois: map[string]vision.ROIScan{"menu_bar": scanText("Finder File Edit View Go 10:00", image.Rect(10, 4, 1260, 28))}},
},
}
r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, RunConfig{
VM: "builtin.guest.macos:unknown", GuestLang: "en-US:0", FullName: "Alice SecretName", AccountName: "alice", SLAAccepted: true,
}, Options{DisableSleep: true})
if err != nil {
t.Fatal(err)
}
r.Start(context.Background())
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if r.Status().Status == StatusPausedForUser {
break
}
time.Sleep(5 * time.Millisecond)
}
st := r.Status()
if st.Status != StatusPausedForUser || st.PauseReason != "unknown_setup_page" {
t.Fatalf("expected unknown_setup_page pause, got %+v", st)
}
if strings.Contains(st.UnknownPageSummary, "Alice SecretName") {
t.Fatalf("unknown page summary leaked user full name: %q", st.UnknownPageSummary)
}
// User manually clicks past the unknown page -> Resume completes to Desktop!
mh.advance()
r.Resume()
r.Wait()
if r.Status().Status != StatusCompleted {
t.Fatalf("expected resume to reach completed desktop, got %+v", r.Status())
}
}
func TestWatchdogCatchesBootLoopAndQemuFatal(t *testing.T) {
t0 := time.Date(2026, 12, 3, 12, 0, 0, 0, time.UTC)
wd := NewWatchdog(defaultWatchdogConfig(), t0)
// 1. Three cold-reboot cycles within 5 minutes trigger boot_loop_detected.
for i := 1; i <= 3; i++ {
reason, _, tripped := wd.Check(t0.Add(time.Duration(i)*time.Minute), pluginsdk.VMTelemetry{ColdRebootCount: i}, StageInstallWait, false)
if i < 3 && tripped {
t.Fatalf("tripped too early at cycle %d", i)
}
if i == 3 && (!tripped || reason != "boot_loop_detected") {
t.Fatalf("expected boot_loop_detected on 3rd cycle, got tripped=%v reason=%q", tripped, reason)
}
}
// 2. Fatal QEMU error trips immediately.
wd2 := NewWatchdog(defaultWatchdogConfig(), t0)
if reason, _, tripped := wd2.Check(t0.Add(10*time.Second), pluginsdk.VMTelemetry{
QemuErrors: []string{"fatal: WHPX partition failed"},
}, StageInstallWait, false); !tripped || reason != "qemu_fatal_error" {
t.Fatalf("expected qemu_fatal_error, got tripped=%v reason=%q", tripped, reason)
}
// 3. Stage 3 zero disk growth + frozen screen > 15m trips stage3_stalled.
wd3 := NewWatchdog(defaultWatchdogConfig(), t0)
if reason, _, tripped := wd3.Check(t0.Add(16*time.Minute), pluginsdk.VMTelemetry{DiskBytes: 1 << 30, CPUPercent: 0.5}, StageInstallWait, false); !tripped || reason != "stage3_stalled" {
t.Fatalf("expected stage3_stalled, got tripped=%v reason=%q", tripped, reason)
}
}
func TestValidateConfigRejectsNonASCIIAndMissingSLA(t *testing.T) {
bad := RunConfig{VM: "macos:dev", FullName: "中文名", AccountName: "dev", GuestLang: "zh-Hans:0", SLAAccepted: true}
if err := ValidateConfig(&bad); err == nil {
t.Fatal("non-ASCII full_name must be rejected")
}
noSLA := RunConfig{VM: "macos:dev", FullName: "Dev", AccountName: "dev", GuestLang: "zh-Hans:0", SLAAccepted: false}
if err := ValidateConfig(&noSLA); err == nil {
t.Fatal("SLAAccepted=false must be rejected")
}
badLayout := RunConfig{VM: "macos:dev", FullName: "Dev", AccountName: "dev", GuestLang: "zh-Hans:1", SLAAccepted: true}
if err := ValidateConfig(&badLayout); err == nil {
t.Fatal("non-:0 GuestLang must be rejected")
}
recOnly := RunConfig{VM: "macos:dev", Mode: ModeRecoveryOnly, GuestLang: "zh-Hans:0", SLAAccepted: true}
if err := ValidateConfig(&recOnly); err != nil {
t.Fatalf("recovery_only without account credentials must validate, got %v", err)
}
recOnlyNoSLA := RunConfig{VM: "macos:dev", Mode: ModeRecoveryOnly, GuestLang: "zh-Hans:0", SLAAccepted: false}
if err := ValidateConfig(&recOnlyNoSLA); err == nil {
t.Fatal("recovery_only with SLAAccepted=false must still be rejected")
}
_ = filepath.Clean(".")
}
func TestReplayCapturedRecoveryScreenshot(t *testing.T) {
imgPath := strings.TrimSpace(os.Getenv("REIMS_REPLAY_IMAGE"))
if imgPath == "" {
t.Skip("set REIMS_REPLAY_IMAGE to replay a real captured Recovery frame")
}
f, err := os.Open(imgPath)
if err != nil {
t.Fatal(err)
}
defer f.Close()
img, _, err := image.Decode(f)
if err != nil {
t.Fatal(err)
}
cropTop, _ := strconv.Atoi(strings.TrimSpace(os.Getenv("REIMS_REPLAY_CROP_TOP")))
if cropTop > 0 {
b := img.Bounds()
img = vision.Crop(img, image.Rect(0, cropTop, b.Dx(), b.Dy()))
}
langs, _, err := ocr.ListWinOCRLanguages()
if err != nil || len(langs) == 0 {
t.Skip("WinRT OCR unavailable")
}
eng, err := ocr.NewWinOCREngine(langs[0])
if err != nil {
t.Fatal(err)
}
defer eng.Close()
loc := vision.NewLocalLocator(eng)
b := img.Bounds()
menuScan, err := loc.ScanROI(context.Background(), img, "menu_bar", nil)
if err != nil {
t.Fatal(err)
}
t.Logf("Frame=%dx%d menu_bar ROI=%v text=%q", b.Dx(), b.Dy(), menuScan.ROI, menuScan.Text)
for _, ln := range menuScan.Lines {
t.Logf(" line=%q rect=%v words=%+v", ln.Text, ln.Rect, ln.Words)
}
_, pt, ok := rules.FindHit(menuScan.Lines, []string{"Utilities", "实用工具", "工具程式", "ユーティリティ"}, true)
t.Logf("FindHit(实用工具): ok=%v pt=%v (pct=%.2f%%, %.2f%%)", ok, pt, float64(pt.X)*100/float64(b.Dx()), float64(pt.Y)*100/float64(b.Dy()))
if !ok {
t.Fatalf("failed to locate 实用工具 in menu_bar text=%q", menuScan.Text)
}
}
func TestReplayCapturedLoginScreenshot(t *testing.T) {
imgPath := strings.TrimSpace(os.Getenv("REIMS_REPLAY_LOGIN_IMAGE"))
if imgPath == "" {
t.Skip("set REIMS_REPLAY_LOGIN_IMAGE to replay a real captured macOS login screen")
}
f, err := os.Open(imgPath)
if err != nil {
t.Fatal(err)
}
defer f.Close()
img, _, err := image.Decode(f)
if err != nil {
t.Fatal(err)
}
langs, _, err := ocr.ListWinOCRLanguages()
if err != nil || len(langs) == 0 {
t.Skip("WinRT OCR unavailable")
}
eng, err := ocr.NewWinOCREngine(langs[0])
if err != nil {
t.Fatal(err)
}
defer eng.Close()
loc := vision.NewLocalLocator(eng)
r := &Runner{locator: loc, cfg: RunConfig{FullName: "test", AccountName: "test"}}
menuScan, _ := loc.ScanROI(context.Background(), img, "menu_bar", nil)
titleScan, _ := loc.ScanROI(context.Background(), img, "title_band", nil)
bodyScan, _ := loc.ScanROI(context.Background(), img, "body", nil)
modalScan, _ := loc.ScanROI(context.Background(), img, "modal", nil)
loginScan, _ := loc.ScanROI(context.Background(), img, "login_band", nil)
t.Logf("menu_bar=%q title_band=%q body=%q login_band=%q", menuScan.Text, titleScan.Text, bodyScan.Text, loginScan.Text)
pt, confident, ok := r.detectLoginScreen(menuScan, titleScan, bodyScan, modalScan, loginScan)
t.Logf("detectLoginScreen: ok=%v confident=%v pt=%v", ok, confident, pt)
if !ok {
t.Fatalf("failed to detect macOS login screen from title_band=%q login_band=%q", titleScan.Text, loginScan.Text)
}
}
func TestLooksLikeMacOSLockClockHeader(t *testing.T) {
for _, tc := range []struct {
name string
menu, title, body string
want bool
}{
{"tahoe zh-Hans lock clock", "", "12 月 3 日 周 四 7 : 12", "", true},
{"tahoe en-US lock clock", "", "Thursday, December 3\n7:12", "", true},
{"desktop menu bar rejected", "Finder File Edit View 14:25", "12 月 3 日 周 四 7 : 12", "", false},
{"recovery utilities rejected", "恢复 文件 编辑 实用工具 窗口", "12 月 3 日 7:12", "重新安装 macOS", false},
{"setup assistant rejected", "", "选择国家或地区", "中国大陆", false},
{"terminal mount/timestamp rejected", "", "mounted /Volumes/REIMSPROV at 08:54", "Preparing to run macOS Installer...", false},
{"terminal iso timestamp rejected", "", "2026-12-03 08:54:12 Dec startosinstall", "", false},
{"terminal shell menu rejected", "终端 Shell 编辑 显示 窗口", "12 月 3 日 周 四 7 : 12", "", false},
{"long log text in body rejected", "", "Thursday, December 3 7:12", "Some very long non-wallpaper terminal output text here", false},
} {
if got := looksLikeMacOSLockClockHeader(tc.menu, tc.title, tc.body); got != tc.want {
t.Errorf("%s: got %v, want %v", tc.name, got, tc.want)
}
}
}
func TestDetectLoginScreenRejectsTerminalWithAccountNameAndRestart(t *testing.T) {
r := &Runner{cfg: RunConfig{FullName: "test", AccountName: "test"}}
menu := vision.ROIScan{Text: "终端 Shell 编辑 显示"}
title := vision.ROIScan{Text: "-bash-3.2# sh /Volumes/REIMSHELP/install.sh\n2026-12-03 08:54:12 mount test"}
body := vision.ROIScan{
Text: "Preparing to run macOS Installer...\nInstalling provision.pkg for test\nRestarting...",
Lines: []ocr.Line{
{Text: "Preparing to run macOS Installer..."},
{Text: "test"},
{Text: "Restarting..."},
},
}
if _, _, ok := r.detectLoginScreen(menu, title, body, vision.ROIScan{}, vision.ROIScan{}); ok {
t.Fatal("Recovery Terminal printing 'test' and 'Restarting...' must NEVER match Login Screen")
}
}
func TestDualSignalProvisionReadyAndLoginUnlockFlow(t *testing.T) {
dataDir := t.TempDir()
eng, err := rules.LoadEngine(dataDir)
if err != nil {
t.Fatal(err)
}
// Pre-seed checkpoint at Stage 3 (after Recovery Terminal launched install.sh).
vmKey := "builtin.driver.reims-macos::tahoe-prov"
cfg := RunConfig{
VM: vmKey,
GuestLang: "zh-Hans:0",
FullName: "Reims User",
AccountName: "reims",
SecretSetting: "account_password",
Appearance: "dark",
SLAAccepted: true,
HasProvisionDisk: true,
}
if err := saveCheckpoint(dataDir, Checkpoint{
Version: 1,
VM: vmKey,
Stage: StageInstallWait,
Status: StatusRunning,
Config: cfg,
StartedAt: time.Now().UTC(),
}); err != nil {
t.Fatal(err)
}
mh := &mockHost{
telemetry: pluginsdk.VMTelemetry{
State: "running",
Phase: "installer",
BootMilestones: []pluginsdk.TelemetryMilestone{
{Key: "serial:provision_ready", Count: 1},
},
},
screens: []mockScreen{
// 0: Still blank while serial:provision_ready already arrived -> Stage 3 exits via zero-OCR!
{blank: true},
// 1: Post-finish_install reboot landed directly on macOS Login Screen.
{
advanceOnlyAtBottom: true,
rois: map[string]vision.ROIScan{
"body": {
Text: "Reims User\n输入密码",
Lines: []ocr.Line{
{Text: "Reims User", Rect: image.Rect(560, 340, 720, 380)},
{Text: "输入密码", Rect: image.Rect(560, 410, 720, 445)},
},
},
},
},
// 2: Desktop reached immediately after DPAPI TypeSecret + Return (no Setup Assistant!).
{
rois: map[string]vision.ROIScan{
"menu_bar": scanText("访达 文件 编辑 显示 前往 窗口 帮助 14:25", image.Rect(10, 4, 1260, 28)),
},
},
},
}
r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, cfg, Options{
PollInterval: time.Millisecond,
Stage3Interval: time.Millisecond,
PostActionWait: time.Millisecond,
DisableSleep: true,
})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
r.Start(ctx)
r.Wait()
st := r.Status()
if st.Status != StatusCompleted || st.Stage != StageDesktopReady {
t.Fatalf("unexpected final status: %+v", st)
}
if mh.finishInstall != 1 || mh.restarts != 1 {
t.Fatalf("expected finishInstall=1 restarts=1, got %d / %d", mh.finishInstall, mh.restarts)
}
if len(mh.typedSecrets) != 1 || mh.typedSecrets[0] != "account_password" {
t.Fatalf("expected exactly 1 DPAPI TypeSecret login unlock, got %v", mh.typedSecrets)
}
hasSerialRule, hasLoginRule := false, false
for _, id := range st.MatchedRules {
if id == "provision.serial_ready" {
hasSerialRule = true
}
if id == "provision.login_unlock" {
hasLoginRule = true
}
}
if !hasSerialRule || !hasLoginRule {
t.Fatalf("expected provision.serial_ready & provision.login_unlock in %v", st.MatchedRules)
}
}
func TestInstallPkgUnsupportedFallbackFlow(t *testing.T) {
dataDir := t.TempDir()
eng, err := rules.LoadEngine(dataDir)
if err != nil {
t.Fatal(err)
}
vmKey := "builtin.driver.reims-macos::tahoe-fallback"
cfg := RunConfig{
VM: vmKey,
GuestLang: "zh-Hans:0",
FullName: "Reims User",
AccountName: "reims",
SecretSetting: "account_password",
SLAAccepted: true,
HasProvisionDisk: true,
}
if err := saveCheckpoint(dataDir, Checkpoint{
Version: 1,
VM: vmKey,
Stage: StageOfflineTerminal,
Status: StatusRunning,
Config: cfg,
StartedAt: time.Now().UTC(),
}); err != nil {
t.Fatal(err)
}
mh := &mockHost{
telemetry: pluginsdk.VMTelemetry{State: "running", Phase: "installer", DiskDeltaBytes: 4 << 20, CPUPercent: 35},
screens: []mockScreen{
// 0: Terminal already foreground showing startosinstall rejected --installpackage and fell back cleanly.
{
advanceOnScan: true,
rois: map[string]vision.ROIScan{
"menu_bar": scanText("终端 Shell 编辑", image.Rect(40, 4, 240, 26)),
"terminal": scanText("REIMS_INSTALLPKG_UNSUPPORTED\nFalling back to plain startosinstall...\nPreparing to run macOS Installer", image.Rect(40, 80, 900, 260)),
},
},
// 1: Stage 3 falls back to Setup Assistant OCR detection -> Stage 4 finish_install + restart.
{
rois: map[string]vision.ROIScan{
"title_band": scanText("选择国家或地区", image.Rect(300, 120, 900, 180)),
},
},
// 2: Post-restart desktop ready (short-circuit test end).
{
rois: map[string]vision.ROIScan{
"menu_bar": scanText("Finder File Edit View Go Window Help 14:25", image.Rect(10, 4, 1260, 28)),
},
},
},
}
r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, cfg, Options{
PollInterval: time.Millisecond,
Stage3Interval: time.Millisecond,
PostActionWait: time.Millisecond,
DisableSleep: true,
})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
r.Start(ctx)
r.Wait()
st := r.Status()
if st.Status != StatusCompleted {
t.Fatalf("expected fallback run to complete, got %+v", st)
}
cp, ok := LoadCheckpoint(dataDir, vmKey)
if !ok || !cp.ProvisionFallbackNeeded {
t.Fatalf("expected ProvisionFallbackNeeded=true in checkpoint, got ok=%v cp=%+v", ok, cp)
}
}
func TestRecoveryOnlyHotkeyAndLockPolicyFlow(t *testing.T) {
dataDir := t.TempDir()
eng, err := rules.LoadEngine(dataDir)
if err != nil {
t.Fatal(err)
}
mh := &mockHost{
telemetry: pluginsdk.VMTelemetry{State: "running", Phase: "installer", DiskBytes: 4 << 30, DiskDeltaBytes: 10 << 20, CPUPercent: 45},
screens: []mockScreen{
{blank: true},
// 1: Recovery language selector -> Return
{rois: map[string]vision.ROIScan{"body": scanText("以简体中文作为主要语言", image.Rect(300, 200, 900, 260))}},
// 2: Recovery main -> Shift+Cmd+T opens Terminal
{rois: map[string]vision.ROIScan{
"menu_bar": scanText("实用工具", image.Rect(200, 4, 280, 28)),
"body": scanText("重新安装 macOS", image.Rect(400, 250, 800, 310)),
}},
// 3: Terminal ready -> types install.sh
{rois: map[string]vision.ROIScan{
"menu_bar": scanText("终端 Shell 编辑", image.Rect(40, 4, 260, 28)),
"terminal": scanText("-bash-3.2#", image.Rect(100, 100, 400, 140)),
}},
// 4: install.sh running -> Stage 3
{advanceOnScan: true, rois: map[string]vision.ROIScan{"terminal": scanText("Using target volume Macintosh HD\nPreparing to run macOS Installer", image.Rect(100, 100, 900, 240))}},
// 5: Stage 3 reboot -> Apple progress -> Setup Assistant -> Stage 4 finish_install + restart
{vmStopped: true},
{appleProg: true},
{rois: map[string]vision.ROIScan{"title_band": scanText("选择国家或地区", image.Rect(300, 120, 900, 180))}},
// 8: Post-restart Setup Assistant -> recovery_only completes immediately!
{rois: map[string]vision.ROIScan{"title_band": scanText("选择国家或地区", image.Rect(300, 120, 900, 180))}},
},
}
r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, RunConfig{
VM: "builtin.driver.reims-macos::tahoe-recovery-only",
Mode: ModeRecoveryOnly,
GuestLang: "zh-Hans:0",
SLAAccepted: true,
}, Options{DisableSleep: true})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
r.Start(ctx)
r.Wait()
st := r.Status()
if st.Status != StatusCompleted || st.Stage != StageDesktopReady {
t.Fatalf("expected recovery_only completed, got %+v", st)
}
if mh.beginPolicy != "lock" {
t.Fatalf("expected TakeoverPolicy=lock, got %q", mh.beginPolicy)
}
if !mh.sessionBegan || !mh.sessionEnded {
t.Fatalf("expected session began & ended, got began=%v ended=%v", mh.sessionBegan, mh.sessionEnded)
}
if mh.finishInstall != 1 || mh.restarts != 1 {
t.Fatalf("expected finishInstall=1 restarts=1, got %d / %d", mh.finishInstall, mh.restarts)
}
if len(mh.typedSecrets) != 0 {
t.Fatalf("recovery_only must never call TypeSecret, got %v", mh.typedSecrets)
}
foundHotkey := false
for _, k := range mh.keys {
if k == "shift+meta_l+t" {
foundHotkey = true
}
}
if !foundHotkey {
t.Fatalf("expected shift+meta_l+t hotkey, got keys=%v", mh.keys)
}
hasBootRule := false
for _, id := range st.MatchedRules {
if id == "recovery_only.system_booted" {
hasBootRule = true
}
}
if !hasBootRule {
t.Fatalf("expected recovery_only.system_booted in matched rules %v", st.MatchedRules)
}
}
func TestRecoveryHotkeyFallsBackToUtilitiesMenu(t *testing.T) {
dataDir := t.TempDir()
eng, err := rules.LoadEngine(dataDir)
if err != nil {
t.Fatal(err)
}
mh := &mockHost{
ignoreHotkey: true,
telemetry: pluginsdk.VMTelemetry{State: "running", Phase: "installer", DiskDeltaBytes: 10 << 20, CPUPercent: 40},
screens: []mockScreen{
// 0: Recovery main -> Shift+Cmd+T ignored -> clicks Utilities
{rois: map[string]vision.ROIScan{
"menu_bar": scanText("实用工具", image.Rect(200, 4, 280, 28)),
"body": scanText("重新安装 macOS", image.Rect(400, 250, 800, 310)),
}},
// 1: Utilities dropdown -> clicks Terminal
{rois: map[string]vision.ROIScan{
"menu_dropdown": scanText("终端", image.Rect(200, 90, 320, 120)),
}},
// 2: Terminal open -> types install.sh
{rois: map[string]vision.ROIScan{
"menu_bar": scanText("终端 Shell 编辑", image.Rect(40, 4, 260, 28)),
"terminal": scanText("-bash-3.2#", image.Rect(100, 100, 400, 140)),
}},
// 3: install.sh running -> Stage 3
{advanceOnScan: true, rois: map[string]vision.ROIScan{"terminal": scanText("startosinstall running", image.Rect(100, 100, 900, 240))}},
// 4: Stage 3 -> Setup Assistant -> Stage 4 finish_install + restart
{rois: map[string]vision.ROIScan{"title_band": scanText("选择国家或地区", image.Rect(300, 120, 900, 180))}},
// 5: Post-restart Setup Assistant -> complete
{rois: map[string]vision.ROIScan{"title_band": scanText("选择国家或地区", image.Rect(300, 120, 900, 180))}},
},
}
r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, RunConfig{
VM: "builtin.driver.reims-macos::tahoe-fallback-menu",
Mode: ModeRecoveryOnly,
GuestLang: "zh-Hans:0",
SLAAccepted: true,
}, Options{DisableSleep: true})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
r.Start(ctx)
r.Wait()
st := r.Status()
if st.Status != StatusCompleted {
t.Fatalf("expected fallback flow to complete, got %+v", st)
}
hasFallbackRule := false
for _, id := range st.MatchedRules {
if id == "recovery.open_terminal_menu_fallback" {
hasFallbackRule = true
}
}
if !hasFallbackRule {
t.Fatalf("expected recovery.open_terminal_menu_fallback in %v", st.MatchedRules)
}
}
func TestUserHUDPauseAndResumeFlow(t *testing.T) {
dataDir := t.TempDir()
eng, err := rules.LoadEngine(dataDir)
if err != nil {
t.Fatal(err)
}
vmKey := "builtin.driver.reims-macos::hud-pause"
cfg := RunConfig{
VM: vmKey,
Mode: ModeRecoveryOnly,
GuestLang: "zh-Hans:0",
SLAAccepted: true,
}
if err := saveCheckpoint(dataDir, Checkpoint{
Version: 1,
VM: vmKey,
Stage: StageSetupAssistant,
Status: StatusRunning,
FinishInstallDone: true,
Config: cfg,
StartedAt: time.Now().UTC(),
}); err != nil {
t.Fatal(err)
}
mh := &mockHost{
telemetry: pluginsdk.VMTelemetry{State: "running", Phase: "normal"},
screens: []mockScreen{
{rois: map[string]vision.ROIScan{"title_band": scanText("选择国家或地区", image.Rect(300, 120, 900, 180))}},
},
}
r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, cfg, Options{DisableSleep: true})
if err != nil {
t.Fatal(err)
}
r.PauseByUser("user_paused")
if st := r.Status(); st.Status != StatusPausedForUser || st.PauseReason != "user_paused" {
t.Fatalf("expected immediate paused_for_user status, got %+v", st)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
r.Start(ctx)
time.Sleep(30 * time.Millisecond)
if st := r.Status(); st.Status != StatusPausedForUser {
t.Fatalf("runner should remain paused until Resume(), got %+v", st)
}
r.Resume()
r.Wait()
if st := r.Status(); st.Status != StatusCompleted {
t.Fatalf("expected completion after Resume(), got %+v", st)
}
}
func TestMarkCheckpointStoppedClearsStaleRunningState(t *testing.T) {
dataDir := t.TempDir()
vmKey := "builtin.driver.reims-macos::stale-run"
if err := saveCheckpoint(dataDir, Checkpoint{
Version: 1,
VM: vmKey,
Stage: StageInstallWait,
Status: StatusRunning,
Config: RunConfig{VM: vmKey, Mode: ModeRecoveryOnly, GuestLang: "zh-Hans:0", SLAAccepted: true},
}); err != nil {
t.Fatal(err)
}
if err := MarkCheckpointStopped(dataDir, vmKey, "Stopped by user"); err != nil {
t.Fatal(err)
}
cp, ok := LoadCheckpoint(dataDir, vmKey)
if !ok || cp.Status != StatusStopped {
t.Fatalf("expected StatusStopped on disk, got ok=%v cp=%+v", ok, cp)
}
}
func TestWatchdogDeduplicatesRebootsAndAllowsHealthyInstallGrowth(t *testing.T) {
t0 := time.Date(2026, 12, 5, 12, 0, 0, 0, time.UTC)
wd := NewWatchdog(defaultWatchdogConfig(), t0)
// 1. Same reboot incrementing both serial:xnu and ColdRebootCount within debounce counts once.
_, _, tripped := wd.Check(t0, pluginsdk.VMTelemetry{
BootMilestones: []pluginsdk.TelemetryMilestone{{Key: "serial:xnu", Count: 1}},
}, StageInstallWait, false)
if tripped {
t.Fatal("initial check must not trip")
}
_, _, tripped = wd.Check(t0.Add(30*time.Second), pluginsdk.VMTelemetry{
ColdRebootCount: 1,
BootMilestones: []pluginsdk.TelemetryMilestone{{Key: "serial:xnu", Count: 2}},
}, StageInstallWait, false)
if tripped {
t.Fatal("single reboot with both cold reboot and serial:xnu must not trip")
}
// Another serial:xnu bump 5s later (same boot) must also be debounced.
_, _, tripped = wd.Check(t0.Add(35*time.Second), pluginsdk.VMTelemetry{
ColdRebootCount: 1,
BootMilestones: []pluginsdk.TelemetryMilestone{{Key: "serial:xnu", Count: 3}},
}, StageInstallWait, false)
if tripped || len(wd.rebootEvents) != 1 {
t.Fatalf("expected 1 debounced reboot event, got tripped=%v events=%d", tripped, len(wd.rebootEvents))
}
// 2. Normal macOS installation reboots accompanied by >= 32 MiB disk growth never false-trip.
wdInstall := NewWatchdog(defaultWatchdogConfig(), t0)
var disk int64 = 1 << 30
for i := 1; i <= 4; i++ {
disk += 256 << 20 // +256 MiB written between install stages
reason, detail, tripped := wdInstall.Check(t0.Add(time.Duration(i)*time.Minute), pluginsdk.VMTelemetry{
ColdRebootCount: i,
DiskBytes: disk,
DiskDeltaBytes: 256 << 20,
}, StageInstallWait, true)
if tripped {
t.Fatalf("healthy install reboot %d falsely tripped watchdog: %s (%s)", i, reason, detail)
}
}
// 3. ResetAfterResume and ResetRebootWindow clear prior reboot history cleanly.
wdReset := NewWatchdog(defaultWatchdogConfig(), t0)
for i := 1; i <= 3; i++ {
wdReset.Check(t0.Add(time.Duration(i)*time.Minute), pluginsdk.VMTelemetry{ColdRebootCount: i}, StageInstallWait, false)
}
wdReset.ResetAfterResume(t0.Add(3*time.Minute + 5*time.Second))
if _, _, tripped := wdReset.Check(t0.Add(3*time.Minute+10*time.Second), pluginsdk.VMTelemetry{ColdRebootCount: 3}, StageInstallWait, false); tripped {
t.Fatal("ResetAfterResume must prevent immediate re-trip on stale reboot events")
}
wdReset.ResetRebootWindow(t0.Add(4 * time.Minute))
if _, _, tripped := wdReset.Check(t0.Add(4*time.Minute+5*time.Second), pluginsdk.VMTelemetry{ColdRebootCount: 4}, StageSetupAssistant, false); tripped {
t.Fatal("ResetRebootWindow must allow intentional Stage 4 restart without tripping Stage 5")
}
}
func TestRecoveryOnlyExitsAtCountryRegionWithNoisyTitleBandAndFallback(t *testing.T) {
dataDir := t.TempDir()
eng, err := rules.LoadEngine(dataDir)
if err != nil {
t.Fatal(err)
}
vmKey := "builtin.driver.reims-macos::tahoe-country-exit"
cfg := RunConfig{
VM: vmKey,
Mode: ModeRecoveryOnly,
GuestLang: "zh-Hans:0",
SLAAccepted: true,
}
if err := saveCheckpoint(dataDir, Checkpoint{
Version: 1,
VM: vmKey,
Stage: StageInstallWait,
Status: StatusRunning,
Config: cfg,
StartedAt: time.Now().UTC(),
}); err != nil {
t.Fatal(err)
}
mh := &mockHost{
telemetry: pluginsdk.VMTelemetry{State: "running", Phase: "installer", DiskBytes: 12 << 30, CPUPercent: 15},
screens: []mockScreen{
// 0: Stage 3 lands on "选择国家或地区" where title_band only picked up "<" back icon,
// and body carries the heading + country list (exact Sequoia/Tahoe Setup Assistant layout).
{rois: map[string]vision.ROIScan{
"menu_bar": scanText("ABC 下午 11:55", image.Rect(900, 4, 1260, 26)),
"title_band": scanText("<", image.Rect(300, 140, 320, 160)),
"body": scanText("选择国家或地区\n阿尔巴尼亚\n阿尔及利亚\n阿富汗", image.Rect(360, 220, 760, 480)),
"login_band": scanText("按下 Command-Option-F5 来查看辅助功能选项", image.Rect(400, 580, 880, 620)),
}},
// 1: Post-restart Stage 5 lands on Setup Assistant again (matched even via VoiceOver/country fallback) -> exits immediately!
{rois: map[string]vision.ROIScan{
"menu_bar": scanText("ABC 下午 11:56", image.Rect(900, 4, 1260, 26)),
"body": scanText("阿尔巴尼亚\n阿尔及利亚\n阿富汗", image.Rect(360, 240, 760, 480)),
"login_band": scanText("按下 escape 键以听取如何通过旁白设置您的 Mac", image.Rect(400, 580, 880, 620)),
}},
},
}
r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, cfg, Options{DisableSleep: true})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
r.Start(ctx)
r.Wait()
st := r.Status()
if st.Status != StatusCompleted || st.Stage != StageDesktopReady {
t.Fatalf("expected recovery_only to exit completed at Setup Assistant, got %+v", st)
}
if mh.finishInstall != 1 || mh.restarts != 1 {
t.Fatalf("expected finishInstall=1 restarts=1, got %d / %d", mh.finishInstall, mh.restarts)
}
if len(mh.clicks) != 0 || len(mh.keys) != 0 || len(mh.typedTexts) != 0 || len(mh.typedSecrets) != 0 {
t.Fatalf("recovery_only must not interact with Setup Assistant: clicks=%v keys=%v texts=%v secrets=%v",
mh.clicks, mh.keys, mh.typedTexts, mh.typedSecrets)
}
sawWaitRebootStage := false
sawCompletedUpdate := false
for _, upd := range mh.sessionUpdates {
if upd.Stage == "stage5_wait_reboot" {
sawWaitRebootStage = true
}
if upd.Stage == StageSetupAssistant {
t.Fatalf("recovery_only should report stage5_wait_reboot instead of stage5_setup_assistant to host HUD")
}
if upd.Status == StatusCompleted {
sawCompletedUpdate = true
}
}
if !sawWaitRebootStage {
t.Fatalf("expected stage5_wait_reboot host session update in recovery_only mode, got %+v", mh.sessionUpdates)
}
if !sawCompletedUpdate || !mh.sessionEnded {
t.Fatalf("expected completed session update before session end, got completedUpdate=%v ended=%v", sawCompletedUpdate, mh.sessionEnded)
}
}
func TestRecoveryOnlySkipsRedundantRestartWhenAlreadyInNormalPhase(t *testing.T) {
dataDir := t.TempDir()
eng, err := rules.LoadEngine(dataDir)
if err != nil {
t.Fatal(err)
}
vmKey := "builtin.driver.reims-macos::already-normal"
cfg := RunConfig{
VM: vmKey,
Mode: ModeRecoveryOnly,
GuestLang: "zh-Hans:0",
SLAAccepted: true,
}
if err := saveCheckpoint(dataDir, Checkpoint{
Version: 1,
VM: vmKey,
Stage: StageInstallWait,
Status: StatusRunning,
Config: cfg,
StartedAt: time.Now().UTC(),
}); err != nil {
t.Fatal(err)
}
mh := &mockHost{
telemetry: pluginsdk.VMTelemetry{State: "running", Phase: "normal"},
finishResp: map[string]any{
"ok": true,
"running": true,
"installer_ejected": false,
"network_enabled": false,
"upgraded_nvme": false,
"recovery_pending": false,
"helper_stripped": false,
},
screens: []mockScreen{
{rois: map[string]vision.ROIScan{
"title_band": scanText("选择国家或地区", image.Rect(300, 210, 760, 250)),
}},
},
}
r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, cfg, Options{DisableSleep: true})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
r.Start(ctx)
r.Wait()
if st := r.Status(); st.Status != StatusCompleted {
t.Fatalf("expected immediate completion in normal phase, got %+v", st)
}
if mh.finishInstall != 1 || mh.restarts != 0 {
t.Fatalf("expected finishInstall=1 and restarts=0 when already normal with no changes, got %d / %d", mh.finishInstall, mh.restarts)
}
}
func TestBeginSessionFailureStillEndsSession(t *testing.T) {
dataDir := t.TempDir()
eng, err := rules.LoadEngine(dataDir)
if err != nil {
t.Fatal(err)
}
mh := &mockHost{
beginErr: errors.New("authorization denied"),
}
cfg := RunConfig{
VM: "builtin.driver.reims-macos::begin-fail",
Mode: ModeRecoveryOnly,
GuestLang: "zh-Hans:0",
SLAAccepted: true,
}
r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, cfg, Options{DisableSleep: true})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
r.Start(ctx)
r.Wait()
if st := r.Status(); st.Status != StatusFailed {
t.Fatalf("expected StatusFailed when BeginSession fails, got %+v", st)
}
if !mh.sessionEnded {
t.Fatal("expected EndSession to be called even when BeginSession fails so host restores manual guide")
}
}
func TestPermissionDeniedInTerminalFlowFailsImmediately(t *testing.T) {
t.Run("hotkey confirmation_denied fails immediately without menu fallback or typing", func(t *testing.T) {
dataDir := t.TempDir()
eng, err := rules.LoadEngine(dataDir)
if err != nil {
t.Fatal(err)
}
mh := &mockHost{
keyPressErr: errors.New("confirmation_denied: user denied recovery permission"),
screens: []mockScreen{
{rois: map[string]vision.ROIScan{
"menu_bar": scanText("实用工具", image.Rect(200, 4, 280, 28)),
"body": scanText("重新安装 macOS", image.Rect(400, 250, 800, 310)),
}},
},
}
cfg := RunConfig{
VM: "builtin.driver.reims-macos::deny-hotkey",
Mode: ModeRecoveryOnly,
GuestLang: "zh-Hans:0",
SLAAccepted: true,
}
_ = saveCheckpoint(dataDir, Checkpoint{
Version: 1,
VM: cfg.VM,
Stage: StageOfflineTerminal,
Status: StatusRunning,
Config: cfg,
})
r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, cfg, Options{DisableSleep: true})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
r.Start(ctx)
r.Wait()
st := r.Status()
if st.Status != StatusFailed || st.PauseReason != "permission_denied" {
t.Fatalf("expected StatusFailed/permission_denied, got %+v", st)
}
if len(mh.clicks) != 0 || len(mh.typedTexts) != 0 {
t.Fatalf("must not fall through to menu click or typing on permission denial: clicks=%v texts=%v", mh.clicks, mh.typedTexts)
}
if !mh.sessionEnded {
t.Fatal("expected EndSession called on permission denial")
}
})
t.Run("waitForTerminalReady confirmation_denied fails immediately", func(t *testing.T) {
dataDir := t.TempDir()
eng, err := rules.LoadEngine(dataDir)
if err != nil {
t.Fatal(err)
}
mh := &mockHost{
screenshotErrAt: 2,
screenshotErr: errors.New("confirmation_denied: user denied installer permission"),
screens: []mockScreen{
{rois: map[string]vision.ROIScan{
"menu_bar": scanText("实用工具", image.Rect(200, 4, 280, 28)),
"body": scanText("重新安装 macOS", image.Rect(400, 250, 800, 310)),
}},
{rois: map[string]vision.ROIScan{
"menu_bar": scanText("终端 Shell 编辑", image.Rect(40, 4, 260, 28)),
}},
},
}
cfg := RunConfig{
VM: "builtin.driver.reims-macos::deny-wait-term",
Mode: ModeRecoveryOnly,
GuestLang: "zh-Hans:0",
SLAAccepted: true,
}
_ = saveCheckpoint(dataDir, Checkpoint{
Version: 1,
VM: cfg.VM,
Stage: StageOfflineTerminal,
Status: StatusRunning,
Config: cfg,
})
r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, cfg, Options{DisableSleep: true})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
r.Start(ctx)
r.Wait()
st := r.Status()
if st.Status != StatusFailed || st.PauseReason != "permission_denied" {
t.Fatalf("expected StatusFailed/permission_denied, got %+v", st)
}
if len(mh.clicks) != 0 || len(mh.typedTexts) != 0 {
t.Fatalf("must not fall through to menu click or typing on waitForTerminalReady denial: clicks=%v texts=%v", mh.clicks, mh.typedTexts)
}
if !mh.sessionEnded {
t.Fatal("expected EndSession called on permission denial")
}
})
}
func TestStaleResumeTokenNeverBypassesSafetyPauseAndStopBeforeStartNeverDeadlocks(t *testing.T) {
dataDir := t.TempDir()
eng, err := rules.LoadEngine(dataDir)
if err != nil {
t.Fatal(err)
}
cfg := RunConfig{
VM: "builtin.driver.reims-macos::stale-resume",
Mode: ModeRecoveryOnly,
GuestLang: "zh-Hans:0",
SLAAccepted: true,
}
// 1. Stop before Start must unblock Wait immediately and prevent BeginSession.
mhStopped := &mockHost{}
rStopped, err := New(mhStopped, &mockLocator{host: mhStopped}, eng, dataDir, cfg, Options{DisableSleep: true})
if err != nil {
t.Fatal(err)
}
rStopped.Stop()
rStopped.Start(context.Background())
rStopped.Wait()
if mhStopped.sessionBegan {
t.Fatal("Stop() before Start() must prevent BeginSession from running")
}
// 2. An earlier Pause+Resume while not blocked in pauseAndWaitResume must NOT
// leave a stale token in resumeCh that auto-skips a later safety pause.
mh := &mockHost{}
r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, cfg, Options{DisableSleep: true})
if err != nil {
t.Fatal(err)
}
r.PauseByUser("user_paused")
r.Resume()
pCtx, pCancel := context.WithTimeout(context.Background(), 120*time.Millisecond)
defer pCancel()
pauseErr := r.pauseAndWaitResume(pCtx, "high_risk_guard:erase", "Paused on erase prompt", "Erase disk")
if !errors.Is(pauseErr, context.DeadlineExceeded) {
t.Fatalf("stale resume token bypassed safety pause! err=%v", pauseErr)
}
}
func TestWatchdogResumeAcknowledgesQemuErrorAndExtendsTimeout(t *testing.T) {
t0 := time.Date(2026, 12, 5, 12, 0, 0, 0, time.UTC)
wd := NewWatchdog(WatchdogConfig{TotalInstallTimeout: 30 * time.Minute}, t0)
// 1. Fatal QEMU error trips once, then Resume acknowledges that exact line so
// it does not infinite-loop; a brand-new fatal line still trips.
tel := pluginsdk.VMTelemetry{QemuErrors: []string{"fatal: device init failed"}}
if reason, _, tripped := wd.Check(t0.Add(time.Minute), tel, StageInstallWait, false); !tripped || reason != "qemu_fatal_error" {
t.Fatalf("expected qemu_fatal_error, got %q tripped=%v", reason, tripped)
}
wd.ResetAfterResume(t0.Add(2 * time.Minute))
if reason, _, tripped := wd.Check(t0.Add(3*time.Minute), tel, StageInstallWait, false); tripped {
t.Fatalf("acknowledged qemu error re-tripped after Resume: %q", reason)
}
// ResetRebootWindow (triggered on Stage 3/4 transitions) must preserve ackedQemuErrors.
wd.ResetRebootWindow(t0.Add(3*time.Minute + 30*time.Second))
if reason, _, tripped := wd.Check(t0.Add(3*time.Minute+45*time.Second), tel, StageSetupAssistant, false); tripped {
t.Fatalf("acknowledged qemu error re-tripped after ResetRebootWindow: %q", reason)
}
tel2 := pluginsdk.VMTelemetry{QemuErrors: []string{"fatal: device init failed", "fatal: second crash"}}
if reason, _, tripped := wd.Check(t0.Add(4*time.Minute), tel2, StageInstallWait, false); !tripped || reason != "qemu_fatal_error" {
t.Fatalf("new qemu error must still trip watchdog, got %q tripped=%v", reason, tripped)
}
// 2. TotalInstallTimeout trips, and Resume extends the budget instead of re-tripping immediately.
wdTO := NewWatchdog(WatchdogConfig{TotalInstallTimeout: 10 * time.Minute}, t0)
if reason, _, tripped := wdTO.Check(t0.Add(11*time.Minute), pluginsdk.VMTelemetry{}, StageInstallWait, true); !tripped || reason != "install_timeout" {
t.Fatalf("expected install_timeout, got %q tripped=%v", reason, tripped)
}
wdTO.ResetAfterResume(t0.Add(12 * time.Minute))
if reason, _, tripped := wdTO.Check(t0.Add(13*time.Minute), pluginsdk.VMTelemetry{}, StageInstallWait, true); tripped {
t.Fatalf("install_timeout re-tripped immediately after Resume: %q", reason)
}
}
func TestRedactDiagnosticTextUnicodeAndUTF8Truncation(t *testing.T) {
cfg := RunConfig{FullName: "Alice", AccountName: "alice"}
// Turkish capital dotted I (İ -> i\u0307) changes byte length on strings.ToLower;
// previously caused a slice bounds panic or UTF-8 corruption.
raw := "İSTANBUL " + strings.Repeat("中文诊断信息", 300) + " ALICE"
got := RedactDiagnosticText(raw, cfg)
if !utf8.ValidString(got) {
t.Fatalf("RedactDiagnosticText produced invalid UTF-8")
}
if strings.Contains(strings.ToLower(got), "alice") {
t.Fatalf("expected user name to be redacted, got %q", got)
}
}
func TestFillAccountFormPrefersExactLabelOverSubtitle(t *testing.T) {
lines := []ocr.Line{
{Text: "Create a password to protect your Mac account", Rect: image.Rect(300, 180, 900, 210)},
{Text: "Password:", Rect: image.Rect(320, 340, 440, 370)},
}
ln, ok := findFormFieldLabel(lines, []string{"Password", "密码"})
if !ok || ln.Rect.Min.Y != 340 {
t.Fatalf("expected exact Password label at Y=340, got ok=%v ln=%+v", ok, ln)
}
}
func TestStaleAndNormalPhaseRunningCheckpointsReorientSafely(t *testing.T) {
eng, err := rules.LoadEngine(t.TempDir())
if err != nil {
t.Fatal(err)
}
// 1. Stale (>2h old) StatusRunning checkpoint falls back to StageBootRecovery.
dataDir := t.TempDir()
vmKey := "builtin.driver.reims-macos:stale-crash"
cfg := RunConfig{VM: vmKey, Mode: ModeRecoveryOnly, GuestLang: "zh-Hans:0", SLAAccepted: true}
now := time.Date(2026, 12, 5, 12, 0, 0, 0, time.UTC)
staleCP := Checkpoint{
Version: 1,
VM: vmKey,
Stage: StageOfflineTerminal,
Status: StatusRunning,
Config: cfg,
StartedAt: now.Add(-5 * time.Hour),
UpdatedAt: now.Add(-3 * time.Hour),
}
raw, _ := json.Marshal(staleCP)
if err := os.MkdirAll(filepath.Join(dataDir, "runs"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(checkpointPath(dataDir, vmKey), raw, 0o600); err != nil {
t.Fatal(err)
}
mh := &mockHost{}
r, err := New(mh, &mockLocator{host: mh}, eng, dataDir, cfg, Options{
DisableSleep: true,
NowFunc: func() time.Time { return now },
})
if err != nil {
t.Fatal(err)
}
if got := r.Status().Stage; got != StageBootRecovery {
t.Fatalf("stale StatusRunning checkpoint stage = %q, want %q", got, StageBootRecovery)
}
// 2. Fresh StatusRunning checkpoint at StageOfflineTerminal re-orients when
// telemetry reports Phase=normal + FinishInstallDone=true (never fires Recovery hotkeys).
dataDir2 := t.TempDir()
vmKey2 := "builtin.driver.reims-macos:normal-reorient"
cfg2 := RunConfig{VM: vmKey2, Mode: ModeRecoveryOnly, GuestLang: "zh-Hans:0", SLAAccepted: true}
if err := saveCheckpoint(dataDir2, Checkpoint{
Version: 1,
VM: vmKey2,
Stage: StageOfflineTerminal,
Status: StatusRunning,
FinishInstallDone: true,
Config: cfg2,
StartedAt: time.Now().UTC(),
}); err != nil {
t.Fatal(err)
}
mh2 := &mockHost{
telemetry: pluginsdk.VMTelemetry{State: "running", Phase: "normal"},
screens: []mockScreen{{
rois: map[string]vision.ROIScan{
"title_band": scanText("选择国家或地区", image.Rect(300, 120, 900, 180)),
},
}},
}
r2, err := New(mh2, &mockLocator{host: mh2}, eng, dataDir2, cfg2, Options{DisableSleep: true})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
r2.Start(ctx)
r2.Wait()
if st := r2.Status(); st.Status != StatusCompleted {
t.Fatalf("expected normal-phase re-oriented run to complete, got %+v", st)
}
for _, k := range mh2.keys {
if strings.Contains(k, "meta_l") {
t.Fatalf("normal-phase re-oriented run must not send Recovery Terminal hotkey, saw keys=%v", mh2.keys)
}
}
}
func TestCheckpointPathCollisionFreeAndValidatesVMRef(t *testing.T) {
dataDir := t.TempDir()
// Distinct keys whose naive separator replacement would collide must get distinct paths.
p1 := checkpointPath(dataDir, "a/b")
p2 := checkpointPath(dataDir, "a_b")
p3 := checkpointPath(dataDir, "VM1")
p4 := checkpointPath(dataDir, "vm1")
if p1 == p2 {
t.Fatalf("a/b and a_b collided at %q", p1)
}
if p3 == p4 {
t.Fatalf("VM1 and vm1 collided at %q", p3)
}
runsDir := filepath.Join(dataDir, "runs")
for _, key := range []string{"..", ".", "CON", "NUL", `..\..\evil`} {
p := checkpointPath(dataDir, key)
if filepath.Dir(p) != runsDir {
t.Fatalf("checkpointPath(%q) escaped runs dir: %q", key, p)
}
base := strings.ToUpper(filepath.Base(p))
if base == "CON.JSON" || base == "NUL.JSON" || base == "...JSON" {
t.Fatalf("checkpointPath(%q) produced unsafe filename %q", key, base)
}
}
// ValidateConfig must reject "."/".." and control characters in VM ref.
for _, badVM := range []string{"..", ".", "vm\x00name", "vm\nname"} {
cfg := RunConfig{VM: badVM, Mode: ModeRecoveryOnly, GuestLang: "zh-Hans:0", SLAAccepted: true}
if err := ValidateConfig(&cfg); err == nil {
t.Fatalf("expected ValidateConfig to reject bad VM %q", badVM)
}
}
}
func TestRedactDiagnosticTextScrubsPIIAndHardwareIdentifiers(t *testing.T) {
raw := "User Alice (alice@example.com) on 192.168.1.42 MAC aa:bb:cc:dd:ee:ff " +
"UUID 123e4567-e89b-12d3-a456-426614174000 serial C02ABC123456 " +
`path /Users/alice/Documents/secret C:\Users\alice\Desktop\file ` +
"token=0123456789abcdef0123456789abcdef01234567"
got := RedactDiagnosticText(raw, RunConfig{FullName: "Alice", AccountName: "alice"})
for _, leak := range []string{
"alice", "Alice", "example.com", "192.168.1.42", "aa:bb:cc:dd:ee:ff",
"123e4567-e89b-12d3-a456-426614174000", "C02ABC123456",
"/Users/alice", `C:\Users\alice`, "0123456789abcdef0123456789abcdef",
} {
if strings.Contains(got, leak) {
t.Fatalf("RedactDiagnosticText leaked %q in %q", leak, got)
}
}
}
func TestFillAccountFormRejectsMissingInputBoxAndMissingMaskDots(t *testing.T) {
eng, err := rules.LoadEngine(t.TempDir())
if err != nil {
t.Fatal(err)
}
cfg := RunConfig{
VM: "builtin.driver.reims-macos:form-guard", Mode: ModeFull,
GuestLang: "zh-Hans:0", FullName: "Reims User", AccountName: "reims",
SecretSetting: "account_password", SLAAccepted: true,
}
bodyScan := vision.ROIScan{
Text: "Password\nVerify",
Lines: []ocr.Line{
{Text: "Password", Rect: image.Rect(320, 360, 440, 390)},
{Text: "Verify", Rect: image.Rect(320, 410, 440, 440)},
},
}
// 1. Uniform blank light-mode screen (no input box next to Password) must pause without calling TypeSecret.
mh1 := &mockHost{}
r1, err := New(mh1, &mockLocator{host: mh1}, eng, t.TempDir(), cfg, Options{DisableSleep: true})
if err != nil {
t.Fatal(err)
}
blankLight := image.NewRGBA(image.Rect(0, 0, 1280, 720))
for y := 0; y < 720; y++ {
for x := 0; x < 1280; x++ {
blankLight.SetRGBA(x, y, color.RGBA{236, 236, 236, 255})
}
}
ctx1, cancel1 := context.WithCancel(context.Background())
go func() {
for i := 0; i < 100; i++ {
if r1.Status().Status == StatusPausedForUser {
cancel1()
return
}
time.Sleep(5 * time.Millisecond)
}
cancel1()
}()
_ = r1.fillAccountForm(ctx1, blankLight, hostclient.ScreenshotMeta{}, bodyScan)
if len(mh1.typedSecrets) != 0 {
t.Fatalf("must NOT call TypeSecret when input box is missing, got %v", mh1.typedSecrets)
}
if st := r1.Status(); st.Status != StatusPausedForUser || st.PauseReason != "account_form_incomplete" {
t.Fatalf("expected account_form_incomplete pause, got %+v", st)
}
// 2. Input boxes exist, but TypeSecret yields no bullet-dot delta -> pause immediately before Verify field!
mh2 := &mockHost{
suppressMaskDots: true,
screens: []mockScreen{{
drawInputFields: []image.Rectangle{
image.Rect(460, 362, 700, 388),
image.Rect(460, 412, 700, 438),
},
}},
}
r2, err := New(mh2, &mockLocator{host: mh2}, eng, t.TempDir(), cfg, Options{DisableSleep: true})
if err != nil {
t.Fatal(err)
}
formImg, _, _ := mh2.Screenshot(context.Background(), pluginsdk.ScreenshotRequest{})
ctx2, cancel2 := context.WithCancel(context.Background())
go func() {
for i := 0; i < 100; i++ {
if r2.Status().Status == StatusPausedForUser {
cancel2()
return
}
time.Sleep(5 * time.Millisecond)
}
cancel2()
}()
_ = r2.fillAccountForm(ctx2, formImg, hostclient.ScreenshotMeta{}, bodyScan)
if len(mh2.typedSecrets) != 1 {
t.Fatalf("expected abort after 1st failed mask-dots check without typing 2nd field, got %d TypeSecret calls", len(mh2.typedSecrets))
}
if st := r2.Status(); st.Status != StatusPausedForUser || st.PauseReason != "account_form_incomplete" {
t.Fatalf("expected account_form_incomplete pause on missing mask dots, got %+v", st)
}
}
func TestLoginUnlockRefusesClockHeaderOnlyAndMissingMaskDots(t *testing.T) {
eng, err := rules.LoadEngine(t.TempDir())
if err != nil {
t.Fatal(err)
}
cfg := RunConfig{
VM: "builtin.driver.reims-macos:login-guard", Mode: ModeFull,
GuestLang: "zh-Hans:0", FullName: "Reims User", AccountName: "reims",
SecretSetting: "account_password", SLAAccepted: true, HasProvisionDisk: true,
}
// 1. Clock-header-only screen: sends one harmless shift wake, then pauses with ZERO TypeSecret calls.
mh := &mockHost{
screens: []mockScreen{{
rois: map[string]vision.ROIScan{
"title_band": scanText("Thursday, December 3\n7:12", image.Rect(400, 100, 880, 220)),
},
}},
}
r, err := New(mh, &mockLocator{host: mh}, eng, t.TempDir(), cfg, Options{DisableSleep: true})
if err != nil {
t.Fatal(err)
}
img, _, _ := mh.Screenshot(context.Background(), pluginsdk.ScreenshotRequest{})
attempts := 0
woke := false
if err := r.tryUnlockLoginScreen(context.Background(), img, image.Point{}, false, "Thursday, December 3 7:12", &attempts, &woke); err != nil {
t.Fatalf("first clock-header wake failed: %v", err)
}
if len(mh.typedSecrets) != 0 || !woke {
t.Fatalf("clock-header-only wake must not type secret; secrets=%v woke=%v", mh.typedSecrets, woke)
}
ctx, cancel := context.WithCancel(context.Background())
go func() {
for i := 0; i < 100; i++ {
if r.Status().Status == StatusPausedForUser {
cancel()
return
}
time.Sleep(5 * time.Millisecond)
}
cancel()
}()
_ = r.tryUnlockLoginScreen(ctx, img, image.Point{}, false, "Thursday, December 3 7:12", &attempts, &woke)
if len(mh.typedSecrets) != 0 {
t.Fatalf("clock-header-only screen must NEVER call TypeSecret, got %v", mh.typedSecrets)
}
if st := r.Status(); st.Status != StatusPausedForUser || st.PauseReason != "login_screen_unconfirmed" {
t.Fatalf("expected login_screen_unconfirmed pause, got %+v", st)
}
// 2. Confident login screen whose password field shows NO mask dots after TypeSecret must pause without pressing Return.
mh2 := &mockHost{suppressMaskDots: true, screens: []mockScreen{{}}}
r2, err := New(mh2, &mockLocator{host: mh2}, eng, t.TempDir(), cfg, Options{DisableSleep: true})
if err != nil {
t.Fatal(err)
}
img2, _, _ := mh2.Screenshot(context.Background(), pluginsdk.ScreenshotRequest{})
ctx2, cancel2 := context.WithCancel(context.Background())
go func() {
for i := 0; i < 100; i++ {
if r2.Status().Status == StatusPausedForUser {
cancel2()
return
}
time.Sleep(5 * time.Millisecond)
}
cancel2()
}()
attempts2 := 0
woke2 := false
_ = r2.tryUnlockLoginScreen(ctx2, img2, image.Pt(640, 427), true, "输入密码", &attempts2, &woke2)
for _, k := range mh2.keys {
if k == "ret" {
t.Fatal("must NOT press Return when login password mask dots did not appear")
}
}
if st := r2.Status(); st.Status != StatusPausedForUser || st.PauseReason != "login_unlock_failed" {
t.Fatalf("expected login_unlock_failed pause, got %+v", st)
}
}
func TestOfflineTerminalRequiresShellPromptBeforeTyping(t *testing.T) {
eng, err := rules.LoadEngine(t.TempDir())
if err != nil {
t.Fatal(err)
}
mh := &mockHost{
screens: []mockScreen{
// Recovery main screen -> runner presses Shift+Cmd+T.
{rois: map[string]vision.ROIScan{
"menu_bar": scanText("实用工具", image.Rect(200, 4, 280, 28)),
"body": scanText("重新安装 macOS", image.Rect(400, 250, 800, 310)),
}},
// Menu bar switches to Terminal, but terminal ROI has NO shell prompt yet.
{rois: map[string]vision.ROIScan{
"menu_bar": scanText("终端 Shell 编辑", image.Rect(40, 4, 260, 28)),
"terminal": scanText("", image.Rect(100, 100, 400, 140)),
}},
},
}
cfg := RunConfig{
VM: "builtin.driver.reims-macos:term-guard", Mode: ModeRecoveryOnly,
GuestLang: "zh-Hans:0", SLAAccepted: true,
}
r, err := New(mh, &mockLocator{host: mh}, eng, t.TempDir(), cfg, Options{DisableSleep: true})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
go func() {
for i := 0; i < 100; i++ {
if r.Status().Status == StatusPausedForUser {
cancel()
return
}
time.Sleep(5 * time.Millisecond)
}
cancel()
}()
_ = r.stepOfflineTerminal(ctx, NewWatchdog(WatchdogConfig{}, time.Now()))
if len(mh.typedTexts) != 0 {
t.Fatalf("must NOT inject install.sh before shell prompt is confirmed, got typedTexts=%v", mh.typedTexts)
}
if st := r.Status(); st.Status != StatusPausedForUser || st.PauseReason != "terminal_not_ready" {
t.Fatalf("expected terminal_not_ready pause, got %+v", st)
}
}
func TestLoginUnlockPausesWhenAfterScreenshotFails(t *testing.T) {
eng, err := rules.LoadEngine(t.TempDir())
if err != nil {
t.Fatal(err)
}
cfg := RunConfig{
VM: "builtin.driver.reims-macos:login-err", Mode: ModeFull,
GuestLang: "zh-Hans:0", FullName: "Reims User", AccountName: "reims",
SecretSetting: "account_password", SLAAccepted: true, HasProvisionDisk: true,
}
mh := &mockHost{
screens: []mockScreen{{}},
screenshotErrAt: 2, // Call 1 = beforeImg (ok), Call 2 = afterImg (fails)
screenshotErr: errors.New("transient capture timeout"),
}
r, err := New(mh, &mockLocator{host: mh}, eng, t.TempDir(), cfg, Options{DisableSleep: true})
if err != nil {
t.Fatal(err)
}
baseImg := image.NewRGBA(image.Rect(0, 0, 1280, 720))
ctx, cancel := context.WithCancel(context.Background())
go func() {
for i := 0; i < 100; i++ {
if r.Status().Status == StatusPausedForUser {
cancel()
return
}
time.Sleep(5 * time.Millisecond)
}
cancel()
}()
attempts := 0
woke := false
_ = r.tryUnlockLoginScreen(ctx, baseImg, image.Pt(640, 427), true, "输入密码", &attempts, &woke)
for _, k := range mh.keys {
if k == "ret" {
t.Fatal("must NOT press Return when post-TypeSecret screenshot fails")
}
}
if attempts != 0 {
t.Fatalf("expected loginAttempts not incremented on screenshot error, got %d", attempts)
}
if st := r.Status(); st.Status != StatusPausedForUser || st.PauseReason != "login_unlock_failed" {
t.Fatalf("expected login_unlock_failed pause, got %+v", st)
}
}
func TestWatchdogResetRebootWindowRebaselinesColdRebootCount(t *testing.T) {
t0 := time.Date(2026, 12, 5, 12, 0, 0, 0, time.UTC)
wd := NewWatchdog(WatchdogConfig{BootLoopThreshold: 3, BootLoopWindow: 5 * time.Minute}, t0)
// Observe 1 cold reboot before intentional Stage 4 restart.
wd.Check(t0.Add(20*time.Second), pluginsdk.VMTelemetry{ColdRebootCount: 1}, StageInstallWait, false)
// Intentional Stage 4 restart happens -> ResetRebootWindow called.
wd.ResetRebootWindow(t0.Add(40 * time.Second))
// First post-restart Check observes ColdRebootCount=2 (the intentional restart) — must NOT count.
if reason, _, tripped := wd.Check(t0.Add(60*time.Second), pluginsdk.VMTelemetry{ColdRebootCount: 2}, StageSetupAssistant, false); tripped {
t.Fatalf("intentional restart tripped watchdog: %s", reason)
}
// Two subsequent reboots must still stay below threshold 3.
if reason, _, tripped := wd.Check(t0.Add(80*time.Second), pluginsdk.VMTelemetry{ColdRebootCount: 3}, StageSetupAssistant, false); tripped {
t.Fatalf("1st post-reset reboot tripped watchdog: %s", reason)
}
if reason, _, tripped := wd.Check(t0.Add(100*time.Second), pluginsdk.VMTelemetry{ColdRebootCount: 4}, StageSetupAssistant, false); tripped {
t.Fatalf("2nd post-reset reboot tripped watchdog (intentional restart was wrongly counted): %s", reason)
}
// 3rd genuine post-reset reboot trips boot_loop_detected.
if reason, _, tripped := wd.Check(t0.Add(120*time.Second), pluginsdk.VMTelemetry{ColdRebootCount: 5}, StageSetupAssistant, false); !tripped || reason != "boot_loop_detected" {
t.Fatalf("expected boot_loop_detected on 3rd genuine post-reset reboot, got tripped=%v reason=%q", tripped, reason)
}
}
func TestRedactDiagnosticTextRespectsWordBoundaryForShortNames(t *testing.T) {
cfg := RunConfig{FullName: "Li", AccountName: "us"}
in := "Click Login using files. Welcome Li! User: us."
got := RedactDiagnosticText(in, cfg)
if !strings.Contains(got, "Click Login using files.") {
t.Fatalf("short names mangled common diagnostic words: %q", got)
}
if strings.Contains(got, "Welcome Li") || strings.Contains(got, "User: us") {
t.Fatalf("standalone short names were not redacted: %q", got)
}
if !strings.Contains(got, "Welcome <user>!") || !strings.Contains(got, "User: <user>.") {
t.Fatalf("expected standalone short names replaced with <user>, got %q", got)
}
// Short CJK names (no spaces between characters) must still be redacted inside adjacent CJK text.
cjkGot := RedactDiagnosticText("欢迎李明使用李明的Mac", RunConfig{FullName: "李明"})
if strings.Contains(cjkGot, "李明") {
t.Fatalf("short CJK name leaked inside adjacent CJK text: %q", cjkGot)
}
if cjkGot != "欢迎<user>使用<user>的Mac" {
t.Fatalf("unexpected CJK redaction result: %q", cjkGot)
}
}
func TestTerminalPromptRecognizesSh32AndBoundsUnreadyForegroundLoop(t *testing.T) {
for _, prompt := range []string{"-sh-3.2# ", "sh-3.2# ", "-zsh", "root#"} {
if !terminalLooksReady(prompt) {
t.Fatalf("terminalLooksReady(%q) = false, want true", prompt)
}
}
eng, err := rules.LoadEngine(t.TempDir())
if err != nil {
t.Fatal(err)
}
mh := &mockHost{
screens: []mockScreen{{
rois: map[string]vision.ROIScan{
"menu_bar": scanText("Terminal Shell Edit", image.Rect(40, 4, 260, 28)),
"terminal": scanText("", image.Rect(100, 100, 400, 140)),
},
}},
}
cfg := RunConfig{
VM: "builtin.driver.reims-macos:term-fg-bound", Mode: ModeRecoveryOnly,
GuestLang: "zh-Hans:0", SLAAccepted: true,
}
r, err := New(mh, &mockLocator{host: mh}, eng, t.TempDir(), cfg, Options{DisableSleep: true})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
go func() {
for i := 0; i < 100; i++ {
if r.Status().Status == StatusPausedForUser {
cancel()
return
}
time.Sleep(5 * time.Millisecond)
}
cancel()
}()
_ = r.stepOfflineTerminal(ctx, NewWatchdog(WatchdogConfig{}, time.Now()))
if st := r.Status(); st.Status != StatusPausedForUser || st.PauseReason != "terminal_not_ready" {
t.Fatalf("expected foreground Terminal without prompt to pause with terminal_not_ready, got %+v", st)
}
}
func TestWaitAfterRuleActionHonorsWaitChangeMSAndStopsOnVisualDiff(t *testing.T) {
eng, err := rules.LoadEngine(t.TempDir())
if err != nil {
t.Fatal(err)
}
cfg := RunConfig{
VM: "builtin.driver.reims-macos:wait-change", Mode: ModeRecoveryOnly,
GuestLang: "zh-Hans:0", SLAAccepted: true,
}
black := image.NewRGBA(image.Rect(0, 0, 160, 90))
white := image.NewRGBA(image.Rect(0, 0, 160, 90))
for i := 0; i < len(white.Pix); i += 4 {
white.Pix[i], white.Pix[i+1], white.Pix[i+2], white.Pix[i+3] = 255, 255, 255, 255
}
mh := &mockHost{
screenshotImgs: []image.Image{black, white},
}
r, err := New(mh, &mockLocator{host: mh}, eng, t.TempDir(), cfg, Options{
PostActionWait: 10 * time.Millisecond,
PollInterval: 10 * time.Millisecond,
DisableSleep: false,
})
if err != nil {
t.Fatal(err)
}
start := time.Now()
rule := rules.Rule{
ID: "setup.create_account",
Verify: rules.Verify{WaitChangeMS: 5000},
}
if err := r.waitAfterRuleAction(context.Background(), black, rule); err != nil {
t.Fatalf("waitAfterRuleAction: %v", err)
}
if elapsed := time.Since(start); elapsed > 2*time.Second {
t.Fatalf("waitAfterRuleAction did not exit early on visual change (elapsed=%v)", elapsed)
}
if mh.screenshotCalls < 2 {
t.Fatalf("expected waitAfterRuleAction to poll until visual change, got %d captures", mh.screenshotCalls)
}
}